Skip to main content

logicaffeine_proof/
engine.rs

1//! Backward chaining proof engine.
2//!
3//! "The machine that crawls backward from the Conclusion to the Axioms."
4//!
5//! This module implements the core proof search algorithm. It takes inference
6//! rules and *hunts* for proofs using backward chaining and unification.
7//!
8//! ## Backward Chaining Strategy
9//!
10//! 1. Start with the goal we want to prove
11//! 2. Find rules whose conclusions unify with our goal
12//! 3. Recursively prove the premises of those rules
13//! 4. Build the derivation tree as we succeed
14//!
15//! ## Example
16//!
17//! ```text
18//! Goal: Mortal(socrates)
19//!
20//! Knowledge Base:
21//!   - Human(socrates)
22//!   - ∀x(Human(x) → Mortal(x))
23//!
24//! Search:
25//!   1. Goal matches conclusion of ∀x(Human(x) → Mortal(x)) with x=socrates
26//!   2. New subgoal: Human(socrates)
27//!   3. Human(socrates) matches knowledge base fact
28//!   4. Build derivation tree: ModusPonens(UniversalInst, PremiseMatch)
29//! ```
30
31use logicaffeine_kernel::prelude::StandardLibrary;
32
33use crate::error::{ProofError, ProofResult};
34use crate::symbols::SymbolCollector;
35use crate::unify::{
36    apply_subst_to_expr, apply_subst_to_term, beta_reduce, compose_substitutions, instantiate_expr,
37    occurs_free,
38    unify_exprs, unify_pattern, unify_terms, Substitution,
39};
40use crate::{DerivationTree, InferenceRule, ProofExpr, ProofGoal, ProofTerm};
41
42/// Default maximum depth for proof search.
43const DEFAULT_MAX_DEPTH: usize = 100;
44
45/// Default node budget for proof search — the total number of `prove_goal` invocations
46/// allowed for one top-level proof. The depth bound alone does NOT guarantee bounded
47/// *time*: with a recursive axiom in scope the branching factor is large, so a depth-100
48/// search can visit `b^100` nodes — effectively a hang. Counting nodes and stopping at the
49/// budget makes every search terminate in bounded time (fail-fast → `verified = false`)
50/// instead of running forever. Generous enough that no legitimate proof reaches it; the
51/// relevance ordering in `try_backward_chain` keeps real proofs far below it.
52const DEFAULT_STEP_BUDGET: usize = 100_000;
53
54/// The backward chaining proof engine.
55///
56/// Searches for proofs by working backwards from the goal, finding rules
57/// whose conclusions match, and recursively proving their premises.
58pub struct BackwardChainer {
59    /// Knowledge base: facts and rules available to the prover.
60    knowledge_base: Vec<ProofExpr>,
61
62    /// Maximum proof depth (prevents infinite loops).
63    max_depth: usize,
64
65    /// Counter for generating fresh variable names.
66    var_counter: usize,
67
68    /// Existentials already opened on the current search branch. Forward
69    /// existential elimination skolemizes `∃x.P(x)` into witness facts; without
70    /// this guard the same existential is re-opened with a fresh constant on
71    /// every recursive `prove_goal`, never adding new reasoning power but
72    /// spinning down to the depth limit (where the oracle, the last resort,
73    /// catches the goal and yields an uncertifiable proof). Recording the
74    /// opened existential collapses that loop to a single elimination.
75    eliminated_existentials: Vec<ProofExpr>,
76
77    /// Loop-detection stack: the canonical keys of the goals currently being
78    /// proved along the active branch (an ancestor chain, pushed on entry to
79    /// `prove_goal` and popped on exit). A *recursive* axiom — one whose
80    /// conclusion shares a predicate with its own antecedent, like Tarski's inner
81    /// transitivity — lets the search re-derive a goal from a fresh instance of
82    /// itself: `Cong(?,?,A,B)` ⇐ `Cong(?',?',A,B)` ⇐ … with new existentials each
83    /// time. The depth bound only stops that after `max_depth` native frames,
84    /// which overflows the stack first. Keying goals modulo their existential
85    /// renaming and refusing to re-enter one already on the branch collapses the
86    /// regress to a finite search — without touching the productive branches,
87    /// which discharge their antecedents against premises/facts, not by re-entry.
88    active_goals: Vec<String>,
89
90    /// Nodes (`prove_goal` invocations) spent on the current top-level proof. Reset when a
91    /// proof starts (depth 0) and incremented on each `prove_goal`; the search aborts once
92    /// it passes `step_budget`. This is the *time* bound the depth limit cannot provide.
93    steps: usize,
94
95    /// The node budget — see [`DEFAULT_STEP_BUDGET`].
96    step_budget: usize,
97
98    /// What a FREE VARIABLE in a knowledge-base equation means — see [`PremiseVariables`].
99    premise_variables: PremiseVariables,
100}
101
102/// What a FREE VARIABLE in a knowledge-base equation means.
103///
104/// The chainer serves two callers with two different answers, and the answer is a property of
105/// where the knowledge base CAME FROM, not of the search:
106///
107/// * Equations handed straight to [`BackwardChainer::add_axiom`] are a REWRITE SYSTEM. A Peano
108///   definition — `Add(Zero, n) = n`, `Add(Succ k, n) = Succ(Add(k, n))` — says nothing at all
109///   unless it stands for every instance; read as facts about one fixed `k` and one fixed `n`,
110///   the pair does not compute `1 + 1`. Nothing downstream re-checks such a search, and this is
111///   what a standalone chainer is for, so it is the default.
112/// * Premises of a THEOREM are KERNEL HYPOTHESES. The trust door registers each as a
113///   declaration `h : P n` whose type mentions `n` as a context LOCAL — Lean's
114///   `variable (n : Int)` — and `verify::close_over_context_locals` closes the finished term
115///   over exactly those. An INSTANCE of such a hypothesis is a proposition the context does not
116///   carry, so no certificate can cite it. A layer whose success is re-checked must therefore
117///   read premises AS STATED: the step is not merely uncertifiable, it is not licensed.
118///
119/// Saying which reading is in force is what keeps the honesty invariant STRUCTURAL. The
120/// alternative — letting the search build the step and catching it downstream — is the one
121/// answer that is wrong either way: a tactic reports a proof and the trust door refuses it.
122#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
123pub enum PremiseVariables {
124    /// An equation stands for ALL its instances (a rewrite schema). The default.
125    #[default]
126    Schematic,
127    /// An equation is about the fixed, arbitrary values its free variables name, so only the
128    /// equation AS STATED is available. Set by every caller whose result the kernel re-checks.
129    Local,
130}
131
132// =============================================================================
133// HELPER FUNCTIONS
134// =============================================================================
135
136/// Convert a ProofTerm to a ProofExpr for reduction.
137///
138/// Terms embed into expressions as atoms or constructors.
139fn term_to_expr(term: &ProofTerm) -> ProofExpr {
140    match term {
141        ProofTerm::Constant(s) => ProofExpr::Atom(s.clone()),
142        ProofTerm::Variable(s) => ProofExpr::Atom(s.clone()),
143        ProofTerm::BoundVarRef(s) => ProofExpr::Atom(s.clone()),
144        ProofTerm::Function(name, args) => {
145            // Check if this is a known constructor
146            if matches!(name.as_str(), "Zero" | "Succ" | "Nil" | "Cons") {
147                ProofExpr::Ctor {
148                    name: name.clone(),
149                    args: args.iter().map(term_to_expr).collect(),
150                }
151            } else {
152                // Otherwise it's a predicate/function
153                ProofExpr::Predicate {
154                    name: name.clone(),
155                    args: args.clone(),
156                    world: None,
157                }
158            }
159        }
160        ProofTerm::Group(terms) => {
161            // Groups become nested predicates or just the single element
162            if terms.len() == 1 {
163                term_to_expr(&terms[0])
164            } else {
165                // Multi-term groups - convert to predicate
166                ProofExpr::Predicate {
167                    name: "Group".into(),
168                    args: terms.clone(),
169                    world: None,
170                }
171            }
172        }
173    }
174}
175
176/// Whether an expression is falsum (⊥). The engine represents absurdity as the
177/// atom `⊥`; we also accept the spelled forms for robustness across producers.
178fn is_falsum(expr: &ProofExpr) -> bool {
179    matches!(expr, ProofExpr::Atom(s) if s == "⊥" || s == "False" || s == "false")
180}
181
182/// Flatten a (possibly nested) conjunction into its individual conjuncts.
183/// `A ∧ (B ∧ C)` becomes `[A, B, C]`; a non-conjunction becomes a singleton.
184fn flatten_conjuncts(expr: &ProofExpr) -> Vec<ProofExpr> {
185    match expr {
186        ProofExpr::And(left, right) => {
187            let mut conjuncts = flatten_conjuncts(left);
188            conjuncts.extend(flatten_conjuncts(right));
189            conjuncts
190        }
191        other => vec![other.clone()],
192    }
193}
194
195/// Reassemble per-conjunct `proofs` (in `flatten_conjuncts` order) into a proof tree that
196/// mirrors `ante`'s `And` structure with BINARY [`InferenceRule::ConjunctionIntro`] nodes —
197/// the only shape the certifier accepts. Each `And` becomes one binary node over the proofs
198/// of its two sides; each leaf consumes the next proof. Recursing left-then-right matches
199/// `flatten_conjuncts`, so the leaves line up with the proofs without reordering.
200fn build_conjunction_tree(
201    ante: &ProofExpr,
202    subst: &Substitution,
203    proofs: &mut std::vec::IntoIter<DerivationTree>,
204) -> DerivationTree {
205    match ante {
206        ProofExpr::And(left, right) => {
207            let lt = build_conjunction_tree(left, subst, proofs);
208            let rt = build_conjunction_tree(right, subst, proofs);
209            DerivationTree::new(
210                apply_subst_to_expr(ante, subst),
211                InferenceRule::ConjunctionIntro,
212                vec![lt, rt],
213            )
214        }
215        _ => proofs
216            .next()
217            .expect("flatten_conjuncts yields exactly one proof per non-And leaf"),
218    }
219}
220
221/// Whether an expression is a ground/atomic *fact* — the kind a subgoal can be
222/// discharged against directly by unification (as opposed to a rule to chain).
223fn is_atomic_fact(expr: &ProofExpr) -> bool {
224    matches!(
225        expr,
226        ProofExpr::Predicate { .. } | ProofExpr::Identity(_, _) | ProofExpr::Atom(_)
227    )
228}
229
230// =============================================================================
231// CERTIFIABLE CONTRADICTION FINDER (gapless, for verified conflict detection)
232// =============================================================================
233//
234// Every derivation these helpers build certifies end-to-end: each step is an
235// explicit PremiseMatch / UniversalInst / ConjunctionIntro / ModusPonens /
236// Contradiction / CaseAnalysis node. Forward-chaining saturates the known facts;
237// a bounded case-analysis layer handles self-referential paradoxes (e.g. the
238// Barber stated with simple predicates) by splitting on a candidate atom and
239// driving both branches to ⊥ — intuitionistically, so the kernel needs no
240// excluded middle.
241
242/// A Horn-style rule: `ante → cons`, optionally under a `∀ binder`.
243struct CertRule {
244    source: ProofExpr,
245    binder: Option<String>,
246    ante: ProofExpr,
247    cons: ProofExpr,
248}
249
250fn cert_is_rule(e: &ProofExpr) -> bool {
251    matches!(e, ProofExpr::Implies(..))
252        || matches!(e, ProofExpr::ForAll { body, .. }
253            if matches!(body.as_ref(), ProofExpr::Implies(..)))
254}
255
256fn cert_extract_rules(all: &[ProofExpr]) -> Vec<CertRule> {
257    let mut rules = Vec::new();
258    for e in all {
259        match e {
260            ProofExpr::Implies(a, c) => rules.push(CertRule {
261                source: e.clone(),
262                binder: None,
263                ante: (**a).clone(),
264                cons: (**c).clone(),
265            }),
266            ProofExpr::ForAll { variable, body } => {
267                if let ProofExpr::Implies(a, c) = body.as_ref() {
268                    rules.push(CertRule {
269                        source: e.clone(),
270                        binder: Some(variable.clone()),
271                        ante: (**a).clone(),
272                        cons: (**c).clone(),
273                    });
274                }
275            }
276            _ => {}
277        }
278    }
279    rules
280}
281
282/// Whether the all-true interpretation — every predicate holding of every tuple, every
283/// uninterpreted operator returning true — satisfies `e`. A premise set entirely of this kind
284/// has a model, so it cannot be refuted. Outside it is whatever that interpretation could make
285/// false: negation, falsum, identity (distinct names may denote distinct things), arithmetic
286/// comparisons and terms, and every construct not listed. An implication needs only its
287/// conclusion inside, a disjunction only one side.
288fn satisfied_when_everything_holds(e: &ProofExpr) -> bool {
289    fn plain_term(t: &ProofTerm) -> bool {
290        match t {
291            ProofTerm::Function(name, args) => {
292                !is_arithmetic_name(name) && args.iter().all(plain_term)
293            }
294            ProofTerm::Group(terms) => terms.iter().all(plain_term),
295            _ => true,
296        }
297    }
298    fn is_arithmetic_name(name: &str) -> bool {
299        matches!(
300            name,
301            "le" | "lt"
302                | "ge"
303                | "gt"
304                | "add"
305                | "sub"
306                | "mul"
307                | "div"
308                | "mod"
309                | "Add"
310                | "Sub"
311                | "Mul"
312                | "Div"
313                | "Lt"
314                | "Gt"
315                | "Lte"
316                | "Gte"
317                | "Le"
318                | "Ge"
319                | "Eq"
320                | "Neq"
321        )
322    }
323    match e {
324        ProofExpr::Predicate { name, args, .. } => {
325            !is_arithmetic_name(name) && args.iter().all(plain_term)
326        }
327        ProofExpr::NeoEvent { roles, .. } => roles.iter().all(|(_, term)| plain_term(term)),
328        ProofExpr::Atom(name) => !matches!(name.as_str(), "⊥" | "False" | "false"),
329        ProofExpr::And(l, r) | ProofExpr::Iff(l, r) => {
330            satisfied_when_everything_holds(l) && satisfied_when_everything_holds(r)
331        }
332        ProofExpr::Or(l, r) => {
333            satisfied_when_everything_holds(l) || satisfied_when_everything_holds(r)
334        }
335        ProofExpr::Implies(_, r) => satisfied_when_everything_holds(r),
336        ProofExpr::ForAll { body, .. }
337        | ProofExpr::Exists { body, .. }
338        | ProofExpr::Temporal { body, .. } => satisfied_when_everything_holds(body),
339        _ => false,
340    }
341}
342
343/// Whether `rules` and `seed` form a Horn set: every rule runs from a conjunction of atoms to
344/// a conjunction of atoms, and every fact is a conjunction of atoms or a negated atom. Atoms
345/// here are uninterpreted predicates and events — an arithmetic comparison, an identity, a
346/// disjunction or an existential keeps the full case-splitting search.
347fn cert_is_horn(rules: &[CertRule], seed: &[(ProofExpr, DerivationTree)]) -> bool {
348    fn atom(e: &ProofExpr) -> bool {
349        matches!(e, ProofExpr::Predicate { .. } | ProofExpr::NeoEvent { .. })
350            && satisfied_when_everything_holds(e)
351    }
352    fn atoms(e: &ProofExpr) -> bool {
353        match e {
354            ProofExpr::And(l, r) => atoms(l) && atoms(r),
355            other => atom(other),
356        }
357    }
358    rules
359        .iter()
360        .all(|rule| atoms(&rule.ante) && atoms(&rule.cons))
361        && seed
362            .iter()
363            .all(|(fact, _)| atoms(fact) || matches!(fact, ProofExpr::Not(inner) if atom(inner)))
364}
365
366/// Seed the non-rule premises as `PremiseMatch` leaves.
367fn cert_seed_facts(all: &[ProofExpr]) -> Vec<(ProofExpr, DerivationTree)> {
368    let mut known: Vec<(ProofExpr, DerivationTree)> = Vec::new();
369    for e in all {
370        if cert_is_rule(e) {
371            continue;
372        }
373        if !known.iter().any(|(p, _)| exprs_structurally_equal(p, e)) {
374            known.push((
375                e.clone(),
376                DerivationTree::leaf(e.clone(), InferenceRule::PremiseMatch),
377            ));
378        }
379    }
380    known
381}
382
383/// ONE Leibniz (`Eq_rec`) step, with the motive's POSITION chosen so the kernel's check can
384/// succeed — the general form of the fix wave 1 made for the order chain's equality edge.
385///
386/// `eq_proof` proves `from = to` and `source` proves some reading of `conclusion` in which
387/// `to` is still `from`; the node returned proves `conclusion`. The certifier builds the
388/// motive by abstracting occurrences of `to` in `conclusion` and then demands
389/// `source : motive from`, so WHICH occurrences are abstracted is not presentation — it is
390/// the entire check. A step that carries one argument of `P(a, cc)` to `P(b, b)` cannot be
391/// expressed by the all-occurrences motive `λz. P(z, z)`: that motive asks for a source
392/// `P(cc, cc)` nobody proved, and the tree is refused at the trust door after the tactic has
393/// already reported success.
394///
395/// All-occurrences is tried FIRST, because it is the motive every historically-green
396/// derivation used and the cheapest one to check; a single position
397/// ([`InferenceRule::RewriteAt`]) is used only when the sweep does not reproduce `source`.
398/// `None` means no position does — i.e. this is not a Leibniz step at all, and the honest
399/// answer is to build nothing rather than to hand `qed` a tree the kernel must refuse.
400pub(crate) fn leibniz_step(
401    conclusion: ProofExpr,
402    from: &ProofTerm,
403    to: &ProofTerm,
404    eq_proof: DerivationTree,
405    source: DerivationTree,
406) -> Option<DerivationTree> {
407    if crate::tactic::substitute_in_expr(&conclusion, to, from) == source.conclusion {
408        return Some(DerivationTree::new(
409            conclusion,
410            InferenceRule::Rewrite {
411                from: from.clone(),
412                to: to.clone(),
413            },
414            vec![eq_proof, source],
415        ));
416    }
417    let (_, occurrences) =
418        crate::tactic::substitute_occurrence_in_expr(&conclusion, to, from, usize::MAX);
419    for k in 0..occurrences {
420        let (one, _) = crate::tactic::substitute_occurrence_in_expr(&conclusion, to, from, k);
421        if one == source.conclusion {
422            return Some(DerivationTree::new(
423                conclusion,
424                InferenceRule::RewriteAt {
425                    from: from.clone(),
426                    to: to.clone(),
427                    occurrence: k,
428                },
429                vec![eq_proof, source],
430            ));
431        }
432    }
433    None
434}
435
436/// Build a certifiable proof that `a = c`, given a directed edge graph in which
437/// each `(b, edge_tree)` in `adj[a]` proves `a = b`. The returned tree chains the
438/// edges along a path from `a` to `c` using `Rewrite` (Leibniz): from a proof of
439/// `a = b` (the running accumulator, `P(b)` for `P = λz. a = z`) and a proof of
440/// `b = d` (the next edge, the equality), `Eq_rec` rewrites `b ↦ d` to yield
441/// `a = d`. A `None` means no path exists. Every node certifies.
442fn cert_eq_path_proof(
443    a: &ProofTerm,
444    c: &ProofTerm,
445    adj: &std::collections::HashMap<String, Vec<(ProofTerm, DerivationTree)>>,
446) -> Option<DerivationTree> {
447    fn term_key(t: &ProofTerm) -> Option<String> {
448        term_skey(t)
449    }
450    let a_key = term_key(a)?;
451    let c_key = term_key(c)?;
452    if a_key == c_key {
453        return None;
454    }
455    // BFS over constants, carrying the running proof of `a = current`.
456    let start_proof = DerivationTree::leaf(
457        ProofExpr::Identity(a.clone(), a.clone()),
458        InferenceRule::Reflexivity,
459    );
460    let mut queue: std::collections::VecDeque<(String, ProofTerm, DerivationTree)> =
461        std::collections::VecDeque::new();
462    queue.push_back((a_key.clone(), a.clone(), start_proof));
463    let mut visited: std::collections::HashSet<String> = std::collections::HashSet::new();
464    visited.insert(a_key.clone());
465
466    while let Some((cur_key, cur_term, acc_proof)) = queue.pop_front() {
467        if cur_key == c_key {
468            // The accumulator already proves `a = c` once we've stepped onto `c`.
469            // (The start node `a = a` is reflexive and never the target, guarded
470            // above.)
471            return Some(acc_proof);
472        }
473        let Some(edges) = adj.get(&cur_key) else {
474            continue;
475        };
476        for (next_term, edge_tree) in edges {
477            let Some(next_key) = term_key(next_term) else {
478                continue;
479            };
480            if visited.contains(&next_key) {
481                continue;
482            }
483            // acc_proof : a = cur ;  edge_tree : cur = next.
484            // Rewrite cur ↦ next in `a = cur` to get `a = next`. The motive's POSITION is
485            // chosen by `leibniz_step`: when `next` already occurs inside `a` (the path
486            // `g(cc) = m`, `m = cc` closing `g(cc) = cc`) the all-occurrences motive
487            // `λz. g(z) = z` asks for a source `g(m) = m` the accumulator never proved.
488            //
489            // A node is marked VISITED only once a step to it was actually built, so an edge
490            // with no expressible motive costs that edge and not the node — another route to
491            // the same term is still open.
492            let new_concl = ProofExpr::Identity(a.clone(), next_term.clone());
493            let step = if cur_key == a_key {
494                // First step: `a = a` rewritten by `a = next` is just the edge.
495                edge_tree.clone()
496            } else {
497                match leibniz_step(
498                    new_concl,
499                    &cur_term,
500                    next_term,
501                    edge_tree.clone(),
502                    acc_proof.clone(),
503                ) {
504                    Some(step) => step,
505                    None => continue,
506                }
507            };
508            visited.insert(next_key.clone());
509            queue.push_back((next_key, next_term.clone(), step));
510        }
511    }
512    None
513}
514
515/// Close an equality contradiction: a known `¬(x = y)` paired with a chain of
516/// known equalities that entails `x = y`. The equalities form an undirected
517/// graph (each `a = b` fact also gives `b = a` via `EqualitySymmetry`); if `x`
518/// and `y` lie in one component, a path proof of `x = y` (or `y = x`, then
519/// symmetrised) discharges the negation. Every emitted node certifies.
520fn cert_equality_close(known: &[(ProofExpr, DerivationTree)]) -> Option<DerivationTree> {
521    use std::collections::HashMap;
522    // Build the symmetric adjacency: each known `a = b` contributes the edge
523    // a→b (its own proof) and b→a (its proof, symmetrised).
524    let mut adj: HashMap<String, Vec<(ProofTerm, DerivationTree)>> = HashMap::new();
525    fn key(t: &ProofTerm) -> Option<String> {
526        match t {
527            ProofTerm::Constant(s) | ProofTerm::Variable(s) | ProofTerm::BoundVarRef(s) => {
528                Some(s.clone())
529            }
530            _ => None,
531        }
532    }
533    for (prop, tree) in known {
534        if let ProofExpr::Identity(l, r) = prop {
535            let (Some(lk), Some(rk)) = (key(l), key(r)) else {
536                continue;
537            };
538            if lk == rk {
539                continue;
540            }
541            adj.entry(lk).or_default().push((r.clone(), tree.clone()));
542            let sym = DerivationTree::new(
543                ProofExpr::Identity(r.clone(), l.clone()),
544                InferenceRule::EqualitySymmetry,
545                vec![tree.clone()],
546            );
547            adj.entry(rk).or_default().push((l.clone(), sym));
548        }
549    }
550    if adj.is_empty() {
551        return None;
552    }
553
554    for (prop, neg_tree) in known {
555        let ProofExpr::Not(inner) = prop else {
556            continue;
557        };
558        let ProofExpr::Identity(x, y) = inner.as_ref() else {
559            continue;
560        };
561        // Prove the EXACT polarity the negation refutes: ¬(x = y) needs `x = y`.
562        if let Some(eq_proof) = cert_eq_path_proof(x, y, &adj) {
563            return Some(DerivationTree::new(
564                ProofExpr::Atom("⊥".into()),
565                InferenceRule::Contradiction,
566                vec![eq_proof, neg_tree.clone()],
567            ));
568        }
569    }
570    None
571}
572
573/// A structural key for a term — atomic names map to themselves, applications to
574/// `head(arg₀,…,argₙ)` recursively. This lets the equality graph treat compound
575/// terms (e.g. `F(A)`) as first-class nodes, the precondition for congruence.
576fn term_skey(t: &ProofTerm) -> Option<String> {
577    match t {
578        ProofTerm::Constant(s) | ProofTerm::Variable(s) | ProofTerm::BoundVarRef(s) => {
579            Some(s.clone())
580        }
581        ProofTerm::Function(f, args) => {
582            let mut parts = Vec::with_capacity(args.len());
583            for a in args {
584                parts.push(term_skey(a)?);
585            }
586            Some(format!("{}({})", f, parts.join(",")))
587        }
588        ProofTerm::Group(args) => {
589            let mut parts = Vec::with_capacity(args.len());
590            for a in args {
591                parts.push(term_skey(a)?);
592            }
593            Some(format!("({})", parts.join(",")))
594        }
595        _ => None,
596    }
597}
598
599/// Collect a term and all its subterms (for the congruence universe).
600fn collect_subterms(t: &ProofTerm, out: &mut Vec<ProofTerm>) {
601    out.push(t.clone());
602    if let ProofTerm::Function(_, args) | ProofTerm::Group(args) = t {
603        for a in args {
604            collect_subterms(a, out);
605        }
606    }
607}
608
609/// Build a proof of `head(xs) = head(ys)` from per-argument equality proofs,
610/// rewriting one differing argument at a time. `arg_proofs[i]` is `None` when
611/// `xs[i]` and `ys[i]` are structurally identical, else a proof of `xs[i]=ys[i]`.
612/// Each step is a `Rewrite` (Leibniz / `Eq_rec`): its motive `λz. head(xs)=head(…z…)`
613/// abstracts the i-th argument of the right-hand side, so the source premise is the
614/// running `head(xs)=head(cur)` and the equality premise the argument proof.
615fn build_congruence_proof(
616    head: &str,
617    xs: &[ProofTerm],
618    ys: &[ProofTerm],
619    arg_proofs: &[Option<DerivationTree>],
620) -> Option<DerivationTree> {
621    let f = |args: &[ProofTerm]| ProofTerm::Function(head.to_string(), args.to_vec());
622    let mut cur: Vec<ProofTerm> = xs.to_vec();
623    let mut acc = DerivationTree::leaf(
624        ProofExpr::Identity(f(xs), f(xs)),
625        InferenceRule::Reflexivity,
626    );
627    for i in 0..xs.len() {
628        let Some(arg_proof) = &arg_proofs[i] else {
629            continue;
630        };
631        let mut next = cur.clone();
632        next[i] = ys[i].clone();
633        let concl = ProofExpr::Identity(f(xs), f(&next));
634        // The argument being introduced may already occur ELSEWHERE in the pair
635        // (`g(a, b) = g(b, b)` from `a = b`), and an all-occurrences motive then reads
636        // `λz. g(a, z) = g(z, z)` and asks for a reflexive source at `a` that does not
637        // exist. `leibniz_step` abstracts the position this step actually carried.
638        acc = leibniz_step(concl, &xs[i], &ys[i], arg_proof.clone(), acc)?;
639        cur = next;
640    }
641    Some(acc)
642}
643
644/// Prove `lhs = rhs` by congruence closure over the hypothesis equalities. Build an
645/// equality graph whose nodes are all subterms (compound included), seed it with the
646/// hypotheses (and their symmetrics), then saturate with congruence edges — for any
647/// two present applications `F(xs)`, `F(ys)` whose arguments are already pairwise
648/// connected, add `F(xs)=F(ys)` (its proof built by [`build_congruence_proof`]) — to
649/// a fixpoint. Finally search for a transitive path `lhs → rhs`. Every emitted node
650/// certifies (Reflexivity / EqualitySymmetry / Rewrite / EqualityTransitivity).
651/// Chain the given EQUATIONS into `lhs = rhs` — the pure-`=` half of a `calc` block, over
652/// exactly the named steps rather than everything in scope.
653pub(crate) fn cert_equality_chain(
654    known: &[(ProofExpr, DerivationTree)],
655    lhs: &ProofTerm,
656    rhs: &ProofTerm,
657) -> Option<DerivationTree> {
658    cert_congruence_path(lhs, rhs, known)
659}
660
661pub(crate) fn cert_congruence_path(
662    lhs: &ProofTerm,
663    rhs: &ProofTerm,
664    hyps: &[(ProofExpr, DerivationTree)],
665) -> Option<DerivationTree> {
666    use std::collections::HashMap;
667    let mut adj: HashMap<String, Vec<(ProofTerm, DerivationTree)>> = HashMap::new();
668
669    // Seed the graph with hypothesis equalities, both directions.
670    for (prop, tree) in hyps {
671        let ProofExpr::Identity(l, r) = prop else {
672            continue;
673        };
674        let (Some(lk), Some(rk)) = (term_skey(l), term_skey(r)) else {
675            continue;
676        };
677        if lk == rk {
678            continue;
679        }
680        adj.entry(lk).or_default().push((r.clone(), tree.clone()));
681        let sym = DerivationTree::new(
682            ProofExpr::Identity(r.clone(), l.clone()),
683            InferenceRule::EqualitySymmetry,
684            vec![tree.clone()],
685        );
686        adj.entry(rk).or_default().push((l.clone(), sym));
687    }
688
689    // The universe of subterms (deduplicated by structural key).
690    let mut universe: Vec<ProofTerm> = Vec::new();
691    for (prop, _) in hyps {
692        if let ProofExpr::Identity(l, r) = prop {
693            collect_subterms(l, &mut universe);
694            collect_subterms(r, &mut universe);
695        }
696    }
697    collect_subterms(lhs, &mut universe);
698    collect_subterms(rhs, &mut universe);
699    let funcs: Vec<ProofTerm> = {
700        let mut seen = std::collections::HashSet::new();
701        universe
702            .into_iter()
703            .filter(|t| matches!(t, ProofTerm::Function(..)))
704            .filter(|t| term_skey(t).is_some_and(|k| seen.insert(k)))
705            .collect()
706    };
707
708    // Saturate congruence edges to a fixpoint.
709    loop {
710        let mut added = false;
711        for i in 0..funcs.len() {
712            for j in 0..funcs.len() {
713                if i == j {
714                    continue;
715                }
716                let (ProofTerm::Function(fi, xs), ProofTerm::Function(fj, ys)) =
717                    (&funcs[i], &funcs[j])
718                else {
719                    continue;
720                };
721                if fi != fj || xs.len() != ys.len() {
722                    continue;
723                }
724                let (ki, kj) = (term_skey(&funcs[i]).unwrap(), term_skey(&funcs[j]).unwrap());
725                let already = adj.get(&ki).is_some_and(|es| {
726                    es.iter()
727                        .any(|(t, _)| term_skey(t).as_deref() == Some(kj.as_str()))
728                });
729                if already {
730                    continue;
731                }
732                let mut arg_proofs: Vec<Option<DerivationTree>> = Vec::with_capacity(xs.len());
733                let mut ok = true;
734                for (x, y) in xs.iter().zip(ys.iter()) {
735                    if term_skey(x) == term_skey(y) {
736                        arg_proofs.push(None);
737                    } else if let Some(p) = cert_eq_path_proof(x, y, &adj) {
738                        arg_proofs.push(Some(p));
739                    } else {
740                        ok = false;
741                        break;
742                    }
743                }
744                if !ok {
745                    continue;
746                }
747                let Some(cong) = build_congruence_proof(fi, xs, ys, &arg_proofs) else {
748                    continue;
749                };
750                let sym = DerivationTree::new(
751                    ProofExpr::Identity(funcs[j].clone(), funcs[i].clone()),
752                    InferenceRule::EqualitySymmetry,
753                    vec![cong.clone()],
754                );
755                adj.entry(ki).or_default().push((funcs[j].clone(), cong));
756                adj.entry(kj).or_default().push((funcs[i].clone(), sym));
757                added = true;
758            }
759        }
760        if !added {
761            break;
762        }
763    }
764
765    cert_eq_path_proof(lhs, rhs, &adj)
766}
767
768/// The inequality `a ≤ b`, encoded as the Prop `le(a, b) = true`.
769pub(crate) fn le_eq(a: ProofTerm, b: ProofTerm) -> ProofExpr {
770    ProofExpr::Identity(
771        ProofTerm::Function("le".to_string(), vec![a, b]),
772        ProofTerm::Constant("true".to_string()),
773    )
774}
775
776/// If `e` is an inequality `le(a, b) = true`, return `(a, b)`.
777pub(crate) fn as_le_pair(e: &ProofExpr) -> Option<(ProofTerm, ProofTerm)> {
778    if let ProofExpr::Identity(lhs, rhs) = e {
779        if let (ProofTerm::Function(name, args), ProofTerm::Constant(t)) = (lhs, rhs) {
780            if name == "le" && args.len() == 2 && t == "true" {
781                return Some((args[0].clone(), args[1].clone()));
782            }
783        }
784    }
785    None
786}
787
788/// An integer-literal operand, if this term is one.
789fn as_int_literal(t: &ProofTerm) -> Option<i64> {
790    match t {
791        ProofTerm::Constant(s) => s.parse::<i64>().ok(),
792        _ => None,
793    }
794}
795
796/// Resolve a term through a substitution to a fixpoint, following chains
797/// (`x → y → c`). A witness that is only transitively bound (the existential cut
798/// leaves `a → _G9` while `_G9 → Q` lives elsewhere in the same substitution) is
799/// thereby fully ground.
800fn resolve_term(t: &ProofTerm, subst: &Substitution) -> ProofTerm {
801    let mut cur = t.clone();
802    for _ in 0..256 {
803        let next = apply_subst_to_term(&cur, subst);
804        if next == cur {
805            break;
806        }
807        cur = next;
808    }
809    cur
810}
811
812/// A term with no free variables — a witness ready to instantiate a quantifier.
813fn is_ground_term(t: &ProofTerm) -> bool {
814    match t {
815        ProofTerm::Variable(_) | ProofTerm::BoundVarRef(_) => false,
816        ProofTerm::Constant(_) => true,
817        ProofTerm::Function(_, args) | ProofTerm::Group(args) => args.iter().all(is_ground_term),
818    }
819}
820
821/// The fully-resolved, GROUND witness for `var` under `subst`, or `None` if it is
822/// unbound or only partially determined — in which case the instantiation must be
823/// rejected rather than leak a dangling metavariable into the certificate.
824fn ground_witness(var: &str, subst: &Substitution) -> Option<ProofTerm> {
825    let resolved = resolve_term(subst.get(var)?, subst);
826    is_ground_term(&resolved).then_some(resolved)
827}
828
829/// Collect the free-variable names of `t` in first-occurrence order (no dups),
830/// for the loop-detection key — so two goals that differ only by which fresh
831/// existential names they use produce the same canonical renaming.
832fn collect_vars_ordered_term(t: &ProofTerm, acc: &mut Vec<String>) {
833    match t {
834        ProofTerm::Variable(v) => {
835            if !acc.iter().any(|x| x == v) {
836                acc.push(v.clone());
837            }
838        }
839        ProofTerm::Function(_, args) | ProofTerm::Group(args) => {
840            for a in args {
841                collect_vars_ordered_term(a, acc);
842            }
843        }
844        ProofTerm::Constant(_) | ProofTerm::BoundVarRef(_) => {}
845    }
846}
847
848/// Did this match INSTANTIATE the premise — bind one of the fact's own FREE variables — rather
849/// than only resolve the goal's metavariables? See [`BackwardChainer::try_match_fact`].
850///
851/// A variable the fact itself BINDS is excluded: `∀x. P(x)` matched against `∀y. P(y)` is the
852/// same proposition α-renamed, and unification may record `x ↦ y` for it. That is not an
853/// instantiation of the premise — the premise's own `∀`-elimination is `UniversalInst`'s job,
854/// and it produces a certificate.
855fn fact_is_instantiated(fact: &ProofExpr, subst: &Substitution) -> bool {
856    if subst.is_empty() {
857        return false;
858    }
859    let mut vars = Vec::new();
860    collect_vars_ordered_expr(fact, &mut vars);
861    let mut bound = Vec::new();
862    collect_binders_expr(fact, &mut bound);
863    vars.iter()
864        .any(|v| !bound.contains(v) && subst.contains_key(v))
865}
866
867/// The names this expression BINDS, at every depth.
868fn collect_binders_expr(e: &ProofExpr, out: &mut Vec<String>) {
869    match e {
870        ProofExpr::ForAll { variable, body } | ProofExpr::Exists { variable, body } => {
871            out.push(variable.clone());
872            collect_binders_expr(body, out);
873        }
874        ProofExpr::And(l, r)
875        | ProofExpr::Or(l, r)
876        | ProofExpr::Implies(l, r)
877        | ProofExpr::Iff(l, r) => {
878            collect_binders_expr(l, out);
879            collect_binders_expr(r, out);
880        }
881        ProofExpr::Not(p) => collect_binders_expr(p, out),
882        ProofExpr::Temporal { body, .. } => collect_binders_expr(body, out),
883        _ => {}
884    }
885}
886
887/// Collect the free-variable names of `e` in first-occurrence order (no dups).
888/// Covers every `ProofExpr` variant so the canonical key never silently leaves a
889/// variable un-renamed (which would weaken — never break — loop detection).
890fn collect_vars_ordered_expr(e: &ProofExpr, acc: &mut Vec<String>) {
891    match e {
892        ProofExpr::Predicate { args, .. } => {
893            for a in args {
894                collect_vars_ordered_term(a, acc);
895            }
896        }
897        ProofExpr::Identity(l, r) => {
898            collect_vars_ordered_term(l, acc);
899            collect_vars_ordered_term(r, acc);
900        }
901        ProofExpr::Term(t) => collect_vars_ordered_term(t, acc),
902        ProofExpr::NeoEvent { roles, .. } => {
903            for (_, t) in roles {
904                collect_vars_ordered_term(t, acc);
905            }
906        }
907        ProofExpr::Ctor { args, .. } => {
908            for a in args {
909                collect_vars_ordered_expr(a, acc);
910            }
911        }
912        ProofExpr::Not(p)
913        | ProofExpr::ForAll { body: p, .. }
914        | ProofExpr::Exists { body: p, .. }
915        | ProofExpr::Modal { body: p, .. }
916        | ProofExpr::Temporal { body: p, .. }
917        | ProofExpr::Lambda { body: p, .. }
918        | ProofExpr::Fixpoint { body: p, .. } => collect_vars_ordered_expr(p, acc),
919        ProofExpr::And(l, r)
920        | ProofExpr::Or(l, r)
921        | ProofExpr::Implies(l, r)
922        | ProofExpr::Iff(l, r)
923        | ProofExpr::App(l, r)
924        | ProofExpr::TemporalBinary {
925            left: l, right: r, ..
926        } => {
927            collect_vars_ordered_expr(l, acc);
928            collect_vars_ordered_expr(r, acc);
929        }
930        ProofExpr::Counterfactual {
931            antecedent,
932            consequent,
933        } => {
934            collect_vars_ordered_expr(antecedent, acc);
935            collect_vars_ordered_expr(consequent, acc);
936        }
937        ProofExpr::Match { scrutinee, arms } => {
938            collect_vars_ordered_expr(scrutinee, acc);
939            for arm in arms {
940                collect_vars_ordered_expr(&arm.body, acc);
941            }
942        }
943        ProofExpr::Atom(_)
944        | ProofExpr::TypedVar { .. }
945        | ProofExpr::Hole(_)
946        | ProofExpr::Unsupported(_) => {}
947    }
948}
949
950/// Does `var` occur as a free variable anywhere in `expr`?
951fn expr_mentions_var(expr: &ProofExpr, var: &str) -> bool {
952    let mut vs = Vec::new();
953    collect_vars_ordered_expr(expr, &mut vs);
954    vs.iter().any(|v| v == var)
955}
956
957/// Witnesses for the `∀`-bound variables of an axiom being instantiated, in binder
958/// order. Each is its pinned ground binding if it has one; a variable that does NOT
959/// occur in `matrix` is *vacuous* — the matrix (and hence the goal) is independent of
960/// it, so it is soundly instantiated with any in-scope entity (here a sibling's
961/// witness). Returns `None` only when a variable is genuinely underdetermined:
962/// unpinned yet occurring in the matrix, which would leak a metavariable into the
963/// certificate.
964fn instantiation_witnesses(
965    bound_vars: &[String],
966    subst: &Substitution,
967    matrix: &ProofExpr,
968) -> Option<Vec<ProofTerm>> {
969    let fallback = bound_vars.iter().find_map(|v| ground_witness(v, subst));
970    bound_vars
971        .iter()
972        .map(|v| {
973            ground_witness(v, subst).or_else(|| {
974                if expr_mentions_var(matrix, v) {
975                    None
976                } else {
977                    fallback.clone()
978                }
979            })
980        })
981        .collect()
982}
983
984/// Rewrite every occurrence of the eigenconstant `eigen` back to `Variable(var)`
985/// in a term — the generalization step of `∀`-introduction, undoing the opaque
986/// substitution the search ran under so the certifier can abstract `λ(var). …`.
987fn rewrite_const_to_var_term(t: &ProofTerm, eigen: &str, var: &str) -> ProofTerm {
988    match t {
989        ProofTerm::Constant(c) if c == eigen => ProofTerm::Variable(var.to_string()),
990        ProofTerm::Function(n, args) => ProofTerm::Function(
991            n.clone(),
992            args.iter()
993                .map(|a| rewrite_const_to_var_term(a, eigen, var))
994                .collect(),
995        ),
996        ProofTerm::Group(args) => ProofTerm::Group(
997            args.iter()
998                .map(|a| rewrite_const_to_var_term(a, eigen, var))
999                .collect(),
1000        ),
1001        other => other.clone(),
1002    }
1003}
1004
1005/// Rewrite `Constant(eigen)` back to `Variable(var)` throughout an expression.
1006fn rewrite_const_to_var_expr(e: &ProofExpr, eigen: &str, var: &str) -> ProofExpr {
1007    let re = |x: &ProofExpr| Box::new(rewrite_const_to_var_expr(x, eigen, var));
1008    let rt = |x: &ProofTerm| rewrite_const_to_var_term(x, eigen, var);
1009    match e {
1010        ProofExpr::Predicate { name, args, world } => ProofExpr::Predicate {
1011            name: name.clone(),
1012            args: args.iter().map(rt).collect(),
1013            world: world.clone(),
1014        },
1015        ProofExpr::Identity(l, r) => ProofExpr::Identity(rt(l), rt(r)),
1016        ProofExpr::Atom(s) => ProofExpr::Atom(s.clone()),
1017        ProofExpr::And(l, r) => ProofExpr::And(re(l), re(r)),
1018        ProofExpr::Or(l, r) => ProofExpr::Or(re(l), re(r)),
1019        ProofExpr::Implies(l, r) => ProofExpr::Implies(re(l), re(r)),
1020        ProofExpr::Iff(l, r) => ProofExpr::Iff(re(l), re(r)),
1021        ProofExpr::Not(p) => ProofExpr::Not(re(p)),
1022        ProofExpr::ForAll { variable, body } => ProofExpr::ForAll {
1023            variable: variable.clone(),
1024            body: re(body),
1025        },
1026        ProofExpr::Exists { variable, body } => ProofExpr::Exists {
1027            variable: variable.clone(),
1028            body: re(body),
1029        },
1030        ProofExpr::Modal {
1031            domain,
1032            force,
1033            flavor,
1034            body,
1035        } => ProofExpr::Modal {
1036            domain: domain.clone(),
1037            force: *force,
1038            flavor: flavor.clone(),
1039            body: re(body),
1040        },
1041        ProofExpr::Counterfactual {
1042            antecedent,
1043            consequent,
1044        } => ProofExpr::Counterfactual {
1045            antecedent: re(antecedent),
1046            consequent: re(consequent),
1047        },
1048        ProofExpr::Temporal { operator, body } => ProofExpr::Temporal {
1049            operator: operator.clone(),
1050            body: re(body),
1051        },
1052        ProofExpr::TemporalBinary {
1053            operator,
1054            left,
1055            right,
1056        } => ProofExpr::TemporalBinary {
1057            operator: operator.clone(),
1058            left: re(left),
1059            right: re(right),
1060        },
1061        ProofExpr::Lambda { variable, body } => ProofExpr::Lambda {
1062            variable: variable.clone(),
1063            body: re(body),
1064        },
1065        ProofExpr::App(l, r) => ProofExpr::App(re(l), re(r)),
1066        ProofExpr::NeoEvent {
1067            event_var,
1068            verb,
1069            roles,
1070        } => ProofExpr::NeoEvent {
1071            event_var: event_var.clone(),
1072            verb: verb.clone(),
1073            roles: roles
1074                .iter()
1075                .map(|(role, t)| (role.clone(), rt(t)))
1076                .collect(),
1077        },
1078        ProofExpr::Ctor { name, args } => ProofExpr::Ctor {
1079            name: name.clone(),
1080            args: args
1081                .iter()
1082                .map(|a| rewrite_const_to_var_expr(a, eigen, var))
1083                .collect(),
1084        },
1085        ProofExpr::Match { scrutinee, arms } => ProofExpr::Match {
1086            scrutinee: re(scrutinee),
1087            arms: arms
1088                .iter()
1089                .map(|arm| crate::MatchArm {
1090                    ctor: arm.ctor.clone(),
1091                    bindings: arm.bindings.clone(),
1092                    body: rewrite_const_to_var_expr(&arm.body, eigen, var),
1093                })
1094                .collect(),
1095        },
1096        ProofExpr::Fixpoint { name, body } => ProofExpr::Fixpoint {
1097            name: name.clone(),
1098            body: re(body),
1099        },
1100        ProofExpr::TypedVar { name, typename } => ProofExpr::TypedVar {
1101            name: name.clone(),
1102            typename: typename.clone(),
1103        },
1104        ProofExpr::Hole(s) => ProofExpr::Hole(s.clone()),
1105        ProofExpr::Term(t) => ProofExpr::Term(rt(t)),
1106        ProofExpr::Unsupported(s) => ProofExpr::Unsupported(s.clone()),
1107    }
1108}
1109
1110/// Rewrite `Constant(eigen)` back to `Variable(var)` throughout a whole derivation
1111/// tree — its conclusions, the terms its rules carry (instantiation witnesses,
1112/// rewrite endpoints, case formulae), and the recorded substitutions. The
1113/// generalization that turns an eigenconstant body proof into a `∀`-abstraction.
1114fn rewrite_tree_const_to_var(tree: &DerivationTree, eigen: &str, var: &str) -> DerivationTree {
1115    // Every payload this rule carries, through the ONE exhaustive mapper. Written as its own
1116    // `match` with an `other => other.clone()` catch-all, this walker covered five rules and
1117    // `tactic::eigen_to_var_tree` covered one, and NEITHER covered `RewriteAt`,
1118    // `UniversalInstTerm` or `ExistentialIntroTerm` — the payload-carrying rules added after
1119    // both were written, which is what a catch-all guarantees will happen again.
1120    let rule = tree.rule.map_payload(
1121        &|n: &str| {
1122            if n == eigen {
1123                var.to_string()
1124            } else {
1125                n.to_string()
1126            }
1127        },
1128        &|t: &ProofTerm| rewrite_const_to_var_term(t, eigen, var),
1129        &|e: &ProofExpr| rewrite_const_to_var_expr(e, eigen, var),
1130    );
1131    DerivationTree {
1132        conclusion: rewrite_const_to_var_expr(&tree.conclusion, eigen, var),
1133        rule,
1134        premises: tree
1135            .premises
1136            .iter()
1137            .map(|p| rewrite_tree_const_to_var(p, eigen, var))
1138            .collect(),
1139        depth: tree.depth,
1140        substitution: tree
1141            .substitution
1142            .iter()
1143            .map(|(k, v)| (k.clone(), rewrite_const_to_var_term(v, eigen, var)))
1144            .collect(),
1145    }
1146}
1147
1148/// The substitution that lets a rule concluding `conclusion` prove `goal`: the goal is the
1149/// whole conclusion, or one of its conjuncts — a rule "∀x(P(x) → A(x) ∧ B(x))" proves B(t)
1150/// as surely as A(t) ∧ B(t), by projecting it out after modus ponens ([`project_goal`]).
1151fn unify_with_conclusion(goal: &ProofExpr, conclusion: &ProofExpr) -> Option<Substitution> {
1152    if let Ok(subst) = unify_exprs(goal, conclusion) {
1153        return Some(subst);
1154    }
1155    if !matches!(conclusion, ProofExpr::And(_, _)) {
1156        return None;
1157    }
1158    flatten_conjuncts(conclusion)
1159        .iter()
1160        .find_map(|conjunct| unify_exprs(goal, conjunct).ok())
1161}
1162
1163/// `concluded` if it proves `goal` outright, else the `ConjunctionElim` chain down to the
1164/// conjunct of its conclusion that `goal` is.
1165fn project_goal(concluded: DerivationTree, goal: &ProofExpr) -> Option<DerivationTree> {
1166    if unify_exprs(goal, &concluded.conclusion).is_ok() {
1167        return Some(concluded);
1168    }
1169    extract_conjunct(&concluded, goal).map(|(projected, _)| projected)
1170}
1171
1172/// Project `target` out of a conjunctive hypothesis. Given `conj`, a derivation
1173/// whose conclusion is a (possibly nested) conjunction, return a derivation of the
1174/// matching conjunct — a chain of `ConjunctionElim` steps down to it — paired with
1175/// the substitution that unifies that conjunct with `target`. This is forward
1176/// ∧-elimination: it lets the search use a conjunct of an assumed `A ∧ B` as a
1177/// standalone fact (so the existential middle of a cut pins against it), while the
1178/// certifier independently re-derives the projection. Returns `None` if no conjunct
1179/// matches.
1180fn extract_conjunct(
1181    conj: &DerivationTree,
1182    target: &ProofExpr,
1183) -> Option<(DerivationTree, Substitution)> {
1184    if let ProofExpr::And(l, r) = &conj.conclusion {
1185        let left = DerivationTree::new(
1186            (**l).clone(),
1187            InferenceRule::ConjunctionElim,
1188            vec![conj.clone()],
1189        );
1190        if let Some(found) = extract_conjunct(&left, target) {
1191            return Some(found);
1192        }
1193        let right = DerivationTree::new(
1194            (**r).clone(),
1195            InferenceRule::ConjunctionElim,
1196            vec![conj.clone()],
1197        );
1198        extract_conjunct(&right, target)
1199    } else if let Ok(subst) = unify_exprs(target, &conj.conclusion) {
1200        Some((conj.clone(), subst))
1201    } else {
1202        None
1203    }
1204}
1205
1206/// Prove `a ≤ b` by chaining the known `≤` facts. `adj` is the DIRECTED graph of
1207/// hypothesis inequalities (`≤` is not symmetric); a path `a → … → b` folds into a
1208/// left-nested `le_trans`, and `a = b` closes by `le_refl`. Every node certifies.
1209fn cert_le_path(
1210    a: &ProofTerm,
1211    b: &ProofTerm,
1212    adj: &std::collections::HashMap<String, Vec<(ProofTerm, DerivationTree)>>,
1213) -> Option<DerivationTree> {
1214    let a_key = term_skey(a)?;
1215    let b_key = term_skey(b)?;
1216    if a_key == b_key {
1217        return Some(DerivationTree::leaf(
1218            le_eq(a.clone(), a.clone()),
1219            InferenceRule::LeRefl,
1220        ));
1221    }
1222    let mut queue: std::collections::VecDeque<(String, Option<DerivationTree>)> =
1223        std::collections::VecDeque::new();
1224    queue.push_back((a_key.clone(), None));
1225    let mut visited: std::collections::HashSet<String> = std::collections::HashSet::new();
1226    visited.insert(a_key);
1227    while let Some((cur_key, acc)) = queue.pop_front() {
1228        let Some(edges) = adj.get(&cur_key) else {
1229            continue;
1230        };
1231        for (next_term, edge_tree) in edges {
1232            let Some(next_key) = term_skey(next_term) else {
1233                continue;
1234            };
1235            if visited.contains(&next_key) {
1236                continue;
1237            }
1238            visited.insert(next_key.clone());
1239            // `acc` proves `a ≤ cur`; `edge_tree` proves `cur ≤ next`.
1240            let step = match &acc {
1241                None => edge_tree.clone(), // cur == a: the edge already proves a ≤ next
1242                Some(acc_proof) => DerivationTree::new(
1243                    le_eq(a.clone(), next_term.clone()),
1244                    InferenceRule::LeTrans,
1245                    vec![acc_proof.clone(), edge_tree.clone()],
1246                ),
1247            };
1248            if next_key == b_key {
1249                return Some(step);
1250            }
1251            queue.push_back((next_key, Some(step)));
1252        }
1253    }
1254    None
1255}
1256
1257/// `x = y ⊢ a ≤ b`, where `{a, b}` is `{x, y}` in either order — an EQUALITY EDGE for the
1258/// order graph.
1259///
1260/// `le_refl x : x ≤ x` is free, and Leibniz carries one of its two `x`s to `y`. That "one of
1261/// its two" is the whole difficulty: an all-occurrences rewrite turns `x ≤ x` into `y ≤ y`,
1262/// which is a different (useless) fact, so this is the first thing in the engine that NEEDS
1263/// [`InferenceRule::RewriteAt`]. The occurrence is SEARCHED rather than assumed to be 0,
1264/// because `y` may also occur inside the other operand (`add(y, 1) ≤ y`): the index chosen is
1265/// the one whose replacement reproduces `le(x, x)` exactly, which is the motive the kernel
1266/// will demand.
1267fn cert_le_from_equality(
1268    from: &ProofTerm,
1269    to: &ProofTerm,
1270    eq_proof: &DerivationTree,
1271    a: &ProofTerm,
1272    b: &ProofTerm,
1273) -> Option<DerivationTree> {
1274    let conclusion = le_eq(a.clone(), b.clone());
1275    let (_, occurrences) =
1276        crate::tactic::substitute_occurrence_in_expr(&conclusion, to, from, usize::MAX);
1277    for k in 0..occurrences {
1278        let (candidate, _) = crate::tactic::substitute_occurrence_in_expr(&conclusion, to, from, k);
1279        // The source must be REFLEXIVE — `le(t, t)` for whatever `t` the un-rewrite
1280        // produced. Requiring `le(from, from)` specifically would only reach edges between
1281        // the equation's two bare sides, and the edges a chain needs are frequently
1282        // CONGRUENT ones (`a = b` giving `a + 1 ≤ b + 1`, with `t = a + 1`).
1283        if let Some((t1, t2)) = as_le_pair(&candidate) {
1284            if t1 == t2 {
1285                let source = DerivationTree::leaf(candidate, InferenceRule::LeRefl);
1286                return Some(DerivationTree::new(
1287                    conclusion,
1288                    InferenceRule::RewriteAt {
1289                        from: from.clone(),
1290                        to: to.clone(),
1291                        occurrence: k,
1292                    },
1293                    vec![eq_proof.clone(), source],
1294                ));
1295            }
1296        }
1297    }
1298    None
1299}
1300
1301/// Every term that a replacement of one free occurrence of `from` by `to` turns `node` into.
1302/// `a` under `a = b` yields `b`; `add(a, 1)` yields `add(b, 1)` — the congruent partner an
1303/// order chain needs when the equation sits UNDER an operator.
1304fn congruent_partners(node: &ProofTerm, from: &ProofTerm, to: &ProofTerm) -> Vec<ProofTerm> {
1305    let probe = ProofExpr::Term(node.clone());
1306    let (_, occurrences) =
1307        crate::tactic::substitute_occurrence_in_expr(&probe, from, to, usize::MAX);
1308    let mut out = Vec::new();
1309    for k in 0..occurrences {
1310        let (candidate, _) = crate::tactic::substitute_occurrence_in_expr(&probe, from, to, k);
1311        if let ProofExpr::Term(t) = candidate {
1312            if &t != node && !out.contains(&t) {
1313                out.push(t);
1314            }
1315        }
1316    }
1317    out
1318}
1319
1320/// Is this proposition a COMPARISON in the canonical `le(a,b) = true` encoding rather than an
1321/// ordinary equality between terms? Comparisons are order facts already; only the others are
1322/// candidates for an equality edge.
1323fn is_comparison_prop(e: &ProofExpr) -> bool {
1324    let ProofExpr::Identity(l, r) = e else {
1325        return false;
1326    };
1327    matches!(r, ProofTerm::Constant(c) if c == "true" || c == "false")
1328        || matches!(l, ProofTerm::Function(n, _) if matches!(n.as_str(), "le" | "lt" | "ge" | "gt"))
1329}
1330
1331/// Prove `a ≤ b` by composing the known order facts — the `Trans` COMPOSITION Lean's `calc`
1332/// performs, over a mixed relation set rather than one fixed relation.
1333///
1334/// Two kinds of edge feed the same directed graph: a `≤` fact is an edge, and an EQUALITY is
1335/// an edge in both directions (through [`cert_le_from_equality`]). That mixture is the point —
1336/// `a = b`, `b ≤ c`, `c ≤ d ⊢ a ≤ d` needs a path that changes relation twice, and the old
1337/// `le`-only graph had no arm that could consume an equality at all, so a `calc` chain with a
1338/// single `=` step in it was unreachable.
1339///
1340/// STRICT edges are deliberately absent, and that is a TRUST boundary, not an oversight. A
1341/// `<` hypothesis tightens to `a + 1 ≤ b` (`lt_succ_le`) and composes fine, but the
1342/// composition's own conclusion can then only be stated as `a + 1 ≤ d`: of the eight `Int`
1343/// order axioms NONE concludes a `lt` (`lt_succ_le` and `lt_add1_le` both take one as a
1344/// premise), so a strict CONCLUSION has no certifiable image. The missing primitive is the
1345/// converse `le_succ_lt : Π a b. (a + 1) ≤ b → a < b`, one new `Int` order axiom; adding it
1346/// here would grow the trusted base to widen a tactic, which is the one trade this campaign
1347/// forbids, so the gap is named instead of closed.
1348pub(crate) fn cert_le_chain(
1349    known: &[(ProofExpr, DerivationTree)],
1350    a: &ProofTerm,
1351    b: &ProofTerm,
1352) -> Option<DerivationTree> {
1353    let mut adj: std::collections::HashMap<String, Vec<(ProofTerm, DerivationTree)>> =
1354        std::collections::HashMap::new();
1355    // The `≤` skeleton. A STRICT `<` fact is discreteness-tightened to the `≤` fact it
1356    // implies (`lt_succ_le`/`lt_add1_le`, both already in the trusted base), so a chain with
1357    // a strict step in it composes — the `le`/`lt` encoding is `Int` by construction (its
1358    // axioms are the `Int` order axioms), so there is no rational reading to protect here.
1359    let mut nodes: Vec<ProofTerm> = vec![a.clone(), b.clone()];
1360    let mut order_facts: Vec<(ProofTerm, ProofTerm, DerivationTree)> = Vec::new();
1361    for (prop, proof) in known {
1362        let tightened = crate::omega_solve::to_le_fact(prop, proof);
1363        if let Some((le_prop, le_proof)) = tightened {
1364            if let Some((x, y)) = as_le_pair(&le_prop) {
1365                order_facts.push((x, y, le_proof));
1366            }
1367        }
1368    }
1369    for (x, y, _) in &order_facts {
1370        for t in [x, y] {
1371            if !nodes.contains(t) {
1372                nodes.push(t.clone());
1373            }
1374        }
1375    }
1376    for (x, y, proof) in &order_facts {
1377        if let Some(xk) = term_skey(x) {
1378            adj.entry(xk).or_default().push((y.clone(), proof.clone()));
1379        }
1380    }
1381    // EQUALITY EDGES. An equality is an order edge in both directions, and — through
1382    // `congruent_partners` — also between the CONGRUENT images of every node already in the
1383    // graph, which is what lets `a = b` bridge `a + 1` to `b + 1`.
1384    let mut equations: Vec<(ProofTerm, ProofTerm, DerivationTree)> = Vec::new();
1385    for (prop, proof) in known {
1386        if as_le_pair(prop).is_some() || is_comparison_prop(prop) {
1387            continue;
1388        }
1389        let ProofExpr::Identity(x, y) = prop else {
1390            continue;
1391        };
1392        if x == y {
1393            continue;
1394        }
1395        equations.push((x.clone(), y.clone(), proof.clone()));
1396        // The symmetric orientation, so a replacement in either direction is available.
1397        equations.push((
1398            y.clone(),
1399            x.clone(),
1400            DerivationTree::new(
1401                ProofExpr::Identity(y.clone(), x.clone()),
1402                InferenceRule::EqualitySymmetry,
1403                vec![proof.clone()],
1404            ),
1405        ));
1406    }
1407    // A hard cap on the congruence expansion. Each equation can add a partner for every node
1408    // already present, so an unbounded frontier is quadratic in a knowledge base the search
1409    // hands us repeatedly. The bound is generous relative to any real order chain and keeps
1410    // this off the hot path's tail.
1411    const MAX_CHAIN_NODES: usize = 128;
1412    for (from, to, eq_proof) in &equations {
1413        if nodes.len() >= MAX_CHAIN_NODES {
1414            break;
1415        }
1416        let frontier = nodes.clone();
1417        for node in &frontier {
1418            for partner in congruent_partners(node, from, to) {
1419                if let (Some(edge), Some(nk)) = (
1420                    cert_le_from_equality(from, to, eq_proof, node, &partner),
1421                    term_skey(node),
1422                ) {
1423                    adj.entry(nk).or_default().push((partner.clone(), edge));
1424                }
1425                if let (Some(edge), Some(pk)) = (
1426                    cert_le_from_equality(from, to, eq_proof, &partner, node),
1427                    term_skey(&partner),
1428                ) {
1429                    adj.entry(pk).or_default().push((node.clone(), edge));
1430                }
1431                if !nodes.contains(&partner) {
1432                    nodes.push(partner);
1433                }
1434            }
1435        }
1436    }
1437    cert_le_path(a, b, &adj)
1438}
1439
1440/// Is a STRICT conclusion certifiable at all — i.e. does the trusted base register a primitive
1441/// that CONCLUDES a `lt`?
1442///
1443/// Of the `Int` order axioms, none does: `lt_succ_le` and `lt_add1_le` both take a `lt` as a
1444/// PREMISE, so a relation chain can consume a strict step and can never produce one. The
1445/// missing primitive is the converse `le_succ_lt : Π a b. (a + 1) ≤ b → a < b`.
1446///
1447/// This asks the kernel rather than hard-coding the answer, and every producer of
1448/// [`InferenceRule::LeSuccLt`] gates on it. The consequence is that a tactic DECLINES a strict
1449/// goal today, with a message naming the missing axiom, instead of handing `qed` a derivation
1450/// the kernel must refuse — and the day the axiom (or, better, a DEFINITION of `lt` as
1451/// `le (add a 1) b`, which removes two axioms instead of adding one) lands, the strict chain
1452/// starts composing with no further change here.
1453pub(crate) fn strict_conclusions_available() -> bool {
1454    let prelude = StandardLibrary::context();
1455    prelude.get_global("le_succ_lt").is_some()
1456        || prelude.get_definition_type("le_succ_lt").is_some()
1457}
1458
1459/// Prove `a < b` by composing the order facts: tighten to `a + 1 ≤ b` through the very same
1460/// mixed chain [`cert_le_chain`] walks, then un-tighten with `le_succ_lt`.
1461///
1462/// `None` when the chain does not reach, and `None` — unconditionally — while the trusted base
1463/// has no primitive concluding a `lt` ([`strict_conclusions_available`]).
1464pub(crate) fn cert_lt_chain(
1465    known: &[(ProofExpr, DerivationTree)],
1466    a: &ProofTerm,
1467    b: &ProofTerm,
1468) -> Option<DerivationTree> {
1469    if !strict_conclusions_available() {
1470        return None;
1471    }
1472    let tightened = cert_le_chain(known, &crate::omega_solve::succ(a), b)?;
1473    Some(DerivationTree::new(
1474        crate::omega_solve::lt_eq(a.clone(), b.clone()),
1475        InferenceRule::LeSuccLt,
1476        vec![tightened],
1477    ))
1478}
1479
1480/// Detect a linear contradiction in the known set: a chain of `≤` facts proving
1481/// `le(m, n) = true` for ground `m > n` (impossible — `le m n ⇝ false`). Returns a
1482/// `⊥` derivation through the Bool no-confusion discriminator, so contradictory
1483/// linear bounds (e.g. `x ≤ 3` with `5 ≤ x`) close any goal by ex falso.
1484fn cert_linarith_close(known: &[(ProofExpr, DerivationTree)]) -> Option<DerivationTree> {
1485    use std::collections::HashMap;
1486    let mut adj: HashMap<String, Vec<(ProofTerm, DerivationTree)>> = HashMap::new();
1487    let mut grounds: Vec<(i64, ProofTerm)> = Vec::new();
1488    for (prop, tree) in known {
1489        if let Some((x, y)) = as_le_pair(prop) {
1490            if let Some(xk) = term_skey(&x) {
1491                adj.entry(xk).or_default().push((y.clone(), tree.clone()));
1492            }
1493            for t in [&x, &y] {
1494                if let Some(v) = as_int_literal(t) {
1495                    grounds.push((v, t.clone()));
1496                }
1497            }
1498        }
1499    }
1500    if adj.is_empty() {
1501        return None;
1502    }
1503    for (mv, m) in &grounds {
1504        for (nv, n) in &grounds {
1505            if mv > nv {
1506                if let Some(le_proof) = cert_le_path(m, n, &adj) {
1507                    return Some(DerivationTree::new(
1508                        ProofExpr::Atom("⊥".into()),
1509                        InferenceRule::LinFalse,
1510                        vec![le_proof],
1511                    ));
1512                }
1513            }
1514        }
1515    }
1516    None
1517}
1518
1519/// General linear refutation (Farkas). Decide unsatisfiability of the `≤`
1520/// hypotheses with Fourier-Motzkin ([`crate::linarith_solve::find_farkas`]), then
1521/// RECONSTRUCT a kernel proof from the non-negative multipliers `λᵢ`: each `lᵢ ≤ rᵢ`
1522/// becomes `0 ≤ rᵢ - lᵢ` (`le_sub`), scaled by `λᵢ` (`le_mul_nonneg`), summed
1523/// (`le_add_mono`) into `le(BigL, BigR)`; the variables cancel, so `BigL` ring-reduces
1524/// to `0` and `BigR` to `-d` (`d > 0`), giving the ground-false `le(0, -d)` that the
1525/// discriminator turns into `⊥`. Handles arbitrary coefficients (where the chain
1526/// `cert_linarith_close` cannot).
1527pub(crate) fn cert_farkas(known: &[(ProofExpr, DerivationTree)]) -> Option<DerivationTree> {
1528    use crate::linarith_solve::{combine, find_farkas, parse_lin};
1529
1530    let mut le_hyps: Vec<(ProofTerm, ProofTerm, DerivationTree)> = Vec::new();
1531    let mut constraints = Vec::new();
1532    for (prop, tree) in known {
1533        if let Some((l, r)) = as_le_pair(prop) {
1534            if let (Some(ll), Some(rl)) = (parse_lin(&l), parse_lin(&r)) {
1535                constraints.push(ll.sub(&rl)); // l - r ≤ 0
1536                le_hyps.push((l, r, tree.clone()));
1537            }
1538        }
1539    }
1540    if le_hyps.is_empty() {
1541        return None;
1542    }
1543    let multipliers = find_farkas(&constraints)?;
1544    let combo = combine(&constraints, &multipliers);
1545    if !combo.is_const() || combo.constant <= 0 {
1546        return None;
1547    }
1548    let d = combo.constant; // Σ λᵢ(lᵢ - rᵢ) = d > 0
1549
1550    let pc = |n: i64| ProofTerm::Constant(n.to_string());
1551    let pf = |op: &str, x: ProofTerm, y: ProofTerm| ProofTerm::Function(op.to_string(), vec![x, y]);
1552
1553    // Per active hypothesis: 0 ≤ rᵢ - lᵢ (le_sub), scaled by λᵢ (le_mul_nonneg).
1554    let mut scaled: Vec<DerivationTree> = Vec::new();
1555    for (&i, &lam) in &multipliers {
1556        if lam <= 0 {
1557            continue;
1558        }
1559        let (l, r, hyp_tree) = &le_hyps[i];
1560        // r + (-1)·l  — the `le_sub` form (sub-free, ring-oracle friendly).
1561        let diff = pf("add", r.clone(), pf("mul", pc(-1), l.clone()));
1562        let sub_i = DerivationTree::new(
1563            le_eq(pc(0), diff.clone()),
1564            InferenceRule::LeSub,
1565            vec![hyp_tree.clone()],
1566        );
1567        let ground = DerivationTree::leaf(le_eq(pc(0), pc(lam)), InferenceRule::Reflexivity);
1568        scaled.push(DerivationTree::new(
1569            le_eq(pf("mul", pc(lam), pc(0)), pf("mul", pc(lam), diff)),
1570            InferenceRule::LeMulNonneg,
1571            vec![ground, sub_i],
1572        ));
1573    }
1574    // Sum them: le(BigL, BigR).
1575    let summed = scaled.into_iter().reduce(|acc, s| {
1576        let (al, ar) = as_le_pair(&acc.conclusion).expect("scaled is an le-fact");
1577        let (sl, sr) = as_le_pair(&s.conclusion).expect("scaled is an le-fact");
1578        DerivationTree::new(
1579            le_eq(pf("add", al, sl), pf("add", ar, sr)),
1580            InferenceRule::LeAddMono,
1581            vec![acc, s],
1582        )
1583    })?;
1584    let (big_l, big_r) = as_le_pair(&summed.conclusion)?;
1585
1586    // Ring-normalize: rewrite BigR → -d, then BigL → 0, giving the ground `le(0, -d)`.
1587    let rw1 = DerivationTree::new(
1588        le_eq(big_l.clone(), pc(-d)),
1589        InferenceRule::Rewrite {
1590            from: big_r.clone(),
1591            to: pc(-d),
1592        },
1593        vec![
1594            DerivationTree::leaf(
1595                ProofExpr::Identity(big_r, pc(-d)),
1596                InferenceRule::ArithDecision,
1597            ),
1598            summed,
1599        ],
1600    );
1601    let rw2 = DerivationTree::new(
1602        le_eq(pc(0), pc(-d)),
1603        InferenceRule::Rewrite {
1604            from: big_l.clone(),
1605            to: pc(0),
1606        },
1607        vec![
1608            DerivationTree::leaf(
1609                ProofExpr::Identity(big_l, pc(0)),
1610                InferenceRule::ArithDecision,
1611            ),
1612            rw1,
1613        ],
1614    );
1615    Some(DerivationTree::new(
1616        ProofExpr::Atom("⊥".into()),
1617        InferenceRule::LinFalse,
1618        vec![rw2],
1619    ))
1620}
1621
1622/// Close a `P` / `¬P` pair in the known set into a `Contradiction` (⊥) node.
1623fn cert_close(known: &[(ProofExpr, DerivationTree)]) -> Option<DerivationTree> {
1624    for (prop, neg_tree) in known {
1625        if let ProofExpr::Not(inner) = prop {
1626            for (other, pos_tree) in known {
1627                if exprs_structurally_equal(other, inner) {
1628                    return Some(DerivationTree::new(
1629                        ProofExpr::Atom("⊥".into()),
1630                        InferenceRule::Contradiction,
1631                        vec![pos_tree.clone(), neg_tree.clone()],
1632                    ));
1633                }
1634            }
1635        }
1636    }
1637    None
1638}
1639
1640/// The atomic sub-formulas of a (possibly conjunctive / negated) proposition.
1641fn cert_atoms_of(expr: &ProofExpr) -> Vec<ProofExpr> {
1642    match expr {
1643        ProofExpr::And(l, r) => {
1644            let mut v = cert_atoms_of(l);
1645            v.extend(cert_atoms_of(r));
1646            v
1647        }
1648        ProofExpr::Not(inner) => cert_atoms_of(inner),
1649        other => vec![other.clone()],
1650    }
1651}
1652
1653/// Whether a proposition mentions no free variables in its predicate arguments.
1654fn cert_is_ground(expr: &ProofExpr) -> bool {
1655    fn term_ground(t: &ProofTerm) -> bool {
1656        match t {
1657            ProofTerm::Variable(_) | ProofTerm::BoundVarRef(_) => false,
1658            ProofTerm::Function(_, args) | ProofTerm::Group(args) => args.iter().all(term_ground),
1659            ProofTerm::Constant(_) => true,
1660        }
1661    }
1662    match expr {
1663        ProofExpr::Predicate { args, .. } => args.iter().all(term_ground),
1664        ProofExpr::Not(inner) => cert_is_ground(inner),
1665        ProofExpr::And(l, r) | ProofExpr::Or(l, r) | ProofExpr::Implies(l, r) => {
1666            cert_is_ground(l) && cert_is_ground(r)
1667        }
1668        ProofExpr::Atom(_) => true,
1669        _ => false,
1670    }
1671}
1672
1673/// Collect constant names appearing in predicate arguments of known facts.
1674fn cert_collect_constants(known: &[(ProofExpr, DerivationTree)]) -> Vec<String> {
1675    fn from_term(t: &ProofTerm, out: &mut Vec<String>) {
1676        match t {
1677            ProofTerm::Constant(c) => {
1678                if !out.contains(c) {
1679                    out.push(c.clone());
1680                }
1681            }
1682            ProofTerm::Function(_, args) | ProofTerm::Group(args) => {
1683                for a in args {
1684                    from_term(a, out);
1685                }
1686            }
1687            _ => {}
1688        }
1689    }
1690    fn from_expr(e: &ProofExpr, out: &mut Vec<String>) {
1691        match e {
1692            ProofExpr::Predicate { args, .. } => {
1693                for a in args {
1694                    from_term(a, out);
1695                }
1696            }
1697            ProofExpr::Not(i) => from_expr(i, out),
1698            ProofExpr::And(l, r) | ProofExpr::Or(l, r) | ProofExpr::Implies(l, r) => {
1699                from_expr(l, out);
1700                from_expr(r, out);
1701            }
1702            _ => {}
1703        }
1704    }
1705    let mut out = Vec::new();
1706    for (p, _) in known {
1707        from_expr(p, &mut out);
1708    }
1709    out
1710}
1711
1712/// Candidate substitutions under which a rule may fire: each binds the rule's
1713/// `∀`-variable to a constant drawn from a known fact that matches one of the
1714/// antecedent's atoms.
1715fn cert_rule_substs(rule: &CertRule, known: &[(ProofExpr, DerivationTree)]) -> Vec<Substitution> {
1716    match &rule.binder {
1717        None => vec![Substitution::new()],
1718        Some(v) => {
1719            let mut substs: Vec<Substitution> = Vec::new();
1720            for atom in cert_atoms_of(&rule.ante) {
1721                for (fact, _) in known {
1722                    if let Ok(s) = unify_exprs(fact, &atom) {
1723                        if s.contains_key(v) && !substs.iter().any(|e| e == &s) {
1724                            substs.push(s);
1725                        }
1726                    }
1727                }
1728            }
1729            substs
1730        }
1731    }
1732}
1733
1734/// Build a gapless proof of `ante` (under `subst`) from the known facts,
1735/// introducing `∧` via `ConjunctionIntro`. Returns `None` if any conjunct is
1736/// not derivable.
1737fn cert_prove_ante(
1738    ante: &ProofExpr,
1739    subst: &Substitution,
1740    known: &[(ProofExpr, DerivationTree)],
1741) -> Option<DerivationTree> {
1742    match ante {
1743        ProofExpr::And(l, r) => {
1744            let lt = cert_prove_ante(l, subst, known)?;
1745            let rt = cert_prove_ante(r, subst, known)?;
1746            let li = apply_subst_to_expr(l, subst);
1747            let ri = apply_subst_to_expr(r, subst);
1748            Some(DerivationTree::new(
1749                ProofExpr::And(Box::new(li), Box::new(ri)),
1750                InferenceRule::ConjunctionIntro,
1751                vec![lt, rt],
1752            ))
1753        }
1754        _ => {
1755            let goal = apply_subst_to_expr(ante, subst);
1756            known
1757                .iter()
1758                .find(|(p, _)| exprs_structurally_equal(p, &goal))
1759                .map(|(_, t)| t.clone())
1760        }
1761    }
1762}
1763
1764/// The negation of a proposition, collapsing double negation: `¬¬P ↦ P`.
1765fn cert_neg(e: &ProofExpr) -> ProofExpr {
1766    match e {
1767        ProofExpr::Not(inner) => (**inner).clone(),
1768        _ => ProofExpr::Not(Box::new(e.clone())),
1769    }
1770}
1771
1772/// A proof of `target` from the known set, by exact structural match.
1773fn cert_lookup(
1774    known: &[(ProofExpr, DerivationTree)],
1775    target: &ProofExpr,
1776) -> Option<DerivationTree> {
1777    known
1778        .iter()
1779        .find(|(p, _)| exprs_structurally_equal(p, target))
1780        .map(|(_, t)| t.clone())
1781}
1782
1783/// The proof of the implication `rule.ante → cons_inst` at this instance — a bare
1784/// `PremiseMatch` for a ground rule, or `UniversalInst` of the source `∀` rule.
1785fn cert_rule_impl_tree(
1786    rule: &CertRule,
1787    subst: &Substitution,
1788    cons_inst: &ProofExpr,
1789) -> Option<DerivationTree> {
1790    match &rule.binder {
1791        None => Some(DerivationTree::leaf(
1792            rule.source.clone(),
1793            InferenceRule::PremiseMatch,
1794        )),
1795        Some(v) => {
1796            let witness = match subst.get(v) {
1797                Some(ProofTerm::Constant(c)) | Some(ProofTerm::Variable(c)) => c.clone(),
1798                _ => return None,
1799            };
1800            let ante_inst = apply_subst_to_expr(&rule.ante, subst);
1801            Some(DerivationTree::new(
1802                ProofExpr::Implies(Box::new(ante_inst), Box::new(cons_inst.clone())),
1803                InferenceRule::UniversalInst(witness),
1804                vec![DerivationTree::leaf(
1805                    rule.source.clone(),
1806                    InferenceRule::PremiseMatch,
1807                )],
1808            ))
1809        }
1810    }
1811}
1812
1813/// n-ary DISJUNCTIVE SYLLOGISM (the heart of unit propagation): peel every refuted
1814/// disjunct off a known disjunction by certified `DisjunctionElim`, returning the
1815/// surviving sub-formula (a single literal once all but one is refuted). `None` if no
1816/// disjunct is refuted (no progress).
1817/// Prove `¬d` when the disjunct `d` is REFUTED by the known set — not only when
1818/// `¬d` is itself known, but when a CONJUNCT of `d` is false (so the whole
1819/// conjunction is), or `d` is a negation of a known fact. This is what lets
1820/// disjunctive syllogism collapse an of-pair clue: its disjuncts are conjunctions
1821/// (`Hunt(x) ∧ In(y,2004) ∧ …`), and a single false conjunct kills the disjunct.
1822/// Every returned tree is certified (`ConjunctionElim` / `Contradiction` / reductio).
1823fn cert_refute(d: &ProofExpr, known: &[(ProofExpr, DerivationTree)]) -> Option<DerivationTree> {
1824    // Directly known negation.
1825    if let Some(t) = cert_lookup(known, &cert_neg(d)) {
1826        return Some(t);
1827    }
1828    match d {
1829        // A conjunction is refuted if either conjunct is — assume the conjunction,
1830        // ∧-eliminate the false conjunct, contradict its refutation, reductio.
1831        ProofExpr::And(l, r) => {
1832            for (side, _other_first) in [(l.as_ref(), true), (r.as_ref(), false)] {
1833                if let Some(neg_side) = cert_refute(side, known) {
1834                    let assume = DerivationTree::leaf(d.clone(), InferenceRule::PremiseMatch);
1835                    let elim = DerivationTree::new(
1836                        side.clone(),
1837                        InferenceRule::ConjunctionElim,
1838                        vec![assume.clone()],
1839                    );
1840                    let contra = DerivationTree::new(
1841                        ProofExpr::Atom("⊥".into()),
1842                        InferenceRule::Contradiction,
1843                        vec![elim, neg_side],
1844                    );
1845                    return Some(DerivationTree::new(
1846                        cert_neg(d),
1847                        InferenceRule::ReductioAdAbsurdum,
1848                        vec![assume, contra],
1849                    ));
1850                }
1851            }
1852            None
1853        }
1854        // `¬x` is refuted when `x` is known — assume `¬x`, contradict `x`, reductio.
1855        ProofExpr::Not(x) => {
1856            let x_tree = cert_lookup(known, x)?;
1857            let assume = DerivationTree::leaf(d.clone(), InferenceRule::PremiseMatch);
1858            let contra = DerivationTree::new(
1859                ProofExpr::Atom("⊥".into()),
1860                InferenceRule::Contradiction,
1861                vec![x_tree, assume.clone()],
1862            );
1863            Some(DerivationTree::new(
1864                cert_neg(d),
1865                InferenceRule::ReductioAdAbsurdum,
1866                vec![assume, contra],
1867            ))
1868        }
1869        _ => None,
1870    }
1871}
1872
1873fn cert_peel_disjunction(
1874    or_tree: &DerivationTree,
1875    known: &[(ProofExpr, DerivationTree)],
1876) -> Option<(ProofExpr, DerivationTree)> {
1877    let ProofExpr::Or(l, r) = &or_tree.conclusion else {
1878        return None;
1879    };
1880    let (l, r) = ((**l).clone(), (**r).clone());
1881    if let Some(neg_l) = cert_refute(&l, known) {
1882        let elim = DerivationTree::new(
1883            r.clone(),
1884            InferenceRule::DisjunctionElim,
1885            vec![or_tree.clone(), neg_l],
1886        );
1887        return Some(cert_peel_disjunction(&elim, known).unwrap_or((r, elim)));
1888    }
1889    if let Some(neg_r) = cert_refute(&r, known) {
1890        let elim = DerivationTree::new(
1891            l.clone(),
1892            InferenceRule::DisjunctionElim,
1893            vec![or_tree.clone(), neg_r],
1894        );
1895        return Some(cert_peel_disjunction(&elim, known).unwrap_or((l, elim)));
1896    }
1897    None
1898}
1899
1900/// Forward UNIT PROPAGATION to a fixpoint — the DPLL inner loop, every step a
1901/// certified inference. Four rules drive a grounded logic grid without any
1902/// case-splitting:
1903///   • **ModusPonens** — a rule whose antecedent is satisfied fires its consequent.
1904///   • **ModusTollens** — a rule whose consequent is refuted refutes its antecedent
1905///     (via reductio: assume the antecedent, derive the consequent, contradict).
1906///   • **Disjunctive syllogism** — a disjunction with all-but-one disjunct refuted
1907///     forces the survivor ([`cert_peel_disjunction`]). This collapses domain
1908///     closures (`In(t,A) ∨ … ∨ In(t,D)`) as the row fills, with NO branching.
1909///   • **Conjunction-negation** — `¬(A ∧ B)` with `A` established refutes `B` (via
1910///     reductio). This is how "exactly one in Florida" (an at-most-one rule, refuted
1911///     by `ModusTollens`) excludes Florida from every other row.
1912/// Together these are the propagation a logic-grid solver runs; case analysis
1913/// ([`cert_derive_falsum`]) is only the rare residual decision.
1914fn cert_saturate(
1915    rules: &[CertRule],
1916    mut known: Vec<(ProofExpr, DerivationTree)>,
1917) -> Vec<(ProofExpr, DerivationTree)> {
1918    let max_rounds = 64;
1919    let mut push_new = |known: &mut Vec<(ProofExpr, DerivationTree)>,
1920                        fact: ProofExpr,
1921                        tree: DerivationTree|
1922     -> bool {
1923        if known
1924            .iter()
1925            .any(|(p, _)| exprs_structurally_equal(p, &fact))
1926        {
1927            false
1928        } else {
1929            known.push((fact, tree));
1930            true
1931        }
1932    };
1933    for _ in 0..max_rounds {
1934        let snapshot = known.clone();
1935        let mut added = false;
1936
1937        // (1) ModusPonens — fire a rule whose antecedent holds.
1938        for rule in rules {
1939            for subst in cert_rule_substs(rule, &snapshot) {
1940                let cons_inst = apply_subst_to_expr(&rule.cons, &subst);
1941                if known
1942                    .iter()
1943                    .any(|(p, _)| exprs_structurally_equal(p, &cons_inst))
1944                {
1945                    continue;
1946                }
1947                let Some(ante_proof) = cert_prove_ante(&rule.ante, &subst, &snapshot) else {
1948                    continue;
1949                };
1950                let Some(impl_tree) = cert_rule_impl_tree(rule, &subst, &cons_inst) else {
1951                    continue;
1952                };
1953                let mp = DerivationTree::new(
1954                    cons_inst.clone(),
1955                    InferenceRule::ModusPonens,
1956                    vec![impl_tree, ante_proof],
1957                );
1958                added |= push_new(&mut known, cons_inst, mp);
1959            }
1960        }
1961
1962        // (2) ModusTollens — a ground rule whose consequent is refuted refutes its
1963        // antecedent. Built from certified primitives: assume the antecedent, derive
1964        // the consequent by ModusPonens, contradict the known negation, reductio.
1965        for rule in rules {
1966            if rule.binder.is_some() {
1967                continue;
1968            }
1969            let neg_cons = cert_neg(&rule.cons);
1970            let Some(nc_tree) = cert_lookup(&snapshot, &neg_cons) else {
1971                continue;
1972            };
1973            let neg_ante = cert_neg(&rule.ante);
1974            if cert_lookup(&known, &neg_ante).is_some() {
1975                continue;
1976            }
1977            let assume = DerivationTree::leaf(rule.ante.clone(), InferenceRule::PremiseMatch);
1978            let rule_tree = DerivationTree::leaf(rule.source.clone(), InferenceRule::PremiseMatch);
1979            let mp = DerivationTree::new(
1980                rule.cons.clone(),
1981                InferenceRule::ModusPonens,
1982                vec![rule_tree, assume.clone()],
1983            );
1984            let contra = DerivationTree::new(
1985                ProofExpr::Atom("⊥".into()),
1986                InferenceRule::Contradiction,
1987                vec![mp, nc_tree],
1988            );
1989            let tree = DerivationTree::new(
1990                neg_ante.clone(),
1991                InferenceRule::ReductioAdAbsurdum,
1992                vec![assume, contra],
1993            );
1994            added |= push_new(&mut known, neg_ante, tree);
1995        }
1996
1997        // (3) Disjunctive syllogism — peel refuted disjuncts off known disjunctions.
1998        for (p, or_tree) in &snapshot {
1999            if !matches!(p, ProofExpr::Or(..)) {
2000                continue;
2001            }
2002            if let Some((lit, tree)) = cert_peel_disjunction(or_tree, &snapshot) {
2003                added |= push_new(&mut known, lit, tree);
2004            }
2005        }
2006
2007        // (4) Conjunction-negation — `¬(A ∧ B)` with `A` established refutes `B`
2008        // (and symmetrically). Built by reductio: assume B, ∧-introduce A∧B,
2009        // contradict ¬(A∧B).
2010        for (p, neg_tree) in &snapshot {
2011            let ProofExpr::Not(inner) = p else { continue };
2012            let ProofExpr::And(a, b) = inner.as_ref() else {
2013                continue;
2014            };
2015            for (known_is_left, known_side, other) in [
2016                (true, a.as_ref(), b.as_ref()),
2017                (false, b.as_ref(), a.as_ref()),
2018            ] {
2019                let Some(side_proof) = cert_prove_ante(known_side, &Substitution::new(), &snapshot)
2020                else {
2021                    continue;
2022                };
2023                let neg_other = cert_neg(other);
2024                if cert_lookup(&known, &neg_other).is_some() {
2025                    continue;
2026                }
2027                let assume = DerivationTree::leaf(other.clone(), InferenceRule::PremiseMatch);
2028                let (l_proof, r_proof) = if known_is_left {
2029                    (side_proof.clone(), assume.clone())
2030                } else {
2031                    (assume.clone(), side_proof.clone())
2032                };
2033                let conj_intro = DerivationTree::new(
2034                    (**inner).clone(),
2035                    InferenceRule::ConjunctionIntro,
2036                    vec![l_proof, r_proof],
2037                );
2038                let contra = DerivationTree::new(
2039                    ProofExpr::Atom("⊥".into()),
2040                    InferenceRule::Contradiction,
2041                    vec![conj_intro, neg_tree.clone()],
2042                );
2043                let tree = DerivationTree::new(
2044                    neg_other.clone(),
2045                    InferenceRule::ReductioAdAbsurdum,
2046                    vec![assume, contra],
2047                );
2048                added |= push_new(&mut known, neg_other, tree);
2049            }
2050        }
2051
2052        // (4b) DISJUNCTION-negation (De Morgan) — `¬(A ∨ B)` refutes EACH disjunct,
2053        // the exact dual of (4). Built from certified primitives by reductio: assume
2054        // the disjunct, `∨`-introduce the whole disjunction, contradict the known
2055        // negation. The negation is written `¬side` LITERALLY rather than through
2056        // `cert_neg`: collapsing `¬¬p` to `p` would claim the disjunct itself, which
2057        // is a classical step this intuitionistic rule does not take (and whose
2058        // kernel type would not match). This is what lets a classical reductio reach
2059        // excluded middle — assuming `¬(p ∨ ¬p)` yields both `¬p` and `¬¬p`, and
2060        // `cert_close` reads the contradiction straight off them.
2061        for (p, neg_tree) in &snapshot {
2062            let ProofExpr::Not(inner) = p else { continue };
2063            let ProofExpr::Or(a, b) = inner.as_ref() else {
2064                continue;
2065            };
2066            for side in [a.as_ref(), b.as_ref()] {
2067                let neg_side = ProofExpr::Not(Box::new(side.clone()));
2068                if cert_lookup(&known, &neg_side).is_some() {
2069                    continue;
2070                }
2071                let assume = DerivationTree::leaf(side.clone(), InferenceRule::PremiseMatch);
2072                let disj_intro = DerivationTree::new(
2073                    (**inner).clone(),
2074                    InferenceRule::DisjunctionIntro,
2075                    vec![assume.clone()],
2076                );
2077                let contra = DerivationTree::new(
2078                    ProofExpr::Atom("⊥".into()),
2079                    InferenceRule::Contradiction,
2080                    vec![disj_intro, neg_tree.clone()],
2081                );
2082                let tree = DerivationTree::new(
2083                    neg_side.clone(),
2084                    InferenceRule::ReductioAdAbsurdum,
2085                    vec![assume, contra],
2086                );
2087                added |= push_new(&mut known, neg_side, tree);
2088            }
2089        }
2090
2091        // (5) Conjunction decomposition — a known `A ∧ B` yields `A` and `B`
2092        // (`ConjunctionElim`). When disjunctive syllogism leaves one surviving
2093        // of-pair disjunct (a conjunction), this surfaces its inner either/or as a
2094        // top-level disjunction the case-split can then decide.
2095        for (p, and_tree) in &snapshot {
2096            let ProofExpr::And(a, b) = p else { continue };
2097            for side in [a.as_ref(), b.as_ref()] {
2098                let elim = DerivationTree::new(
2099                    side.clone(),
2100                    InferenceRule::ConjunctionElim,
2101                    vec![and_tree.clone()],
2102                );
2103                added |= push_new(&mut known, side.clone(), elim);
2104            }
2105        }
2106
2107        if !added {
2108            break;
2109        }
2110    }
2111    known
2112}
2113
2114/// Self-referential pivots to case-split on: rule consequent/antecedent atoms
2115/// instantiated at known constants (ground, with negations stripped).
2116fn cert_candidates(known: &[(ProofExpr, DerivationTree)], rules: &[CertRule]) -> Vec<ProofExpr> {
2117    let consts = cert_collect_constants(known);
2118    let mut cands: Vec<ProofExpr> = Vec::new();
2119    let mut push = |c: ProofExpr, cands: &mut Vec<ProofExpr>| {
2120        if cert_is_ground(&c) && !cands.iter().any(|e| exprs_structurally_equal(e, &c)) {
2121            cands.push(c);
2122        }
2123    };
2124    for rule in rules {
2125        let atoms: Vec<ProofExpr> = cert_atoms_of(&rule.cons)
2126            .into_iter()
2127            .chain(cert_atoms_of(&rule.ante))
2128            .collect();
2129        match &rule.binder {
2130            None => {
2131                for a in atoms {
2132                    push(a, &mut cands);
2133                }
2134            }
2135            Some(v) => {
2136                for k in &consts {
2137                    let k = ProofTerm::Constant(k.clone());
2138                    for a in &atoms {
2139                        push(instantiate_expr(a, v, &k), &mut cands);
2140                    }
2141                }
2142            }
2143        }
2144    }
2145    cands
2146}
2147
2148/// Derive ⊥ from `seed` facts: saturate, then (bounded) case-split. Every node
2149/// of the returned tree is certifiable.
2150fn cert_derive_falsum(
2151    rules: &[CertRule],
2152    seed: &[(ProofExpr, DerivationTree)],
2153    depth: usize,
2154    fresh: &mut u32,
2155) -> Option<DerivationTree> {
2156    cert_derive_falsum_in(rules, seed, depth, fresh, &mut FalsumMemo::default())
2157}
2158
2159/// The fact sets a ⊥ search has already failed to refute, each with the case-split depth it
2160/// was searched to. Splitting on `a` then `b` reaches the same facts as `b` then `a`, so
2161/// without this the atom split re-searches every ordering of the same assumptions — `(2k)^d`
2162/// saturations for `k` candidate atoms — where the distinct fact sets are few. A set that
2163/// failed at depth `d` fails at any depth up to `d` (less depth proves less), so skipping it
2164/// changes no answer, only how often the same one is recomputed.
2165#[derive(Default)]
2166struct FalsumMemo(std::collections::HashMap<Vec<String>, usize>);
2167
2168impl FalsumMemo {
2169    fn key(seed: &[(ProofExpr, DerivationTree)]) -> Vec<String> {
2170        let mut facts: Vec<String> = seed.iter().map(|(fact, _)| format!("{fact:?}")).collect();
2171        facts.sort_unstable();
2172        facts.dedup();
2173        facts
2174    }
2175}
2176
2177fn cert_derive_falsum_in(
2178    rules: &[CertRule],
2179    seed: &[(ProofExpr, DerivationTree)],
2180    depth: usize,
2181    fresh: &mut u32,
2182    memo: &mut FalsumMemo,
2183) -> Option<DerivationTree> {
2184    let key = FalsumMemo::key(seed);
2185    if memo.0.get(&key).is_some_and(|&searched| searched >= depth) {
2186        return None;
2187    }
2188    let found = cert_derive_falsum_step(rules, seed, depth, fresh, memo);
2189    if found.is_none() {
2190        let searched = memo.0.entry(key).or_insert(depth);
2191        *searched = (*searched).max(depth);
2192    }
2193    found
2194}
2195
2196fn cert_derive_falsum_step(
2197    rules: &[CertRule],
2198    seed: &[(ProofExpr, DerivationTree)],
2199    depth: usize,
2200    fresh: &mut u32,
2201    memo: &mut FalsumMemo,
2202) -> Option<DerivationTree> {
2203    // First: eliminate an existential premise by introducing a fresh witness.
2204    // `∃x.P(x)` becomes `P(c)` for a fresh constant `c`, and the whole ⊥
2205    // derivation is wrapped in `ExistentialElim` (a `Match` on `Ex`).
2206    if let Some((idx, exist_tree)) = seed.iter().enumerate().find_map(|(i, (p, t))| {
2207        if matches!(p, ProofExpr::Exists { .. }) {
2208            Some((i, t.clone()))
2209        } else {
2210            None
2211        }
2212    }) {
2213        let (variable, body) = match &seed[idx].0 {
2214            ProofExpr::Exists { variable, body } => (variable.clone(), body.as_ref().clone()),
2215            _ => unreachable!(),
2216        };
2217        let c = format!("__sk{}", *fresh);
2218        *fresh += 1;
2219        let p_c = instantiate_expr(&body, &variable, &ProofTerm::Constant(c.clone()));
2220
2221        let mut seed2: Vec<(ProofExpr, DerivationTree)> = seed
2222            .iter()
2223            .enumerate()
2224            .filter(|(j, _)| *j != idx)
2225            .map(|(_, x)| x.clone())
2226            .collect();
2227        seed2.push((
2228            p_c.clone(),
2229            DerivationTree::leaf(p_c, InferenceRule::PremiseMatch),
2230        ));
2231
2232        return cert_derive_falsum_in(rules, &seed2, depth, fresh, memo).map(|body_proof| {
2233            DerivationTree::new(
2234                ProofExpr::Atom("⊥".into()),
2235                InferenceRule::ExistentialElim { witness: c },
2236                vec![exist_tree, body_proof],
2237            )
2238        });
2239    }
2240
2241    let known = cert_saturate(rules, seed.to_vec());
2242    // Saturation may have DERIVED ⊥ outright — a rule whose consequent IS falsum
2243    // fired. `¬p` unfolds to `p → False`, so every negation in scope is such a
2244    // rule, and `p → False` together with `p` is one modus ponens away from ⊥.
2245    // Without this the proof is built by `cert_saturate` and then thrown away,
2246    // because the closers below only ever look for a `P`/`¬P` PAIR.
2247    if let Some((_, t)) = known.iter().find(|(p, _)| is_falsum(p)) {
2248        return Some(t.clone());
2249    }
2250    if let Some(t) = cert_close(&known) {
2251        return Some(t);
2252    }
2253    if let Some(t) = cert_equality_close(&known) {
2254        return Some(t);
2255    }
2256    if let Some(t) = cert_linarith_close(&known) {
2257        return Some(t);
2258    }
2259    if let Some(t) = cert_farkas(&known) {
2260        return Some(t);
2261    }
2262    // Integer discreteness: tighten strict `<` hypotheses to `a+1 ≤ b` and retry
2263    // the Farkas refutation — catches the strict contradictions rational
2264    // Fourier-Motzkin reports satisfiable (`x < y ∧ y < x+1`).
2265    if let Some(t) = crate::omega_solve::omega_close(&known) {
2266        return Some(t);
2267    }
2268    if depth == 0 {
2269        return None;
2270    }
2271    // A Horn set is refuted by propagation alone or not at all: its least model satisfies it
2272    // unless some negated atom's atom is derived — which `cert_saturate` derives and
2273    // `cert_close` closes on. A case split assumes an atom or its negation, and neither can
2274    // reach what propagation did not, so the splits are skipped rather than exhausted.
2275    if cert_is_horn(rules, seed) {
2276        return None;
2277    }
2278    // Case-split on a disjunction — the DPLL *decision*, taken only after unit
2279    // propagation (`cert_saturate`) is exhausted. From `A ∨ B` derive ⊥ in BOTH the
2280    // (+A) and (+B) branches; each branch assumes its disjunct's conjuncts, which the
2281    // `DisjunctionCases` certifier binds as local hypotheses.
2282    //
2283    // PRODUCTIVITY GATE (not a structural cap): split a disjunction only when assuming
2284    // SOME disjunct IMMEDIATELY closes — saturates to ⊥ at depth 0, with no further
2285    // splitting. That is the signature of a genuine case decision (an of-pair /
2286    // either-or clue, where one arm is already refuted by what's known). A domain
2287    // CLOSURE has no such disjunct — a row may legitimately sit in any value — so it is
2288    // only ever propagated, never split. This is what stops the search from exploding
2289    // over a grid's many closures while still deciding every real clue branch.
2290    let known_has = |x: &ProofExpr, k: &[(ProofExpr, DerivationTree)]| {
2291        k.iter().any(|(q, _)| exprs_structurally_equal(q, x))
2292    };
2293    let seed_with = |d: &ProofExpr| -> Vec<(ProofExpr, DerivationTree)> {
2294        let mut s = seed.to_vec();
2295        for conj in flatten_conjuncts(d) {
2296            if !s.iter().any(|(q, _)| exprs_structurally_equal(q, &conj)) {
2297                s.push((
2298                    conj.clone(),
2299                    DerivationTree::leaf(conj, InferenceRule::PremiseMatch),
2300                ));
2301            }
2302        }
2303        s
2304    };
2305    let established = |x: &ProofExpr, k: &[(ProofExpr, DerivationTree)]| {
2306        flatten_conjuncts(x).iter().all(|c| known_has(c, k))
2307    };
2308    // DECISION (DPLL): GUESS one undetermined disjunction and require BOTH branches to
2309    // close. Strong in-saturation propagation (disjunctive syllogism, at-most-one
2310    // exclusion, conjunction-negation) prunes each branch; a forced disjunction closes
2311    // one branch immediately. ONE decision per level keeps the tree finite-domain
2312    // bounded. By DPLL completeness, if premises + ¬goal are unsatisfiable then any
2313    // decision's branches both close; if this one's do not, the set is satisfiable and
2314    // the goal is not entailed (so don't fall through to the atom split).
2315    if let Some((p, tree_or)) = known.iter().find_map(|(p, t)| match p {
2316        ProofExpr::Or(a, b) if !(established(a, &known) || established(b, &known)) => {
2317            Some((p.clone(), t.clone()))
2318        }
2319        _ => None,
2320    }) {
2321        let ProofExpr::Or(a, b) = &p else {
2322            unreachable!()
2323        };
2324        if let (Some(pa), Some(pb)) = (
2325            cert_derive_falsum_in(rules, &seed_with(a), depth - 1, fresh, memo),
2326            cert_derive_falsum_in(rules, &seed_with(b), depth - 1, fresh, memo),
2327        ) {
2328            return Some(DerivationTree::new(
2329                ProofExpr::Atom("⊥".into()),
2330                InferenceRule::DisjunctionCases,
2331                vec![tree_or, pa, pb],
2332            ));
2333        }
2334        // A disjunction was available to branch on; by DPLL completeness its failure
2335        // to close means the set is satisfiable. Don't fall through to the atom split
2336        // (that is for disjunction-free paradoxes and would re-explore the grid).
2337        return None;
2338    }
2339    for c in cert_candidates(&known, rules) {
2340        let not_c = ProofExpr::Not(Box::new(c.clone()));
2341        // Skip pivots already settled — splitting on them cannot help.
2342        if known
2343            .iter()
2344            .any(|(p, _)| exprs_structurally_equal(p, &c) || exprs_structurally_equal(p, &not_c))
2345        {
2346            continue;
2347        }
2348        let mut seed_pos = seed.to_vec();
2349        seed_pos.push((
2350            c.clone(),
2351            DerivationTree::leaf(c.clone(), InferenceRule::PremiseMatch),
2352        ));
2353        let mut seed_neg = seed.to_vec();
2354        seed_neg.push((
2355            not_c.clone(),
2356            DerivationTree::leaf(not_c.clone(), InferenceRule::PremiseMatch),
2357        ));
2358        if let (Some(p), Some(n)) = (
2359            cert_derive_falsum_in(rules, &seed_pos, depth - 1, fresh, memo),
2360            cert_derive_falsum_in(rules, &seed_neg, depth - 1, fresh, memo),
2361        ) {
2362            return Some(DerivationTree::new(
2363                ProofExpr::Atom("⊥".into()),
2364                InferenceRule::CaseAnalysis {
2365                    case_formula: Box::new(c.clone()),
2366                },
2367                vec![p, n],
2368            ));
2369        }
2370    }
2371    None
2372}
2373
2374/// Check if two expressions are structurally equal.
2375///
2376/// This is syntactic equality after normalization - no unification needed. The match is
2377/// exhaustive on `left`, so every variant — a tensed, modal or event proposition as much as a
2378/// predicate — is equal to itself, and a new variant does not compile until it says when it is.
2379fn exprs_structurally_equal(left: &ProofExpr, right: &ProofExpr) -> bool {
2380    let exprs = |l: &[ProofExpr], r: &[ProofExpr]| {
2381        l.len() == r.len() && l.iter().zip(r).all(|(x, y)| exprs_structurally_equal(x, y))
2382    };
2383    let terms = |l: &[ProofTerm], r: &[ProofTerm]| {
2384        l.len() == r.len() && l.iter().zip(r).all(|(x, y)| terms_structurally_equal(x, y))
2385    };
2386    let eq = exprs_structurally_equal;
2387    match left {
2388        ProofExpr::Atom(a) => matches!(right, ProofExpr::Atom(b) if a == b),
2389
2390        ProofExpr::Ctor { name: n1, args: a1 } => {
2391            matches!(right, ProofExpr::Ctor { name: n2, args: a2 } if n1 == n2 && exprs(a1, a2))
2392        }
2393
2394        ProofExpr::Predicate {
2395            name: n1, args: a1, ..
2396        } => {
2397            matches!(right, ProofExpr::Predicate { name: n2, args: a2, .. } if n1 == n2 && terms(a1, a2))
2398        }
2399
2400        ProofExpr::Identity(l1, r1) => matches!(
2401            right,
2402            ProofExpr::Identity(l2, r2) if terms_structurally_equal(l1, l2) && terms_structurally_equal(r1, r2)
2403        ),
2404
2405        ProofExpr::And(l1, r1) => {
2406            matches!(right, ProofExpr::And(l2, r2) if eq(l1, l2) && eq(r1, r2))
2407        }
2408        ProofExpr::Or(l1, r1) => matches!(right, ProofExpr::Or(l2, r2) if eq(l1, l2) && eq(r1, r2)),
2409        ProofExpr::Implies(l1, r1) => {
2410            matches!(right, ProofExpr::Implies(l2, r2) if eq(l1, l2) && eq(r1, r2))
2411        }
2412        ProofExpr::Iff(l1, r1) => {
2413            matches!(right, ProofExpr::Iff(l2, r2) if eq(l1, l2) && eq(r1, r2))
2414        }
2415
2416        ProofExpr::Not(a) => matches!(right, ProofExpr::Not(b) if eq(a, b)),
2417
2418        ProofExpr::ForAll {
2419            variable: v1,
2420            body: b1,
2421        } => {
2422            matches!(right, ProofExpr::ForAll { variable: v2, body: b2 } if v1 == v2 && eq(b1, b2))
2423        }
2424        ProofExpr::Exists {
2425            variable: v1,
2426            body: b1,
2427        } => {
2428            matches!(right, ProofExpr::Exists { variable: v2, body: b2 } if v1 == v2 && eq(b1, b2))
2429        }
2430
2431        ProofExpr::Modal {
2432            domain: d1,
2433            force: f1,
2434            flavor: k1,
2435            body: b1,
2436        } => matches!(
2437            right,
2438            ProofExpr::Modal { domain: d2, force: f2, flavor: k2, body: b2 }
2439                if d1 == d2 && f1 == f2 && k1 == k2 && eq(b1, b2)
2440        ),
2441
2442        ProofExpr::Counterfactual {
2443            antecedent: a1,
2444            consequent: c1,
2445        } => matches!(
2446            right,
2447            ProofExpr::Counterfactual { antecedent: a2, consequent: c2 } if eq(a1, a2) && eq(c1, c2)
2448        ),
2449
2450        ProofExpr::Temporal {
2451            operator: o1,
2452            body: b1,
2453        } => {
2454            matches!(right, ProofExpr::Temporal { operator: o2, body: b2 } if o1 == o2 && eq(b1, b2))
2455        }
2456        ProofExpr::TemporalBinary {
2457            operator: o1,
2458            left: l1,
2459            right: r1,
2460        } => matches!(
2461            right,
2462            ProofExpr::TemporalBinary { operator: o2, left: l2, right: r2 }
2463                if o1 == o2 && eq(l1, l2) && eq(r1, r2)
2464        ),
2465
2466        ProofExpr::Lambda {
2467            variable: v1,
2468            body: b1,
2469        } => {
2470            matches!(right, ProofExpr::Lambda { variable: v2, body: b2 } if v1 == v2 && eq(b1, b2))
2471        }
2472
2473        ProofExpr::App(f1, a1) => {
2474            matches!(right, ProofExpr::App(f2, a2) if eq(f1, f2) && eq(a1, a2))
2475        }
2476
2477        ProofExpr::NeoEvent {
2478            event_var: e1,
2479            verb: v1,
2480            roles: r1,
2481        } => matches!(
2482            right,
2483            ProofExpr::NeoEvent { event_var: e2, verb: v2, roles: r2 }
2484                if e1 == e2
2485                    && v1 == v2
2486                    && r1.len() == r2.len()
2487                    && r1.iter().zip(r2).all(|((n1, t1), (n2, t2))| n1 == n2 && terms_structurally_equal(t1, t2))
2488        ),
2489
2490        ProofExpr::Match {
2491            scrutinee: s1,
2492            arms: a1,
2493        } => matches!(
2494            right,
2495            ProofExpr::Match { scrutinee: s2, arms: a2 }
2496                if eq(s1, s2)
2497                    && a1.len() == a2.len()
2498                    && a1.iter().zip(a2).all(|(x, y)| x.ctor == y.ctor && x.bindings == y.bindings && eq(&x.body, &y.body))
2499        ),
2500
2501        ProofExpr::Fixpoint { name: n1, body: b1 } => {
2502            matches!(right, ProofExpr::Fixpoint { name: n2, body: b2 } if n1 == n2 && eq(b1, b2))
2503        }
2504
2505        ProofExpr::TypedVar {
2506            name: n1,
2507            typename: t1,
2508        } => {
2509            matches!(right, ProofExpr::TypedVar { name: n2, typename: t2 } if n1 == n2 && t1 == t2)
2510        }
2511
2512        ProofExpr::Hole(h1) => matches!(right, ProofExpr::Hole(h2) if h1 == h2),
2513
2514        ProofExpr::Term(t1) => {
2515            matches!(right, ProofExpr::Term(t2) if terms_structurally_equal(t1, t2))
2516        }
2517
2518        // A construct the pipeline could not read stands for nothing in particular, so it
2519        // matches nothing, not even another spelled the same.
2520        ProofExpr::Unsupported(_) => false,
2521    }
2522}
2523
2524/// Check if two terms are structurally equal.
2525fn terms_structurally_equal(left: &ProofTerm, right: &ProofTerm) -> bool {
2526    match (left, right) {
2527        (ProofTerm::Constant(a), ProofTerm::Constant(b)) => a == b,
2528        (ProofTerm::Variable(a), ProofTerm::Variable(b)) => a == b,
2529        (ProofTerm::BoundVarRef(a), ProofTerm::BoundVarRef(b)) => a == b,
2530        (ProofTerm::Function(n1, a1), ProofTerm::Function(n2, a2)) => {
2531            n1 == n2
2532                && a1.len() == a2.len()
2533                && a1
2534                    .iter()
2535                    .zip(a2)
2536                    .all(|(x, y)| terms_structurally_equal(x, y))
2537        }
2538        (ProofTerm::Group(a1), ProofTerm::Group(a2)) => {
2539            a1.len() == a2.len()
2540                && a1
2541                    .iter()
2542                    .zip(a2)
2543                    .all(|(x, y)| terms_structurally_equal(x, y))
2544        }
2545        _ => false,
2546    }
2547}
2548
2549impl BackwardChainer {
2550    /// Create a new proof engine with empty knowledge base.
2551    pub fn new() -> Self {
2552        Self {
2553            knowledge_base: Vec::new(),
2554            max_depth: DEFAULT_MAX_DEPTH,
2555            var_counter: 0,
2556            eliminated_existentials: Vec::new(),
2557            active_goals: Vec::new(),
2558            steps: 0,
2559            step_budget: DEFAULT_STEP_BUDGET,
2560            premise_variables: PremiseVariables::default(),
2561        }
2562    }
2563
2564    /// Declare what a free variable in this knowledge base MEANS — see [`PremiseVariables`].
2565    pub fn set_premise_variables(&mut self, reading: PremiseVariables) {
2566        self.premise_variables = reading;
2567    }
2568
2569    /// Set the maximum proof search depth.
2570    pub fn set_max_depth(&mut self, depth: usize) {
2571        self.max_depth = depth;
2572    }
2573
2574    /// Set the node budget — the number of search nodes allowed for one top-level proof
2575    /// before the search aborts. See `DEFAULT_STEP_BUDGET`.
2576    pub fn set_step_budget(&mut self, budget: usize) {
2577        self.step_budget = budget;
2578    }
2579
2580    /// Charge one node against the budget; abort the search once it is spent. Called at
2581    /// EVERY recursion hub — `prove_goal` AND the `solve_subgoals`/`prove_rule_antecedent`
2582    /// mutual recursion, which does NOT pass through `prove_goal` and so would otherwise
2583    /// run unbounded behind a recursive axiom. The depth bound caps recursion depth; this
2584    /// caps total work, so the search always terminates in bounded time.
2585    fn charge_budget(&mut self) -> ProofResult<()> {
2586        self.steps += 1;
2587        if self.steps > self.step_budget {
2588            Err(ProofError::DepthExceeded)
2589        } else {
2590            Ok(())
2591        }
2592    }
2593
2594    /// Get a reference to the knowledge base (for debugging).
2595    pub fn knowledge_base(&self) -> &[ProofExpr] {
2596        &self.knowledge_base
2597    }
2598
2599    /// Add an axiom/fact/rule to the knowledge base.
2600    ///
2601    /// Event semantics are automatically abstracted to simple predicates for efficient proof search.
2602    pub fn add_axiom(&mut self, expr: ProofExpr) {
2603        // Pre-process: abstract event semantics to simple predicates — the one normalization
2604        // the certifier applies too (`verify`), so a premise is cited as it was registered.
2605        let abstracted = self.abstract_all_events(&expr);
2606        self.knowledge_base.push(abstracted);
2607    }
2608
2609    /// Attempt to prove a goal.
2610    ///
2611    /// Returns a derivation tree if successful, explaining how the proof was constructed.
2612    /// Event semantics in the goal are automatically abstracted (but De Morgan is not applied
2613    /// to preserve goal pattern matching for reductio strategies). What the problem's definite
2614    /// descriptions presuppose ("the butler" is a butler) holds for this proof alone.
2615    pub fn prove(&mut self, goal: ProofExpr) -> ProofResult<DerivationTree> {
2616        // Pre-process: unify definite descriptions across all axioms
2617        // This handles Russell's theory of definite descriptions, where multiple
2618        // "the X" references should refer to the same entity.
2619        self.unify_definite_descriptions();
2620
2621        // Pre-process: abstract event semantics in the goal
2622        // Use abstract_events_only which doesn't apply De Morgan (to preserve ¬∃ pattern)
2623        let normalized_goal = self.abstract_events_only(&goal);
2624        // The whole prove→certify pipeline runs on a large-stack thread (see
2625        // `verify::on_big_stack`), so the recursive search here needs no thread of its
2626        // own — the native-stack ceiling is already lifted for legitimately deep proofs.
2627        self.prove_presupposing(ProofGoal::new(normalized_goal))
2628    }
2629
2630    /// Prove a goal with pre-populated context assumptions.
2631    ///
2632    /// This allows proving goals like "x > 5" given assumptions like "x > 10" in the context.
2633    /// The oracle (Z3) will use these context assumptions when verifying.
2634    pub fn prove_with_goal(&mut self, goal: ProofGoal) -> ProofResult<DerivationTree> {
2635        self.unify_definite_descriptions();
2636
2637        // Normalize the target
2638        let normalized_target = self.abstract_events_only(&goal.target);
2639
2640        // Normalize each context assumption
2641        let normalized_context: Vec<ProofExpr> = goal
2642            .context
2643            .iter()
2644            .map(|expr| self.abstract_events_only(expr))
2645            .collect();
2646
2647        let normalized_goal = ProofGoal::with_context(normalized_target, normalized_context);
2648        self.prove_presupposing(normalized_goal)
2649    }
2650
2651    /// Prove `goal` with what the problem's definite descriptions presuppose — the premises',
2652    /// the goal's and its context's — taken as premises (see
2653    /// [`SymbolCollector::presuppositions`]); the certifier registers the same facts as
2654    /// hypotheses. They belong to this problem: once the search ends they are gone, so a later
2655    /// goal on the same engine presupposes only what it and the premises describe.
2656    fn prove_presupposing(&mut self, goal: ProofGoal) -> ProofResult<DerivationTree> {
2657        let mut symbols = SymbolCollector::new();
2658        for premise in self.knowledge_base.iter().chain(&goal.context) {
2659            symbols.collect(premise);
2660        }
2661        symbols.collect(&goal.target);
2662        let premises = self.knowledge_base.len();
2663        let presupposed = symbols.presuppositions(&self.knowledge_base);
2664        self.knowledge_base.extend(presupposed);
2665        let proof = self.prove_goal(goal, 0);
2666        self.knowledge_base.truncate(premises);
2667        proof
2668    }
2669
2670    /// Unify definite descriptions across axioms.
2671    ///
2672    /// When multiple axioms contain the same definite description pattern
2673    /// (e.g., "the barber" creates `∃x ((barber(x) ∧ ∀y (barber(y) → y=x)) ∧ P(x))`),
2674    /// this function:
2675    /// 1. Identifies all axioms with the same defining predicate
2676    /// 2. Extracts the properties attributed to the definite description
2677    /// 3. Replaces them with a unified Skolem constant and extracted properties
2678    fn unify_definite_descriptions(&mut self) {
2679        // Collect definite descriptions by their defining predicate
2680        let mut definite_descs: std::collections::HashMap<String, Vec<(usize, String, ProofExpr)>> =
2681            std::collections::HashMap::new();
2682
2683        for (idx, axiom) in self.knowledge_base.iter().enumerate() {
2684            if let Some((pred_name, var_name, property)) = self.extract_definite_description(axiom)
2685            {
2686                definite_descs
2687                    .entry(pred_name)
2688                    .or_default()
2689                    .push((idx, var_name, property));
2690            }
2691        }
2692
2693        // Discourse-telescoped premises reference a description's variable
2694        // FREE ("The barber shaves..." after "The barber is a man." emits
2695        // shave(x, z) with x anaphoric). Those occurrences must be bound to
2696        // the same unified constant, or the telescoped axioms are inert.
2697        let mut anaphor_bindings: Vec<(String, ProofTerm)> = Vec::new();
2698
2699        // For each group of definite descriptions with the same predicate
2700        for (pred_name, descs) in definite_descs {
2701            if descs.is_empty() {
2702                continue;
2703            }
2704
2705            // Create a unified Skolem constant for this definite description
2706            let skolem_name = format!("the_{}", pred_name);
2707            let skolem_const = ProofTerm::Constant(skolem_name.clone());
2708
2709            // Add the defining property: pred(skolem)
2710            let defining_fact = ProofExpr::Predicate {
2711                name: pred_name.clone(),
2712                args: vec![skolem_const.clone()],
2713                world: None,
2714            };
2715            self.knowledge_base.push(defining_fact);
2716
2717            // CRITICAL: Add uniqueness constraint: ∀y (pred(y) → y = skolem)
2718            // This is essential for proofs that assume ∃x pred(x) - they need to
2719            // unify their Skolem constant with our unified constant.
2720            let uniqueness = ProofExpr::ForAll {
2721                variable: "_u".to_string(),
2722                body: Box::new(ProofExpr::Implies(
2723                    Box::new(ProofExpr::Predicate {
2724                        name: pred_name.clone(),
2725                        args: vec![ProofTerm::Variable("_u".to_string())],
2726                        world: None,
2727                    }),
2728                    Box::new(ProofExpr::Identity(
2729                        ProofTerm::Variable("_u".to_string()),
2730                        skolem_const.clone(),
2731                    )),
2732                )),
2733            };
2734            self.knowledge_base.push(uniqueness);
2735
2736            // Replace axioms with the extracted properties
2737            let mut indices_to_remove: Vec<usize> = Vec::new();
2738            for (idx, var_name, property) in descs {
2739                anaphor_bindings.push((var_name.clone(), skolem_const.clone()));
2740                // Substitute the original variable with the Skolem constant
2741                let substituted = self.substitute_term_in_expr(
2742                    &property,
2743                    &ProofTerm::Variable(var_name),
2744                    &skolem_const,
2745                );
2746                // Normalize the property (especially for ∀x ¬(P ∧ Q) → ∀x (P → ¬Q))
2747                let normalized = self.normalize_for_proof(&substituted);
2748                self.knowledge_base.push(normalized);
2749                indices_to_remove.push(idx);
2750            }
2751
2752            // Remove the original existential axioms (in reverse order to preserve indices)
2753            indices_to_remove.sort_unstable_by(|a, b| b.cmp(a));
2754            for idx in indices_to_remove {
2755                self.knowledge_base.remove(idx);
2756            }
2757        }
2758
2759        // Bind free anaphoric occurrences of each description's variable
2760        // throughout the knowledge base (free occurrences only — binders that
2761        // shadow the name keep their bodies untouched).
2762        if !anaphor_bindings.is_empty() {
2763            let kb = std::mem::take(&mut self.knowledge_base);
2764            self.knowledge_base = kb
2765                .into_iter()
2766                .map(|axiom| {
2767                    let mut bound = axiom;
2768                    for (var_name, skolem) in &anaphor_bindings {
2769                        bound = self.substitute_free_var_in_expr(&bound, var_name, skolem);
2770                    }
2771                    bound
2772                })
2773                .collect();
2774        }
2775    }
2776
2777    /// Normalize an expression for proof search.
2778    ///
2779    /// Applies transformations like: ∀x ¬(P ∧ Q) → ∀x (P → ¬Q)
2780    fn normalize_for_proof(&self, expr: &ProofExpr) -> ProofExpr {
2781        match expr {
2782            ProofExpr::ForAll { variable, body } => {
2783                // Check for pattern: ∀x ¬(P ∧ Q) → ∀x (P → ¬Q)
2784                if let ProofExpr::Not(inner) = body.as_ref() {
2785                    if let ProofExpr::And(left, right) = inner.as_ref() {
2786                        return ProofExpr::ForAll {
2787                            variable: variable.clone(),
2788                            body: Box::new(ProofExpr::Implies(
2789                                Box::new(self.normalize_for_proof(left)),
2790                                Box::new(ProofExpr::Not(Box::new(self.normalize_for_proof(right)))),
2791                            )),
2792                        };
2793                    }
2794                }
2795                ProofExpr::ForAll {
2796                    variable: variable.clone(),
2797                    body: Box::new(self.normalize_for_proof(body)),
2798                }
2799            }
2800            ProofExpr::And(left, right) => ProofExpr::And(
2801                Box::new(self.normalize_for_proof(left)),
2802                Box::new(self.normalize_for_proof(right)),
2803            ),
2804            ProofExpr::Or(left, right) => ProofExpr::Or(
2805                Box::new(self.normalize_for_proof(left)),
2806                Box::new(self.normalize_for_proof(right)),
2807            ),
2808            ProofExpr::Implies(left, right) => ProofExpr::Implies(
2809                Box::new(self.normalize_for_proof(left)),
2810                Box::new(self.normalize_for_proof(right)),
2811            ),
2812            ProofExpr::Not(inner) => ProofExpr::Not(Box::new(self.normalize_for_proof(inner))),
2813            ProofExpr::Exists { variable, body } => ProofExpr::Exists {
2814                variable: variable.clone(),
2815                body: Box::new(self.normalize_for_proof(body)),
2816            },
2817            other => other.clone(),
2818        }
2819    }
2820
2821    /// Extract a definite description from an axiom.
2822    ///
2823    /// Pattern: ∃x ((P(x) ∧ ∀y (P(y) → y = x)) ∧ Q(x))
2824    /// Returns: Some((predicate_name, variable_name, Q(x)))
2825    fn extract_definite_description(
2826        &self,
2827        expr: &ProofExpr,
2828    ) -> Option<(String, String, ProofExpr)> {
2829        // Match: ∃x (body)
2830        let (var, body) = match expr {
2831            ProofExpr::Exists { variable, body } => (variable.clone(), body.as_ref()),
2832            _ => return None,
2833        };
2834
2835        // Match: (defining_part ∧ property)
2836        let (defining_part, property) = match body {
2837            ProofExpr::And(left, right) => (left.as_ref(), right.as_ref().clone()),
2838            _ => return None,
2839        };
2840
2841        // Match defining_part: (P(x) ∧ ∀y (P(y) → y = x))
2842        let (type_pred, uniqueness) = match defining_part {
2843            ProofExpr::And(left, right) => (left.as_ref(), right.as_ref()),
2844            _ => return None,
2845        };
2846
2847        // Extract predicate name from P(x)
2848        let pred_name = match type_pred {
2849            ProofExpr::Predicate { name, args, .. } if args.len() == 1 => {
2850                // Verify the arg is our variable
2851                if let ProofTerm::Variable(v) = &args[0] {
2852                    if v == &var {
2853                        name.clone()
2854                    } else {
2855                        return None;
2856                    }
2857                } else {
2858                    return None;
2859                }
2860            }
2861            _ => return None,
2862        };
2863
2864        // Verify uniqueness constraint: ∀y (P(y) → y = x)
2865        match uniqueness {
2866            ProofExpr::ForAll {
2867                variable: _,
2868                body: inner_body,
2869            } => {
2870                match inner_body.as_ref() {
2871                    ProofExpr::Implies(ante, cons) => {
2872                        // Verify antecedent is P(y)
2873                        if let ProofExpr::Predicate { name, .. } = ante.as_ref() {
2874                            if name != &pred_name {
2875                                return None;
2876                            }
2877                        } else {
2878                            return None;
2879                        }
2880                        // Verify consequent is an identity (y = x)
2881                        if !matches!(cons.as_ref(), ProofExpr::Identity(_, _)) {
2882                            return None;
2883                        }
2884                    }
2885                    _ => return None,
2886                }
2887            }
2888            _ => return None,
2889        }
2890
2891        Some((pred_name, var, property))
2892    }
2893
2894    /// Internal proof search with depth tracking.
2895    /// The canonical loop-detection key of a goal: its target with every free
2896    /// variable renamed to a positional placeholder in first-occurrence order, plus
2897    /// a fingerprint of its context. Two goals that differ only by their fresh
2898    /// existential names — the signature of a recursive-axiom regress — map to the
2899    /// same key; a goal proved under a *richer* context (an added hypothesis from
2900    /// →I or ∨-elim) gets a different key, so legitimate re-proofs are never pruned.
2901    fn loop_key(goal: &ProofGoal) -> String {
2902        use std::hash::{Hash, Hasher};
2903        let mut order: Vec<String> = Vec::new();
2904        collect_vars_ordered_expr(&goal.target, &mut order);
2905        let mut subst = Substitution::new();
2906        for (i, v) in order.iter().enumerate() {
2907            subst.insert(
2908                v.clone(),
2909                ProofTerm::Constant(format!("\u{27ea}{i}\u{27eb}")),
2910            );
2911        }
2912        let canon = apply_subst_to_expr(&goal.target, &subst);
2913        let mut hasher = std::collections::hash_map::DefaultHasher::new();
2914        goal.context.len().hash(&mut hasher);
2915        for c in &goal.context {
2916            format!("{c:?}").hash(&mut hasher);
2917        }
2918        format!("{canon:?}#{:x}", hasher.finish())
2919    }
2920
2921    fn prove_goal(&mut self, goal: ProofGoal, depth: usize) -> ProofResult<DerivationTree> {
2922        // Node budget: a guarantee of bounded *time*. Reset at the start of a top-level
2923        // proof, then count every node; once the budget is spent the search fails-fast
2924        // (reusing `DepthExceeded` — both are resource bounds) rather than running forever
2925        // on the exponential branching a recursive axiom can induce.
2926        if depth == 0 {
2927            self.steps = 0;
2928        }
2929        self.charge_budget()?;
2930
2931        // Check depth limit
2932        if depth > self.max_depth {
2933            return Err(ProofError::DepthExceeded);
2934        }
2935
2936        // Loop detection: refuse to re-enter a goal already being proved on this
2937        // branch. A recursive axiom can otherwise regress through ever-fresh
2938        // existential instances of the same goal until the native stack overflows
2939        // (the depth bound trips too late). Pruning the re-entry leaves the
2940        // productive branches — which discharge antecedents against premises or
2941        // facts, not by re-deriving the same goal — untouched.
2942        let key = Self::loop_key(&goal);
2943
2944        // Loop detection: refuse to re-enter a goal already being proved on this
2945        // branch. A recursive axiom can otherwise regress through ever-fresh
2946        // existential instances of the same goal until the native stack overflows
2947        // (the depth bound trips too late). Pruning the re-entry leaves the
2948        // productive branches — which discharge antecedents against premises or
2949        // facts, not by re-deriving the same goal — untouched.
2950        if self.active_goals.contains(&key) {
2951            return Err(ProofError::NoProofFound);
2952        }
2953        self.active_goals.push(key);
2954        let result = self.prove_goal_inner(goal, depth);
2955        self.active_goals.pop();
2956        result
2957    }
2958
2959    fn prove_goal_inner(&mut self, goal: ProofGoal, depth: usize) -> ProofResult<DerivationTree> {
2960        // Check depth limit
2961        if depth > self.max_depth {
2962            return Err(ProofError::DepthExceeded);
2963        }
2964
2965        // PRIORITY: Check for inductive goals FIRST
2966        // Goals with TypedVar (e.g., n:Nat) require structural induction,
2967        // not direct unification which would incorrectly ground the variable.
2968        if let Some((_, typename)) = self.find_typed_var(&goal.target) {
2969            // For known inductive types, require induction to succeed
2970            // Falling back to direct matching would incorrectly unify the TypedVar
2971            let is_known_inductive = matches!(typename.as_str(), "Nat" | "List");
2972
2973            if let Some(tree) = self.try_structural_induction(&goal, depth)? {
2974                return Ok(tree);
2975            }
2976
2977            // For known inductive types, if induction fails, the proof fails
2978            // (don't allow incorrect direct unification)
2979            if is_known_inductive {
2980                return Err(ProofError::NoProofFound);
2981            }
2982            // For unknown types, fall through to other strategies
2983        }
2984
2985        // Strategy 0a: Falsum goal — conflict detection.
2986        // A goal of ⊥ asks whether the premises are jointly inconsistent. Search
2987        // the KB + context for a contradiction; the resulting derivation certifies
2988        // to a kernel-checked proof of `False`.
2989        if is_falsum(&goal.target) {
2990            // Prefer the gapless finder (its derivations certify end-to-end);
2991            // fall back to the heuristic one so a contradiction is still surfaced
2992            // for inspection even when it cannot yet be certified.
2993            if let Some(tree) = self.find_certifiable_contradiction(&goal.context, depth)? {
2994                return Ok(tree);
2995            }
2996            if let Some(tree) = self.find_contradiction(&goal.context, depth)? {
2997                return Ok(tree);
2998            }
2999            return Err(ProofError::NoProofFound);
3000        }
3001
3002        // Strategy 0: Reflexivity by computation
3003        // Try to prove a = b by normalizing both sides
3004        if let Some(tree) = self.try_reflexivity(&goal)? {
3005            return Ok(tree);
3006        }
3007
3008        // Strategy 0b: Arithmetic decision over Int (proof-producing oracle).
3009        // Discharges Int equalities (e.g. x+y = y+x) the certifier turns into a
3010        // kernel-checked proof via the ring axioms.
3011        if let Some(tree) = self.try_arithmetic(&goal)? {
3012            return Ok(tree);
3013        }
3014
3015        // Strategy 0c: Linear arithmetic over `Int` — chain `≤` facts by transitivity,
3016        // add inequalities, and decide ground facts by computation, certified by the
3017        // `le_trans`/`le_refl`/`le_add_mono` axioms.
3018        if let Some(tree) = self.try_linarith(&goal, depth)? {
3019            return Ok(tree);
3020        }
3021
3022        // Strategy 1: Direct fact matching
3023        if let Some(tree) = self.try_match_fact(&goal)? {
3024            return Ok(tree);
3025        }
3026
3027        // Strategy 1b: a NEGATION goal in a finite-domain (grid) setting is proved
3028        // fastest and most completely by the certified contradiction finder — unit
3029        // propagation + bounded case analysis. Run it HERE, before the disjunction-
3030        // elimination strategy (5b), which can blow up on a clue's nested either/or.
3031        // Assume the negated proposition and drive it to ⊥. It only short-circuits
3032        // when it actually closes, so a miss leaves the later strategies untouched.
3033        // A DIRECT ModusTollens (a rule whose consequent is refuted) is more specific,
3034        // so prefer it — the grid contradiction finder only fires when it does not apply.
3035        if matches!(goal.target, ProofExpr::Not(_)) {
3036            if let Some(tree) = self.try_modus_tollens(&goal, depth)? {
3037                return Ok(tree);
3038            }
3039            // A double-negation goal `¬¬X` is introduced by `DoubleNegation` (prove X);
3040            // don't let the grid contradiction finder preempt that more specific rule.
3041            let is_double_neg = matches!(&goal.target, ProofExpr::Not(inner) if matches!(inner.as_ref(), ProofExpr::Not(_)));
3042            if !is_double_neg {
3043                if let Some(tree) = self.try_reductio_ad_absurdum(&goal, depth)? {
3044                    return Ok(tree);
3045                }
3046            }
3047        }
3048
3049        // Strategy 2: Introduction rules (structural decomposition)
3050        if let Some(tree) = self.try_intro_rules(&goal, depth)? {
3051            return Ok(tree);
3052        }
3053
3054        // Strategy 3: Backward chaining on implications
3055        if let Some(tree) = self.try_backward_chain(&goal, depth)? {
3056            return Ok(tree);
3057        }
3058
3059        // Strategy 3b: Modus Tollens (from P → Q and ¬Q, derive ¬P)
3060        if let Some(tree) = self.try_modus_tollens(&goal, depth)? {
3061            return Ok(tree);
3062        }
3063
3064        // Strategy 4: Universal instantiation
3065        if let Some(tree) = self.try_universal_inst(&goal, depth)? {
3066            return Ok(tree);
3067        }
3068
3069        // Strategy 5: Existential introduction
3070        if let Some(tree) = self.try_existential_intro(&goal, depth)? {
3071            return Ok(tree);
3072        }
3073
3074        // Strategy 5b: Disjunction elimination (disjunctive syllogism)
3075        if let Some(tree) = self.try_disjunction_elimination(&goal, depth)? {
3076            return Ok(tree);
3077        }
3078
3079        // Strategy 5c: Proof by contradiction (reductio ad absurdum)
3080        // For negation goals, assume the positive and derive contradiction
3081        if let Some(tree) = self.try_reductio_ad_absurdum(&goal, depth)? {
3082            return Ok(tree);
3083        }
3084
3085        // Strategy 5d: Existential elimination from premises
3086        // Extract witnesses from ∃x P(x) premises and add to context
3087        if let Some(tree) = self.try_existential_elimination(&goal, depth)? {
3088            return Ok(tree);
3089        }
3090
3091        // Strategy 6: Equality rewriting (Leibniz's Law)
3092        if let Some(tree) = self.try_equality_rewrite(&goal, depth)? {
3093            return Ok(tree);
3094        }
3095
3096        // Strategy 7: Ex falso quodlibet — a last resort, only at the top level.
3097        // If the premises are jointly contradictory, any goal follows. The
3098        // contradiction is a property of the KB, so one check at depth 0 suffices;
3099        // a consistent KB returns `None` and the goal still fails honestly.
3100        if depth == 0 && !is_falsum(&goal.target) {
3101            if let Some(false_tree) = self.find_certifiable_contradiction(&goal.context, depth)? {
3102                return Ok(DerivationTree::new(
3103                    goal.target.clone(),
3104                    InferenceRule::ExFalso,
3105                    vec![false_tree],
3106                ));
3107            }
3108        }
3109
3110        // Strategy 8: Classical reductio (proof by contradiction) — last resort at the
3111        // top level for a POSITIVE goal G: assume ¬G and search for ⊥; if found, G
3112        // follows via the `dne` axiom. Classical, explicit, kernel-checked.
3113        if depth == 0 && !is_falsum(&goal.target) && !matches!(goal.target, ProofExpr::Not(_)) {
3114            let mut ext = goal.context.clone();
3115            ext.push(ProofExpr::Not(Box::new(goal.target.clone())));
3116            if let Some(false_tree) = self.find_certifiable_contradiction(&ext, depth)? {
3117                return Ok(DerivationTree::new(
3118                    goal.target.clone(),
3119                    InferenceRule::ClassicalReductio,
3120                    vec![false_tree],
3121                ));
3122            }
3123        }
3124
3125        // Strategy 9: Oracle fallback (Z3) — the ABSOLUTE last resort. It is a COMPLETE solver over
3126        // the whole goal + knowledge base, so (a) it runs only at the TOP LEVEL (`depth == 0`):
3127        // invoking it per recursive subgoal is an O(nodes) Z3-call blowup that hangs a deep
3128        // backward-chaining search, and is redundant since a decomposed subgoal is oracle-provable
3129        // only if the goal it came from is; and (b) it runs only AFTER every certifiable kernel
3130        // strategy (incl. ex-falso / reductio above), so a kernel-checkable proof is never lost to a
3131        // non-certifiable Z3 "Verified by Z3" result.
3132        #[cfg(feature = "verification")]
3133        if depth == 0 {
3134            if let Some(tree) = self.try_oracle_fallback(&goal)? {
3135                return Ok(tree);
3136            }
3137        }
3138
3139        // No proof found
3140        Err(ProofError::NoProofFound)
3141    }
3142
3143    // =========================================================================
3144    // STRATEGY 0: REFLEXIVITY BY COMPUTATION
3145    // =========================================================================
3146
3147    /// Try to prove an identity a = b by normalizing both sides.
3148    ///
3149    /// If both sides reduce to structurally identical expressions,
3150    /// the proof is by reflexivity (a = a).
3151    fn try_reflexivity(&self, goal: &ProofGoal) -> ProofResult<Option<DerivationTree>> {
3152        if let ProofExpr::Identity(left_term, right_term) = &goal.target {
3153            // Convert terms to expressions for reduction
3154            let left_expr = term_to_expr(left_term);
3155            let right_expr = term_to_expr(right_term);
3156
3157            // Normalize both sides using full reduction (beta + iota + fix)
3158            let left_normal = beta_reduce(&left_expr);
3159            let right_normal = beta_reduce(&right_expr);
3160
3161            // Check structural equality after normalization
3162            if exprs_structurally_equal(&left_normal, &right_normal) {
3163                return Ok(Some(DerivationTree::leaf(
3164                    goal.target.clone(),
3165                    InferenceRule::Reflexivity,
3166                )));
3167            }
3168        }
3169        Ok(None)
3170    }
3171
3172    /// Strategy 0b: decide an `Int` equality with the proof-producing oracle.
3173    ///
3174    /// The oracle ([`crate::arith::prove_int_eq`]) searches for a real kernel
3175    /// proof (computation + the ring axioms). If it finds one, we emit an
3176    /// `ArithDecision` leaf; the certifier re-runs the oracle to produce the
3177    /// kernel term, which `infer_type` re-checks — so the oracle is never
3178    /// trusted. Non-arithmetic identities are left to other strategies.
3179    fn try_arithmetic(&self, goal: &ProofGoal) -> ProofResult<Option<DerivationTree>> {
3180        if let ProofExpr::Identity(left_term, right_term) = &goal.target {
3181            // Only engage for genuine Int-arithmetic identities (an arithmetic
3182            // operator at the head of a side). This keeps the strategy from
3183            // hijacking unrelated reflexive identities (e.g. f(a)=f(a) over
3184            // non-Int terms), which it would otherwise close with a type-wrong
3185            // `refl Int …` that fails certification.
3186            // Accept both the kernel-vocabulary heads (`add`/`mul`/…) and the frontend's canonical
3187            // capitalized `Add`/`Sub`/`Mul`/`Div` (what `term_to_proof_term` emits, lowered to the
3188            // kernel by `proof_term_to_kernel_term`) — so an arithmetic identity written in a `.lg`
3189            // theorem reaches the oracle, not just one built directly from the kernel names.
3190            let is_arith = |t: &ProofTerm| {
3191                matches!(
3192                    t,
3193                    ProofTerm::Function(n, _)
3194                        if matches!(
3195                            n.as_str(),
3196                            "add" | "sub" | "mul" | "div" | "mod" | "Add" | "Sub" | "Mul" | "Div"
3197                        )
3198                )
3199            };
3200            if !is_arith(left_term) && !is_arith(right_term) {
3201                return Ok(None);
3202            }
3203            let (kl, kr) = match (
3204                crate::certifier::proof_term_to_kernel_term(left_term),
3205                crate::certifier::proof_term_to_kernel_term(right_term),
3206            ) {
3207                (Ok(a), Ok(b)) => (a, b),
3208                _ => return Ok(None),
3209            };
3210
3211            if crate::arith::prove_int_eq(StandardLibrary::context(), &kl, &kr).is_some() {
3212                return Ok(Some(DerivationTree::leaf(
3213                    goal.target.clone(),
3214                    InferenceRule::ArithDecision,
3215                )));
3216            }
3217        }
3218        Ok(None)
3219    }
3220
3221    // =========================================================================
3222    // STRATEGY 1: DIRECT FACT MATCHING
3223    // =========================================================================
3224
3225    /// Try to match the goal directly against a fact in the knowledge base.
3226    fn try_match_fact(&self, goal: &ProofGoal) -> ProofResult<Option<DerivationTree>> {
3227        // Also check local context
3228        for fact in goal.context.iter().chain(self.knowledge_base.iter()) {
3229            if let Ok(subst) = unify_exprs(&goal.target, fact) {
3230                // A premise is used AS STATED. Its free variables are LOCALS — Lean's
3231                // `variable (x : Int)`, and what `close_over_context_locals` λ-abstracts at
3232                // the trust door — not schematic placeholders, so INSTANTIATING one is not a
3233                // step this layer has a rule for (a schema must be written `∀x. …`, which
3234                // `UniversalInst` handles and which the certifier can check).
3235                //
3236                // Unification is symmetric, so a match could bind either side. Binding the
3237                // GOAL's own metavariables is the search's business and stays allowed; binding
3238                // one of the FACT's variables built a `PremiseMatch` leaf naming a proposition
3239                // nobody registered, and `certify_hypothesis` — which resolves a hypothesis by
3240                // α-equivalence of its TYPE — could never find it. `auto` reported a proof and
3241                // the trust door refused it, which is the one answer that is wrong either way.
3242                if fact_is_instantiated(fact, &subst) {
3243                    continue;
3244                }
3245                return Ok(Some(
3246                    DerivationTree::leaf(goal.target.clone(), InferenceRule::PremiseMatch)
3247                        .with_substitution(subst),
3248                ));
3249            }
3250        }
3251        // Forward ∧-elimination: a conjunct of an assumed `A ∧ B` is itself a usable
3252        // fact. Project it out with a `ConjunctionElim` chain — this is what lets the
3253        // existential middle of a cut pin against a conjunctive hypothesis instead of
3254        // fanning out into an unbounded search (the difference between milliseconds and
3255        // a blow-up for `(Cong ∧ Cong) → Cong`-shaped theorems).
3256        for fact in goal.context.iter().chain(self.knowledge_base.iter()) {
3257            if matches!(fact, ProofExpr::And(_, _)) {
3258                let leaf = DerivationTree::leaf(fact.clone(), InferenceRule::PremiseMatch);
3259                if let Some((tree, subst)) = extract_conjunct(&leaf, &goal.target) {
3260                    return Ok(Some(tree.with_substitution(subst)));
3261                }
3262            }
3263        }
3264        Ok(None)
3265    }
3266
3267    // =========================================================================
3268    // STRATEGY 2: INTRODUCTION RULES
3269    // =========================================================================
3270
3271    /// Try introduction rules based on the goal's structure.
3272    fn try_intro_rules(
3273        &mut self,
3274        goal: &ProofGoal,
3275        depth: usize,
3276    ) -> ProofResult<Option<DerivationTree>> {
3277        match &goal.target {
3278            // Conjunction Introduction: To prove A ∧ B, prove A and prove B
3279            ProofExpr::And(left, right) => {
3280                let left_goal = ProofGoal::with_context((**left).clone(), goal.context.clone());
3281                let right_goal = ProofGoal::with_context((**right).clone(), goal.context.clone());
3282
3283                // Try to prove both sides
3284                if let (Ok(left_proof), Ok(right_proof)) = (
3285                    self.prove_goal(left_goal, depth + 1),
3286                    self.prove_goal(right_goal, depth + 1),
3287                ) {
3288                    return Ok(Some(DerivationTree::new(
3289                        goal.target.clone(),
3290                        InferenceRule::ConjunctionIntro,
3291                        vec![left_proof, right_proof],
3292                    )));
3293                }
3294            }
3295
3296            // Disjunction Introduction: To prove A ∨ B, prove A or prove B
3297            ProofExpr::Or(left, right) => {
3298                // Try left side first
3299                let left_goal = ProofGoal::with_context((**left).clone(), goal.context.clone());
3300                if let Ok(left_proof) = self.prove_goal(left_goal, depth + 1) {
3301                    return Ok(Some(DerivationTree::new(
3302                        goal.target.clone(),
3303                        InferenceRule::DisjunctionIntro,
3304                        vec![left_proof],
3305                    )));
3306                }
3307
3308                // Try right side
3309                let right_goal = ProofGoal::with_context((**right).clone(), goal.context.clone());
3310                if let Ok(right_proof) = self.prove_goal(right_goal, depth + 1) {
3311                    return Ok(Some(DerivationTree::new(
3312                        goal.target.clone(),
3313                        InferenceRule::DisjunctionIntro,
3314                        vec![right_proof],
3315                    )));
3316                }
3317            }
3318
3319            // Biconditional Introduction (↔I): to prove P ↔ Q, prove both directions
3320            // P → Q and Q → P (each by →I), then combine. Certified as `conj` over the
3321            // two implications (Iff ≡ And (P→Q) (Q→P)).
3322            ProofExpr::Iff(left, right) => {
3323                let pq = ProofExpr::Implies(left.clone(), right.clone());
3324                let qp = ProofExpr::Implies(right.clone(), left.clone());
3325                let pq_goal = ProofGoal::with_context(pq, goal.context.clone());
3326                let qp_goal = ProofGoal::with_context(qp, goal.context.clone());
3327                if let (Ok(pq_proof), Ok(qp_proof)) = (
3328                    self.prove_goal(pq_goal, depth + 1),
3329                    self.prove_goal(qp_goal, depth + 1),
3330                ) {
3331                    return Ok(Some(DerivationTree::new(
3332                        goal.target.clone(),
3333                        InferenceRule::BicondIntro,
3334                        vec![pq_proof, qp_proof],
3335                    )));
3336                }
3337            }
3338
3339            // Universal Introduction (∀I): to prove ∀x.φ(x), prove φ(c) for a FRESH
3340            // EIGENCONSTANT c — an opaque term the search can neither unify nor
3341            // instantiate — then generalize c back to x. Proving the body with x left
3342            // as a `Variable` is unsound for search: a strategy could bind x by
3343            // unification (e.g. match goal `Cong(c,d,a,b)` against hypothesis
3344            // `Cong(a,b,c,d)` by setting a:=c,…), producing a tree the kernel rejects
3345            // but the engine has already committed to. The eigenconstant makes such a
3346            // match fail, forcing the genuinely-arbitrary proof; the certifier then
3347            // abstracts `λ(x:Entity). …` over the generalized body.
3348            ProofExpr::ForAll { variable, body } => {
3349                let eigen = self.fresh_eigenconstant();
3350                let eigen_term = ProofTerm::Constant(eigen.clone());
3351                let body_expr = instantiate_expr(body, variable, &eigen_term);
3352                let body_ctx: Vec<ProofExpr> = goal
3353                    .context
3354                    .iter()
3355                    .map(|c| instantiate_expr(c, variable, &eigen_term))
3356                    .collect();
3357                let body_goal = ProofGoal::with_context(body_expr, body_ctx);
3358                if let Ok(body_proof) = self.prove_goal(body_goal, depth + 1) {
3359                    let generalized = rewrite_tree_const_to_var(&body_proof, &eigen, variable);
3360                    return Ok(Some(DerivationTree::new(
3361                        goal.target.clone(),
3362                        InferenceRule::UniversalIntro {
3363                            variable: variable.clone(),
3364                            var_type: "Entity".to_string(),
3365                        },
3366                        vec![generalized],
3367                    )));
3368                }
3369            }
3370
3371            // Implication Introduction (→I): to prove P → Q, assume P (discharge it
3372            // into the local context) and prove Q. The certifier binds P as a local
3373            // hypothesis and wraps the Q-proof in `λ(hp:P). …`.
3374            ProofExpr::Implies(ant, con) => {
3375                let mut ext = goal.context.clone();
3376                ext.push((**ant).clone());
3377                let con_goal = ProofGoal::with_context((**con).clone(), ext);
3378                if let Ok(con_proof) = self.prove_goal(con_goal, depth + 1) {
3379                    return Ok(Some(DerivationTree::new(
3380                        goal.target.clone(),
3381                        InferenceRule::ImpliesIntro,
3382                        vec![con_proof],
3383                    )));
3384                }
3385            }
3386
3387            // Double Negation: To prove ¬¬P, prove P
3388            ProofExpr::Not(inner) => {
3389                if let ProofExpr::Not(core) = &**inner {
3390                    let core_goal = ProofGoal::with_context((**core).clone(), goal.context.clone());
3391                    if let Ok(core_proof) = self.prove_goal(core_goal, depth + 1) {
3392                        return Ok(Some(DerivationTree::new(
3393                            goal.target.clone(),
3394                            InferenceRule::DoubleNegation,
3395                            vec![core_proof],
3396                        )));
3397                    }
3398                }
3399            }
3400
3401            _ => {}
3402        }
3403
3404        Ok(None)
3405    }
3406
3407    // =========================================================================
3408    // STRATEGY 3: BACKWARD CHAINING ON IMPLICATIONS
3409    // =========================================================================
3410
3411    /// Try backward chaining: find P → Goal in KB, then prove P.
3412    fn try_backward_chain(
3413        &mut self,
3414        goal: &ProofGoal,
3415        depth: usize,
3416    ) -> ProofResult<Option<DerivationTree>> {
3417        // Collect every KB implication whose consequent unifies with the goal, and SCORE
3418        // each by how many of its (instantiated) antecedent conjuncts can be discharged
3419        // DIRECTLY against a known fact or hypothesis. Trying the most-pinnable rule first
3420        // finds a direct proof — an axiom whose whole antecedent is already among the
3421        // premises (e.g. Tarski's five-segment, with all seven antecedents as givens) —
3422        // before a recursive axiom (inner transitivity) sends the search into exponential
3423        // re-derivation. This is the relevance signal that lets the prover pick the rule it
3424        // actually needs; it only REORDERS candidates, so nothing that was provable becomes
3425        // unprovable.
3426        struct Candidate {
3427            impl_expr: ProofExpr,
3428            antecedent: ProofExpr,
3429            /// The whole consequent, instantiated — what modus ponens concludes; the goal is
3430            /// this, or one of its conjuncts, projected out after.
3431            conclusion: ProofExpr,
3432            subst: Substitution,
3433            score: usize,
3434        }
3435        let kb_implications: Vec<ProofExpr> = self
3436            .knowledge_base
3437            .iter()
3438            .filter(|e| matches!(e, ProofExpr::Implies(_, _)))
3439            .cloned()
3440            .collect();
3441        let mut candidates: Vec<Candidate> = Vec::new();
3442        for impl_expr in kb_implications {
3443            let renamed = self.rename_variables(&impl_expr);
3444            if let ProofExpr::Implies(ant, con) = renamed {
3445                if let Some(subst) = unify_with_conclusion(&goal.target, &con) {
3446                    let antecedent = apply_subst_to_expr(&ant, &subst);
3447                    let conclusion = apply_subst_to_expr(&con, &subst);
3448                    let score = self.antecedent_pinnability(&antecedent, &goal.context);
3449                    candidates.push(Candidate {
3450                        impl_expr,
3451                        antecedent,
3452                        conclusion,
3453                        subst,
3454                        score,
3455                    });
3456                }
3457            }
3458        }
3459        // Most-pinnable antecedent first; stable, so equal scores keep KB order.
3460        candidates.sort_by(|a, b| b.score.cmp(&a.score));
3461
3462        for cand in candidates {
3463            let ant_goal = ProofGoal::with_context(cand.antecedent, goal.context.clone());
3464            if let Ok(ant_proof) = self.prove_goal(ant_goal, depth + 1) {
3465                let impl_leaf =
3466                    DerivationTree::leaf(cand.impl_expr.clone(), InferenceRule::PremiseMatch);
3467                let concluded = DerivationTree::new(
3468                    cand.conclusion,
3469                    InferenceRule::ModusPonens,
3470                    vec![impl_leaf, ant_proof],
3471                );
3472                if let Some(projected) = project_goal(concluded, &goal.target) {
3473                    return Ok(Some(projected.with_substitution(cand.subst)));
3474                }
3475            }
3476        }
3477
3478        Ok(None)
3479    }
3480
3481    /// How many of `ant`'s conjuncts can be discharged immediately against a known fact or
3482    /// a conjunct of a conjunctive hypothesis — the relevance score for
3483    /// [`Self::try_backward_chain`]. A rule whose antecedent is entirely pinnable needs no
3484    /// recursive search at all, so it is the one to try first.
3485    fn antecedent_pinnability(&self, ant: &ProofExpr, context: &[ProofExpr]) -> usize {
3486        flatten_conjuncts(ant)
3487            .iter()
3488            .filter(|c| self.subgoal_pinnable(c, context))
3489            .count()
3490    }
3491
3492    /// Relevance of a (possibly `∀`-wrapped) rule to `goal` — how worthwhile it is to try
3493    /// FIRST when backward-chaining. A universal FACT whose matrix unifies with the goal
3494    /// is the best (direct instantiation, no antecedent, terminating). Next, an implication
3495    /// whose consequent unifies with the goal, ranked by how many of its antecedent
3496    /// conjuncts are already discharge-able against hypotheses — so the axiom that needs no
3497    /// recursive search outranks a recursive one. A non-matching rule scores 0. This is a
3498    /// pure ORDERING signal: every rule is still tried, just in a smarter order, so the
3499    /// direct proof is reached before a recursive axiom explodes the search.
3500    fn rule_relevance(&mut self, rule: &ProofExpr, goal: &ProofGoal) -> usize {
3501        let renamed = self.rename_variables(rule);
3502        let mut matrix: &ProofExpr = &renamed;
3503        while let ProofExpr::ForAll { body, .. } = matrix {
3504            matrix = body.as_ref();
3505        }
3506        match matrix {
3507            ProofExpr::Implies(ant, con) => {
3508                if let Ok(subst) = unify_exprs(&goal.target, con) {
3509                    let ant_inst = apply_subst_to_expr(ant, &subst);
3510                    // +2 so any matching implication outranks a non-match; pinnable
3511                    // antecedent conjuncts add on top (a fully-pinned antecedent wins).
3512                    2 + self.antecedent_pinnability(&ant_inst, &goal.context)
3513                } else {
3514                    0
3515                }
3516            }
3517            other => {
3518                // A universal fact that unifies: direct, terminating — rank above any
3519                // implication so it discharges before a (possibly recursive) rule chain.
3520                if unify_exprs(&goal.target, other).is_ok() {
3521                    1000
3522                } else {
3523                    0
3524                }
3525            }
3526        }
3527    }
3528
3529    // =========================================================================
3530    // STRATEGY 3b: MODUS TOLLENS
3531    // =========================================================================
3532
3533    /// Try Modus Tollens: from P → Q and ¬Q, derive ¬P.
3534    ///
3535    /// If the goal is ¬P:
3536    /// 1. Look for implications P → Q in the KB
3537    /// 2. Check if ¬Q is known (in KB or context) OR can be proved
3538    /// 3. If so, derive ¬P by Modus Tollens
3539    fn try_modus_tollens(
3540        &mut self,
3541        goal: &ProofGoal,
3542        depth: usize,
3543    ) -> ProofResult<Option<DerivationTree>> {
3544        // Modus Tollens only applies when goal is a negation: ¬P
3545        let inner_goal = match &goal.target {
3546            ProofExpr::Not(inner) => (**inner).clone(),
3547            _ => return Ok(None),
3548        };
3549
3550        // Collect all implications from KB, including those inside ForAll
3551        let implications: Vec<ProofExpr> = self
3552            .knowledge_base
3553            .iter()
3554            .chain(goal.context.iter())
3555            .flat_map(|expr| {
3556                match expr {
3557                    ProofExpr::Implies(_, _) => vec![expr.clone()],
3558                    ProofExpr::ForAll { body, .. } => {
3559                        // Extract implications from inside universal quantifiers
3560                        if let ProofExpr::Implies(_, _) = body.as_ref() {
3561                            vec![*body.clone()]
3562                        } else {
3563                            vec![]
3564                        }
3565                    }
3566                    _ => vec![],
3567                }
3568            })
3569            .collect();
3570
3571        // Collect all negations from KB and context (for direct matching)
3572        let negations: Vec<ProofExpr> = self
3573            .knowledge_base
3574            .iter()
3575            .chain(goal.context.iter())
3576            .filter_map(|expr| {
3577                if let ProofExpr::Not(inner) = expr {
3578                    Some((**inner).clone())
3579                } else {
3580                    None
3581                }
3582            })
3583            .collect();
3584
3585        // For each implication P → Q
3586        for impl_expr in &implications {
3587            if let ProofExpr::Implies(antecedent, consequent) = impl_expr {
3588                // Check if the antecedent P matches our inner goal (we want to prove ¬P)
3589                if let Ok(subst) = unify_exprs(&inner_goal, antecedent) {
3590                    // Apply substitution to the consequent Q
3591                    let q = apply_subst_to_expr(consequent, &subst);
3592
3593                    // First, check if ¬Q is directly in our known facts
3594                    for negated in &negations {
3595                        if exprs_structurally_equal(negated, &q) {
3596                            // We have P → Q and ¬Q, so we can derive ¬P
3597                            let impl_leaf = DerivationTree::leaf(
3598                                impl_expr.clone(),
3599                                InferenceRule::PremiseMatch,
3600                            );
3601                            let neg_q_leaf = DerivationTree::leaf(
3602                                ProofExpr::Not(Box::new(q.clone())),
3603                                InferenceRule::PremiseMatch,
3604                            );
3605
3606                            return Ok(Some(
3607                                DerivationTree::new(
3608                                    goal.target.clone(),
3609                                    InferenceRule::ModusTollens,
3610                                    vec![impl_leaf, neg_q_leaf],
3611                                )
3612                                .with_substitution(subst),
3613                            ));
3614                        }
3615                    }
3616
3617                    // Second, try to prove ¬Q recursively (for chaining)
3618                    let neg_q_goal = ProofGoal::with_context(
3619                        ProofExpr::Not(Box::new(q.clone())),
3620                        goal.context.clone(),
3621                    );
3622
3623                    if let Ok(neg_q_proof) = self.prove_goal(neg_q_goal, depth + 1) {
3624                        // We proved ¬Q, so we can derive ¬P
3625                        let impl_leaf =
3626                            DerivationTree::leaf(impl_expr.clone(), InferenceRule::PremiseMatch);
3627
3628                        return Ok(Some(
3629                            DerivationTree::new(
3630                                goal.target.clone(),
3631                                InferenceRule::ModusTollens,
3632                                vec![impl_leaf, neg_q_proof],
3633                            )
3634                            .with_substitution(subst),
3635                        ));
3636                    }
3637                }
3638            }
3639        }
3640
3641        Ok(None)
3642    }
3643
3644    // =========================================================================
3645    // STRATEGY 4: UNIVERSAL INSTANTIATION
3646    // =========================================================================
3647
3648    /// Try universal instantiation: if KB has ∀x.P(x), try to prove P(t) for some term t.
3649    fn try_universal_inst(
3650        &mut self,
3651        goal: &ProofGoal,
3652        depth: usize,
3653    ) -> ProofResult<Option<DerivationTree>> {
3654        // Look for universal quantifiers in KB, then ORDER them by relevance to the goal:
3655        // the rule whose antecedent is most directly dischargeable (or a universal fact,
3656        // which terminates) is tried first, so a direct proof is found before a recursive
3657        // axiom drives the search into exponential re-derivation. Pure reordering — every
3658        // rule is still tried — so nothing provable becomes unprovable.
3659        let universal_exprs: Vec<ProofExpr> = self
3660            .knowledge_base
3661            .iter()
3662            .filter(|expr| matches!(expr, ProofExpr::ForAll { .. }))
3663            .cloned()
3664            .collect();
3665        let mut scored: Vec<(usize, ProofExpr)> = universal_exprs
3666            .into_iter()
3667            .map(|u| (self.rule_relevance(&u, goal), u))
3668            .collect();
3669        scored.sort_by(|a, b| b.0.cmp(&a.0));
3670        let universals: Vec<ProofExpr> = scored.into_iter().map(|(_, u)| u).collect();
3671
3672        for forall_expr in universals {
3673            // Freshen every variable so instantiation cannot capture variables in
3674            // the goal, then peel *all* leading universal quantifiers. A rule may
3675            // bind several variables (`∀x∀y∀z …`); only peeling one leaves the
3676            // matrix still quantified and unusable — that was the transitivity gap.
3677            let renamed = self.rename_variables(&forall_expr);
3678            let mut body: &ProofExpr = &renamed;
3679            let mut bound_vars: Vec<String> = Vec::new();
3680            while let ProofExpr::ForAll {
3681                variable,
3682                body: inner,
3683            } = body
3684            {
3685                bound_vars.push(variable.clone());
3686                body = inner.as_ref();
3687            }
3688            if bound_vars.is_empty() {
3689                continue;
3690            }
3691
3692            // Case A: the matrix unifies directly with the goal — a universal fact
3693            // (e.g. ∀x∀y R(x,y) discharging R(a,b)), including one whose matrix is
3694            // itself existential (∀b c d. ∃x. Cong(b,x,c,d) discharging ∃x. Cong(P,x,Q,R)).
3695            if let Ok(subst) = unify_exprs(&goal.target, body) {
3696                // Build NESTED UniversalInst nodes so a multi-binder fact applies to ALL
3697                // witnesses, not just the first. A variable vacuous in the matrix is
3698                // defaulted to an entity; only a genuinely-underdetermined one aborts.
3699                if let Some(witnesses) = instantiation_witnesses(&bound_vars, &subst, body) {
3700                    let mut inst_node =
3701                        DerivationTree::leaf(forall_expr.clone(), InferenceRule::PremiseMatch);
3702                    for witness in &witnesses {
3703                        inst_node = DerivationTree::new(
3704                            goal.target.clone(),
3705                            InferenceRule::UniversalInst(format!("{}", witness)),
3706                            vec![inst_node],
3707                        );
3708                    }
3709                    return Ok(Some(inst_node.with_substitution(subst)));
3710                }
3711            }
3712
3713            // Case B: the matrix is an implication ∀…(P → Q). Unify Q with the
3714            // goal, then prove P. Any bound variable that does NOT appear in Q (a
3715            // "middle term", e.g. the `y` in transitivity) is left open by that
3716            // unification and is resolved while proving P against the KB.
3717            if let ProofExpr::Implies(ant, con) = body {
3718                if let Some(subst) = unify_with_conclusion(&goal.target, con) {
3719                    let ant_inst = apply_subst_to_expr(&**ant, &subst);
3720                    if let Ok((ant_proof, final_subst)) =
3721                        self.prove_rule_antecedent(&ant_inst, &subst, &goal.context, depth + 1)
3722                    {
3723                        // Each bound variable must be pinned by the conclusion
3724                        // unification or the antecedent solve — or be vacuous in the
3725                        // matrix (then defaulted). A genuinely-underdetermined variable
3726                        // aborts this rule rather than leak a metavariable into the cert.
3727                        let witnesses =
3728                            match instantiation_witnesses(&bound_vars, &final_subst, body) {
3729                                Some(w) => w,
3730                                None => continue,
3731                            };
3732                        // Build NESTED UniversalInst nodes — one per bound variable, in
3733                        // binder order — so the certifier applies the universal proof to
3734                        // ALL witnesses (`((forall x) y) z`), fully instantiating
3735                        // ∀x∀y∀z. A single node with one witness left the inner
3736                        // quantifiers unfilled (the "expected Entity, found And" bug).
3737                        let instantiated = apply_subst_to_expr(body, &final_subst);
3738                        let mut inst_node =
3739                            DerivationTree::leaf(forall_expr.clone(), InferenceRule::PremiseMatch);
3740                        for witness in &witnesses {
3741                            inst_node = DerivationTree::new(
3742                                instantiated.clone(),
3743                                InferenceRule::UniversalInst(format!("{}", witness)),
3744                                vec![inst_node],
3745                            );
3746                        }
3747                        let concluded = DerivationTree::new(
3748                            apply_subst_to_expr(con, &final_subst),
3749                            InferenceRule::ModusPonens,
3750                            vec![inst_node, ant_proof],
3751                        );
3752                        if let Some(projected) = project_goal(concluded, &goal.target) {
3753                            return Ok(Some(projected.with_substitution(final_subst)));
3754                        }
3755                    }
3756                }
3757            }
3758        }
3759
3760        Ok(None)
3761    }
3762
3763    /// Prove the antecedent of an instantiated rule, returning both its proof and
3764    /// the bindings it forced. The antecedent may be a conjunction whose conjuncts
3765    /// share a still-open variable (a middle term); [`Self::solve_subgoals`]
3766    /// resolves it by threading bindings left to right.
3767    fn prove_rule_antecedent(
3768        &mut self,
3769        antecedent: &ProofExpr,
3770        subst: &Substitution,
3771        context: &[ProofExpr],
3772        depth: usize,
3773    ) -> ProofResult<(DerivationTree, Substitution)> {
3774        let conjuncts = flatten_conjuncts(antecedent);
3775        let (proofs, final_subst) = self.solve_subgoals(&conjuncts, subst, context, depth)?;
3776        let tree = if proofs.len() == 1 {
3777            proofs
3778                .into_iter()
3779                .next()
3780                .expect("exactly one antecedent proof")
3781        } else {
3782            // Fold the per-conjunct proofs into a BINARY-nested `ConjunctionIntro` tree
3783            // that mirrors the antecedent's own `And` structure — the certifier's
3784            // `ConjunctionIntro` is binary (`conj P Q · ·`), so a 7-conjunct antecedent
3785            // becomes 6 nested binary nodes, not one illegal flat node. O(n), no extra
3786            // proving: `flatten_conjuncts` and this fold share the same left-to-right
3787            // recursion, so the flat proofs align exactly with the leaves.
3788            let mut proofs = proofs.into_iter();
3789            build_conjunction_tree(antecedent, &final_subst, &mut proofs)
3790        };
3791        Ok((tree, final_subst))
3792    }
3793
3794    /// Whether `g` can be discharged *immediately* by a known fact — either it
3795    /// unifies with an atomic fact, or with a conjunct of a conjunctive hypothesis
3796    /// (forward ∧-elimination). Such a subgoal pins its variables cheaply, so it is
3797    /// preferred over one that would need a recursive rule search.
3798    fn subgoal_pinnable(&self, g: &ProofExpr, context: &[ProofExpr]) -> bool {
3799        context
3800            .iter()
3801            .chain(self.knowledge_base.iter())
3802            .any(|fact| {
3803                if is_atomic_fact(fact) {
3804                    unify_exprs(g, fact).is_ok()
3805                } else if matches!(fact, ProofExpr::And(_, _)) {
3806                    flatten_conjuncts(fact)
3807                        .iter()
3808                        .any(|c| unify_exprs(g, c).is_ok())
3809                } else {
3810                    false
3811                }
3812            })
3813    }
3814
3815    /// Choose which subgoal to solve next, cheapest first: a ground subgoal (no
3816    /// branching) over a fact-pinnable one (binds a middle term immediately) over an
3817    /// open one that needs a rule search. Conjunctions are left in place (score
3818    /// highest) — the caller expands them at the head. Returns an index into
3819    /// `subgoals`; ties resolve to the lowest index, keeping the search deterministic.
3820    fn select_subgoal(
3821        &self,
3822        subgoals: &[ProofExpr],
3823        subst: &Substitution,
3824        context: &[ProofExpr],
3825    ) -> usize {
3826        let mut best = 0;
3827        let mut best_score = u8::MAX;
3828        for (i, sg) in subgoals.iter().enumerate() {
3829            let g = apply_subst_to_expr(sg, subst);
3830            let score = if matches!(g, ProofExpr::And(_, _)) {
3831                3
3832            } else if self.collect_variables(&g).is_empty() {
3833                0
3834            } else if self.subgoal_pinnable(&g, context) {
3835                1
3836            } else {
3837                2
3838            };
3839            if score < best_score {
3840                best_score = score;
3841                best = i;
3842                if score == 0 {
3843                    break;
3844                }
3845            }
3846        }
3847        best
3848    }
3849
3850    /// Prove a flat list of subgoals under a shared substitution, threading the
3851    /// bindings discovered for each subgoal into the rest — SLD resolution with
3852    /// backtracking. A subgoal that still mentions a variable after substitution
3853    /// is *open*: its variable is a middle term, bound from the knowledge base by
3854    /// trying facts first (terminating) and then rule consequents (recursive).
3855    fn solve_subgoals(
3856        &mut self,
3857        subgoals: &[ProofExpr],
3858        subst: &Substitution,
3859        context: &[ProofExpr],
3860        depth: usize,
3861    ) -> ProofResult<(Vec<DerivationTree>, Substitution)> {
3862        self.charge_budget()?;
3863        if depth > self.max_depth {
3864            return Err(ProofError::DepthExceeded);
3865        }
3866        if subgoals.is_empty() {
3867            return Ok((Vec::new(), subst.clone()));
3868        }
3869        // A nested conjunction at the head expands into the subgoal list.
3870        let head = apply_subst_to_expr(&subgoals[0], subst);
3871        if matches!(head, ProofExpr::And(_, _)) {
3872            let mut expanded = flatten_conjuncts(&head);
3873            expanded.extend_from_slice(&subgoals[1..]);
3874            return self.solve_subgoals(&expanded, subst, context, depth);
3875        }
3876
3877        // Cheapest-first selection: solve a GROUND subgoal (no branching), or one a
3878        // direct fact / conjunct pins immediately, before an open subgoal that would
3879        // otherwise drive an unbounded rule search. This is constraint propagation —
3880        // a shared middle term gets bound by its easiest sibling first — and is what
3881        // keeps the existential cut behind a recursive axiom from blowing up. The
3882        // chosen subgoal is SOLVED first but its proof is re-INSERTED at its original
3883        // position, so the returned order still matches the (order-sensitive)
3884        // `ConjunctionIntro` reconstruction in `prove_rule_antecedent`.
3885        let idx = self.select_subgoal(subgoals, subst, context);
3886        let first = &subgoals[idx];
3887        let rest: Vec<ProofExpr> = subgoals
3888            .iter()
3889            .enumerate()
3890            .filter(|(i, _)| *i != idx)
3891            .map(|(_, e)| e.clone())
3892            .collect();
3893        let g = apply_subst_to_expr(first, subst);
3894
3895        // Ground subgoal (no open variable): prove it with the full strategy
3896        // suite, so non-Horn antecedents (negations, disjunctions, induction, …)
3897        // stay exactly as provable as a top-level goal. No new bindings arise.
3898        // Recurse at `depth + 1` so a recursive axiom (whose antecedent re-enters the
3899        // chainer) is bounded by `max_depth` instead of overflowing the stack.
3900        if self.collect_variables(&g).is_empty() {
3901            let proof = self.prove_goal(
3902                ProofGoal::with_context(g.clone(), context.to_vec()),
3903                depth + 1,
3904            )?;
3905            let (mut proofs, out) = self.solve_subgoals(&rest, subst, context, depth)?;
3906            proofs.insert(idx, proof);
3907            return Ok((proofs, out));
3908        }
3909
3910        // Open subgoal — Option 1: discharge directly against a known fact, OR against
3911        // a conjunct of a conjunctive hypothesis (forward ∧-elimination), binding the
3912        // middle term; backtrack over the choice if the rest cannot close.
3913        let facts: Vec<ProofExpr> = context
3914            .iter()
3915            .chain(self.knowledge_base.iter())
3916            .filter(|e| is_atomic_fact(e) || matches!(e, ProofExpr::And(_, _)))
3917            .cloned()
3918            .collect();
3919        for fact in &facts {
3920            let matched: Option<(DerivationTree, Substitution)> =
3921                if matches!(fact, ProofExpr::And(_, _)) {
3922                    let src = DerivationTree::leaf(fact.clone(), InferenceRule::PremiseMatch);
3923                    extract_conjunct(&src, &g)
3924                } else if is_atomic_fact(fact) {
3925                    unify_exprs(&g, fact).ok().map(|delta| {
3926                        let leaf = DerivationTree::leaf(
3927                            apply_subst_to_expr(&g, &delta),
3928                            InferenceRule::PremiseMatch,
3929                        );
3930                        (leaf, delta)
3931                    })
3932                } else {
3933                    None
3934                };
3935            if let Some((leaf, delta)) = matched {
3936                let combined = compose_substitutions(subst.clone(), delta.clone());
3937                if let Ok((mut proofs, out)) = self.solve_subgoals(&rest, &combined, context, depth)
3938                {
3939                    proofs.insert(idx, leaf.with_substitution(delta));
3940                    return Ok((proofs, out));
3941                }
3942            }
3943        }
3944
3945        // Open subgoal — Option 2: chain through a rule whose consequent unifies
3946        // with the subgoal, recursively proving that rule's antecedent.
3947        let rules: Vec<ProofExpr> = self
3948            .knowledge_base
3949            .iter()
3950            .filter(|e| matches!(e, ProofExpr::ForAll { .. } | ProofExpr::Implies(_, _)))
3951            .cloned()
3952            .collect();
3953        for rule in &rules {
3954            let renamed = self.rename_variables(rule);
3955            let mut matrix: &ProofExpr = &renamed;
3956            while let ProofExpr::ForAll { body, .. } = matrix {
3957                matrix = body.as_ref();
3958            }
3959            if let ProofExpr::Implies(ant, con) = matrix {
3960                if let Ok(delta) = unify_exprs(&g, &**con) {
3961                    let combined = compose_substitutions(subst.clone(), delta.clone());
3962                    let ant_inst = apply_subst_to_expr(&**ant, &combined);
3963                    if let Ok((ant_proof, s_ant)) =
3964                        self.prove_rule_antecedent(&ant_inst, &combined, context, depth + 1)
3965                    {
3966                        // Build NESTED UniversalInst nodes — one per bound variable, in
3967                        // binder order — so a multi-binder rule is fully instantiated.
3968                        // Each variable must be pinned or vacuous in the matrix; a
3969                        // genuinely-underdetermined one aborts rather than leak a metavar.
3970                        let mut bound_vars = Vec::new();
3971                        let mut peel: &ProofExpr = &renamed;
3972                        while let ProofExpr::ForAll { variable, body } = peel {
3973                            bound_vars.push(variable.clone());
3974                            peel = body;
3975                        }
3976                        let witnesses = match instantiation_witnesses(&bound_vars, &s_ant, matrix) {
3977                            Some(w) => w,
3978                            None => continue,
3979                        };
3980                        let resolved = apply_subst_to_expr(&g, &s_ant);
3981                        let instantiated = apply_subst_to_expr(matrix, &s_ant);
3982                        let mut inst_node =
3983                            DerivationTree::leaf(rule.clone(), InferenceRule::PremiseMatch);
3984                        for witness in &witnesses {
3985                            inst_node = DerivationTree::new(
3986                                instantiated.clone(),
3987                                InferenceRule::UniversalInst(format!("{}", witness)),
3988                                vec![inst_node],
3989                            );
3990                        }
3991                        let mp = DerivationTree::new(
3992                            resolved,
3993                            InferenceRule::ModusPonens,
3994                            vec![inst_node, ant_proof],
3995                        );
3996                        if let Ok((mut proofs, out)) =
3997                            self.solve_subgoals(&rest, &s_ant, context, depth)
3998                        {
3999                            proofs.insert(idx, mp);
4000                            return Ok((proofs, out));
4001                        }
4002                    }
4003                }
4004            } else if let Ok(delta) = unify_exprs(&g, matrix) {
4005                // A universally-quantified FACT (no antecedent) — e.g. Tarski A1
4006                // `∀a b. Cong(a,b,b,a)`: instantiate it by unifying its matrix with
4007                // the subgoal directly. Without this only `Implies` rules are chained,
4008                // so a universal fact is unreachable when it must discharge an open
4009                // antecedent (the existential cut behind recursive axioms).
4010                let combined = compose_substitutions(subst.clone(), delta.clone());
4011                let resolved = apply_subst_to_expr(&g, &combined);
4012                // Recover the original ∀-variable order and each variable's witness by
4013                // unifying the ORIGINAL matrix against the resolved (ground) goal, then
4014                // apply the fact to each witness in turn (nested `UniversalInst`).
4015                let mut vars = Vec::new();
4016                let mut orig_body: &ProofExpr = rule;
4017                while let ProofExpr::ForAll { variable, body } = orig_body {
4018                    vars.push(variable.clone());
4019                    orig_body = body;
4020                }
4021                if let Ok(wsubst) = unify_exprs(orig_body, &resolved) {
4022                    let witnesses = match instantiation_witnesses(&vars, &wsubst, orig_body) {
4023                        Some(w) => w,
4024                        None => continue,
4025                    };
4026                    let mut node = DerivationTree::leaf(rule.clone(), InferenceRule::PremiseMatch);
4027                    for witness in &witnesses {
4028                        node = DerivationTree::new(
4029                            resolved.clone(),
4030                            InferenceRule::UniversalInst(format!("{}", witness)),
4031                            vec![node],
4032                        );
4033                    }
4034                    if let Ok((mut proofs, out)) =
4035                        self.solve_subgoals(&rest, &combined, context, depth)
4036                    {
4037                        proofs.insert(idx, node);
4038                        return Ok((proofs, out));
4039                    }
4040                }
4041            }
4042        }
4043
4044        Err(ProofError::NoProofFound)
4045    }
4046
4047    // =========================================================================
4048    // STRATEGY 5: EXISTENTIAL INTRODUCTION
4049    // =========================================================================
4050
4051    /// Try existential introduction: to prove ∃x.P(x), find a witness t and prove P(t).
4052    fn try_existential_intro(
4053        &mut self,
4054        goal: &ProofGoal,
4055        depth: usize,
4056    ) -> ProofResult<Option<DerivationTree>> {
4057        if let ProofExpr::Exists { variable, body } = &goal.target {
4058            // We need to find a witness that makes the body true
4059            // Try each constant/ground term in our KB as a potential witness
4060            let witnesses = self.collect_witnesses(&goal.context);
4061
4062            for witness in witnesses {
4063                let instantiated = instantiate_expr(body, variable, &witness);
4064
4065                // Try to prove the instantiated body
4066                let inst_goal = ProofGoal::with_context(instantiated, goal.context.clone());
4067
4068                if let Ok(body_proof) = self.prove_goal(inst_goal, depth + 1) {
4069                    let witness_str = format!("{}", witness);
4070                    // Witness type from an explicit TypedVar if present (arithmetic /
4071                    // induction), else the FOL domain `Entity` — matching the rest of
4072                    // the encoding (`∀` ranges over Entity, predicates are Entity→Prop),
4073                    // so an untyped `∃y.P(y)` certifies as `Ex Entity …`, not `Ex Nat …`.
4074                    let witness_type =
4075                        extract_type_from_exists_body(body).unwrap_or_else(|| "Entity".to_string());
4076                    return Ok(Some(DerivationTree::new(
4077                        goal.target.clone(),
4078                        InferenceRule::ExistentialIntro {
4079                            witness: witness_str,
4080                            witness_type,
4081                        },
4082                        vec![body_proof],
4083                    )));
4084                }
4085            }
4086        }
4087
4088        Ok(None)
4089    }
4090
4091    // =========================================================================
4092    // STRATEGY 5b: DISJUNCTION ELIMINATION (DISJUNCTIVE SYLLOGISM)
4093    // =========================================================================
4094
4095    /// Try disjunction elimination: if KB has A ∨ B and ¬A, conclude B (and vice versa).
4096    ///
4097    /// Disjunctive syllogism:
4098    /// - From A ∨ B and ¬A, derive B
4099    /// - From A ∨ B and ¬B, derive A
4100    fn try_disjunction_elimination(
4101        &mut self,
4102        goal: &ProofGoal,
4103        depth: usize,
4104    ) -> ProofResult<Option<DerivationTree>> {
4105        // Collect disjunctions from KB and context
4106        let disjunctions: Vec<(ProofExpr, ProofExpr, ProofExpr)> = self
4107            .knowledge_base
4108            .iter()
4109            .chain(goal.context.iter())
4110            .filter_map(|expr| {
4111                if let ProofExpr::Or(left, right) = expr {
4112                    Some((expr.clone(), (**left).clone(), (**right).clone()))
4113                } else {
4114                    None
4115                }
4116            })
4117            .collect();
4118
4119        // Collect negations from KB and context
4120        let negations: Vec<ProofExpr> = self
4121            .knowledge_base
4122            .iter()
4123            .chain(goal.context.iter())
4124            .filter_map(|expr| {
4125                if let ProofExpr::Not(inner) = expr {
4126                    Some((**inner).clone())
4127                } else {
4128                    None
4129                }
4130            })
4131            .collect();
4132
4133        // For each disjunction A ∨ B
4134        for (disj_expr, left, right) in &disjunctions {
4135            // Check if ¬left is in KB (so right must be true)
4136            for negated in &negations {
4137                if exprs_structurally_equal(negated, left) {
4138                    // We have A ∨ B and ¬A, so B is true
4139                    // Check if B matches our goal
4140                    if let Ok(subst) = unify_exprs(&goal.target, right) {
4141                        let disj_leaf =
4142                            DerivationTree::leaf(disj_expr.clone(), InferenceRule::PremiseMatch);
4143                        let neg_leaf = DerivationTree::leaf(
4144                            ProofExpr::Not(Box::new(left.clone())),
4145                            InferenceRule::PremiseMatch,
4146                        );
4147                        return Ok(Some(
4148                            DerivationTree::new(
4149                                goal.target.clone(),
4150                                InferenceRule::DisjunctionElim,
4151                                vec![disj_leaf, neg_leaf],
4152                            )
4153                            .with_substitution(subst),
4154                        ));
4155                    }
4156                }
4157
4158                // Check if ¬right is in KB (so left must be true)
4159                if exprs_structurally_equal(negated, right) {
4160                    // We have A ∨ B and ¬B, so A is true
4161                    // Check if A matches our goal
4162                    if let Ok(subst) = unify_exprs(&goal.target, left) {
4163                        let disj_leaf =
4164                            DerivationTree::leaf(disj_expr.clone(), InferenceRule::PremiseMatch);
4165                        let neg_leaf = DerivationTree::leaf(
4166                            ProofExpr::Not(Box::new(right.clone())),
4167                            InferenceRule::PremiseMatch,
4168                        );
4169                        return Ok(Some(
4170                            DerivationTree::new(
4171                                goal.target.clone(),
4172                                InferenceRule::DisjunctionElim,
4173                                vec![disj_leaf, neg_leaf],
4174                            )
4175                            .with_substitution(subst),
4176                        ));
4177                    }
4178                }
4179            }
4180        }
4181
4182        // No literal disjunction settled the goal. The disjunction the syllogism
4183        // needs is often itself a CONSEQUENCE — "Every color is red or blue" at a
4184        // witness yields `Red(c) ∨ Blue(c)` only after universal instantiation +
4185        // modus ponens. So, for a goal `B` and each known negation `¬A`, try to
4186        // PROVE the disjunction `A ∨ B` (or `B ∨ A`); if it goes through, the
4187        // proven disjunction becomes the first premise of the elimination. This
4188        // is the general elimination step every disjunctive-syllogism chain over
4189        // a closed domain relies on. The conclusion is a single disjunct, never
4190        // itself a disjunction — skipping `Or` goals keeps the recursive
4191        // disjunction proof from chasing ever-larger `A ∨ (A ∨ …)` targets.
4192        if depth < self.max_depth && !matches!(goal.target, ProofExpr::Or(..)) {
4193            for negated in &negations {
4194                if exprs_structurally_equal(negated, &goal.target) {
4195                    continue;
4196                }
4197                for orient_left in [true, false] {
4198                    let disjunction = if orient_left {
4199                        ProofExpr::Or(Box::new(negated.clone()), Box::new(goal.target.clone()))
4200                    } else {
4201                        ProofExpr::Or(Box::new(goal.target.clone()), Box::new(negated.clone()))
4202                    };
4203                    // Already covered by a literal disjunction above.
4204                    if disjunctions
4205                        .iter()
4206                        .any(|(d, _, _)| exprs_structurally_equal(d, &disjunction))
4207                    {
4208                        continue;
4209                    }
4210                    let disj_goal =
4211                        ProofGoal::with_context(disjunction.clone(), goal.context.clone());
4212                    // Derive the disjunction from a FACT or a universal rule's
4213                    // consequent only. Routing through full `prove_goal` would
4214                    // hand the `A ∨ B` goal to disjunction INTRODUCTION, which
4215                    // re-proves a disjunct — bouncing back to this very goal in an
4216                    // unbounded `Blue ↦ Red ∨ Blue ↦ Blue` cycle. A closed-domain
4217                    // disjunction is always a consequence, never an introduction.
4218                    let disj_proof = self
4219                        .try_match_fact(&disj_goal)?
4220                        .map(Ok)
4221                        .or_else(|| self.try_universal_inst(&disj_goal, depth + 1).transpose())
4222                        .transpose()?;
4223                    if let Some(disj_proof) = disj_proof {
4224                        let neg_leaf = DerivationTree::leaf(
4225                            ProofExpr::Not(Box::new(negated.clone())),
4226                            InferenceRule::PremiseMatch,
4227                        );
4228                        return Ok(Some(DerivationTree::new(
4229                            goal.target.clone(),
4230                            InferenceRule::DisjunctionElim,
4231                            vec![disj_proof, neg_leaf],
4232                        )));
4233                    }
4234                }
4235            }
4236        }
4237
4238        // The negation the syllogism needs may itself have to be PROVED, not just
4239        // looked up. A closed-domain rule `∀x(ante(x) → (D₁(x) ∨ D₂(x)))` at a
4240        // witness yields `D₁(c) ∨ D₂(c)`; when the goal is one disjunct (say
4241        // `D₂(c)`) and the OTHER disjunct is refutable (`¬D₁(c)` follows from a
4242        // uniqueness/identity constraint), disjunctive syllogism still applies —
4243        // we derive the disjunction from the rule and prove `¬D₁(c)` as a
4244        // sub-goal (which the negation strategies discharge by reductio). This is
4245        // the elimination step a logic grid leans on once it has pinned a cell.
4246        if depth < self.max_depth && !matches!(goal.target, ProofExpr::Or(..)) {
4247            let disjunctive_rules: Vec<(ProofExpr, ProofExpr)> = self
4248                .knowledge_base
4249                .iter()
4250                .chain(goal.context.iter())
4251                .filter_map(|e| match e {
4252                    ProofExpr::ForAll { body, .. } => match body.as_ref() {
4253                        ProofExpr::Implies(_, cons) => match cons.as_ref() {
4254                            ProofExpr::Or(l, r) => Some(((**l).clone(), (**r).clone())),
4255                            _ => None,
4256                        },
4257                        _ => None,
4258                    },
4259                    ProofExpr::Implies(_, cons) => match cons.as_ref() {
4260                        ProofExpr::Or(l, r) => Some(((**l).clone(), (**r).clone())),
4261                        _ => None,
4262                    },
4263                    ProofExpr::Or(l, r) => Some(((**l).clone(), (**r).clone())),
4264                    _ => None,
4265                })
4266                .collect();
4267
4268            for (d_left, d_right) in &disjunctive_rules {
4269                // Match the goal against one disjunct template; the OTHER, under
4270                // the same binding, is the disjunct to refute.
4271                for goal_is_right in [true, false] {
4272                    let (goal_template, other_template) = if goal_is_right {
4273                        (d_right, d_left)
4274                    } else {
4275                        (d_left, d_right)
4276                    };
4277                    let Ok(subst) = unify_exprs(&goal.target, goal_template) else {
4278                        continue;
4279                    };
4280                    let other = apply_subst_to_expr(other_template, &subst);
4281                    if self.contains_quantifier(&other) {
4282                        continue;
4283                    }
4284                    // The disjunction `A ∨ B` (in the rule's orientation) the
4285                    // elimination consumes. Derive it from the rule, never by
4286                    // introduction (which would re-enter this goal).
4287                    let goal_disjunct = apply_subst_to_expr(goal_template, &subst);
4288                    let disjunction = if goal_is_right {
4289                        ProofExpr::Or(Box::new(other.clone()), Box::new(goal_disjunct))
4290                    } else {
4291                        ProofExpr::Or(Box::new(goal_disjunct), Box::new(other.clone()))
4292                    };
4293                    let disj_goal =
4294                        ProofGoal::with_context(disjunction.clone(), goal.context.clone());
4295                    let disj_proof = match self.try_match_fact(&disj_goal)? {
4296                        Some(p) => Some(p),
4297                        None => match self.try_universal_inst(&disj_goal, depth + 1)? {
4298                            Some(p) => Some(p),
4299                            // A GROUNDED rule `ante → (A ∨ B)` yields the disjunction
4300                            // by modus ponens once `ante` is proved. Backward-chain
4301                            // into it: the implication's consequent IS the disjunction,
4302                            // so this derives it without disjunction introduction (no
4303                            // re-proving a single disjunct, no cycle).
4304                            None => self.try_backward_chain(&disj_goal, depth + 1)?,
4305                        },
4306                    };
4307                    let Some(disj_proof) = disj_proof else {
4308                        continue;
4309                    };
4310                    // Prove the negation of the other disjunct as a sub-goal.
4311                    let neg_goal = ProofGoal::with_context(
4312                        ProofExpr::Not(Box::new(other.clone())),
4313                        goal.context.clone(),
4314                    );
4315                    if let Ok(neg_proof) = self.prove_goal(neg_goal, depth + 1) {
4316                        return Ok(Some(DerivationTree::new(
4317                            goal.target.clone(),
4318                            InferenceRule::DisjunctionElim,
4319                            vec![disj_proof, neg_proof],
4320                        )));
4321                    }
4322                }
4323            }
4324        }
4325
4326        // Last resort — general case analysis (intuitionistic ∨-elimination): for a
4327        // disjunction `A ∨ B` in the KB, prove the goal under EACH disjunct. Unlike
4328        // disjunctive syllogism above, no negation is needed. Skip a disjunction
4329        // whose disjunct is already in context (it has been decided — re-splitting
4330        // would loop). The certifier's `DisjunctionCases` binds each disjunct as a
4331        // local hypothesis that the branch proof cites.
4332        if depth < self.max_depth {
4333            for (disj_expr, left, right) in &disjunctions {
4334                let decided = goal.context.iter().any(|c| {
4335                    exprs_structurally_equal(c, left) || exprs_structurally_equal(c, right)
4336                });
4337                if decided {
4338                    continue;
4339                }
4340                let mut left_ctx = goal.context.clone();
4341                left_ctx.push(left.clone());
4342                let left_branch = match self.prove_goal(
4343                    ProofGoal::with_context(goal.target.clone(), left_ctx),
4344                    depth + 1,
4345                ) {
4346                    Ok(t) => t,
4347                    Err(_) => continue,
4348                };
4349                let mut right_ctx = goal.context.clone();
4350                right_ctx.push(right.clone());
4351                let right_branch = match self.prove_goal(
4352                    ProofGoal::with_context(goal.target.clone(), right_ctx),
4353                    depth + 1,
4354                ) {
4355                    Ok(t) => t,
4356                    Err(_) => continue,
4357                };
4358                let disj_leaf =
4359                    DerivationTree::leaf(disj_expr.clone(), InferenceRule::PremiseMatch);
4360                return Ok(Some(DerivationTree::new(
4361                    goal.target.clone(),
4362                    InferenceRule::DisjunctionCases,
4363                    vec![disj_leaf, left_branch, right_branch],
4364                )));
4365            }
4366        }
4367
4368        Ok(None)
4369    }
4370
4371    // =========================================================================
4372    // STRATEGY 5c: PROOF BY CONTRADICTION (REDUCTIO AD ABSURDUM)
4373    // =========================================================================
4374
4375    /// Try proof by contradiction: to prove ¬P, assume P and derive a contradiction.
4376    ///
4377    /// This implements reductio ad absurdum:
4378    /// 1. To prove ¬∃x P(x), assume ∃x P(x), derive contradiction, conclude ¬∃x P(x)
4379    /// 2. To prove ¬P, assume P, derive contradiction, conclude ¬P
4380    ///
4381    /// A contradiction is detected when both Q and ¬Q are derivable.
4382    fn try_reductio_ad_absurdum(
4383        &mut self,
4384        goal: &ProofGoal,
4385        depth: usize,
4386    ) -> ProofResult<Option<DerivationTree>> {
4387        // Only apply to negation goals
4388        let assumed = match &goal.target {
4389            ProofExpr::Not(inner) => (**inner).clone(),
4390            _ => return Ok(None),
4391        };
4392
4393        // Aggressive depth limit - reductio is expensive
4394        if depth > 5 {
4395            return Ok(None);
4396        }
4397
4398        // Special handling for existence negation goals: ¬∃x P(x)
4399        // This is crucial for paradoxes like the Barber Paradox
4400        if let ProofExpr::Exists { .. } = &assumed {
4401            return self.try_existence_negation_proof(&goal, &assumed, depth);
4402        }
4403
4404        // For non-existence goals, skip if they contain other quantifiers
4405        // (to avoid infinite loops with universal instantiation)
4406        if self.contains_quantifier(&assumed) {
4407            return Ok(None);
4408        }
4409
4410        // Create a temporary context with the assumption added
4411        let mut extended_context = goal.context.clone();
4412        extended_context.push(assumed.clone());
4413
4414        // Also Skolemize existentials from the assumption (but be careful)
4415        let skolemized = self.skolemize_existential(&assumed);
4416        for sk in &skolemized {
4417            extended_context.push(sk.clone());
4418        }
4419
4420        // Prefer the gapless certifiable contradiction finder: its ⊥-derivation
4421        // certifies end to end (saturation + equality closure + bounded case
4422        // split), so the reductio it feeds becomes a kernel-checked `¬P`. Fall
4423        // back to the heuristic finder only when the certifiable one cannot close.
4424        if let Some(contradiction_proof) =
4425            self.find_certifiable_contradiction(&extended_context, depth)?
4426        {
4427            let assumption_leaf =
4428                DerivationTree::leaf(assumed.clone(), InferenceRule::PremiseMatch);
4429            return Ok(Some(DerivationTree::new(
4430                goal.target.clone(),
4431                InferenceRule::ReductioAdAbsurdum,
4432                vec![assumption_leaf, contradiction_proof],
4433            )));
4434        }
4435
4436        // Look for contradiction in the extended context + KB
4437        // Note: find_contradiction does NOT call prove_goal recursively
4438        if let Some(contradiction_proof) = self.find_contradiction(&extended_context, depth)? {
4439            // Found a contradiction! Build the reductio proof
4440            let assumption_leaf =
4441                DerivationTree::leaf(assumed.clone(), InferenceRule::PremiseMatch);
4442
4443            return Ok(Some(DerivationTree::new(
4444                goal.target.clone(),
4445                InferenceRule::ReductioAdAbsurdum,
4446                vec![assumption_leaf, contradiction_proof],
4447            )));
4448        }
4449
4450        Ok(None)
4451    }
4452
4453    /// Try to prove ¬∃x P(x) by assuming ∃x P(x) and deriving contradiction.
4454    ///
4455    /// This is the core strategy for existence paradoxes like the Barber Paradox.
4456    /// Steps:
4457    /// 1. Assume ∃x P(x)
4458    /// 2. Skolemize to get P(c) for fresh constant c
4459    /// 3. Skolemize KB existentials (definite descriptions) to extract inner structure
4460    /// 4. Abstract event semantics to simple predicates
4461    /// 5. Instantiate universal premises with the Skolem constant
4462    /// 6. Extract uniqueness constraints and derive equalities
4463    /// 7. Look for contradiction (possibly via case analysis)
4464    fn try_existence_negation_proof(
4465        &mut self,
4466        goal: &ProofGoal,
4467        assumed_existence: &ProofExpr,
4468        depth: usize,
4469    ) -> ProofResult<Option<DerivationTree>> {
4470        // Skolemize the assumed existence: ∃x P(x) → P(c)
4471        let witness_facts = self.skolemize_existential(assumed_existence);
4472
4473        if witness_facts.is_empty() {
4474            return Ok(None);
4475        }
4476
4477        // Build extended context with witness facts
4478        let mut extended_context = goal.context.clone();
4479        extended_context.push(assumed_existence.clone());
4480
4481        // Add witness facts, abstracting events
4482        for fact in &witness_facts {
4483            let abstracted = self.abstract_all_events(fact);
4484            if !extended_context.contains(&abstracted) {
4485                extended_context.push(abstracted);
4486            }
4487            if !extended_context.contains(fact) {
4488                extended_context.push(fact.clone());
4489            }
4490        }
4491
4492        // Extract any Skolem constants from the witness facts
4493        let mut skolem_constants = self.extract_skolem_constants(&witness_facts);
4494
4495        // CRITICAL: Skolemize KB existentials to extract definite description structure.
4496        // Natural language "The barber" creates:
4497        // ∃y ((barber(y) ∧ ∀z (barber(z) → z = y)) ∧ ∀x ...)
4498        // We need to Skolemize these to access the inner universals.
4499        let kb_skolemized = self.skolemize_kb_existentials();
4500        for fact in &kb_skolemized {
4501            let abstracted = self.abstract_all_events(fact);
4502            if !extended_context.contains(&abstracted) {
4503                extended_context.push(abstracted);
4504            }
4505            if !extended_context.contains(fact) {
4506                extended_context.push(fact.clone());
4507            }
4508        }
4509
4510        // Extract additional Skolem constants from KB
4511        let kb_skolems = self.extract_skolem_constants(&kb_skolemized);
4512        for sk in kb_skolems {
4513            if !skolem_constants.contains(&sk) {
4514                skolem_constants.push(sk);
4515            }
4516        }
4517
4518        // Also extract unified definite description constants (e.g., "the_barber")
4519        // These are created by unify_definite_descriptions and should be treated like Skolems
4520        for expr in &self.knowledge_base {
4521            self.collect_unified_constants(expr, &mut skolem_constants);
4522        }
4523
4524        // Instantiate universal premises with Skolem constants
4525        let instantiated =
4526            self.instantiate_universals_with_constants(&extended_context, &skolem_constants);
4527        for inst in &instantiated {
4528            let abstracted = self.abstract_all_events(inst);
4529            if !extended_context.contains(&abstracted) {
4530                extended_context.push(abstracted);
4531            }
4532        }
4533
4534        // Also process KB universals
4535        let kb_instantiated = self.instantiate_kb_universals_with_constants(&skolem_constants);
4536        for inst in &kb_instantiated {
4537            let abstracted = self.abstract_all_events(inst);
4538            if !extended_context.contains(&abstracted) {
4539                extended_context.push(abstracted);
4540            }
4541        }
4542
4543        // CRITICAL: Extract uniqueness constraints from definite descriptions
4544        // and derive equalities between Skolem constants and KB witnesses.
4545        // This handles Russell's definite descriptions: "The barber" creates
4546        // ∃y ((barber(y) ∧ ∀z (barber(z) → z = y)) ∧ ...)
4547        let derived_equalities = self
4548            .derive_equalities_from_uniqueness_constraints(&extended_context, &skolem_constants);
4549
4550        // Add derived equalities to context
4551        for eq in &derived_equalities {
4552            if !extended_context.contains(eq) {
4553                extended_context.push(eq.clone());
4554            }
4555        }
4556
4557        // Apply derived equalities to substitute terms throughout context
4558        // This unifies facts about different barbers (sk_0, y, v) into a single entity
4559        let unified_context =
4560            self.apply_equalities_to_context(&extended_context, &derived_equalities);
4561
4562        // Look for direct contradiction first (in unified context)
4563        if let Some(contradiction_proof) = self.find_contradiction(&unified_context, depth)? {
4564            let assumption_leaf =
4565                DerivationTree::leaf(assumed_existence.clone(), InferenceRule::PremiseMatch);
4566
4567            return Ok(Some(DerivationTree::new(
4568                goal.target.clone(),
4569                InferenceRule::ReductioAdAbsurdum,
4570                vec![assumption_leaf, contradiction_proof],
4571            )));
4572        }
4573
4574        // Try case analysis for self-referential structures (like Barber Paradox)
4575        if let Some(case_proof) =
4576            self.try_case_analysis_contradiction(&unified_context, &skolem_constants, depth)?
4577        {
4578            let assumption_leaf =
4579                DerivationTree::leaf(assumed_existence.clone(), InferenceRule::PremiseMatch);
4580
4581            return Ok(Some(DerivationTree::new(
4582                goal.target.clone(),
4583                InferenceRule::ReductioAdAbsurdum,
4584                vec![assumption_leaf, case_proof],
4585            )));
4586        }
4587
4588        Ok(None)
4589    }
4590
4591    /// Skolemize all existential expressions in the KB.
4592    ///
4593    /// This is essential for definite descriptions from natural language.
4594    /// "The barber" creates `∃y ((barber(y) ∧ ∀z (barber(z) → z = y)) ∧ ...)`.
4595    /// We Skolemize to extract the inner structure.
4596    fn skolemize_kb_existentials(&mut self) -> Vec<ProofExpr> {
4597        let mut results = Vec::new();
4598
4599        for expr in &self.knowledge_base.clone() {
4600            if let ProofExpr::Exists { .. } = expr {
4601                let skolemized = self.skolemize_existential(expr);
4602                results.extend(skolemized);
4603            }
4604        }
4605
4606        results
4607    }
4608
4609    // =========================================================================
4610    // EQUATIONAL REASONING FOR DEFINITE DESCRIPTIONS
4611    // =========================================================================
4612
4613    /// Derive equalities from uniqueness constraints in definite descriptions.
4614    ///
4615    /// Given facts like `barber(sk_0)` and uniqueness constraints like
4616    /// `∀z (barber(z) → z = y)`, derive `sk_0 = y`.
4617    ///
4618    /// This is essential for Russell's definite descriptions where
4619    /// "The barber" creates `∃y ((barber(y) ∧ ∀z (barber(z) → z = y)) ∧ ...)`.
4620    fn derive_equalities_from_uniqueness_constraints(
4621        &self,
4622        context: &[ProofExpr],
4623        skolem_constants: &[String],
4624    ) -> Vec<ProofExpr> {
4625        let mut equalities = Vec::new();
4626
4627        // Collect all uniqueness constraints from KB and context
4628        // Pattern: ∀z (P(z) → z = c) where c is a constant/variable
4629        let uniqueness_constraints = self.extract_uniqueness_constraints(context);
4630
4631        // For each Skolem constant, check if it satisfies predicates
4632        // with uniqueness constraints
4633        for skolem in skolem_constants {
4634            for (predicate_name, unique_entity) in &uniqueness_constraints {
4635                // Check if we have predicate(skolem) in context
4636                let skolem_term = ProofTerm::Constant(skolem.clone());
4637                let skolem_satisfies_predicate = context
4638                    .iter()
4639                    .any(|expr| self.predicate_matches(expr, predicate_name, &skolem_term));
4640
4641                if skolem_satisfies_predicate {
4642                    // Derive: skolem = unique_entity
4643                    let equality = ProofExpr::Identity(skolem_term.clone(), unique_entity.clone());
4644                    if !equalities.contains(&equality) {
4645                        equalities.push(equality);
4646                    }
4647
4648                    // Also add the symmetric version for easier matching
4649                    let sym_equality =
4650                        ProofExpr::Identity(unique_entity.clone(), skolem_term.clone());
4651                    if !equalities.contains(&sym_equality) {
4652                        equalities.push(sym_equality);
4653                    }
4654                }
4655            }
4656        }
4657
4658        // Derive transitive equalities: if sk_0 = y and sk_0 = v, then y = v
4659        let mut transitive_equalities = Vec::new();
4660        for eq1 in &equalities {
4661            if let ProofExpr::Identity(t1, t2) = eq1 {
4662                for eq2 in &equalities {
4663                    if let ProofExpr::Identity(t3, t4) = eq2 {
4664                        // If t1 = t2 and t1 = t4, then t2 = t4
4665                        if t1 == t3 && t2 != t4 {
4666                            let trans_eq = ProofExpr::Identity(t2.clone(), t4.clone());
4667                            if !equalities.contains(&trans_eq)
4668                                && !transitive_equalities.contains(&trans_eq)
4669                            {
4670                                transitive_equalities.push(trans_eq);
4671                            }
4672                        }
4673                        // If t1 = t2 and t3 = t1, then t2 = t3
4674                        if t1 == t4 && t2 != t3 {
4675                            let trans_eq = ProofExpr::Identity(t2.clone(), t3.clone());
4676                            if !equalities.contains(&trans_eq)
4677                                && !transitive_equalities.contains(&trans_eq)
4678                            {
4679                                transitive_equalities.push(trans_eq);
4680                            }
4681                        }
4682                    }
4683                }
4684            }
4685        }
4686        equalities.extend(transitive_equalities);
4687
4688        equalities
4689    }
4690
4691    /// Extract uniqueness constraints from context and KB.
4692    ///
4693    /// Looks for patterns like `∀z (P(z) → z = c)` which establish
4694    /// that c is the unique entity satisfying P.
4695    fn extract_uniqueness_constraints(&self, context: &[ProofExpr]) -> Vec<(String, ProofTerm)> {
4696        let mut constraints = Vec::new();
4697
4698        for expr in context.iter().chain(self.knowledge_base.iter()) {
4699            self.extract_uniqueness_from_expr(expr, &mut constraints);
4700        }
4701
4702        constraints
4703    }
4704
4705    /// Recursively extract uniqueness constraints from an expression.
4706    fn extract_uniqueness_from_expr(
4707        &self,
4708        expr: &ProofExpr,
4709        constraints: &mut Vec<(String, ProofTerm)>,
4710    ) {
4711        match expr {
4712            // Direct uniqueness pattern: ∀z (P(z) → z = c)
4713            ProofExpr::ForAll { variable, body } => {
4714                if let ProofExpr::Implies(ante, cons) = body.as_ref() {
4715                    if let ProofExpr::Identity(left, right) = cons.as_ref() {
4716                        // Check if it's "z = c" where z is the quantified variable
4717                        let var_term = ProofTerm::Variable(variable.clone());
4718                        if left == &var_term {
4719                            // Extract the predicate name from the antecedent
4720                            if let Some(pred_name) =
4721                                self.extract_unary_predicate_name(ante, variable)
4722                            {
4723                                // right is the unique entity
4724                                constraints.push((pred_name, right.clone()));
4725                            }
4726                        } else if right == &var_term {
4727                            // Check c = z form
4728                            if let Some(pred_name) =
4729                                self.extract_unary_predicate_name(ante, variable)
4730                            {
4731                                constraints.push((pred_name, left.clone()));
4732                            }
4733                        }
4734                    }
4735                }
4736                // Recurse into body for nested structures
4737                self.extract_uniqueness_from_expr(body, constraints);
4738            }
4739
4740            // Conjunction: extract from both sides
4741            ProofExpr::And(left, right) => {
4742                self.extract_uniqueness_from_expr(left, constraints);
4743                self.extract_uniqueness_from_expr(right, constraints);
4744            }
4745
4746            // Existential: extract from body (definite descriptions are wrapped in ∃)
4747            ProofExpr::Exists { body, .. } => {
4748                self.extract_uniqueness_from_expr(body, constraints);
4749            }
4750
4751            _ => {}
4752        }
4753    }
4754
4755    /// Extract the predicate name from a unary predicate application.
4756    ///
4757    /// Given P(z) where z is the variable, returns "P".
4758    fn extract_unary_predicate_name(&self, expr: &ProofExpr, var: &str) -> Option<String> {
4759        match expr {
4760            ProofExpr::Predicate { name, args, .. } => {
4761                if args.len() == 1 {
4762                    if let ProofTerm::Variable(v) = &args[0] {
4763                        if v == var {
4764                            return Some(name.clone());
4765                        }
4766                    }
4767                }
4768                None
4769            }
4770            _ => None,
4771        }
4772    }
4773
4774    /// Check if an expression is a predicate with the given name applied to the term.
4775    fn predicate_matches(&self, expr: &ProofExpr, pred_name: &str, term: &ProofTerm) -> bool {
4776        match expr {
4777            ProofExpr::Predicate { name, args, .. } => {
4778                name == pred_name && args.len() == 1 && &args[0] == term
4779            }
4780            _ => false,
4781        }
4782    }
4783
4784    /// Apply derived equalities to substitute terms throughout context.
4785    ///
4786    /// This unifies facts about different entities (sk_0, y, v) by replacing
4787    /// all occurrences with a canonical representative (the first Skolem constant).
4788    fn apply_equalities_to_context(
4789        &self,
4790        context: &[ProofExpr],
4791        equalities: &[ProofExpr],
4792    ) -> Vec<ProofExpr> {
4793        if equalities.is_empty() {
4794            return context.to_vec();
4795        }
4796
4797        // Build a substitution map from equalities
4798        // Use the first term as the canonical representative
4799        let mut substitutions: Vec<(&ProofTerm, &ProofTerm)> = Vec::new();
4800        for eq in equalities {
4801            if let ProofExpr::Identity(t1, t2) = eq {
4802                // Prefer Skolem constants as canonical (they're from our assumption)
4803                if let ProofTerm::Constant(c) = t1 {
4804                    if c.starts_with("sk_") {
4805                        substitutions.push((t2, t1)); // t2 → t1 (Skolem)
4806                        continue;
4807                    }
4808                }
4809                if let ProofTerm::Constant(c) = t2 {
4810                    if c.starts_with("sk_") {
4811                        substitutions.push((t1, t2)); // t1 → t2 (Skolem)
4812                        continue;
4813                    }
4814                }
4815                // Default: first term is canonical
4816                substitutions.push((t2, t1));
4817            }
4818        }
4819
4820        // Apply substitutions to each expression in context
4821        let mut unified_context = Vec::new();
4822        for expr in context {
4823            let mut unified = expr.clone();
4824            for (from, to) in &substitutions {
4825                unified = self.substitute_term_in_expr(&unified, from, to);
4826            }
4827            // Add abstracted version too
4828            let abstracted = self.abstract_all_events(&unified);
4829            if !unified_context.contains(&unified) {
4830                unified_context.push(unified);
4831            }
4832            if !unified_context.contains(&abstracted) {
4833                unified_context.push(abstracted);
4834            }
4835        }
4836
4837        // Also add implications with substituted terms
4838        // This ensures cyclic implications like P(sk,sk) → ¬P(sk,sk) are in context
4839        for expr in context {
4840            if let ProofExpr::ForAll { variable, body } = expr {
4841                if let ProofExpr::Implies(_, _) = body.as_ref() {
4842                    // Find any Skolem constants and instantiate
4843                    for (from, to) in &substitutions {
4844                        if let ProofTerm::Constant(c) = to {
4845                            if c.starts_with("sk_") {
4846                                // Instantiate this universal with the Skolem constant
4847                                let instantiated = instantiate_expr(body, variable, to);
4848                                let abstracted = self.abstract_all_events(&instantiated);
4849                                if !unified_context.contains(&abstracted) {
4850                                    unified_context.push(abstracted);
4851                                }
4852                            }
4853                        }
4854                    }
4855                }
4856            }
4857        }
4858
4859        unified_context
4860    }
4861
4862    /// Extract Skolem constants from a list of expressions.
4863    fn extract_skolem_constants(&self, exprs: &[ProofExpr]) -> Vec<String> {
4864        let mut constants = Vec::new();
4865        for expr in exprs {
4866            self.collect_skolem_constants_from_expr(expr, &mut constants);
4867        }
4868        constants.sort();
4869        constants.dedup();
4870        constants
4871    }
4872
4873    /// Helper to collect Skolem constants from an expression.
4874    fn collect_skolem_constants_from_expr(&self, expr: &ProofExpr, constants: &mut Vec<String>) {
4875        match expr {
4876            ProofExpr::Predicate { args, .. } => {
4877                for arg in args {
4878                    self.collect_skolem_constants_from_term(arg, constants);
4879                }
4880            }
4881            ProofExpr::And(l, r)
4882            | ProofExpr::Or(l, r)
4883            | ProofExpr::Implies(l, r)
4884            | ProofExpr::Iff(l, r) => {
4885                self.collect_skolem_constants_from_expr(l, constants);
4886                self.collect_skolem_constants_from_expr(r, constants);
4887            }
4888            ProofExpr::Not(inner) => {
4889                self.collect_skolem_constants_from_expr(inner, constants);
4890            }
4891            ProofExpr::Identity(l, r) => {
4892                self.collect_skolem_constants_from_term(l, constants);
4893                self.collect_skolem_constants_from_term(r, constants);
4894            }
4895            ProofExpr::NeoEvent { roles, .. } => {
4896                for (_, term) in roles {
4897                    self.collect_skolem_constants_from_term(term, constants);
4898                }
4899            }
4900            _ => {}
4901        }
4902    }
4903
4904    /// Helper to collect Skolem constants from a term.
4905    /// Collect unified definite description constants (e.g., "the_barber")
4906    /// These are created by unify_definite_descriptions and start with "the_".
4907    fn collect_unified_constants(&self, expr: &ProofExpr, constants: &mut Vec<String>) {
4908        match expr {
4909            ProofExpr::Predicate { args, .. } => {
4910                for arg in args {
4911                    if let ProofTerm::Constant(name) = arg {
4912                        if name.starts_with("the_") && !constants.contains(name) {
4913                            constants.push(name.clone());
4914                        }
4915                    }
4916                }
4917            }
4918            ProofExpr::And(left, right)
4919            | ProofExpr::Or(left, right)
4920            | ProofExpr::Implies(left, right)
4921            | ProofExpr::Iff(left, right) => {
4922                self.collect_unified_constants(left, constants);
4923                self.collect_unified_constants(right, constants);
4924            }
4925            ProofExpr::Not(inner) => self.collect_unified_constants(inner, constants),
4926            ProofExpr::ForAll { body, .. } | ProofExpr::Exists { body, .. } => {
4927                self.collect_unified_constants(body, constants);
4928            }
4929            ProofExpr::Identity(t1, t2) => {
4930                if let ProofTerm::Constant(name) = t1 {
4931                    if name.starts_with("the_") && !constants.contains(name) {
4932                        constants.push(name.clone());
4933                    }
4934                }
4935                if let ProofTerm::Constant(name) = t2 {
4936                    if name.starts_with("the_") && !constants.contains(name) {
4937                        constants.push(name.clone());
4938                    }
4939                }
4940            }
4941            _ => {}
4942        }
4943    }
4944
4945    fn collect_skolem_constants_from_term(&self, term: &ProofTerm, constants: &mut Vec<String>) {
4946        match term {
4947            ProofTerm::Constant(name) if name.starts_with("sk_") => {
4948                constants.push(name.clone());
4949            }
4950            ProofTerm::Function(_, args) => {
4951                for arg in args {
4952                    self.collect_skolem_constants_from_term(arg, constants);
4953                }
4954            }
4955            ProofTerm::Group(terms) => {
4956                for t in terms {
4957                    self.collect_skolem_constants_from_term(t, constants);
4958                }
4959            }
4960            _ => {}
4961        }
4962    }
4963
4964    /// Instantiate universal quantifiers in the context with given constants.
4965    fn instantiate_universals_with_constants(
4966        &self,
4967        context: &[ProofExpr],
4968        constants: &[String],
4969    ) -> Vec<ProofExpr> {
4970        let mut results = Vec::new();
4971
4972        for expr in context {
4973            if let ProofExpr::ForAll { variable, body } = expr {
4974                for constant in constants {
4975                    let instantiated =
4976                        instantiate_expr(body, variable, &ProofTerm::Constant(constant.clone()));
4977                    results.push(instantiated);
4978                }
4979            }
4980        }
4981
4982        results
4983    }
4984
4985    /// Instantiate universal quantifiers in KB with given constants.
4986    fn instantiate_kb_universals_with_constants(&self, constants: &[String]) -> Vec<ProofExpr> {
4987        let mut results = Vec::new();
4988
4989        for expr in &self.knowledge_base {
4990            if let ProofExpr::ForAll { variable, body } = expr {
4991                for constant in constants {
4992                    let instantiated =
4993                        instantiate_expr(body, variable, &ProofTerm::Constant(constant.clone()));
4994                    results.push(instantiated);
4995                }
4996            }
4997        }
4998
4999        results
5000    }
5001
5002    // =========================================================================
5003    // CASE ANALYSIS (TERTIUM NON DATUR)
5004    // =========================================================================
5005
5006    /// Try case analysis to derive a contradiction.
5007    ///
5008    /// For self-referential structures like the Barber Paradox:
5009    /// - Split on a predicate P(c, c) where c is a Skolem constant
5010    /// - Case 1: Assume P(c, c), derive ¬P(c, c) → contradiction
5011    /// - Case 2: Assume ¬P(c, c), derive P(c, c) → contradiction
5012    /// Either way we get contradiction (law of excluded middle).
5013    fn try_case_analysis_contradiction(
5014        &mut self,
5015        context: &[ProofExpr],
5016        skolem_constants: &[String],
5017        depth: usize,
5018    ) -> ProofResult<Option<DerivationTree>> {
5019        // Find candidate predicates for case splitting
5020        // Look for self-referential predicates: P(c, c) where c is a Skolem constant
5021        let candidates = self.find_case_split_candidates(context, skolem_constants);
5022
5023        for candidate in candidates {
5024            // Case 1: Assume the candidate is true
5025            let mut context_with_pos = context.to_vec();
5026            if !context_with_pos.contains(&candidate) {
5027                context_with_pos.push(candidate.clone());
5028            }
5029
5030            // Case 2: Assume the candidate is false
5031            let negated = ProofExpr::Not(Box::new(candidate.clone()));
5032            let mut context_with_neg = context.to_vec();
5033            if !context_with_neg.contains(&negated) {
5034                context_with_neg.push(negated.clone());
5035            }
5036
5037            // Try to derive contradiction in both cases
5038            let case1_contradiction = self.find_contradiction(&context_with_pos, depth)?;
5039            let case2_contradiction = self.find_contradiction(&context_with_neg, depth)?;
5040
5041            // If both cases lead to contradiction, we have a proof
5042            if let (Some(case1_proof), Some(case2_proof)) =
5043                (case1_contradiction, case2_contradiction)
5044            {
5045                // Build the case analysis proof tree
5046                let case1_tree = DerivationTree::new(
5047                    ProofExpr::Atom("⊥".into()),
5048                    InferenceRule::PremiseMatch,
5049                    vec![case1_proof],
5050                );
5051                let case2_tree = DerivationTree::new(
5052                    ProofExpr::Atom("⊥".into()),
5053                    InferenceRule::PremiseMatch,
5054                    vec![case2_proof],
5055                );
5056
5057                return Ok(Some(DerivationTree::new(
5058                    ProofExpr::Atom("⊥".into()),
5059                    InferenceRule::CaseAnalysis {
5060                        case_formula: Box::new(candidate.clone()),
5061                    },
5062                    vec![case1_tree, case2_tree],
5063                )));
5064            }
5065        }
5066
5067        Ok(None)
5068    }
5069
5070    /// Find candidate predicates for case splitting.
5071    ///
5072    /// Looks for:
5073    /// 1. Self-referential predicates: P(c, c) where c is a Skolem constant
5074    /// 2. Predicates that appear in contradictory implications: P → ¬P and ¬P → P
5075    fn find_case_split_candidates(
5076        &self,
5077        context: &[ProofExpr],
5078        skolem_constants: &[String],
5079    ) -> Vec<ProofExpr> {
5080        let mut candidates = Vec::new();
5081
5082        // Strategy 1: Find self-referential predicates P(c, c)
5083        for expr in context {
5084            if let ProofExpr::Predicate { name, args, world } = expr {
5085                // Check if it's a binary predicate with the same Skolem constant twice
5086                if args.len() == 2 {
5087                    if let (ProofTerm::Constant(c1), ProofTerm::Constant(c2)) = (&args[0], &args[1])
5088                    {
5089                        if c1 == c2 && skolem_constants.contains(c1) {
5090                            candidates.push(expr.clone());
5091                        }
5092                    }
5093                }
5094            }
5095        }
5096
5097        // Strategy 2: Find predicates involved in cyclic implications
5098        // Look for patterns like: (P → ¬P) ∧ (¬P → P)
5099        let implications: Vec<(ProofExpr, ProofExpr)> = context
5100            .iter()
5101            .chain(self.knowledge_base.iter())
5102            .filter_map(|e| {
5103                if let ProofExpr::Implies(ante, cons) = e {
5104                    Some(((**ante).clone(), (**cons).clone()))
5105                } else {
5106                    None
5107                }
5108            })
5109            .collect();
5110
5111        for (ante, cons) in &implications {
5112            // Check for P → ¬P pattern
5113            if let ProofExpr::Not(inner) = cons {
5114                if exprs_structurally_equal(ante, inner) {
5115                    // Found P → ¬P, check if ¬P → P also exists
5116                    let neg_ante = ProofExpr::Not(Box::new(ante.clone()));
5117                    for (a2, c2) in &implications {
5118                        if exprs_structurally_equal(a2, &neg_ante)
5119                            && exprs_structurally_equal(c2, ante)
5120                        {
5121                            // Found the cyclic pair - ante is a good candidate
5122                            if !candidates.contains(ante) {
5123                                candidates.push(ante.clone());
5124                            }
5125                        }
5126                    }
5127                }
5128            }
5129        }
5130
5131        // Strategy 3: Generate self-referential predicates for Skolem constants
5132        // For each Skolem constant sk_N, look for predicates P and create P(sk_N, sk_N)
5133        for const_name in skolem_constants {
5134            // Look for action predicates in implications
5135            for expr in context.iter().chain(self.knowledge_base.iter()) {
5136                if let ProofExpr::Implies(ante, cons) = expr {
5137                    // Extract predicate names from consequences
5138                    self.extract_predicate_template(cons, const_name, &mut candidates);
5139                }
5140            }
5141        }
5142
5143        candidates
5144    }
5145
5146    /// Extract a predicate template and instantiate with a Skolem constant.
5147    fn extract_predicate_template(
5148        &self,
5149        expr: &ProofExpr,
5150        skolem: &str,
5151        candidates: &mut Vec<ProofExpr>,
5152    ) {
5153        match expr {
5154            ProofExpr::Predicate { name, args, world } if args.len() == 2 => {
5155                // Create a self-referential version: P(sk, sk)
5156                let self_ref = ProofExpr::Predicate {
5157                    name: name.clone(),
5158                    args: vec![
5159                        ProofTerm::Constant(skolem.to_string()),
5160                        ProofTerm::Constant(skolem.to_string()),
5161                    ],
5162                    world: world.clone(),
5163                };
5164                if !candidates.contains(&self_ref) {
5165                    candidates.push(self_ref);
5166                }
5167            }
5168            ProofExpr::Not(inner) => {
5169                self.extract_predicate_template(inner, skolem, candidates);
5170            }
5171            ProofExpr::NeoEvent { verb, .. } => {
5172                // Create abstracted predicate version
5173                let self_ref = ProofExpr::Predicate {
5174                    name: verb.to_lowercase(),
5175                    args: vec![
5176                        ProofTerm::Constant(skolem.to_string()),
5177                        ProofTerm::Constant(skolem.to_string()),
5178                    ],
5179                    world: None,
5180                };
5181                if !candidates.contains(&self_ref) {
5182                    candidates.push(self_ref);
5183                }
5184            }
5185            _ => {}
5186        }
5187    }
5188
5189    // =========================================================================
5190    // STRATEGY 5d: EXISTENTIAL ELIMINATION
5191    // =========================================================================
5192
5193    /// Try to eliminate existential quantifiers from premises.
5194    ///
5195    /// For each ∃x P(x) in the KB or context:
5196    /// 1. Generate a fresh Skolem constant c
5197    /// 2. Add P(c) to the context
5198    /// 3. Abstract any event semantics to simple predicates
5199    /// 4. Try to prove the goal with the extended context
5200    fn try_existential_elimination(
5201        &mut self,
5202        goal: &ProofGoal,
5203        depth: usize,
5204    ) -> ProofResult<Option<DerivationTree>> {
5205        // Depth guard to prevent infinite loops
5206        if depth > 8 {
5207            return Ok(None);
5208        }
5209
5210        // Find existential expressions in KB and context
5211        let existentials: Vec<ProofExpr> = self
5212            .knowledge_base
5213            .iter()
5214            .chain(goal.context.iter())
5215            .filter(|e| matches!(e, ProofExpr::Exists { .. }))
5216            .cloned()
5217            .collect();
5218
5219        if existentials.is_empty() {
5220            return Ok(None);
5221        }
5222
5223        // Try eliminating each existential
5224        for exist_expr in existentials {
5225            // Open each existential at most once per branch — re-opening it with a
5226            // fresh witness adds no facts the first opening did not, and only feeds
5227            // the depth-limit/oracle loop.
5228            if self
5229                .eliminated_existentials
5230                .iter()
5231                .any(|e| exprs_structurally_equal(e, &exist_expr))
5232            {
5233                continue;
5234            }
5235
5236            // Skolemize a single level, keeping the witness constant `c` so the
5237            // certificate's `Ex`-match binds the SAME constant the body is proved
5238            // over (the certifier mirrors this one elimination as one match).
5239            let Some((witness_const, witness_facts)) =
5240                self.skolemize_existential_with_const(&exist_expr)
5241            else {
5242                continue;
5243            };
5244
5245            if witness_facts.is_empty() {
5246                continue;
5247            }
5248
5249            // Abstract event semantics in witness facts
5250            let abstracted_facts: Vec<ProofExpr> = witness_facts
5251                .iter()
5252                .map(|f| self.abstract_all_events(f))
5253                .collect();
5254
5255            // Build extended context with witness facts
5256            let mut extended_context = goal.context.clone();
5257            for fact in &abstracted_facts {
5258                if !extended_context.contains(fact) {
5259                    extended_context.push(fact.clone());
5260                }
5261            }
5262
5263            // Also add the original witness facts (in case abstraction changes things)
5264            for fact in &witness_facts {
5265                if !extended_context.contains(fact) {
5266                    extended_context.push(fact.clone());
5267                }
5268            }
5269
5270            // Try to prove the goal with the extended context
5271            let extended_goal = ProofGoal::with_context(goal.target.clone(), extended_context);
5272
5273            // Mark this existential opened for the duration of the inner search,
5274            // then restore so sibling branches may open it themselves.
5275            self.eliminated_existentials.push(exist_expr.clone());
5276            let inner_result = self.prove_goal(extended_goal, depth + 1);
5277            self.eliminated_existentials.pop();
5278
5279            if let Ok(inner_proof) = inner_result {
5280                // The existential premise is discharged from the KB/context, so a
5281                // `PremiseMatch` leaf carrying `∃x.P(x)` is its derivation. The
5282                // certifier consumes `[existential, body]` and produces a single
5283                // `Ex`-match bound to `witness_const`, with the witness body's
5284                // conjuncts available to the body proof as projected hypotheses.
5285                let existential_premise =
5286                    DerivationTree::leaf(exist_expr.clone(), InferenceRule::PremiseMatch);
5287
5288                return Ok(Some(DerivationTree::new(
5289                    goal.target.clone(),
5290                    InferenceRule::ExistentialElim {
5291                        witness: witness_const,
5292                    },
5293                    vec![existential_premise, inner_proof],
5294                )));
5295            }
5296        }
5297
5298        Ok(None)
5299    }
5300
5301    /// Check if an expression contains quantifiers.
5302    fn contains_quantifier(&self, expr: &ProofExpr) -> bool {
5303        match expr {
5304            ProofExpr::ForAll { .. } | ProofExpr::Exists { .. } => true,
5305            ProofExpr::And(l, r)
5306            | ProofExpr::Or(l, r)
5307            | ProofExpr::Implies(l, r)
5308            | ProofExpr::Iff(l, r) => self.contains_quantifier(l) || self.contains_quantifier(r),
5309            ProofExpr::Not(inner) => self.contains_quantifier(inner),
5310            _ => false,
5311        }
5312    }
5313
5314    /// Skolemize an existential expression.
5315    ///
5316    /// Given ∃x P(x), introduce a fresh Skolem constant c and return P(c).
5317    /// For nested structures like ∃x((type(x) ∧ unique(x)) ∧ prop(x)),
5318    /// we extract the predicates with the Skolem constant.
5319    fn skolemize_existential(&mut self, expr: &ProofExpr) -> Vec<ProofExpr> {
5320        let mut results = Vec::new();
5321
5322        if let ProofExpr::Exists { variable, body } = expr {
5323            // Generate a fresh Skolem constant
5324            let skolem = format!("sk_{}", self.fresh_var());
5325
5326            let instantiated =
5327                instantiate_expr(body, variable, &ProofTerm::Constant(skolem.clone()));
5328
5329            // Flatten conjunctions into separate facts
5330            self.flatten_conjunction(&instantiated, &mut results);
5331
5332            // Handle nested existentials in the result
5333            let mut i = 0;
5334            while i < results.len() {
5335                if let ProofExpr::Exists { .. } = &results[i] {
5336                    let nested = results.remove(i);
5337                    let nested_skolem = self.skolemize_existential(&nested);
5338                    results.extend(nested_skolem);
5339                } else {
5340                    i += 1;
5341                }
5342            }
5343        }
5344
5345        results
5346    }
5347
5348    /// Skolemize a single level of an existential, exposing the witness constant.
5349    ///
5350    /// Given `∃x.P(x)`, introduce a fresh Skolem constant `c` and return
5351    /// `(c, [conjuncts of P(c)])` — the body instantiated at `c` and flattened
5352    /// into its top-level conjuncts. Unlike [`skolemize_existential`], this does
5353    /// NOT recurse into nested existentials in the result: it eliminates exactly
5354    /// one quantifier so the certifier can mirror it with a single `Ex`-match
5355    /// bound to `c`. The returned constant is recorded as the `ExistentialElim`
5356    /// witness so the certificate's Match-bound variable lines up with the facts
5357    /// the body proof references.
5358    fn skolemize_existential_with_const(
5359        &mut self,
5360        expr: &ProofExpr,
5361    ) -> Option<(String, Vec<ProofExpr>)> {
5362        if let ProofExpr::Exists { variable, body } = expr {
5363            let skolem = format!("sk_{}", self.fresh_var());
5364            let instantiated =
5365                instantiate_expr(body, variable, &ProofTerm::Constant(skolem.clone()));
5366            let mut results = Vec::new();
5367            self.flatten_conjunction(&instantiated, &mut results);
5368            Some((skolem, results))
5369        } else {
5370            None
5371        }
5372    }
5373
5374    /// Flatten a conjunction into a list of its components.
5375    fn flatten_conjunction(&self, expr: &ProofExpr, results: &mut Vec<ProofExpr>) {
5376        match expr {
5377            ProofExpr::And(left, right) => {
5378                self.flatten_conjunction(left, results);
5379                self.flatten_conjunction(right, results);
5380            }
5381            other => results.push(other.clone()),
5382        }
5383    }
5384
5385    // =========================================================================
5386    // DEFINITE DESCRIPTION SIMPLIFICATION
5387    // =========================================================================
5388
5389    // =========================================================================
5390    // EVENT SEMANTICS ABSTRACTION
5391    // =========================================================================
5392
5393    /// Abstract Neo-Davidsonian event semantics to simple predicates.
5394    ///
5395    /// Converts: ∃e(Shave(e) ∧ Agent(e, x) ∧ Theme(e, y)) → shaves(x, y)
5396    ///
5397    /// This allows the proof engine to reason about events using simpler
5398    /// predicate logic, which is essential for paradoxes like the Barber Paradox.
5399    fn abstract_event_to_predicate(&self, expr: &ProofExpr) -> Option<ProofExpr> {
5400        match expr {
5401            // Direct NeoEvent abstraction
5402            ProofExpr::NeoEvent { verb, roles, .. } => {
5403                // Extract Agent and Theme/Patient roles
5404                let agent = roles
5405                    .iter()
5406                    .find(|(role, _)| role == "Agent")
5407                    .map(|(_, term)| term.clone());
5408
5409                let theme = roles
5410                    .iter()
5411                    .find(|(role, _)| role == "Theme" || role == "Patient")
5412                    .map(|(_, term)| term.clone());
5413
5414                // Build a simple predicate: verb(agent, theme) or verb(agent)
5415                let mut args = Vec::new();
5416                if let Some(a) = agent {
5417                    args.push(a);
5418                }
5419                if let Some(t) = theme {
5420                    args.push(t);
5421                }
5422
5423                // Lowercase the verb for predicate naming convention
5424                let pred_name = verb.to_lowercase();
5425
5426                Some(ProofExpr::Predicate {
5427                    name: pred_name,
5428                    args,
5429                    world: None,
5430                })
5431            }
5432
5433            // Handle Exists wrapping an event expression
5434            ProofExpr::Exists { variable, body } => {
5435                // Check if this is an event quantification
5436                if !self.is_event_variable(variable) {
5437                    return None;
5438                }
5439
5440                // Try direct NeoEvent abstraction
5441                if let Some(abstracted) = self.abstract_event_to_predicate(body) {
5442                    return Some(abstracted);
5443                }
5444
5445                // Try to parse conjunction of event predicates
5446                // Pattern: ∃e(Verb(e) ∧ Agent(e, x) ∧ Theme(e, y)) → verb(x, y)
5447                if let Some(abstracted) = self.abstract_event_conjunction(variable, body) {
5448                    return Some(abstracted);
5449                }
5450
5451                None
5452            }
5453
5454            _ => None,
5455        }
5456    }
5457
5458    /// Abstract a conjunction of event predicates to a simple predicate.
5459    ///
5460    /// Handles: Verb(e) ∧ Agent(e, x) ∧ Theme(e, y) → verb(x, y)
5461    fn abstract_event_conjunction(&self, event_var: &str, body: &ProofExpr) -> Option<ProofExpr> {
5462        // Flatten the conjunction to get all components
5463        let mut components = Vec::new();
5464        self.flatten_conjunction(body, &mut components);
5465
5466        // Find verb predicate (single arg that matches event_var)
5467        let mut verb_name: Option<String> = None;
5468        let mut agent: Option<ProofTerm> = None;
5469        let mut theme: Option<ProofTerm> = None;
5470
5471        for comp in &components {
5472            if let ProofExpr::Predicate { name, args, .. } = comp {
5473                // Check if first arg is the event variable
5474                let first_is_event = args.first().map_or(false, |arg| {
5475                    matches!(arg, ProofTerm::Variable(v) | ProofTerm::BoundVarRef(v) if v == event_var)
5476                });
5477
5478                if !first_is_event && args.len() == 1 {
5479                    // Single arg predicate that's the event var
5480                    if let Some(ProofTerm::Variable(v) | ProofTerm::BoundVarRef(v)) = args.first() {
5481                        if v == event_var {
5482                            verb_name = Some(name.clone());
5483                            continue;
5484                        }
5485                    }
5486                }
5487
5488                if first_is_event {
5489                    match name.as_str() {
5490                        "Agent" if args.len() == 2 => {
5491                            agent = Some(args[1].clone());
5492                        }
5493                        "Theme" | "Patient" if args.len() == 2 => {
5494                            theme = Some(args[1].clone());
5495                        }
5496                        _ if args.len() == 1 && verb_name.is_none() => {
5497                            // This is probably the verb predicate: Verb(e)
5498                            verb_name = Some(name.clone());
5499                        }
5500                        _ => {}
5501                    }
5502                }
5503            }
5504        }
5505
5506        // If we found a verb, construct the simple predicate
5507        if let Some(verb) = verb_name {
5508            let mut args = Vec::new();
5509            if let Some(a) = agent {
5510                args.push(a);
5511            }
5512            if let Some(t) = theme {
5513                args.push(t);
5514            }
5515
5516            return Some(ProofExpr::Predicate {
5517                name: verb.to_lowercase(),
5518                args,
5519                world: None,
5520            });
5521        }
5522
5523        None
5524    }
5525
5526    /// Check if a variable name looks like an event variable.
5527    ///
5528    /// Event variables are typically named "e", "e1", "e2", etc.
5529    fn is_event_variable(&self, var: &str) -> bool {
5530        var == "e"
5531            || var.starts_with("e_")
5532            || (var.starts_with('e')
5533                && var.len() == 2
5534                && var.chars().nth(1).map_or(false, |c| c.is_ascii_digit()))
5535    }
5536
5537    /// Recursively abstract all events in an expression.
5538    ///
5539    /// This transforms the entire expression tree, replacing event semantics
5540    /// with simple predicates wherever possible. `pub(crate)` so the
5541    /// verify/certify boundary can register hypotheses and the goal in the
5542    /// SAME abstracted language the search runs in.
5543    pub(crate) fn abstract_all_events(&self, expr: &ProofExpr) -> ProofExpr {
5544        // First try direct abstraction
5545        if let Some(abstracted) = self.abstract_event_to_predicate(expr) {
5546            return abstracted;
5547        }
5548
5549        // Otherwise recurse into the structure
5550        match expr {
5551            ProofExpr::And(left, right) => ProofExpr::And(
5552                Box::new(self.abstract_all_events(left)),
5553                Box::new(self.abstract_all_events(right)),
5554            ),
5555            ProofExpr::Or(left, right) => ProofExpr::Or(
5556                Box::new(self.abstract_all_events(left)),
5557                Box::new(self.abstract_all_events(right)),
5558            ),
5559            ProofExpr::Implies(left, right) => ProofExpr::Implies(
5560                Box::new(self.abstract_all_events(left)),
5561                Box::new(self.abstract_all_events(right)),
5562            ),
5563            ProofExpr::Iff(left, right) => ProofExpr::Iff(
5564                Box::new(self.abstract_all_events(left)),
5565                Box::new(self.abstract_all_events(right)),
5566            ),
5567            ProofExpr::Not(inner) => {
5568                // Apply De Morgan for quantifiers: ¬∃x.P ≡ ∀x.¬P
5569                // This normalization is crucial for efficient proof search
5570                // (Converting negated existentials to universals helps the prover)
5571                if let ProofExpr::Exists { variable, body } = inner.as_ref() {
5572                    return self.requantify(
5573                        true,
5574                        variable,
5575                        self.abstract_all_events(&ProofExpr::Not(body.clone())),
5576                    );
5577                }
5578                // Note: We do NOT convert ¬∀x.P to ∃x.¬P because the prover
5579                // works better with universal quantifiers for backward chaining.
5580                ProofExpr::Not(Box::new(self.abstract_all_events(inner)))
5581            }
5582            ProofExpr::ForAll { variable, body } => {
5583                // Check for pattern: ∀x ¬(P ∧ Q) → ∀x (P → ¬Q)
5584                // This converts to implication form for better backward chaining
5585                if let ProofExpr::Not(inner) = body.as_ref() {
5586                    if let ProofExpr::And(left, right) = inner.as_ref() {
5587                        let implication = ProofExpr::Implies(
5588                            Box::new(self.abstract_all_events(left)),
5589                            Box::new(self.abstract_all_events(&ProofExpr::Not(right.clone()))),
5590                        );
5591                        return self.requantify(true, variable, implication);
5592                    }
5593                }
5594                self.requantify(true, variable, self.abstract_all_events(body))
5595            }
5596            ProofExpr::Exists { variable, body } => {
5597                // Check if this is an event quantification that should be abstracted
5598                if self.is_event_variable(variable) {
5599                    if let Some(abstracted) = self.abstract_event_to_predicate(body) {
5600                        return abstracted;
5601                    }
5602                }
5603                // Otherwise keep the existential and recurse
5604                self.requantify(false, variable, self.abstract_all_events(body))
5605            }
5606            // For other expressions, return as-is
5607            other => other.clone(),
5608        }
5609    }
5610
5611    /// Rebuild a quantifier over its abstracted body. Abstraction erases an event variable into
5612    /// the predicate its event becomes (`∃e(Bark(e) ∧ Agent(e, John))` is `bark(John)`), so a
5613    /// binder of that variable goes with it: `∀e((Bark(e) ∧ Agent(e, John)) → ψ)` is
5614    /// `bark(John) → ψ`. Left behind, the binder is vacuous, and a vacuous binder is one the
5615    /// search never instantiates. Every other binder stays.
5616    fn requantify(&self, universal: bool, variable: &str, body: ProofExpr) -> ProofExpr {
5617        if self.is_event_variable(variable) && !occurs_free(variable, &body) {
5618            return body;
5619        }
5620        let (variable, body) = (variable.to_string(), Box::new(body));
5621        if universal {
5622            ProofExpr::ForAll { variable, body }
5623        } else {
5624            ProofExpr::Exists { variable, body }
5625        }
5626    }
5627
5628    /// Abstract event semantics WITHOUT applying De Morgan transformations.
5629    ///
5630    /// This is used for goals where we want to preserve the ¬∃ pattern
5631    /// for reductio ad absurdum strategies.
5632    fn abstract_events_only(&self, expr: &ProofExpr) -> ProofExpr {
5633        // First try direct abstraction
5634        if let Some(abstracted) = self.abstract_event_to_predicate(expr) {
5635            return abstracted;
5636        }
5637
5638        // Otherwise recurse into the structure
5639        match expr {
5640            ProofExpr::And(left, right) => ProofExpr::And(
5641                Box::new(self.abstract_events_only(left)),
5642                Box::new(self.abstract_events_only(right)),
5643            ),
5644            ProofExpr::Or(left, right) => ProofExpr::Or(
5645                Box::new(self.abstract_events_only(left)),
5646                Box::new(self.abstract_events_only(right)),
5647            ),
5648            ProofExpr::Implies(left, right) => ProofExpr::Implies(
5649                Box::new(self.abstract_events_only(left)),
5650                Box::new(self.abstract_events_only(right)),
5651            ),
5652            ProofExpr::Iff(left, right) => ProofExpr::Iff(
5653                Box::new(self.abstract_events_only(left)),
5654                Box::new(self.abstract_events_only(right)),
5655            ),
5656            ProofExpr::Not(inner) => {
5657                // Just recurse, no De Morgan transformation
5658                ProofExpr::Not(Box::new(self.abstract_events_only(inner)))
5659            }
5660            ProofExpr::ForAll { variable, body } => {
5661                self.requantify(true, variable, self.abstract_events_only(body))
5662            }
5663            ProofExpr::Exists { variable, body } => {
5664                // Check if this is an event quantification that should be abstracted
5665                if self.is_event_variable(variable) {
5666                    if let Some(abstracted) = self.abstract_event_to_predicate(body) {
5667                        return abstracted;
5668                    }
5669                }
5670                // Otherwise keep the existential and recurse
5671                self.requantify(false, variable, self.abstract_events_only(body))
5672            }
5673            // For other expressions, return as-is
5674            other => other.clone(),
5675        }
5676    }
5677
5678    /// Look for a contradiction in the knowledge base and context.
5679    ///
5680    /// A contradiction exists when both P and ¬P are derivable.
5681    /// Find a contradiction in KB + context and return a **gapless** derivation
5682    /// the certifier can turn into a kernel proof of `False`.
5683    ///
5684    /// Unlike the heuristic [`find_contradiction`], every step here is justified
5685    /// by an explicit rule — `PremiseMatch`, `UniversalInst`, `ModusPonens`,
5686    /// `Contradiction` — so the resulting tree certifies end-to-end. It forward-
5687    /// chains over Horn-style rules (`A → C` and `∀x. A(x) → C(x)`) until some
5688    /// proposition `P` and its negation `¬P` are both derivable.
5689    ///
5690    /// This powers verified conflict detection on clean predicate rule sets. The
5691    /// heuristic finder remains for the paradox/reductio path (which needs a
5692    /// separate gapless-emission pass before it can certify).
5693    fn find_certifiable_contradiction(
5694        &self,
5695        context: &[ProofExpr],
5696        _depth: usize,
5697    ) -> ProofResult<Option<DerivationTree>> {
5698        let all: Vec<ProofExpr> = self
5699            .knowledge_base
5700            .iter()
5701            .chain(context.iter())
5702            .cloned()
5703            .collect();
5704        // Premises the all-true interpretation satisfies have a model, so no refutation of
5705        // them exists — and a case-splitting search for one would exhaust every split first.
5706        if all.iter().all(satisfied_when_everything_holds) {
5707            return Ok(None);
5708        }
5709        let rules = cert_extract_rules(&all);
5710        let seed = cert_seed_facts(&all);
5711        // `depth` bounds nested case splits / DPLL decisions. A small grid's
5712        // determined cells resolve by propagation within a few decisions; kept
5713        // moderate so the per-cell solve stays fast.
5714        let mut fresh = 0u32;
5715        Ok(cert_derive_falsum(&rules, &seed, 6, &mut fresh))
5716    }
5717
5718    fn find_contradiction(
5719        &mut self,
5720        context: &[ProofExpr],
5721        depth: usize,
5722    ) -> ProofResult<Option<DerivationTree>> {
5723        // Collect all expressions from KB and context
5724        let all_exprs: Vec<ProofExpr> = self
5725            .knowledge_base
5726            .iter()
5727            .chain(context.iter())
5728            .cloned()
5729            .collect();
5730
5731        // Strategy 1: Look for direct P and ¬P pairs
5732        for expr in &all_exprs {
5733            if let ProofExpr::Not(inner) = expr {
5734                // We have ¬P, check if P exists directly
5735                for other in &all_exprs {
5736                    if exprs_structurally_equal(other, inner) {
5737                        // Found both P and ¬P directly
5738                        let pos_leaf =
5739                            DerivationTree::leaf((**inner).clone(), InferenceRule::PremiseMatch);
5740                        let neg_leaf =
5741                            DerivationTree::leaf(expr.clone(), InferenceRule::PremiseMatch);
5742                        return Ok(Some(DerivationTree::new(
5743                            ProofExpr::Atom("⊥".into()),
5744                            InferenceRule::Contradiction,
5745                            vec![pos_leaf, neg_leaf],
5746                        )));
5747                    }
5748                }
5749            }
5750        }
5751
5752        // Strategy 2: Look for implications that derive contradictory results
5753        // Check if context fact P triggers P → ¬P (immediate contradiction)
5754        // Or if P triggers P → Q where ¬Q is also in context
5755        // Note: Extract implications from both top-level and inside ForAll quantifiers
5756        let mut implications: Vec<(ProofExpr, ProofExpr)> = Vec::new();
5757        for e in &all_exprs {
5758            if let ProofExpr::Implies(ante, cons) = e {
5759                implications.push(((**ante).clone(), (**cons).clone()));
5760            }
5761            // Also extract from inside ForAll (important for barber paradox!)
5762            if let ProofExpr::ForAll { body, .. } = e {
5763                if let ProofExpr::Implies(ante, cons) = body.as_ref() {
5764                    implications.push(((**ante).clone(), (**cons).clone()));
5765                }
5766            }
5767        }
5768
5769        // For each fact in the context, see if it triggers contradictory implications
5770        for fact in context {
5771            // Find all implications where fact matches the antecedent
5772            let mut derivable_consequences: Vec<ProofExpr> = Vec::new();
5773
5774            for (ante, cons) in &implications {
5775                // Try to unify the antecedent with the fact
5776                if let Ok(subst) = unify_exprs(fact, ante) {
5777                    let instantiated_cons = apply_subst_to_expr(cons, &subst);
5778                    derivable_consequences.push(instantiated_cons);
5779                }
5780
5781                // Also try matching conjunctive antecedents with multiple facts
5782                if let ProofExpr::And(left, right) = ante {
5783                    // Try to find facts matching both parts of the conjunction
5784                    if let Some(subst) =
5785                        self.try_match_conjunction_antecedent(left, right, &all_exprs)
5786                    {
5787                        let instantiated_cons = apply_subst_to_expr(cons, &subst);
5788                        if !derivable_consequences.contains(&instantiated_cons) {
5789                            derivable_consequences.push(instantiated_cons);
5790                        }
5791                    }
5792                }
5793            }
5794
5795            // Check if any derived consequence contradicts the triggering fact
5796            for cons in &derivable_consequences {
5797                // Check if cons = ¬fact (the classic barber structure: P → ¬P)
5798                if let ProofExpr::Not(inner) = cons {
5799                    if exprs_structurally_equal(inner, fact) {
5800                        // fact triggered an implication that derives ¬fact
5801                        // This is a contradiction: fact ∧ ¬fact
5802                        let pos_leaf =
5803                            DerivationTree::leaf(fact.clone(), InferenceRule::PremiseMatch);
5804                        let neg_leaf =
5805                            DerivationTree::leaf(cons.clone(), InferenceRule::ModusPonens);
5806                        return Ok(Some(DerivationTree::new(
5807                            ProofExpr::Atom("⊥".into()),
5808                            InferenceRule::Contradiction,
5809                            vec![pos_leaf, neg_leaf],
5810                        )));
5811                    }
5812                }
5813
5814                // Check if cons contradicts any other fact in context
5815                for other in context {
5816                    if std::ptr::eq(fact as *const _, other as *const _) {
5817                        continue; // Skip the triggering fact itself
5818                    }
5819                    // Check if cons = ¬other
5820                    if let ProofExpr::Not(inner) = cons {
5821                        if exprs_structurally_equal(inner, other) {
5822                            let pos_leaf =
5823                                DerivationTree::leaf(other.clone(), InferenceRule::PremiseMatch);
5824                            let neg_leaf =
5825                                DerivationTree::leaf(cons.clone(), InferenceRule::ModusPonens);
5826                            return Ok(Some(DerivationTree::new(
5827                                ProofExpr::Atom("⊥".into()),
5828                                InferenceRule::Contradiction,
5829                                vec![pos_leaf, neg_leaf],
5830                            )));
5831                        }
5832                    }
5833                    // Check if other = ¬cons
5834                    if let ProofExpr::Not(inner_other) = other {
5835                        if exprs_structurally_equal(inner_other, cons) {
5836                            let pos_leaf =
5837                                DerivationTree::leaf(cons.clone(), InferenceRule::ModusPonens);
5838                            let neg_leaf =
5839                                DerivationTree::leaf(other.clone(), InferenceRule::PremiseMatch);
5840                            return Ok(Some(DerivationTree::new(
5841                                ProofExpr::Atom("⊥".into()),
5842                                InferenceRule::Contradiction,
5843                                vec![pos_leaf, neg_leaf],
5844                            )));
5845                        }
5846                    }
5847                }
5848            }
5849
5850            // Check if any pair of consequences contradicts each other
5851            for i in 0..derivable_consequences.len() {
5852                for j in (i + 1)..derivable_consequences.len() {
5853                    let cons1 = &derivable_consequences[i];
5854                    let cons2 = &derivable_consequences[j];
5855
5856                    // Check if cons1 = ¬cons2 or cons2 = ¬cons1
5857                    if let ProofExpr::Not(inner1) = cons1 {
5858                        if exprs_structurally_equal(inner1, cons2) {
5859                            // cons1 = ¬cons2, contradiction!
5860                            let pos_leaf =
5861                                DerivationTree::leaf(cons2.clone(), InferenceRule::ModusPonens);
5862                            let neg_leaf =
5863                                DerivationTree::leaf(cons1.clone(), InferenceRule::ModusPonens);
5864                            return Ok(Some(DerivationTree::new(
5865                                ProofExpr::Atom("⊥".into()),
5866                                InferenceRule::Contradiction,
5867                                vec![pos_leaf, neg_leaf],
5868                            )));
5869                        }
5870                    }
5871                    if let ProofExpr::Not(inner2) = cons2 {
5872                        if exprs_structurally_equal(inner2, cons1) {
5873                            // cons2 = ¬cons1, contradiction!
5874                            let pos_leaf =
5875                                DerivationTree::leaf(cons1.clone(), InferenceRule::ModusPonens);
5876                            let neg_leaf =
5877                                DerivationTree::leaf(cons2.clone(), InferenceRule::ModusPonens);
5878                            return Ok(Some(DerivationTree::new(
5879                                ProofExpr::Atom("⊥".into()),
5880                                InferenceRule::Contradiction,
5881                                vec![pos_leaf, neg_leaf],
5882                            )));
5883                        }
5884                    }
5885                }
5886            }
5887        }
5888
5889        // Strategy 3: Try to find self-referential contradictions (like Barber Paradox)
5890        if let Some(proof) = self.find_self_referential_contradiction(context, depth)? {
5891            return Ok(Some(proof));
5892        }
5893
5894        Ok(None)
5895    }
5896
5897    /// Try to match a conjunctive antecedent with facts in the context.
5898    ///
5899    /// For an antecedent like (man(z) ∧ shave(z,z)), we need to find facts
5900    /// that match both parts with consistent variable bindings.
5901    fn try_match_conjunction_antecedent(
5902        &self,
5903        left: &ProofExpr,
5904        right: &ProofExpr,
5905        facts: &[ProofExpr],
5906    ) -> Option<Substitution> {
5907        // Try to find a fact that matches the left part
5908        for fact1 in facts {
5909            if let Ok(subst1) = unify_exprs(fact1, left) {
5910                // Apply this substitution to the right part
5911                let instantiated_right = apply_subst_to_expr(right, &subst1);
5912                // Now look for a fact that matches the instantiated right part
5913                for fact2 in facts {
5914                    if let Ok(subst2) = unify_exprs(fact2, &instantiated_right) {
5915                        // Combine substitutions
5916                        let mut combined = subst1.clone();
5917                        for (k, v) in subst2.iter() {
5918                            combined.insert(k.clone(), v.clone());
5919                        }
5920                        return Some(combined);
5921                    }
5922                }
5923            }
5924        }
5925        // Also try right then left
5926        for fact1 in facts {
5927            if let Ok(subst1) = unify_exprs(fact1, right) {
5928                let instantiated_left = apply_subst_to_expr(left, &subst1);
5929                for fact2 in facts {
5930                    if let Ok(subst2) = unify_exprs(fact2, &instantiated_left) {
5931                        let mut combined = subst1.clone();
5932                        for (k, v) in subst2.iter() {
5933                            combined.insert(k.clone(), v.clone());
5934                        }
5935                        return Some(combined);
5936                    }
5937                }
5938            }
5939        }
5940        None
5941    }
5942
5943    /// Special case: find self-referential contradictions (like the Barber Paradox).
5944    ///
5945    /// Pattern: If we have ∀x(P(x) → Q(b, x)) and ∀x(P(x) → ¬Q(b, x)),
5946    /// then for x = b with P(b), we get Q(b, b) ∧ ¬Q(b, b).
5947    ///
5948    /// This uses direct pattern matching WITHOUT recursive prove_goal calls
5949    /// to avoid infinite recursion.
5950    fn find_self_referential_contradiction(
5951        &mut self,
5952        context: &[ProofExpr],
5953        _depth: usize,
5954    ) -> ProofResult<Option<DerivationTree>> {
5955        // Collect all expressions from KB and context
5956        let all_exprs: Vec<ProofExpr> = self
5957            .knowledge_base
5958            .iter()
5959            .chain(context.iter())
5960            .cloned()
5961            .collect();
5962
5963        // Look for pairs of universal implications with contradictory conclusions
5964        // that can be instantiated with the same witness
5965        for expr1 in &all_exprs {
5966            if let ProofExpr::ForAll {
5967                variable: var1,
5968                body: body1,
5969            } = expr1
5970            {
5971                if let ProofExpr::Implies(ante1, cons1) = body1.as_ref() {
5972                    for expr2 in &all_exprs {
5973                        if std::ptr::eq(expr1, expr2) {
5974                            continue; // Skip same expression
5975                        }
5976                        if let ProofExpr::ForAll {
5977                            variable: var2,
5978                            body: body2,
5979                        } = expr2
5980                        {
5981                            if let ProofExpr::Implies(ante2, cons2) = body2.as_ref() {
5982                                // Check if cons2 = ¬cons1 (structurally)
5983                                if let ProofExpr::Not(neg_cons2) = cons2.as_ref() {
5984                                    // Check if cons1 and neg_cons2 have matching structure
5985                                    // For barber: cons1 = shaves(barber, x), neg_cons2 = shaves(barber, x)
5986
5987                                    // Try instantiating with x = barber (the self-referential case)
5988                                    // We look for constant terms in cons1 that could be witnesses
5989                                    let witnesses = self.extract_constants_from_expr(cons1);
5990
5991                                    for witness_name in &witnesses {
5992                                        let witness = ProofTerm::Constant(witness_name.clone());
5993
5994                                        // Instantiate both antecedents and consequents with this witness
5995                                        let ante1_inst = instantiate_expr(ante1, var1, &witness);
5996                                        let cons1_inst = instantiate_expr(cons1, var1, &witness);
5997
5998                                        let ante2_inst = instantiate_expr(ante2, var2, &witness);
5999                                        let cons2_inst = instantiate_expr(cons2, var2, &witness);
6000
6001                                        // Check if cons1_inst and ¬cons2_inst contradict
6002                                        // cons2_inst should be ¬X where X = cons1_inst
6003                                        if let ProofExpr::Not(inner2) = &cons2_inst {
6004                                            if exprs_structurally_equal(&cons1_inst, inner2) {
6005                                                // Now check if both antecedents could hold
6006                                                // ante1 typically is ¬P(x,x) and ante2 is P(x,x)
6007                                                // These are complementary - one must hold
6008                                                // For the paradox, we consider BOTH cases
6009
6010                                                // If ante1 = ¬P(x,x) and ante2 = P(x,x), and x = witness,
6011                                                // we have a tertium non datur case:
6012                                                // - Either P(w,w) holds → cons2_inst = ¬cons1_inst
6013                                                // - Or ¬P(w,w) holds → cons1_inst
6014
6015                                                // Check if ante1 and ante2 are complements
6016                                                if self.are_complements(&ante1_inst, &ante2_inst) {
6017                                                    // By excluded middle, one antecedent holds
6018                                                    // If cons1_inst and cons2_inst = ¬cons1_inst,
6019                                                    // we have a contradiction
6020                                                    let pos_leaf = DerivationTree::leaf(
6021                                                        cons1_inst.clone(),
6022                                                        InferenceRule::ModusPonens,
6023                                                    );
6024                                                    let neg_leaf = DerivationTree::leaf(
6025                                                        cons2_inst,
6026                                                        InferenceRule::ModusPonens,
6027                                                    );
6028                                                    return Ok(Some(DerivationTree::new(
6029                                                        ProofExpr::Atom("⊥".into()),
6030                                                        InferenceRule::Contradiction,
6031                                                        vec![pos_leaf, neg_leaf],
6032                                                    )));
6033                                                }
6034                                            }
6035                                        }
6036                                    }
6037                                }
6038                            }
6039                        }
6040                    }
6041                }
6042            }
6043        }
6044
6045        Ok(None)
6046    }
6047
6048    /// Check if two expressions are complements (one is the negation of the other).
6049    fn are_complements(&self, expr1: &ProofExpr, expr2: &ProofExpr) -> bool {
6050        // Check if expr1 = ¬expr2
6051        if let ProofExpr::Not(inner1) = expr1 {
6052            if exprs_structurally_equal(inner1, expr2) {
6053                return true;
6054            }
6055        }
6056        // Check if expr2 = ¬expr1
6057        if let ProofExpr::Not(inner2) = expr2 {
6058            if exprs_structurally_equal(inner2, expr1) {
6059                return true;
6060            }
6061        }
6062        false
6063    }
6064
6065    /// Extract constant names from an expression.
6066    fn extract_constants_from_expr(&self, expr: &ProofExpr) -> Vec<String> {
6067        let mut constants = Vec::new();
6068        self.extract_constants_recursive(expr, &mut constants);
6069        constants
6070    }
6071
6072    fn extract_constants_recursive(&self, expr: &ProofExpr, constants: &mut Vec<String>) {
6073        match expr {
6074            ProofExpr::Predicate { args, .. } => {
6075                for arg in args {
6076                    self.extract_constants_from_term_recursive(arg, constants);
6077                }
6078            }
6079            ProofExpr::Identity(l, r) => {
6080                self.extract_constants_from_term_recursive(l, constants);
6081                self.extract_constants_from_term_recursive(r, constants);
6082            }
6083            ProofExpr::And(l, r)
6084            | ProofExpr::Or(l, r)
6085            | ProofExpr::Implies(l, r)
6086            | ProofExpr::Iff(l, r) => {
6087                self.extract_constants_recursive(l, constants);
6088                self.extract_constants_recursive(r, constants);
6089            }
6090            ProofExpr::Not(inner) => {
6091                self.extract_constants_recursive(inner, constants);
6092            }
6093            ProofExpr::ForAll { body, .. } | ProofExpr::Exists { body, .. } => {
6094                self.extract_constants_recursive(body, constants);
6095            }
6096            _ => {}
6097        }
6098    }
6099
6100    fn extract_constants_from_term_recursive(&self, term: &ProofTerm, constants: &mut Vec<String>) {
6101        match term {
6102            ProofTerm::Constant(name) => {
6103                if !constants.contains(name) {
6104                    constants.push(name.clone());
6105                }
6106            }
6107            ProofTerm::Function(_, args) => {
6108                for arg in args {
6109                    self.extract_constants_from_term_recursive(arg, constants);
6110                }
6111            }
6112            ProofTerm::Group(terms) => {
6113                for t in terms {
6114                    self.extract_constants_from_term_recursive(t, constants);
6115                }
6116            }
6117            _ => {}
6118        }
6119    }
6120
6121    // =========================================================================
6122    // STRATEGY 6: EQUALITY REWRITING (LEIBNIZ'S LAW)
6123    // =========================================================================
6124
6125    /// Try rewriting using equalities in the knowledge base.
6126    ///
6127    /// Leibniz's Law: If a = b and P(a), then P(b).
6128    /// Also handles symmetry (a = b ⊢ b = a) and transitivity (a = b, b = c ⊢ a = c).
6129    fn try_equality_rewrite(
6130        &mut self,
6131        goal: &ProofGoal,
6132        depth: usize,
6133    ) -> ProofResult<Option<DerivationTree>> {
6134        // Collect equalities from KB and context
6135        let equalities: Vec<(ProofTerm, ProofTerm)> = self
6136            .knowledge_base
6137            .iter()
6138            .chain(goal.context.iter())
6139            .filter_map(|expr| {
6140                if let ProofExpr::Identity(l, r) = expr {
6141                    Some((l.clone(), r.clone()))
6142                } else {
6143                    None
6144                }
6145            })
6146            .collect();
6147
6148        if equalities.is_empty() {
6149            return Ok(None);
6150        }
6151
6152        // Handle special case: goal is itself an equality (symmetry/transitivity)
6153        if let ProofExpr::Identity(goal_l, goal_r) = &goal.target {
6154            // Try symmetry: a = b ⊢ b = a
6155            if let Some(tree) = self.try_equality_symmetry(goal_l, goal_r, &equalities, depth)? {
6156                return Ok(Some(tree));
6157            }
6158
6159            // Try transitivity: a = b, b = c ⊢ a = c
6160            if let Some(tree) =
6161                self.try_equality_transitivity(goal_l, goal_r, &equalities, depth)?
6162            {
6163                return Ok(Some(tree));
6164            }
6165
6166            // Try equational rewriting: use axioms to rewrite LHS step by step
6167            // Only if we have depth budget remaining (prevents infinite recursion)
6168            if depth + 3 < self.max_depth {
6169                if let Some(tree) =
6170                    self.try_equational_identity_rewrite(goal, goal_l, goal_r, depth)?
6171                {
6172                    return Ok(Some(tree));
6173                }
6174            }
6175
6176            // General congruence closure: `F(a)=F(b)` from `a=b`, closed through
6177            // transitivity and nested applications ("equals added to equals").
6178            if let Some(tree) = self.try_congruence(goal)? {
6179                return Ok(Some(tree));
6180            }
6181
6182            return Ok(None);
6183        }
6184
6185        // Try rewriting: substitute one term for another (for non-Identity goals)
6186        for (eq_from, eq_to) in &equalities {
6187            // Try forward: a = b, P(a) ⊢ P(b)
6188            if let Some(tree) = self.try_rewrite_with_equality(goal, eq_from, eq_to, depth)? {
6189                return Ok(Some(tree));
6190            }
6191
6192            // Try backward: a = b, P(b) ⊢ P(a)
6193            if let Some(tree) = self.try_rewrite_with_equality(goal, eq_to, eq_from, depth)? {
6194                return Ok(Some(tree));
6195            }
6196        }
6197
6198        Ok(None)
6199    }
6200
6201    /// Try to prove goal by substituting `from` with `to` in some known fact.
6202    fn try_rewrite_with_equality(
6203        &mut self,
6204        goal: &ProofGoal,
6205        from: &ProofTerm,
6206        to: &ProofTerm,
6207        depth: usize,
6208    ) -> ProofResult<Option<DerivationTree>> {
6209        // Create the "source" expression by substituting `to` with `from` in the goal
6210        // If goal is P(b) and we have a = b, we want to find P(a)
6211        let source_goal = self.substitute_term_in_expr(&goal.target, to, from);
6212
6213        // Check if source_goal differs from the goal (substitution had effect)
6214        if source_goal == goal.target {
6215            return Ok(None);
6216        }
6217
6218        // Try to prove the source goal
6219        let source_proof_goal = ProofGoal::with_context(source_goal.clone(), goal.context.clone());
6220        if let Ok(source_proof) = self.prove_goal(source_proof_goal, depth + 1) {
6221            // Also need a proof of the equality
6222            let equality = ProofExpr::Identity(from.clone(), to.clone());
6223            let eq_proof_goal = ProofGoal::with_context(equality.clone(), goal.context.clone());
6224
6225            if let Ok(eq_proof) = self.prove_goal(eq_proof_goal, depth + 1) {
6226                return Ok(Some(DerivationTree::new(
6227                    goal.target.clone(),
6228                    InferenceRule::Rewrite {
6229                        from: from.clone(),
6230                        to: to.clone(),
6231                    },
6232                    vec![eq_proof, source_proof],
6233                )));
6234            }
6235        }
6236
6237        Ok(None)
6238    }
6239
6240    /// Try equality symmetry: a = b ⊢ b = a
6241    fn try_equality_symmetry(
6242        &mut self,
6243        goal_l: &ProofTerm,
6244        goal_r: &ProofTerm,
6245        equalities: &[(ProofTerm, ProofTerm)],
6246        _depth: usize,
6247    ) -> ProofResult<Option<DerivationTree>> {
6248        // Check if we have r = l in KB (so we can derive l = r)
6249        for (eq_l, eq_r) in equalities {
6250            if eq_l == goal_r && eq_r == goal_l {
6251                // Found r = l, can derive l = r by symmetry
6252                let source = ProofExpr::Identity(goal_r.clone(), goal_l.clone());
6253                return Ok(Some(DerivationTree::new(
6254                    ProofExpr::Identity(goal_l.clone(), goal_r.clone()),
6255                    InferenceRule::EqualitySymmetry,
6256                    vec![DerivationTree::leaf(source, InferenceRule::PremiseMatch)],
6257                )));
6258            }
6259        }
6260        Ok(None)
6261    }
6262
6263    /// Prove an `Identity` goal by congruence closure over the known equalities
6264    /// (knowledge base + local context). Decision and proof reconstruction live in
6265    /// [`cert_congruence_path`]; every emitted node certifies, so a spurious
6266    /// congruence would fail the kernel rather than admit a false equation.
6267    fn try_congruence(&mut self, goal: &ProofGoal) -> ProofResult<Option<DerivationTree>> {
6268        let ProofExpr::Identity(lhs, rhs) = &goal.target else {
6269            return Ok(None);
6270        };
6271        let hyps: Vec<(ProofExpr, DerivationTree)> = self
6272            .knowledge_base
6273            .iter()
6274            .chain(goal.context.iter())
6275            .filter_map(|e| match e {
6276                ProofExpr::Identity(l, r) => Some((
6277                    e.clone(),
6278                    DerivationTree::leaf(
6279                        ProofExpr::Identity(l.clone(), r.clone()),
6280                        InferenceRule::PremiseMatch,
6281                    ),
6282                )),
6283                _ => None,
6284            })
6285            .collect();
6286        if hyps.is_empty() {
6287            return Ok(None);
6288        }
6289        Ok(cert_congruence_path(lhs, rhs, &hyps))
6290    }
6291
6292    /// Prove an inequality goal `a ≤ b` (encoded `le(a, b) = true`) by chaining the
6293    /// known `≤` facts transitively. The directed-graph search and proof
6294    /// reconstruction live in [`cert_le_path`]; every node certifies via the
6295    /// `le_trans`/`le_refl` axioms, so a spurious chain fails the kernel.
6296    fn try_linarith(
6297        &mut self,
6298        goal: &ProofGoal,
6299        depth: usize,
6300    ) -> ProofResult<Option<DerivationTree>> {
6301        // A STRICT goal composes through the same chain, tightened: `a < b` is `a + 1 ≤ b`
6302        // over ℤ. It is gated on the trusted base actually having a primitive that concludes
6303        // a `lt` — see `strict_conclusions_available`.
6304        if let Some((sa, sb)) = crate::omega_solve::as_lt_pair(&goal.target) {
6305            if let (Some(av), Some(bv)) = (as_int_literal(&sa), as_int_literal(&sb)) {
6306                return Ok((av < bv).then(|| {
6307                    DerivationTree::leaf(goal.target.clone(), InferenceRule::Reflexivity)
6308                }));
6309            }
6310            let known: Vec<(ProofExpr, DerivationTree)> = goal
6311                .context
6312                .iter()
6313                .chain(self.knowledge_base.iter())
6314                .map(|e| {
6315                    (
6316                        e.clone(),
6317                        DerivationTree::leaf(e.clone(), InferenceRule::PremiseMatch),
6318                    )
6319                })
6320                .collect();
6321            return Ok(cert_lt_chain(&known, &sa, &sb));
6322        }
6323        let Some((ga, gb)) = as_le_pair(&goal.target) else {
6324            return Ok(None);
6325        };
6326        // Ground case: both operands are literals — decided by computation. `le m n`
6327        // reduces to `true`/`false`, so `m ≤ n` closes by reflexivity exactly when it
6328        // holds (and is left unproven, soundly, when it does not).
6329        if let (Some(av), Some(bv)) = (as_int_literal(&ga), as_int_literal(&gb)) {
6330            return Ok((av <= bv)
6331                .then(|| DerivationTree::leaf(goal.target.clone(), InferenceRule::Reflexivity)));
6332        }
6333        // Addition: `a + c ≤ b + d` from `a ≤ b` and `c ≤ d`, each proved recursively
6334        // (a Farkas primitive — `le_add_mono`).
6335        if let (ProofTerm::Function(fl, la), ProofTerm::Function(fr, ra)) = (&ga, &gb) {
6336            if fl == "add" && fr == "add" && la.len() == 2 && ra.len() == 2 {
6337                let g0 = ProofGoal::with_context(
6338                    le_eq(la[0].clone(), ra[0].clone()),
6339                    goal.context.clone(),
6340                );
6341                let g1 = ProofGoal::with_context(
6342                    le_eq(la[1].clone(), ra[1].clone()),
6343                    goal.context.clone(),
6344                );
6345                if let (Ok(p0), Ok(p1)) = (
6346                    self.prove_goal(g0, depth + 1),
6347                    self.prove_goal(g1, depth + 1),
6348                ) {
6349                    return Ok(Some(DerivationTree::new(
6350                        goal.target.clone(),
6351                        InferenceRule::LeAddMono,
6352                        vec![p0, p1],
6353                    )));
6354                }
6355            }
6356        }
6357        // The mixed-relation chain: `≤` edges AND equality edges, composed. `calc`'s job.
6358        let known: Vec<(ProofExpr, DerivationTree)> = goal
6359            .context
6360            .iter()
6361            .chain(self.knowledge_base.iter())
6362            .map(|e| {
6363                (
6364                    e.clone(),
6365                    DerivationTree::leaf(e.clone(), InferenceRule::PremiseMatch),
6366                )
6367            })
6368            .collect();
6369        Ok(cert_le_chain(&known, &ga, &gb))
6370    }
6371
6372    /// Try equality transitivity: a = b, b = c ⊢ a = c
6373    fn try_equality_transitivity(
6374        &mut self,
6375        goal_l: &ProofTerm,
6376        goal_r: &ProofTerm,
6377        equalities: &[(ProofTerm, ProofTerm)],
6378        _depth: usize,
6379    ) -> ProofResult<Option<DerivationTree>> {
6380        // Look for a = b and b = c where we want a = c
6381        for (eq1_l, eq1_r) in equalities {
6382            if eq1_l == goal_l {
6383                // Found a = b, now look for b = c
6384                for (eq2_l, eq2_r) in equalities {
6385                    if eq2_l == eq1_r && eq2_r == goal_r {
6386                        // Found a = b and b = c, derive a = c
6387                        let premise1 = ProofExpr::Identity(eq1_l.clone(), eq1_r.clone());
6388                        let premise2 = ProofExpr::Identity(eq2_l.clone(), eq2_r.clone());
6389                        return Ok(Some(DerivationTree::new(
6390                            ProofExpr::Identity(goal_l.clone(), goal_r.clone()),
6391                            InferenceRule::EqualityTransitivity,
6392                            vec![
6393                                DerivationTree::leaf(premise1, InferenceRule::PremiseMatch),
6394                                DerivationTree::leaf(premise2, InferenceRule::PremiseMatch),
6395                            ],
6396                        )));
6397                    }
6398                }
6399            }
6400        }
6401        Ok(None)
6402    }
6403
6404    /// Try equational rewriting for Identity goals.
6405    ///
6406    /// For a goal `f(a) = b`, find an axiom `f(x) = g(x)` that matches,
6407    /// rewrite to get `g(a) = b`, and recursively prove that.
6408    fn try_equational_identity_rewrite(
6409        &mut self,
6410        goal: &ProofGoal,
6411        goal_l: &ProofTerm,
6412        goal_r: &ProofTerm,
6413        depth: usize,
6414    ) -> ProofResult<Option<DerivationTree>> {
6415        // First, try congruence: if both sides have the same outermost function/ctor,
6416        // recursively prove the arguments are equal.
6417        if let (ProofTerm::Function(name_l, args_l), ProofTerm::Function(name_r, args_r)) =
6418            (goal_l, goal_r)
6419        {
6420            if name_l == name_r && args_l.len() == args_r.len() {
6421                // Prove each differing argument equal; identical arguments need no
6422                // rewrite. (`None` marks a position left untouched.)
6423                let mut arg_proofs: Vec<Option<DerivationTree>> = Vec::new();
6424                let mut all_ok = true;
6425                for (arg_l, arg_r) in args_l.iter().zip(args_r.iter()) {
6426                    if arg_l == arg_r {
6427                        arg_proofs.push(None);
6428                        continue;
6429                    }
6430                    let arg_goal_expr = ProofExpr::Identity(arg_l.clone(), arg_r.clone());
6431                    let arg_goal = ProofGoal::with_context(arg_goal_expr, goal.context.clone());
6432                    match self.prove_goal(arg_goal, depth + 1) {
6433                        Ok(proof) => arg_proofs.push(Some(proof)),
6434                        Err(_) => {
6435                            all_ok = false;
6436                            break;
6437                        }
6438                    }
6439                }
6440                if all_ok {
6441                    // Congruence: `f(a₀…) = f(b₀…)`, each differing argument rewritten
6442                    // in turn via `Rewrite` (Leibniz) — a real certificate, not a
6443                    // reflexivity placeholder that ignores the argument proofs. `None`
6444                    // when no motive reproduces the running source, in which case there is
6445                    // nothing certifiable to return and the search moves on.
6446                    if let Some(proof) = build_congruence_proof(name_l, args_l, args_r, &arg_proofs)
6447                    {
6448                        return Ok(Some(proof));
6449                    }
6450                }
6451            }
6452        }
6453        // Collect Identity axioms from KB
6454        let axioms: Vec<(ProofTerm, ProofTerm)> = self
6455            .knowledge_base
6456            .iter()
6457            .filter_map(|e| {
6458                if let ProofExpr::Identity(l, r) = e {
6459                    Some((l.clone(), r.clone()))
6460                } else {
6461                    None
6462                }
6463            })
6464            .collect();
6465
6466        // Try each axiom to rewrite the goal's LHS
6467        for (axiom_l, axiom_r) in &axioms {
6468            // Rename variables in axiom to avoid capture (use same map for both sides!)
6469            let mut var_map = std::collections::HashMap::new();
6470            let renamed_l = self.rename_term_vars_with_map(axiom_l, &mut var_map);
6471            let renamed_r = self.rename_term_vars_with_map(axiom_r, &mut var_map);
6472
6473            // Try to unify axiom LHS with goal LHS
6474            // e.g., unify(Add(Succ(k), n), Add(Succ(Zero), Succ(Zero)))
6475            //       => {k: Zero, n: Succ(Zero)}
6476            if let Ok(subst) = unify_terms(&renamed_l, goal_l) {
6477                // Apply substitution to axiom RHS to get the rewritten term
6478                let rewritten = self.apply_subst_to_term(&renamed_r, &subst);
6479
6480                // Direct hit: the axiom's instance IS the goal. The node cites the equation
6481                // AT THE INSTANCE the rewrite used — the proposition the step actually
6482                // depends on — and records the substitution that produced it, so the tree
6483                // says what it assumed rather than naming the schema and leaving a reader to
6484                // guess which instance was meant.
6485                //
6486                // Whether the instance is LICENSED is the knowledge base's question, not the
6487                // search's, and [`PremiseVariables`] is where its owner answers it. Under the
6488                // SCHEMATIC reading — a rewrite system handed straight to `add_axiom` — the
6489                // step is the whole point: `Add(S Z, S Z) = S (S Z)` from the two Peano
6490                // equations is pure rewriting. Under the LOCAL reading — premises that are
6491                // kernel hypotheses, whose free variables the trust door registers as context
6492                // locals — the instance is a proposition no context carries, so the step is
6493                // not taken at all and no layer above can report it.
6494                //
6495                // An EMPTY substitution used the equation as stated, which both readings
6496                // license, so it never depends on the flag.
6497                if terms_structurally_equal(&rewritten, goal_r) {
6498                    if subst.is_empty() || self.premise_variables == PremiseVariables::Schematic {
6499                        return Ok(Some(
6500                            DerivationTree::leaf(
6501                                ProofExpr::Identity(goal_l.clone(), rewritten.clone()),
6502                                InferenceRule::PremiseMatch,
6503                            )
6504                            .with_substitution(subst),
6505                        ));
6506                    }
6507                    continue;
6508                }
6509
6510                // Otherwise, create a new goal with the rewritten LHS
6511                let new_goal_expr = ProofExpr::Identity(rewritten.clone(), goal_r.clone());
6512                let new_goal = ProofGoal::with_context(new_goal_expr.clone(), goal.context.clone());
6513
6514                // Recursively try to prove the new goal
6515                if let Ok(sub_proof) = self.prove_goal(new_goal, depth + 1) {
6516                    // `goal_l = rewritten` followed by `rewritten = goal_r` is TRANSITIVITY,
6517                    // not Leibniz: the `Rewrite` node this used to build put the axiom where
6518                    // the certifier expects a proof of `from = to` and the sub-proof where it
6519                    // expects `P from`, so the motive it computed was inhabited by neither.
6520                    // The first half is the equation at the instance the rewrite used — the
6521                    // same node, and the same licensing question, as the direct hit above.
6522                    if subst.is_empty() || self.premise_variables == PremiseVariables::Schematic {
6523                        return Ok(Some(DerivationTree::new(
6524                            goal.target.clone(),
6525                            InferenceRule::EqualityTransitivity,
6526                            vec![
6527                                DerivationTree::leaf(
6528                                    ProofExpr::Identity(goal_l.clone(), rewritten.clone()),
6529                                    InferenceRule::PremiseMatch,
6530                                )
6531                                .with_substitution(subst),
6532                                sub_proof,
6533                            ],
6534                        )));
6535                    }
6536                    continue;
6537                }
6538            }
6539        }
6540
6541        Ok(None)
6542    }
6543
6544    /// Rename variables in a term to fresh names (consistently).
6545    fn rename_term_vars(&mut self, term: &ProofTerm) -> ProofTerm {
6546        let mut var_map = std::collections::HashMap::new();
6547        self.rename_term_vars_with_map(term, &mut var_map)
6548    }
6549
6550    fn rename_term_vars_with_map(
6551        &mut self,
6552        term: &ProofTerm,
6553        var_map: &mut std::collections::HashMap<String, String>,
6554    ) -> ProofTerm {
6555        match term {
6556            ProofTerm::Variable(name) => {
6557                // Check if we've already renamed this variable
6558                if let Some(fresh) = var_map.get(name) {
6559                    ProofTerm::Variable(fresh.clone())
6560                } else {
6561                    // Create fresh name and remember it
6562                    let fresh = format!("_v{}", self.var_counter);
6563                    self.var_counter += 1;
6564                    var_map.insert(name.clone(), fresh.clone());
6565                    ProofTerm::Variable(fresh)
6566                }
6567            }
6568            ProofTerm::Function(name, args) => ProofTerm::Function(
6569                name.clone(),
6570                args.iter()
6571                    .map(|a| self.rename_term_vars_with_map(a, var_map))
6572                    .collect(),
6573            ),
6574            ProofTerm::Group(terms) => ProofTerm::Group(
6575                terms
6576                    .iter()
6577                    .map(|t| self.rename_term_vars_with_map(t, var_map))
6578                    .collect(),
6579            ),
6580            other => other.clone(),
6581        }
6582    }
6583
6584    /// Apply a substitution to a term.
6585    fn apply_subst_to_term(&self, term: &ProofTerm, subst: &Substitution) -> ProofTerm {
6586        match term {
6587            ProofTerm::Variable(name) => {
6588                if let Some(replacement) = subst.get(name) {
6589                    replacement.clone()
6590                } else {
6591                    term.clone()
6592                }
6593            }
6594            ProofTerm::Function(name, args) => ProofTerm::Function(
6595                name.clone(),
6596                args.iter()
6597                    .map(|a| self.apply_subst_to_term(a, subst))
6598                    .collect(),
6599            ),
6600            ProofTerm::Group(terms) => ProofTerm::Group(
6601                terms
6602                    .iter()
6603                    .map(|t| self.apply_subst_to_term(t, subst))
6604                    .collect(),
6605            ),
6606            other => other.clone(),
6607        }
6608    }
6609
6610    /// Substitute a term for another in an expression.
6611    /// Substitute only FREE occurrences of a variable: binders that shadow the
6612    /// name (∀x, ∃x, λx) leave their bodies untouched. Used to bind anaphoric
6613    /// free variables (discourse-telescoped definite descriptions) without
6614    /// capturing unrelated bound variables that share the name.
6615    fn substitute_free_var_in_expr(
6616        &self,
6617        expr: &ProofExpr,
6618        var_name: &str,
6619        to: &ProofTerm,
6620    ) -> ProofExpr {
6621        fn in_term(term: &ProofTerm, var_name: &str, to: &ProofTerm) -> ProofTerm {
6622            match term {
6623                ProofTerm::Variable(v) if v == var_name => to.clone(),
6624                ProofTerm::Function(name, args) => ProofTerm::Function(
6625                    name.clone(),
6626                    args.iter().map(|a| in_term(a, var_name, to)).collect(),
6627                ),
6628                ProofTerm::Group(terms) => {
6629                    ProofTerm::Group(terms.iter().map(|t| in_term(t, var_name, to)).collect())
6630                }
6631                other => other.clone(),
6632            }
6633        }
6634
6635        match expr {
6636            ProofExpr::Predicate { name, args, world } => ProofExpr::Predicate {
6637                name: name.clone(),
6638                args: args.iter().map(|a| in_term(a, var_name, to)).collect(),
6639                world: world.clone(),
6640            },
6641            ProofExpr::Identity(l, r) => {
6642                ProofExpr::Identity(in_term(l, var_name, to), in_term(r, var_name, to))
6643            }
6644            ProofExpr::NeoEvent {
6645                event_var,
6646                verb,
6647                roles,
6648            } => ProofExpr::NeoEvent {
6649                event_var: event_var.clone(),
6650                verb: verb.clone(),
6651                roles: roles
6652                    .iter()
6653                    .map(|(role, t)| (role.clone(), in_term(t, var_name, to)))
6654                    .collect(),
6655            },
6656            ProofExpr::And(l, r) => ProofExpr::And(
6657                Box::new(self.substitute_free_var_in_expr(l, var_name, to)),
6658                Box::new(self.substitute_free_var_in_expr(r, var_name, to)),
6659            ),
6660            ProofExpr::Or(l, r) => ProofExpr::Or(
6661                Box::new(self.substitute_free_var_in_expr(l, var_name, to)),
6662                Box::new(self.substitute_free_var_in_expr(r, var_name, to)),
6663            ),
6664            ProofExpr::Implies(l, r) => ProofExpr::Implies(
6665                Box::new(self.substitute_free_var_in_expr(l, var_name, to)),
6666                Box::new(self.substitute_free_var_in_expr(r, var_name, to)),
6667            ),
6668            ProofExpr::Iff(l, r) => ProofExpr::Iff(
6669                Box::new(self.substitute_free_var_in_expr(l, var_name, to)),
6670                Box::new(self.substitute_free_var_in_expr(r, var_name, to)),
6671            ),
6672            ProofExpr::Not(inner) => ProofExpr::Not(Box::new(
6673                self.substitute_free_var_in_expr(inner, var_name, to),
6674            )),
6675            ProofExpr::ForAll { variable, body } if variable != var_name => ProofExpr::ForAll {
6676                variable: variable.clone(),
6677                body: Box::new(self.substitute_free_var_in_expr(body, var_name, to)),
6678            },
6679            ProofExpr::Exists { variable, body } if variable != var_name => ProofExpr::Exists {
6680                variable: variable.clone(),
6681                body: Box::new(self.substitute_free_var_in_expr(body, var_name, to)),
6682            },
6683            ProofExpr::Lambda { variable, body } if variable != var_name => ProofExpr::Lambda {
6684                variable: variable.clone(),
6685                body: Box::new(self.substitute_free_var_in_expr(body, var_name, to)),
6686            },
6687            ProofExpr::Modal {
6688                domain,
6689                force,
6690                flavor,
6691                body,
6692            } => ProofExpr::Modal {
6693                domain: domain.clone(),
6694                force: *force,
6695                flavor: flavor.clone(),
6696                body: Box::new(self.substitute_free_var_in_expr(body, var_name, to)),
6697            },
6698            ProofExpr::Temporal { operator, body } => ProofExpr::Temporal {
6699                operator: operator.clone(),
6700                body: Box::new(self.substitute_free_var_in_expr(body, var_name, to)),
6701            },
6702            ProofExpr::TemporalBinary {
6703                operator,
6704                left,
6705                right,
6706            } => ProofExpr::TemporalBinary {
6707                operator: operator.clone(),
6708                left: Box::new(self.substitute_free_var_in_expr(left, var_name, to)),
6709                right: Box::new(self.substitute_free_var_in_expr(right, var_name, to)),
6710            },
6711            // Shadowing binders (the guards above failed) and atoms pass through.
6712            other => other.clone(),
6713        }
6714    }
6715
6716    fn substitute_term_in_expr(
6717        &self,
6718        expr: &ProofExpr,
6719        from: &ProofTerm,
6720        to: &ProofTerm,
6721    ) -> ProofExpr {
6722        match expr {
6723            ProofExpr::Predicate { name, args, world } => {
6724                let new_args: Vec<_> = args
6725                    .iter()
6726                    .map(|arg| self.substitute_in_term(arg, from, to))
6727                    .collect();
6728                ProofExpr::Predicate {
6729                    name: name.clone(),
6730                    args: new_args,
6731                    world: world.clone(),
6732                }
6733            }
6734            ProofExpr::Identity(l, r) => ProofExpr::Identity(
6735                self.substitute_in_term(l, from, to),
6736                self.substitute_in_term(r, from, to),
6737            ),
6738            ProofExpr::And(l, r) => ProofExpr::And(
6739                Box::new(self.substitute_term_in_expr(l, from, to)),
6740                Box::new(self.substitute_term_in_expr(r, from, to)),
6741            ),
6742            ProofExpr::Or(l, r) => ProofExpr::Or(
6743                Box::new(self.substitute_term_in_expr(l, from, to)),
6744                Box::new(self.substitute_term_in_expr(r, from, to)),
6745            ),
6746            ProofExpr::Implies(l, r) => ProofExpr::Implies(
6747                Box::new(self.substitute_term_in_expr(l, from, to)),
6748                Box::new(self.substitute_term_in_expr(r, from, to)),
6749            ),
6750            ProofExpr::Not(inner) => {
6751                ProofExpr::Not(Box::new(self.substitute_term_in_expr(inner, from, to)))
6752            }
6753            ProofExpr::ForAll { variable, body } => ProofExpr::ForAll {
6754                variable: variable.clone(),
6755                body: Box::new(self.substitute_term_in_expr(body, from, to)),
6756            },
6757            ProofExpr::Exists { variable, body } => ProofExpr::Exists {
6758                variable: variable.clone(),
6759                body: Box::new(self.substitute_term_in_expr(body, from, to)),
6760            },
6761            // For other expressions, return as-is
6762            other => other.clone(),
6763        }
6764    }
6765
6766    /// Substitute a term for another in a ProofTerm.
6767    fn substitute_in_term(&self, term: &ProofTerm, from: &ProofTerm, to: &ProofTerm) -> ProofTerm {
6768        if term == from {
6769            return to.clone();
6770        }
6771        match term {
6772            ProofTerm::Function(name, args) => {
6773                let new_args: Vec<_> = args
6774                    .iter()
6775                    .map(|arg| self.substitute_in_term(arg, from, to))
6776                    .collect();
6777                ProofTerm::Function(name.clone(), new_args)
6778            }
6779            ProofTerm::Group(terms) => {
6780                let new_terms: Vec<_> = terms
6781                    .iter()
6782                    .map(|t| self.substitute_in_term(t, from, to))
6783                    .collect();
6784                ProofTerm::Group(new_terms)
6785            }
6786            other => other.clone(),
6787        }
6788    }
6789
6790    // =========================================================================
6791    // STRATEGY 7: STRUCTURAL INDUCTION
6792    // =========================================================================
6793
6794    /// Try structural induction on inductive types (Nat, List, etc.).
6795    ///
6796    /// First attempts to infer the motive using Miller pattern unification
6797    /// (`?Motive(#n) = Goal` → `?Motive = λn.Goal`). Falls back to crude
6798    /// substitution if pattern unification fails.
6799    ///
6800    /// When the goal contains a TypedVar like `n:Nat`, we split into:
6801    /// - Base case: P(Zero)
6802    /// - Step case: ∀k. P(k) → P(Succ(k))
6803    fn try_structural_induction(
6804        &mut self,
6805        goal: &ProofGoal,
6806        depth: usize,
6807    ) -> ProofResult<Option<DerivationTree>> {
6808        // Look for TypedVar in the goal
6809        if let Some((var_name, typename)) = self.find_typed_var(&goal.target) {
6810            // Try motive inference via pattern unification first
6811            if let Some(motive) = self.try_infer_motive(&goal.target, &var_name) {
6812                match typename.as_str() {
6813                    "Nat" => {
6814                        if let Ok(Some(proof)) =
6815                            self.try_nat_induction_with_motive(goal, &var_name, &motive, depth)
6816                        {
6817                            return Ok(Some(proof));
6818                        }
6819                    }
6820                    "List" => {
6821                        // TODO: Add try_list_induction_with_motive
6822                    }
6823                    _ => {}
6824                }
6825            }
6826
6827            // Fallback: crude substitution approach
6828            match typename.as_str() {
6829                "Nat" => self.try_nat_induction(goal, &var_name, depth),
6830                "List" => self.try_list_induction(goal, &var_name, depth),
6831                _ => Ok(None), // Unknown inductive type
6832            }
6833        } else {
6834            Ok(None)
6835        }
6836    }
6837
6838    /// Try to infer the induction motive using Miller pattern unification.
6839    ///
6840    /// Given a goal like `Add(n:Nat, Zero) = n:Nat`, creates the pattern
6841    /// `?Motive(#n) = Goal` and solves for `?Motive = λn. Goal`.
6842    fn try_infer_motive(&self, goal: &ProofExpr, var_name: &str) -> Option<ProofExpr> {
6843        // Create the pattern: ?Motive(#var_name)
6844        let motive_hole = ProofExpr::Hole("Motive".to_string());
6845        let pattern = ProofExpr::App(
6846            Box::new(motive_hole),
6847            Box::new(ProofExpr::Term(ProofTerm::BoundVarRef(
6848                var_name.to_string(),
6849            ))),
6850        );
6851
6852        // The body is the goal itself (with TypedVar replaced by Variable for unification)
6853        let body = self.convert_typed_var_to_variable(goal, var_name);
6854
6855        // Unify: ?Motive(#n) = body
6856        match unify_pattern(&pattern, &body) {
6857            Ok(solution) => solution.get("Motive").cloned(),
6858            Err(_) => None,
6859        }
6860    }
6861
6862    /// Convert TypedVar to regular Variable for pattern unification.
6863    ///
6864    /// Pattern unification expects Variable("n") in the body to match BoundVarRef("n")
6865    /// in the pattern, but our goals have TypedVar { name: "n", typename: "Nat" }.
6866    fn convert_typed_var_to_variable(&self, expr: &ProofExpr, var_name: &str) -> ProofExpr {
6867        match expr {
6868            ProofExpr::TypedVar { name, .. } if name == var_name => {
6869                // Convert to Atom so it becomes a Variable in terms
6870                ProofExpr::Atom(name.clone())
6871            }
6872            ProofExpr::Identity(l, r) => ProofExpr::Identity(
6873                self.convert_typed_var_in_term(l, var_name),
6874                self.convert_typed_var_in_term(r, var_name),
6875            ),
6876            ProofExpr::Predicate { name, args, world } => ProofExpr::Predicate {
6877                name: name.clone(),
6878                args: args
6879                    .iter()
6880                    .map(|a| self.convert_typed_var_in_term(a, var_name))
6881                    .collect(),
6882                world: world.clone(),
6883            },
6884            ProofExpr::And(l, r) => ProofExpr::And(
6885                Box::new(self.convert_typed_var_to_variable(l, var_name)),
6886                Box::new(self.convert_typed_var_to_variable(r, var_name)),
6887            ),
6888            ProofExpr::Or(l, r) => ProofExpr::Or(
6889                Box::new(self.convert_typed_var_to_variable(l, var_name)),
6890                Box::new(self.convert_typed_var_to_variable(r, var_name)),
6891            ),
6892            ProofExpr::Not(inner) => ProofExpr::Not(Box::new(
6893                self.convert_typed_var_to_variable(inner, var_name),
6894            )),
6895            _ => expr.clone(),
6896        }
6897    }
6898
6899    /// Convert TypedVar to Variable in a ProofTerm.
6900    fn convert_typed_var_in_term(&self, term: &ProofTerm, var_name: &str) -> ProofTerm {
6901        match term {
6902            ProofTerm::Variable(v) => {
6903                // Check for "name:Type" pattern
6904                if v == var_name || v.starts_with(&format!("{}:", var_name)) {
6905                    ProofTerm::Variable(var_name.to_string())
6906                } else {
6907                    term.clone()
6908                }
6909            }
6910            ProofTerm::Function(name, args) => ProofTerm::Function(
6911                name.clone(),
6912                args.iter()
6913                    .map(|a| self.convert_typed_var_in_term(a, var_name))
6914                    .collect(),
6915            ),
6916            ProofTerm::Group(terms) => ProofTerm::Group(
6917                terms
6918                    .iter()
6919                    .map(|t| self.convert_typed_var_in_term(t, var_name))
6920                    .collect(),
6921            ),
6922            _ => term.clone(),
6923        }
6924    }
6925
6926    /// Perform structural induction on Nat using pattern unification.
6927    ///
6928    /// Uses Miller pattern unification to infer the motive, then applies
6929    /// it to constructors via beta reduction.
6930    ///
6931    /// Base case: P(Zero)
6932    /// Step case: ∀k. P(k) → P(Succ(k))
6933    fn try_nat_induction_with_motive(
6934        &mut self,
6935        goal: &ProofGoal,
6936        var_name: &str,
6937        motive: &ProofExpr,
6938        depth: usize,
6939    ) -> ProofResult<Option<DerivationTree>> {
6940        // Base case: P(Zero)
6941        // Apply the motive lambda to Zero constructor
6942        let zero_ctor = ProofExpr::Ctor {
6943            name: "Zero".into(),
6944            args: vec![],
6945        };
6946        let base_goal_expr = beta_reduce(&ProofExpr::App(
6947            Box::new(motive.clone()),
6948            Box::new(zero_ctor),
6949        ));
6950
6951        let base_goal = ProofGoal::with_context(base_goal_expr, goal.context.clone());
6952        let base_proof = match self.prove_goal(base_goal, depth + 1) {
6953            Ok(proof) => proof,
6954            Err(_) => return Ok(None),
6955        };
6956
6957        // Step case: ∀k. P(k) → P(Succ(k))
6958        let fresh_k = self.fresh_var();
6959        let k_var = ProofExpr::Atom(fresh_k.clone());
6960
6961        // Induction hypothesis: P(k)
6962        let ih = beta_reduce(&ProofExpr::App(
6963            Box::new(motive.clone()),
6964            Box::new(k_var.clone()),
6965        ));
6966
6967        // Step conclusion: P(Succ(k))
6968        let succ_k = ProofExpr::Ctor {
6969            name: "Succ".into(),
6970            args: vec![k_var],
6971        };
6972        let step_goal_expr =
6973            beta_reduce(&ProofExpr::App(Box::new(motive.clone()), Box::new(succ_k)));
6974
6975        // Add IH to context for step case
6976        let mut step_context = goal.context.clone();
6977        step_context.push(ih.clone());
6978
6979        let step_goal = ProofGoal::with_context(step_goal_expr, step_context);
6980        let step_proof = match self.try_step_case_with_equational_reasoning(&step_goal, &ih, depth)
6981        {
6982            Ok(proof) => proof,
6983            Err(_) => return Ok(None),
6984        };
6985
6986        Ok(Some(DerivationTree::new(
6987            goal.target.clone(),
6988            InferenceRule::StructuralInduction {
6989                variable: var_name.to_string(),
6990                ind_type: "Nat".to_string(),
6991                step_var: fresh_k,
6992            },
6993            vec![base_proof, step_proof],
6994        )))
6995    }
6996
6997    /// Perform structural induction on Nat (legacy crude substitution).
6998    ///
6999    /// Base case: P(Zero)
7000    /// Step case: ∀k. P(k) → P(Succ(k))
7001    fn try_nat_induction(
7002        &mut self,
7003        goal: &ProofGoal,
7004        var_name: &str,
7005        depth: usize,
7006    ) -> ProofResult<Option<DerivationTree>> {
7007        // Create Zero constructor
7008        let zero = ProofExpr::Ctor {
7009            name: "Zero".into(),
7010            args: vec![],
7011        };
7012
7013        // Base case: substitute Zero for the induction variable
7014        let base_goal_expr = self.substitute_typed_var(&goal.target, var_name, &zero);
7015        let base_goal = ProofGoal::with_context(base_goal_expr, goal.context.clone());
7016
7017        // Try to prove base case
7018        let base_proof = match self.prove_goal(base_goal, depth + 1) {
7019            Ok(proof) => proof,
7020            Err(_) => return Ok(None), // Can't prove base case
7021        };
7022
7023        // Step case: assume P(k), prove P(Succ(k))
7024        let fresh_k = self.fresh_var();
7025
7026        // Create k as a variable
7027        let k_var = ProofExpr::Atom(fresh_k.clone());
7028
7029        // Create Succ(k)
7030        let succ_k = ProofExpr::Ctor {
7031            name: "Succ".into(),
7032            args: vec![k_var.clone()],
7033        };
7034
7035        // Induction hypothesis: P(k)
7036        let ih = self.substitute_typed_var(&goal.target, var_name, &k_var);
7037
7038        // Step goal: P(Succ(k))
7039        let step_goal_expr = self.substitute_typed_var(&goal.target, var_name, &succ_k);
7040
7041        // Add IH to context for step case
7042        let mut step_context = goal.context.clone();
7043        step_context.push(ih.clone());
7044
7045        let step_goal = ProofGoal::with_context(step_goal_expr, step_context);
7046
7047        // Try to prove step case with IH in context
7048        let step_proof = match self.try_step_case_with_equational_reasoning(&step_goal, &ih, depth)
7049        {
7050            Ok(proof) => proof,
7051            Err(_) => return Ok(None), // Can't prove step case
7052        };
7053
7054        // Build the induction proof tree
7055        Ok(Some(DerivationTree::new(
7056            goal.target.clone(),
7057            InferenceRule::StructuralInduction {
7058                variable: var_name.to_string(),
7059                ind_type: "Nat".to_string(),
7060                step_var: fresh_k,
7061            },
7062            vec![base_proof, step_proof],
7063        )))
7064    }
7065
7066    /// Perform structural induction on List.
7067    ///
7068    /// Base case: P(Nil)
7069    /// Step case: ∀h,t. P(t) → P(Cons(h,t))
7070    fn try_list_induction(
7071        &mut self,
7072        goal: &ProofGoal,
7073        var_name: &str,
7074        depth: usize,
7075    ) -> ProofResult<Option<DerivationTree>> {
7076        // Create Nil constructor
7077        let nil = ProofExpr::Ctor {
7078            name: "Nil".into(),
7079            args: vec![],
7080        };
7081
7082        // Base case: substitute Nil for the induction variable
7083        let base_goal_expr = self.substitute_typed_var(&goal.target, var_name, &nil);
7084        let base_goal = ProofGoal::with_context(base_goal_expr, goal.context.clone());
7085
7086        // Try to prove base case
7087        let base_proof = match self.prove_goal(base_goal, depth + 1) {
7088            Ok(proof) => proof,
7089            Err(_) => return Ok(None),
7090        };
7091
7092        // Step case: assume P(t), prove P(Cons(h, t))
7093        let fresh_h = self.fresh_var();
7094        let fresh_t = self.fresh_var();
7095
7096        let h_var = ProofExpr::Atom(fresh_h);
7097        let t_var = ProofExpr::Atom(fresh_t.clone());
7098
7099        let cons_ht = ProofExpr::Ctor {
7100            name: "Cons".into(),
7101            args: vec![h_var, t_var.clone()],
7102        };
7103
7104        // Induction hypothesis: P(t)
7105        let ih = self.substitute_typed_var(&goal.target, var_name, &t_var);
7106
7107        // Step goal: P(Cons(h, t))
7108        let step_goal_expr = self.substitute_typed_var(&goal.target, var_name, &cons_ht);
7109
7110        let mut step_context = goal.context.clone();
7111        step_context.push(ih.clone());
7112
7113        let step_goal = ProofGoal::with_context(step_goal_expr, step_context);
7114
7115        let step_proof = match self.try_step_case_with_equational_reasoning(&step_goal, &ih, depth)
7116        {
7117            Ok(proof) => proof,
7118            Err(_) => return Ok(None),
7119        };
7120
7121        Ok(Some(DerivationTree::new(
7122            goal.target.clone(),
7123            InferenceRule::StructuralInduction {
7124                variable: var_name.to_string(),
7125                ind_type: "List".to_string(),
7126                step_var: fresh_t,
7127            },
7128            vec![base_proof, step_proof],
7129        )))
7130    }
7131
7132    /// Try to prove the step case, potentially using equational reasoning.
7133    ///
7134    /// The step case often requires:
7135    /// 1. Applying a recursive axiom to simplify the goal
7136    /// 2. Using the induction hypothesis
7137    /// 3. Congruence reasoning (e.g., Succ(x) = Succ(y) if x = y)
7138    fn try_step_case_with_equational_reasoning(
7139        &mut self,
7140        goal: &ProofGoal,
7141        ih: &ProofExpr,
7142        depth: usize,
7143    ) -> ProofResult<DerivationTree> {
7144        // First, try direct proof (might work for simple cases)
7145        if let Ok(proof) = self.prove_goal(goal.clone(), depth + 1) {
7146            return Ok(proof);
7147        }
7148
7149        // For Identity goals, try equational reasoning
7150        if let ProofExpr::Identity(lhs, rhs) = &goal.target {
7151            // Try to rewrite LHS using axioms and see if we can reach RHS
7152            if let Some(proof) = self.try_equational_proof(goal, lhs, rhs, ih, depth)? {
7153                return Ok(proof);
7154            }
7155        }
7156
7157        Err(ProofError::NoProofFound)
7158    }
7159
7160    /// Try equational reasoning: rewrite LHS to match RHS using axioms and IH.
7161    ///
7162    /// For the step case of induction, we need to:
7163    /// 1. Find an axiom that matches the goal's LHS pattern
7164    /// 2. Use the axiom to rewrite LHS
7165    /// 3. Apply the induction hypothesis to simplify
7166    /// 4. Check if the result equals RHS
7167    fn try_equational_proof(
7168        &mut self,
7169        goal: &ProofGoal,
7170        lhs: &ProofTerm,
7171        rhs: &ProofTerm,
7172        ih: &ProofExpr,
7173        _depth: usize,
7174    ) -> ProofResult<Option<DerivationTree>> {
7175        // Find applicable equations from KB (Identity axioms)
7176        let equations: Vec<ProofExpr> = self
7177            .knowledge_base
7178            .iter()
7179            .filter(|e| matches!(e, ProofExpr::Identity(_, _)))
7180            .cloned()
7181            .collect();
7182
7183        // Try each equation to rewrite LHS
7184        for eq_axiom in &equations {
7185            if let ProofExpr::Identity(_, _) = &eq_axiom {
7186                // Rename variables in the axiom to avoid capture
7187                let renamed_axiom = self.rename_variables(&eq_axiom);
7188                if let ProofExpr::Identity(renamed_lhs, renamed_rhs) = renamed_axiom {
7189                    // Unify axiom LHS with goal LHS
7190                    // This binds axiom variables to goal terms
7191                    // e.g., unify(Add(Succ(x), m), Add(Succ(k), Zero)) gives {x->k, m->Zero}
7192                    if let Ok(subst) = unify_terms(&renamed_lhs, lhs) {
7193                        // Apply the substitution to the axiom's RHS
7194                        // This gives us what LHS rewrites to
7195                        let rewritten = self.apply_subst_to_term_with(&renamed_rhs, &subst);
7196
7197                        // Now check if rewritten equals RHS (possibly using IH)
7198                        if self.terms_equal_with_ih(&rewritten, rhs, ih) {
7199                            // Success! Build proof using the axiom and IH
7200                            let axiom_leaf =
7201                                DerivationTree::leaf(eq_axiom.clone(), InferenceRule::PremiseMatch);
7202
7203                            let ih_leaf =
7204                                DerivationTree::leaf(ih.clone(), InferenceRule::PremiseMatch);
7205
7206                            return Ok(Some(DerivationTree::new(
7207                                goal.target.clone(),
7208                                InferenceRule::PremiseMatch, // Equational step
7209                                vec![axiom_leaf, ih_leaf],
7210                            )));
7211                        }
7212                    }
7213                }
7214            }
7215        }
7216
7217        Ok(None)
7218    }
7219
7220    /// Check if two terms are equal, potentially using the induction hypothesis.
7221    fn terms_equal_with_ih(&self, t1: &ProofTerm, t2: &ProofTerm, ih: &ProofExpr) -> bool {
7222        // Direct equality
7223        if t1 == t2 {
7224            return true;
7225        }
7226
7227        // Try using IH: if IH is `x = y`, and t1 contains x, replace with y
7228        if let ProofExpr::Identity(ih_lhs, ih_rhs) = ih {
7229            // Check if t1 can be transformed to t2 using IH
7230            let t1_with_ih = self.rewrite_term_with_equation(t1, ih_lhs, ih_rhs);
7231            if &t1_with_ih == t2 {
7232                return true;
7233            }
7234
7235            // Also try the other direction
7236            let t2_with_ih = self.rewrite_term_with_equation(t2, ih_rhs, ih_lhs);
7237            if t1 == &t2_with_ih {
7238                return true;
7239            }
7240        }
7241
7242        false
7243    }
7244
7245    /// Rewrite occurrences of `from` to `to` in the term.
7246    fn rewrite_term_with_equation(
7247        &self,
7248        term: &ProofTerm,
7249        from: &ProofTerm,
7250        to: &ProofTerm,
7251    ) -> ProofTerm {
7252        // If term matches `from`, return `to`
7253        if term == from {
7254            return to.clone();
7255        }
7256
7257        // Recursively rewrite in subterms
7258        match term {
7259            ProofTerm::Function(name, args) => {
7260                let new_args: Vec<ProofTerm> = args
7261                    .iter()
7262                    .map(|a| self.rewrite_term_with_equation(a, from, to))
7263                    .collect();
7264                ProofTerm::Function(name.clone(), new_args)
7265            }
7266            ProofTerm::Group(terms) => {
7267                let new_terms: Vec<ProofTerm> = terms
7268                    .iter()
7269                    .map(|t| self.rewrite_term_with_equation(t, from, to))
7270                    .collect();
7271                ProofTerm::Group(new_terms)
7272            }
7273            _ => term.clone(),
7274        }
7275    }
7276
7277    /// Apply substitution to a ProofTerm with given substitution.
7278    fn apply_subst_to_term_with(&self, term: &ProofTerm, subst: &Substitution) -> ProofTerm {
7279        match term {
7280            ProofTerm::Variable(v) => subst.get(v).cloned().unwrap_or_else(|| term.clone()),
7281            ProofTerm::Function(name, args) => ProofTerm::Function(
7282                name.clone(),
7283                args.iter()
7284                    .map(|a| self.apply_subst_to_term_with(a, subst))
7285                    .collect(),
7286            ),
7287            ProofTerm::Group(terms) => ProofTerm::Group(
7288                terms
7289                    .iter()
7290                    .map(|t| self.apply_subst_to_term_with(t, subst))
7291                    .collect(),
7292            ),
7293            ProofTerm::Constant(_) => term.clone(),
7294            ProofTerm::BoundVarRef(_) => term.clone(),
7295        }
7296    }
7297
7298    /// Find a TypedVar in the expression.
7299    fn find_typed_var(&self, expr: &ProofExpr) -> Option<(String, String)> {
7300        match expr {
7301            ProofExpr::TypedVar { name, typename } => Some((name.clone(), typename.clone())),
7302            ProofExpr::Identity(l, r) => self
7303                .find_typed_var_in_term(l)
7304                .or_else(|| self.find_typed_var_in_term(r)),
7305            ProofExpr::Predicate { args, .. } => {
7306                for arg in args {
7307                    if let Some(tv) = self.find_typed_var_in_term(arg) {
7308                        return Some(tv);
7309                    }
7310                }
7311                None
7312            }
7313            ProofExpr::And(l, r)
7314            | ProofExpr::Or(l, r)
7315            | ProofExpr::Implies(l, r)
7316            | ProofExpr::Iff(l, r) => self.find_typed_var(l).or_else(|| self.find_typed_var(r)),
7317            ProofExpr::Not(inner) => self.find_typed_var(inner),
7318            ProofExpr::ForAll { body, .. } | ProofExpr::Exists { body, .. } => {
7319                self.find_typed_var(body)
7320            }
7321            _ => None,
7322        }
7323    }
7324
7325    /// Find a TypedVar embedded in a ProofTerm.
7326    fn find_typed_var_in_term(&self, term: &ProofTerm) -> Option<(String, String)> {
7327        match term {
7328            ProofTerm::Variable(v) => {
7329                // Check if this variable name is in our KB as a TypedVar
7330                // Actually, TypedVar should be in the expression, not the term
7331                // Let's check if the variable name contains type annotation
7332                if v.contains(':') {
7333                    let parts: Vec<&str> = v.splitn(2, ':').collect();
7334                    if parts.len() == 2 {
7335                        return Some((parts[0].to_string(), parts[1].to_string()));
7336                    }
7337                }
7338                None
7339            }
7340            ProofTerm::Function(_, args) => {
7341                for arg in args {
7342                    if let Some(tv) = self.find_typed_var_in_term(arg) {
7343                        return Some(tv);
7344                    }
7345                }
7346                None
7347            }
7348            ProofTerm::Group(terms) => {
7349                for t in terms {
7350                    if let Some(tv) = self.find_typed_var_in_term(t) {
7351                        return Some(tv);
7352                    }
7353                }
7354                None
7355            }
7356            ProofTerm::Constant(_) => None,
7357            ProofTerm::BoundVarRef(_) => None, // Pattern-level, no TypedVar
7358        }
7359    }
7360
7361    /// Substitute a TypedVar with a given expression throughout the goal.
7362    fn substitute_typed_var(
7363        &self,
7364        expr: &ProofExpr,
7365        var_name: &str,
7366        replacement: &ProofExpr,
7367    ) -> ProofExpr {
7368        match expr {
7369            ProofExpr::TypedVar { name, .. } if name == var_name => replacement.clone(),
7370            ProofExpr::Identity(l, r) => {
7371                let new_l = self.substitute_typed_var_in_term(l, var_name, replacement);
7372                let new_r = self.substitute_typed_var_in_term(r, var_name, replacement);
7373                ProofExpr::Identity(new_l, new_r)
7374            }
7375            ProofExpr::Predicate { name, args, world } => {
7376                let new_args: Vec<ProofTerm> = args
7377                    .iter()
7378                    .map(|a| self.substitute_typed_var_in_term(a, var_name, replacement))
7379                    .collect();
7380                ProofExpr::Predicate {
7381                    name: name.clone(),
7382                    args: new_args,
7383                    world: world.clone(),
7384                }
7385            }
7386            ProofExpr::And(l, r) => ProofExpr::And(
7387                Box::new(self.substitute_typed_var(l, var_name, replacement)),
7388                Box::new(self.substitute_typed_var(r, var_name, replacement)),
7389            ),
7390            ProofExpr::Or(l, r) => ProofExpr::Or(
7391                Box::new(self.substitute_typed_var(l, var_name, replacement)),
7392                Box::new(self.substitute_typed_var(r, var_name, replacement)),
7393            ),
7394            ProofExpr::Implies(l, r) => ProofExpr::Implies(
7395                Box::new(self.substitute_typed_var(l, var_name, replacement)),
7396                Box::new(self.substitute_typed_var(r, var_name, replacement)),
7397            ),
7398            ProofExpr::Iff(l, r) => ProofExpr::Iff(
7399                Box::new(self.substitute_typed_var(l, var_name, replacement)),
7400                Box::new(self.substitute_typed_var(r, var_name, replacement)),
7401            ),
7402            ProofExpr::Not(inner) => ProofExpr::Not(Box::new(self.substitute_typed_var(
7403                inner,
7404                var_name,
7405                replacement,
7406            ))),
7407            ProofExpr::ForAll { variable, body } => ProofExpr::ForAll {
7408                variable: variable.clone(),
7409                body: Box::new(self.substitute_typed_var(body, var_name, replacement)),
7410            },
7411            ProofExpr::Exists { variable, body } => ProofExpr::Exists {
7412                variable: variable.clone(),
7413                body: Box::new(self.substitute_typed_var(body, var_name, replacement)),
7414            },
7415            _ => expr.clone(),
7416        }
7417    }
7418
7419    /// Substitute a TypedVar in a ProofTerm.
7420    fn substitute_typed_var_in_term(
7421        &self,
7422        term: &ProofTerm,
7423        var_name: &str,
7424        replacement: &ProofExpr,
7425    ) -> ProofTerm {
7426        match term {
7427            ProofTerm::Variable(v) => {
7428                // Check for TypedVar pattern "name:Type"
7429                if v == var_name || v.starts_with(&format!("{}:", var_name)) {
7430                    self.expr_to_term(replacement)
7431                } else {
7432                    term.clone()
7433                }
7434            }
7435            ProofTerm::Function(name, args) => ProofTerm::Function(
7436                name.clone(),
7437                args.iter()
7438                    .map(|a| self.substitute_typed_var_in_term(a, var_name, replacement))
7439                    .collect(),
7440            ),
7441            ProofTerm::Group(terms) => ProofTerm::Group(
7442                terms
7443                    .iter()
7444                    .map(|t| self.substitute_typed_var_in_term(t, var_name, replacement))
7445                    .collect(),
7446            ),
7447            ProofTerm::Constant(_) => term.clone(),
7448            ProofTerm::BoundVarRef(_) => term.clone(),
7449        }
7450    }
7451
7452    /// Convert a ProofExpr to a ProofTerm (for use in substitution).
7453    fn expr_to_term(&self, expr: &ProofExpr) -> ProofTerm {
7454        match expr {
7455            ProofExpr::Atom(s) => ProofTerm::Variable(s.clone()),
7456            ProofExpr::Ctor { name, args } => ProofTerm::Function(
7457                name.clone(),
7458                args.iter().map(|a| self.expr_to_term(a)).collect(),
7459            ),
7460            ProofExpr::TypedVar { name, .. } => ProofTerm::Variable(name.clone()),
7461            _ => ProofTerm::Constant(format!("{}", expr)),
7462        }
7463    }
7464
7465    // =========================================================================
7466    // HELPER METHODS
7467    // =========================================================================
7468
7469    /// Generate a fresh variable name.
7470    fn fresh_var(&mut self) -> String {
7471        self.var_counter += 1;
7472        format!("_G{}", self.var_counter)
7473    }
7474
7475    /// A fresh eigenconstant name for universal introduction: an opaque `Constant`
7476    /// the search cannot unify against (unlike a `Variable`, which it could bind),
7477    /// so the bound variable of a `∀` is proved as a genuinely arbitrary element.
7478    /// The distinctive prefix can never be a numeral or collide with a real symbol.
7479    fn fresh_eigenconstant(&mut self) -> String {
7480        self.var_counter += 1;
7481        format!("__eigen{}", self.var_counter)
7482    }
7483
7484    /// Rename all variables in an expression to fresh names.
7485    fn rename_variables(&mut self, expr: &ProofExpr) -> ProofExpr {
7486        let vars = self.collect_variables(expr);
7487        let mut subst = Substitution::new();
7488
7489        for var in vars {
7490            let fresh = self.fresh_var();
7491            subst.insert(var, ProofTerm::Variable(fresh));
7492        }
7493
7494        apply_subst_to_expr(expr, &subst)
7495    }
7496
7497    /// Collect all variable names in an expression.
7498    fn collect_variables(&self, expr: &ProofExpr) -> Vec<String> {
7499        let mut vars = Vec::new();
7500        self.collect_variables_recursive(expr, &mut vars);
7501        vars
7502    }
7503
7504    fn collect_variables_recursive(&self, expr: &ProofExpr, vars: &mut Vec<String>) {
7505        match expr {
7506            ProofExpr::Predicate { args, .. } => {
7507                for arg in args {
7508                    self.collect_term_variables(arg, vars);
7509                }
7510            }
7511            ProofExpr::Identity(l, r) => {
7512                self.collect_term_variables(l, vars);
7513                self.collect_term_variables(r, vars);
7514            }
7515            ProofExpr::And(l, r)
7516            | ProofExpr::Or(l, r)
7517            | ProofExpr::Implies(l, r)
7518            | ProofExpr::Iff(l, r) => {
7519                self.collect_variables_recursive(l, vars);
7520                self.collect_variables_recursive(r, vars);
7521            }
7522            ProofExpr::Not(inner) => self.collect_variables_recursive(inner, vars),
7523            ProofExpr::ForAll { variable, body } | ProofExpr::Exists { variable, body } => {
7524                if !vars.contains(variable) {
7525                    vars.push(variable.clone());
7526                }
7527                self.collect_variables_recursive(body, vars);
7528            }
7529            ProofExpr::Lambda { variable, body } => {
7530                if !vars.contains(variable) {
7531                    vars.push(variable.clone());
7532                }
7533                self.collect_variables_recursive(body, vars);
7534            }
7535            ProofExpr::App(f, a) => {
7536                self.collect_variables_recursive(f, vars);
7537                self.collect_variables_recursive(a, vars);
7538            }
7539            ProofExpr::NeoEvent { roles, .. } => {
7540                for (_, term) in roles {
7541                    self.collect_term_variables(term, vars);
7542                }
7543            }
7544            _ => {}
7545        }
7546    }
7547
7548    fn collect_term_variables(&self, term: &ProofTerm, vars: &mut Vec<String>) {
7549        match term {
7550            ProofTerm::Variable(v) => {
7551                if !vars.contains(v) {
7552                    vars.push(v.clone());
7553                }
7554            }
7555            ProofTerm::Function(_, args) => {
7556                for arg in args {
7557                    self.collect_term_variables(arg, vars);
7558                }
7559            }
7560            ProofTerm::Group(terms) => {
7561                for t in terms {
7562                    self.collect_term_variables(t, vars);
7563                }
7564            }
7565            ProofTerm::Constant(_) => {}
7566            ProofTerm::BoundVarRef(_) => {} // Pattern-level, no variables
7567        }
7568    }
7569
7570    /// Collect potential witnesses (constants) from the knowledge base.
7571    /// The ground terms an existential goal may be witnessed by: those of the goal's
7572    /// context first — where an opened existential's witness lives, the one its body is
7573    /// about — then the knowledge base's.
7574    fn collect_witnesses(&self, context: &[ProofExpr]) -> Vec<ProofTerm> {
7575        let mut witnesses = Vec::new();
7576
7577        for expr in context.iter().chain(&self.knowledge_base) {
7578            self.collect_constants_from_expr(expr, &mut witnesses);
7579        }
7580
7581        witnesses
7582    }
7583
7584    fn collect_constants_from_expr(&self, expr: &ProofExpr, constants: &mut Vec<ProofTerm>) {
7585        match expr {
7586            ProofExpr::Predicate { args, .. } => {
7587                for arg in args {
7588                    self.collect_constants_from_term(arg, constants);
7589                }
7590            }
7591            ProofExpr::Identity(l, r) => {
7592                self.collect_constants_from_term(l, constants);
7593                self.collect_constants_from_term(r, constants);
7594            }
7595            ProofExpr::And(l, r)
7596            | ProofExpr::Or(l, r)
7597            | ProofExpr::Implies(l, r)
7598            | ProofExpr::Iff(l, r) => {
7599                self.collect_constants_from_expr(l, constants);
7600                self.collect_constants_from_expr(r, constants);
7601            }
7602            ProofExpr::Not(inner) => self.collect_constants_from_expr(inner, constants),
7603            ProofExpr::ForAll { body, .. } | ProofExpr::Exists { body, .. } => {
7604                self.collect_constants_from_expr(body, constants);
7605            }
7606            ProofExpr::NeoEvent { roles, .. } => {
7607                for (_, term) in roles {
7608                    self.collect_constants_from_term(term, constants);
7609                }
7610            }
7611            _ => {}
7612        }
7613    }
7614
7615    fn collect_constants_from_term(&self, term: &ProofTerm, constants: &mut Vec<ProofTerm>) {
7616        match term {
7617            ProofTerm::Constant(_) => {
7618                if !constants.contains(term) {
7619                    constants.push(term.clone());
7620                }
7621            }
7622            ProofTerm::Function(_, args) => {
7623                // The function application itself could be a witness
7624                if !constants.contains(term) {
7625                    constants.push(term.clone());
7626                }
7627                for arg in args {
7628                    self.collect_constants_from_term(arg, constants);
7629                }
7630            }
7631            ProofTerm::Group(terms) => {
7632                for t in terms {
7633                    self.collect_constants_from_term(t, constants);
7634                }
7635            }
7636            ProofTerm::Variable(_) => {}
7637            ProofTerm::BoundVarRef(_) => {} // Pattern-level, not a constant
7638        }
7639    }
7640
7641    // =========================================================================
7642    // STRATEGY 7: ORACLE FALLBACK (Z3)
7643    // =========================================================================
7644
7645    /// Attempt to prove using Z3 as an oracle.
7646    ///
7647    /// This is the fallback when all structural proof strategies fail.
7648    /// Z3 will verify arithmetic, comparisons, and uninterpreted function reasoning.
7649    #[cfg(feature = "verification")]
7650    fn try_oracle_fallback(&self, goal: &ProofGoal) -> ProofResult<Option<DerivationTree>> {
7651        crate::oracle::try_oracle(goal, &self.knowledge_base)
7652    }
7653}
7654
7655// =============================================================================
7656// HELPER FUNCTIONS
7657// =============================================================================
7658
7659/// Extract the type from an existential body if it contains type information.
7660///
7661/// Looks for TypedVar patterns in the body that might indicate the type
7662/// of the existentially quantified variable. Returns None if no type
7663/// information is found.
7664fn extract_type_from_exists_body(body: &ProofExpr) -> Option<String> {
7665    match body {
7666        // Direct TypedVar in body
7667        ProofExpr::TypedVar { typename, .. } => Some(typename.clone()),
7668
7669        // Recurse into conjunctions
7670        ProofExpr::And(l, r) => {
7671            extract_type_from_exists_body(l).or_else(|| extract_type_from_exists_body(r))
7672        }
7673
7674        // Recurse into disjunctions
7675        ProofExpr::Or(l, r) => {
7676            extract_type_from_exists_body(l).or_else(|| extract_type_from_exists_body(r))
7677        }
7678
7679        // Recurse into nested quantifiers
7680        ProofExpr::Exists { body, .. } | ProofExpr::ForAll { body, .. } => {
7681            extract_type_from_exists_body(body)
7682        }
7683
7684        // No type information found
7685        _ => None,
7686    }
7687}
7688
7689impl Default for BackwardChainer {
7690    fn default() -> Self {
7691        Self::new()
7692    }
7693}
7694
7695#[cfg(test)]
7696#[path = "../../logicaffeine_tests/unit/logicaffeine_proof/engine/tests.rs"]
7697mod tests;