Skip to main content

logicaffeine_compile/
ui_bridge.rs

1//! UI bridge for web interface integration.
2//!
3//! This module provides high-level, UI-friendly wrappers around the compilation
4//! pipeline, returning structured results suitable for display in the browser.
5//!
6//! # Key Functions
7//!
8//! | Function | Purpose |
9//! |----------|---------|
10//! | [`compile_for_ui`] | Compile LOGOS to FOL (UI format) |
11//! | [`compile_for_proof`] | Compile and search for proofs |
12//! | [`compile_theorem_for_ui`] | Compile theorems with derivation trees |
13//! | [`verify_theorem`] | Verify a theorem is provable |
14//! | [`interpret_for_ui`] | Run imperative code and return output |
15//! | [`generate_rust_code`] | Generate Rust source (requires `codegen` feature) |
16//!
17//! # Result Types
18//!
19//! All functions return serializable result types:
20//! - [`CompileResult`] - Tokens, FOL, AST, errors
21//! - [`ProofCompileResult`] - FOL with proof search results
22//! - [`TheoremCompileResult`] - Theorem verification with derivation tree
23//! - [`InterpreterResult`] - Program output lines and errors
24//!
25//! # Token Categories
26//!
27//! The [`TokenCategory`] enum provides syntactic highlighting categories:
28//! Quantifier, Noun, Verb, Adjective, Connective, Determiner, etc.
29
30use serde::{Deserialize, Serialize};
31use std::collections::HashSet;
32
33use logicaffeine_base::{Arena, Interner};
34use logicaffeine_language::{
35    analysis::DiscoveryPass,
36    arena_ctx::AstContext,
37    ast::{self, LogicExpr, Term},
38    compile::{compile_forest, compile_forest_with_options},
39    drs,
40    error::socratic_explanation,
41    lexer::Lexer,
42    mwe,
43    parser::Parser,
44    pragmatics,
45    registry::SymbolRegistry,
46    semantics,
47    token::TokenType,
48    CompileOptions, OutputFormat, ParseError,
49};
50use logicaffeine_proof::{DerivationTree, ProofExpr, ProofTerm};
51
52// Re-export interpreter result from our interpreter module
53pub use crate::interpreter::InterpreterResult;
54
55// ═══════════════════════════════════════════════════════════════════
56// Token Visualization
57// ═══════════════════════════════════════════════════════════════════
58
59/// Syntactic category of a token for UI highlighting.
60#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
61pub enum TokenCategory {
62    /// Universal/existential quantifiers: every, some, no, most
63    Quantifier,
64    /// Common nouns: dog, cat, person
65    Noun,
66    /// Main verbs: runs, loves, gives
67    Verb,
68    /// Adjective modifiers: tall, happy, red
69    Adjective,
70    /// Logical connectives: and, or, not, if
71    Connective,
72    /// Articles and determiners: a, an, the
73    Determiner,
74    /// Prepositional words: in, on, to, with
75    Preposition,
76    /// Personal and relative pronouns: he, she, who
77    Pronoun,
78    /// Modal auxiliaries: can, must, might
79    Modal,
80    /// Sentence-ending punctuation
81    Punctuation,
82    /// Proper names (capitalized)
83    Proper,
84    /// Uncategorized tokens
85    Other,
86}
87
88/// Token information for UI display with position and category.
89#[derive(Debug, Clone, Serialize, Deserialize)]
90pub struct TokenInfo {
91    /// Byte offset of token start in source string.
92    pub start: usize,
93    /// Byte offset of token end (exclusive) in source string.
94    pub end: usize,
95    /// The actual text of the token.
96    pub text: String,
97    /// Syntactic category for highlighting.
98    pub category: TokenCategory,
99}
100
101fn categorize_token(kind: &TokenType, _interner: &Interner) -> TokenCategory {
102    match kind {
103        TokenType::All
104        | TokenType::Some
105        | TokenType::No
106        | TokenType::Any
107        | TokenType::Most
108        | TokenType::Few
109        | TokenType::Many
110        | TokenType::Cardinal(_)
111        | TokenType::AtLeast(_)
112        | TokenType::AtMost(_) => TokenCategory::Quantifier,
113        TokenType::Noun(_) => TokenCategory::Noun,
114        TokenType::Verb { .. } => TokenCategory::Verb,
115        TokenType::Adjective(_) | TokenType::NonIntersectiveAdjective(_) => {
116            TokenCategory::Adjective
117        }
118        TokenType::And
119        | TokenType::Or
120        | TokenType::Not
121        | TokenType::If
122        | TokenType::Then
123        | TokenType::Iff
124        | TokenType::Because => TokenCategory::Connective,
125        TokenType::Article(_) => TokenCategory::Determiner,
126        TokenType::Preposition(_) => TokenCategory::Preposition,
127        TokenType::Pronoun { .. } => TokenCategory::Pronoun,
128        TokenType::Must
129        | TokenType::Can
130        | TokenType::Should
131        | TokenType::Shall
132        | TokenType::Would
133        | TokenType::Could
134        | TokenType::May
135        | TokenType::Cannot
136        | TokenType::Might => TokenCategory::Modal,
137        TokenType::Period | TokenType::Comma => TokenCategory::Punctuation,
138        TokenType::ProperName(_) => TokenCategory::Proper,
139        _ => TokenCategory::Other,
140    }
141}
142
143/// Tokenizes input text and returns token information for UI display.
144///
145/// Each token includes its byte position, text content, and syntactic
146/// category for syntax highlighting in the browser interface.
147pub fn tokenize_for_ui(input: &str) -> Vec<TokenInfo> {
148    let mut interner = Interner::new();
149    let mut lexer = Lexer::new(input, &mut interner);
150    let tokens = lexer.tokenize();
151
152    tokens
153        .iter()
154        .map(|t| TokenInfo {
155            start: t.span.start,
156            end: t.span.end,
157            text: input[t.span.start..t.span.end].to_string(),
158            category: categorize_token(&t.kind, &interner),
159        })
160        .collect()
161}
162
163// ═══════════════════════════════════════════════════════════════════
164// AST Visualization
165// ═══════════════════════════════════════════════════════════════════
166
167/// AST node for tree visualization in the UI.
168#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
169pub struct AstNode {
170    /// Display label for this node (e.g., "∀x", "Run(x)").
171    pub label: String,
172    /// Node type for styling (e.g., "quantifier", "predicate", "connective").
173    pub node_type: String,
174    /// Child nodes in the AST.
175    pub children: Vec<AstNode>,
176}
177
178impl AstNode {
179    pub fn leaf(label: &str, node_type: &str) -> Self {
180        AstNode {
181            label: label.to_string(),
182            node_type: node_type.to_string(),
183            children: Vec::new(),
184        }
185    }
186
187    pub fn with_children(label: &str, node_type: &str, children: Vec<AstNode>) -> Self {
188        AstNode {
189            label: label.to_string(),
190            node_type: node_type.to_string(),
191            children,
192        }
193    }
194}
195
196/// Converts a logic expression to an AST node for tree visualization.
197///
198/// Every variant gets a node in the notation the Logic Output prints — the operator symbols
199/// come from the one table in `logicaffeine_language::debug` — with its sub-expressions and
200/// terms as children. The match has no fallback arm, so a new variant cannot reach the tree
201/// as a `Debug` dump: it must be given a node here.
202pub fn expr_to_ast_node(expr: &LogicExpr, interner: &Interner) -> AstNode {
203    use logicaffeine_language::debug::{
204        aspect_symbol, binary_temporal_symbol, connective_symbol, focus_symbol, modal_symbol,
205        quantifier_symbol, temporal_symbol, voice_symbol, DisplayWith,
206    };
207    let node = |e: &LogicExpr| expr_to_ast_node(e, interner);
208    let term = |t: &Term| term_to_ast_node(t, interner);
209    let name = |sym: &logicaffeine_base::Symbol| interner.resolve(*sym).to_string();
210    // A node with no sub-expression to open: labelled in the notation itself.
211    let written = |node_type: &str| AstNode::leaf(&expr.with(interner).to_string(), node_type);
212    match expr {
213        LogicExpr::Predicate {
214            name: pred, args, ..
215        } => AstNode::with_children(
216            &format!("{}({})", name(pred), args.len()),
217            "predicate",
218            args.iter().map(|t| term(t)).collect(),
219        ),
220        LogicExpr::Identity { left, right } => {
221            AstNode::with_children("=", "identity", vec![term(left), term(right)])
222        }
223        LogicExpr::Metaphor { tenor, vehicle } => {
224            AstNode::with_children("Metaphor", "metaphor", vec![term(tenor), term(vehicle)])
225        }
226        LogicExpr::Quantifier {
227            kind,
228            variable,
229            body,
230            ..
231        } => AstNode::with_children(
232            &format!("{}{}", quantifier_symbol(kind), name(variable)),
233            "quantifier",
234            vec![node(body)],
235        ),
236        LogicExpr::Categorical(_) => written("categorical"),
237        LogicExpr::Relation(_) => written("relation"),
238        LogicExpr::Modal { vector, operand } => {
239            AstNode::with_children(modal_symbol(vector), "modal", vec![node(operand)])
240        }
241        LogicExpr::Temporal { operator, body } => {
242            AstNode::with_children(temporal_symbol(operator), "temporal", vec![node(body)])
243        }
244        LogicExpr::TemporalBinary {
245            operator,
246            left,
247            right,
248        } => AstNode::with_children(
249            binary_temporal_symbol(operator),
250            "temporal",
251            vec![node(left), node(right)],
252        ),
253        LogicExpr::Aspectual { operator, body } => {
254            AstNode::with_children(aspect_symbol(operator), "aspect", vec![node(body)])
255        }
256        LogicExpr::Voice { operator, body } => {
257            AstNode::with_children(voice_symbol(operator), "voice", vec![node(body)])
258        }
259        LogicExpr::BinaryOp { left, op, right } => AstNode::with_children(
260            connective_symbol(op),
261            "binary_op",
262            vec![node(left), node(right)],
263        ),
264        LogicExpr::UnaryOp { op, operand } => {
265            AstNode::with_children(connective_symbol(op), "unary_op", vec![node(operand)])
266        }
267        LogicExpr::Question { wh_variable, body } => AstNode::with_children(
268            &format!("?{}", name(wh_variable)),
269            "question",
270            vec![node(body)],
271        ),
272        LogicExpr::YesNoQuestion { body } => {
273            AstNode::with_children("?", "question", vec![node(body)])
274        }
275        LogicExpr::Atom(sym) => AstNode::leaf(&name(sym), "atom"),
276        LogicExpr::Lambda { variable, body } => {
277            AstNode::with_children(&format!("λ{}", name(variable)), "lambda", vec![node(body)])
278        }
279        LogicExpr::App { function, argument } => {
280            AstNode::with_children("apply", "application", vec![node(function), node(argument)])
281        }
282        LogicExpr::Intensional { operator, content } => {
283            AstNode::with_children(&name(operator), "intensional", vec![node(content)])
284        }
285        LogicExpr::Event { predicate, adverbs } => {
286            let mut children = vec![node(predicate)];
287            children.extend(adverbs.iter().map(|a| AstNode::leaf(&name(a), "modifier")));
288            AstNode::with_children("event", "event", children)
289        }
290        // A Neo-Davidsonian event: its verb over the event variable, each thematic role a
291        // branch holding its filler, and each adverbial modifier a leaf.
292        LogicExpr::NeoEvent(data) => {
293            let mut children: Vec<AstNode> = data
294                .roles
295                .iter()
296                .map(|(role, filler)| {
297                    AstNode::with_children(&format!("{:?}", role), "role", vec![term(filler)])
298                })
299                .collect();
300            children.extend(
301                data.modifiers
302                    .iter()
303                    .map(|m| AstNode::leaf(&name(m), "modifier")),
304            );
305            AstNode::with_children(
306                &format!("∃{} {}", name(&data.event_var), name(&data.verb)),
307                "event",
308                children,
309            )
310        }
311        LogicExpr::Imperative { action } => {
312            AstNode::with_children("!", "speech_act", vec![node(action)])
313        }
314        LogicExpr::Exclamative { body, .. } => {
315            AstNode::with_children("Exclaim", "speech_act", vec![node(body)])
316        }
317        LogicExpr::Optative { wish } => {
318            AstNode::with_children("Wish", "speech_act", vec![node(wish)])
319        }
320        LogicExpr::Implicature {
321            assertion,
322            implicature,
323        } => AstNode::with_children(
324            "+>",
325            "implicature",
326            vec![node(assertion), node(implicature)],
327        ),
328        LogicExpr::SpeechAct {
329            performer,
330            act_type,
331            content,
332        } => AstNode::with_children(
333            &format!("{}!{}", name(act_type), name(performer)),
334            "speech_act",
335            vec![node(content)],
336        ),
337        LogicExpr::Counterfactual {
338            antecedent,
339            consequent,
340        } => AstNode::with_children(
341            "□→",
342            "conditional",
343            vec![node(antecedent), node(consequent)],
344        ),
345        LogicExpr::Causal { effect, cause } => {
346            AstNode::with_children("Cause", "causal", vec![node(cause), node(effect)])
347        }
348        LogicExpr::Concessive { main, concession } => AstNode::with_children(
349            "Concessive",
350            "concessive",
351            vec![node(main), node(concession)],
352        ),
353        LogicExpr::Comparative { .. } => written("comparative"),
354        LogicExpr::Superlative { .. } => written("superlative"),
355        LogicExpr::Scopal { operator, body } => {
356            AstNode::with_children(&name(operator), "scopal", vec![node(body)])
357        }
358        LogicExpr::Control {
359            verb,
360            subject,
361            object,
362            infinitive,
363        } => {
364            let mut children = vec![term(subject)];
365            children.extend(object.map(|o| term(o)));
366            children.push(node(infinitive));
367            AstNode::with_children(&name(verb), "control", children)
368        }
369        LogicExpr::Presupposition {
370            assertion,
371            presupposition,
372        } => AstNode::with_children(
373            "presupposes",
374            "presupposition",
375            vec![node(assertion), node(presupposition)],
376        ),
377        LogicExpr::Focus {
378            kind,
379            focused,
380            scope,
381        } => AstNode::with_children(
382            focus_symbol(kind),
383            "focus",
384            vec![term(focused), node(scope)],
385        ),
386        LogicExpr::TemporalAnchor { anchor, body } => {
387            AstNode::with_children(&format!("@{}", name(anchor)), "temporal", vec![node(body)])
388        }
389        LogicExpr::Distributive { predicate } => {
390            AstNode::with_children("*", "distributive", vec![node(predicate)])
391        }
392        LogicExpr::GroupQuantifier {
393            group_var,
394            count,
395            restriction,
396            body,
397            ..
398        } => AstNode::with_children(
399            &format!("∃{} (group of {})", name(group_var), count),
400            "quantifier",
401            vec![node(restriction), node(body)],
402        ),
403    }
404}
405
406fn term_to_ast_node(term: &Term, interner: &Interner) -> AstNode {
407    match term {
408        Term::Constant(sym) => AstNode::leaf(interner.resolve(*sym), "constant"),
409        Term::Variable(sym) => AstNode::leaf(interner.resolve(*sym), "variable"),
410        Term::Function(name, args) => {
411            let name_str = interner.resolve(*name);
412            let arg_nodes: Vec<AstNode> =
413                args.iter().map(|t| term_to_ast_node(t, interner)).collect();
414            AstNode::with_children(&format!("{}()", name_str), "function", arg_nodes)
415        }
416        Term::Group(terms) => {
417            let term_nodes: Vec<AstNode> = terms
418                .iter()
419                .map(|t| term_to_ast_node(t, interner))
420                .collect();
421            AstNode::with_children("⊕", "group", term_nodes)
422        }
423        // A proposition used as a term (`believes that …`): its own structure beneath it.
424        Term::Proposition(expr) => {
425            AstNode::with_children("[ ]", "proposition", vec![expr_to_ast_node(expr, interner)])
426        }
427        _ => {
428            use logicaffeine_language::debug::DisplayWith;
429            AstNode::leaf(&term.with(interner).to_string(), "term")
430        }
431    }
432}
433
434// ═══════════════════════════════════════════════════════════════════
435// Compilation Results
436// ═══════════════════════════════════════════════════════════════════
437
438#[derive(Debug, Clone, Serialize, Deserialize)]
439/// Result of compiling English input to FOL with UI metadata.
440pub struct CompileResult {
441    /// Primary FOL output (Unicode format), if compilation succeeded.
442    pub logic: Option<String>,
443    /// Simplified FOL with modals stripped (for verification).
444    pub simple_logic: Option<String>,
445    /// Kripke semantics output with explicit world quantification.
446    pub kripke_logic: Option<String>,
447    /// AST tree representation for visualization.
448    pub ast: Option<AstNode>,
449    /// All scope readings in Unicode format.
450    pub readings: Vec<String>,
451    /// All scope readings in simplified format.
452    pub simple_readings: Vec<String>,
453    /// All scope readings in Kripke format.
454    pub kripke_readings: Vec<String>,
455    /// Tokenization with categories for syntax highlighting.
456    pub tokens: Vec<TokenInfo>,
457    /// Parse/compile error message, if any.
458    pub error: Option<String>,
459}
460
461/// Compile English input to FOL with full UI metadata.
462pub fn compile_for_ui(input: &str) -> CompileResult {
463    let tokens = tokenize_for_ui(input);
464    let readings = compile_forest(input);
465
466    // Generate Simple readings (modals stripped) - deduplicated
467    let simple_readings: Vec<String> = {
468        let raw = compile_forest_with_options(
469            input,
470            CompileOptions {
471                format: OutputFormat::SimpleFOL,
472                pragmatic: false,
473            },
474        );
475        let mut seen = HashSet::new();
476        raw.into_iter().filter(|r| seen.insert(r.clone())).collect()
477    };
478
479    // Generate Kripke readings with explicit world quantification
480    let kripke_readings = compile_forest_with_options(
481        input,
482        CompileOptions {
483            format: OutputFormat::Kripke,
484            pragmatic: false,
485        },
486    );
487
488    let mut interner = Interner::new();
489    let mut lexer = Lexer::new(input, &mut interner);
490    let lex_tokens = lexer.tokenize();
491
492    let mwe_trie = mwe::build_mwe_trie();
493    let lex_tokens = mwe::apply_mwe_pipeline(lex_tokens, &mwe_trie, &mut interner);
494
495    // Pass 1: Discovery
496    let type_registry = {
497        let mut discovery = DiscoveryPass::new(&lex_tokens, &mut interner);
498        discovery.run()
499    };
500
501    let expr_arena = Arena::new();
502    let term_arena = Arena::new();
503    let np_arena = Arena::new();
504    let sym_arena = Arena::new();
505    let role_arena = Arena::new();
506    let pp_arena = Arena::new();
507
508    let ctx = AstContext::new(
509        &expr_arena,
510        &term_arena,
511        &np_arena,
512        &sym_arena,
513        &role_arena,
514        &pp_arena,
515    );
516
517    // Pass 2: Parse
518    let mut world_state = drs::WorldState::new();
519    let mut parser = Parser::new(
520        lex_tokens,
521        &mut world_state,
522        &mut interner,
523        ctx,
524        type_registry,
525    );
526
527    match parser.parse() {
528        Ok(ast) => {
529            let ast = semantics::apply_axioms(ast, ctx.exprs, ctx.terms, &mut interner);
530            let ast = pragmatics::apply_pragmatics(ast, ctx.exprs, &interner);
531            let ast_node = expr_to_ast_node(ast, &interner);
532            let mut registry = SymbolRegistry::new();
533            let logic = ast.transpile_discourse(&mut registry, &interner, OutputFormat::Unicode);
534            let simple_logic =
535                ast.transpile_discourse(&mut registry, &interner, OutputFormat::SimpleFOL);
536
537            let kripke_ast =
538                semantics::apply_kripke_lowering(ast, ctx.exprs, ctx.terms, &mut interner);
539            let kripke_logic =
540                kripke_ast.transpile_discourse(&mut registry, &interner, OutputFormat::Kripke);
541
542            CompileResult {
543                logic: Some(logic),
544                simple_logic: Some(simple_logic),
545                kripke_logic: Some(kripke_logic),
546                ast: Some(ast_node),
547                readings,
548                simple_readings,
549                kripke_readings,
550                tokens,
551                error: None,
552            }
553        }
554        Err(e) => {
555            let advice = socratic_explanation(&e, &interner);
556            CompileResult {
557                logic: None,
558                simple_logic: None,
559                kripke_logic: None,
560                ast: None,
561                readings: Vec::new(),
562                simple_readings: Vec::new(),
563                kripke_readings: Vec::new(),
564                tokens,
565                error: Some(advice),
566            }
567        }
568    }
569}
570
571// ═══════════════════════════════════════════════════════════════════
572// Proof Integration
573// ═══════════════════════════════════════════════════════════════════
574
575/// Result of compiling English to a proof expression.
576///
577/// Used by the proof engine to search for derivations. Contains the
578/// converted proof expression, the simplified FOL string representation,
579/// and any compilation error.
580#[derive(Debug, Clone)]
581pub struct ProofCompileResult {
582    /// The compiled proof expression, or `None` on error.
583    pub proof_expr: Option<ProofExpr>,
584    /// Simplified FOL string representation for display.
585    pub logic_string: Option<String>,
586    /// Error message if compilation failed.
587    pub error: Option<String>,
588}
589
590/// Compile English input to ProofExpr for the proof engine.
591pub fn compile_for_proof(input: &str) -> ProofCompileResult {
592    use logicaffeine_language::proof_convert::logic_expr_to_proof_expr;
593
594    let mut interner = Interner::new();
595    let mut lexer = Lexer::new(input, &mut interner);
596    let lex_tokens = lexer.tokenize();
597
598    let mwe_trie = mwe::build_mwe_trie();
599    let lex_tokens = mwe::apply_mwe_pipeline(lex_tokens, &mwe_trie, &mut interner);
600
601    let type_registry = {
602        let mut discovery = DiscoveryPass::new(&lex_tokens, &mut interner);
603        discovery.run()
604    };
605
606    let expr_arena = Arena::new();
607    let term_arena = Arena::new();
608    let np_arena = Arena::new();
609    let sym_arena = Arena::new();
610    let role_arena = Arena::new();
611    let pp_arena = Arena::new();
612
613    let ctx = AstContext::new(
614        &expr_arena,
615        &term_arena,
616        &np_arena,
617        &sym_arena,
618        &role_arena,
619        &pp_arena,
620    );
621
622    let mut world_state = drs::WorldState::new();
623    let mut parser = Parser::new(
624        lex_tokens,
625        &mut world_state,
626        &mut interner,
627        ctx,
628        type_registry,
629    );
630
631    match parser.parse() {
632        Ok(ast) => {
633            let ast = semantics::apply_axioms(ast, ctx.exprs, ctx.terms, &mut interner);
634            let ast = pragmatics::apply_pragmatics(ast, ctx.exprs, &interner);
635
636            let mut registry = SymbolRegistry::new();
637            let logic_string = ast.transpile(&mut registry, &interner, OutputFormat::SimpleFOL);
638            let proof_expr = logic_expr_to_proof_expr(ast, &interner);
639
640            ProofCompileResult {
641                proof_expr: Some(proof_expr),
642                logic_string: Some(logic_string),
643                error: None,
644            }
645        }
646        Err(e) => {
647            let advice = socratic_explanation(&e, &interner);
648            ProofCompileResult {
649                proof_expr: None,
650                logic_string: None,
651                error: Some(advice),
652            }
653        }
654    }
655}
656
657/// Result of compiling and verifying a theorem block.
658///
659/// Contains the parsed theorem structure (name, premises, goal) along
660/// with the proof derivation tree if automatic proof search succeeded.
661#[derive(Debug, Clone)]
662pub struct TheoremCompileResult {
663    /// The theorem's declared name.
664    pub name: String,
665    /// Compiled premise expressions (axioms).
666    pub premises: Vec<ProofExpr>,
667    /// The goal expression to prove, or `None` on parse error.
668    pub goal: Option<ProofExpr>,
669    /// Simplified FOL string of the goal for display.
670    pub goal_string: Option<String>,
671    /// Derivation tree from backward chaining, if proof found.
672    pub derivation: Option<DerivationTree>,
673    /// True iff the derivation was certified AND kernel type-checked.
674    /// A derivation alone (`derivation.is_some()`) never implies this.
675    pub verified: bool,
676    /// Where verification broke (certification or type-check), if it did.
677    pub verification_error: Option<String>,
678    /// For a wh-question goal ("Who is in Florida?"), the certified witness(es); `None`
679    /// when the goal is a closed proposition.
680    pub answer: Option<Vec<String>>,
681    /// For a recognized finite-domain grid, the cells the certified prover could fill —
682    /// attached whenever the premises take the grid form, no flag required.
683    pub grid: Option<SolvedGrid>,
684    /// Error message if compilation or proof failed.
685    pub error: Option<String>,
686    /// How many obligations the DECLARED method left open and the automation closed.
687    ///
688    /// `0` means the author's own proof was complete — and also that there was no proof at
689    /// all: a count is a fact about a certificate, so an unverified theorem reports 0, exactly
690    /// as the prose door annotates only its certified arm. The TEXT door
691    /// (`logicaffeine_language::compile_theorem`) has always said this in prose — "Proved!
692    /// \[kernel-verified\] (2 residual obligations discharged by automation)" — and this door
693    /// silently dropped it, so two Surface A doors reported the same `verified: true` with
694    /// different amounts of disclosure. A `Proof:` line that declares a METHOD and closes
695    /// nothing (`By induction on n.` on a goal needing no induction) reaches `verified: true`
696    /// here, and this is the field that says the machine, not the author, did the work.
697    ///
698    /// It is disclosure, never trust: every swept obligation is assembled into the SAME
699    /// derivation and certified through `qed` → `check_derivation` → the kernel, so
700    /// `verified` means exactly what it meant before.
701    pub discharged: usize,
702}
703
704/// A solved (or partially solved) logic grid: the row entities plus one column per
705/// declared category closure. Every filled cell is an entailment the no-Z3 certified
706/// prover (CDCL+RUP / kernel) closed, so the whole table is independently checkable.
707#[derive(Debug, Clone, PartialEq)]
708pub struct SolvedGrid {
709    /// Display header for the identity column — the row sort (e.g. "Trip").
710    pub row_label: String,
711    /// The row entities in declaration order (e.g. Alpha, Beta, Gamma, Delta).
712    pub rows: Vec<String>,
713    /// One column per category closure (year, state, friend, activity, …).
714    pub columns: Vec<GridColumn>,
715}
716
717/// One category column of a [`SolvedGrid`].
718#[derive(Debug, Clone, PartialEq)]
719pub struct GridColumn {
720    /// Category header (the value sort, e.g. "Year"), best-effort from the declarations.
721    pub label: String,
722    /// The category's domain values in closure order.
723    pub values: Vec<String>,
724    /// The determined value for each row (parallel to [`SolvedGrid::rows`]), or `None`
725    /// where the prover could not force a unique value.
726    pub cells: Vec<Option<String>>,
727}
728
729/// The `Proof:` line a `## Theorem` block declared, lowered to what a driver needs.
730///
731/// There is ONE lowering of [`ProofStrategy`](logicaffeine_language::ast::theorem::ProofStrategy)
732/// in this crate, and it lives in [`declared_proof`]. Every Surface A door reads the declared
733/// method from here, which is the invariant that keeps two doors from reaching opposite
734/// verdicts on the same input.
735#[derive(Debug, Clone, Default)]
736struct DeclaredProof {
737    /// The tactic-script source to run, or `None` for `Auto` (automatic proof search).
738    script: Option<String>,
739    /// The INFERENCE-RULE name a one-word `Proof:` line gave (`ProofStrategy::ByRule`).
740    /// Only the diagnostic depends on it: a word the tactic namespace does not carry is
741    /// reported as a rule name rather than as a bad tactic.
742    rule_name: Option<String>,
743    /// `Given (h): …` names, parallel to the premises, so a script can cite `h`.
744    premise_names: Vec<Option<String>>,
745}
746
747/// Lower a theorem block's declared proof strategy. EXHAUSTIVE on purpose: a `_ => None`
748/// arm turned every non-`Auto`, non-`Script` strategy into a third, undefined state — "not
749/// auto, no script" — which reported the theorem as unproved with no error at all.
750fn declared_proof(theorem: &ast::theorem::TheoremBlock<'_>) -> DeclaredProof {
751    use ast::theorem::ProofStrategy;
752    let (script, rule_name) = match &theorem.strategy {
753        ProofStrategy::Auto => (None, None),
754        ProofStrategy::Script(s) => (Some(s.clone()), None),
755        ProofStrategy::ByRule(rule) => (Some(rule.clone()), Some(rule.clone())),
756        ProofStrategy::Induction(variable) => (Some(format!("induction {variable}")), None),
757    };
758    DeclaredProof {
759        script,
760        rule_name,
761        premise_names: theorem.premise_names.clone(),
762    }
763}
764
765/// Prove a Surface A theorem BY THE METHOD ITS AUTHOR DECLARED.
766///
767/// `verify_theorem`, [`prove_theorem_trace`] and [`theorem_certificate`] used to run
768/// automatic proof search unconditionally, ignoring the `Proof:` line entirely. A theorem
769/// whose declared proof was a tactic script was therefore certified by a search nobody
770/// wrote; worse, a theorem whose script is BROKEN still got a kernel term — and a portable
771/// CERTIFICATE — from these doors while `compile_theorem` failed loudly on the same input.
772/// Two doors, opposite verdicts, and no test between them.
773///
774/// `Auto` keeps the definition-aware automatic path. A declared script runs through the one
775/// vernacular driver. The two cannot be combined: `ProofState` carries no `## Define`
776/// environment, so a script plus definitions is refused rather than proved with the
777/// definitions silently dropped.
778///
779/// The second half of the answer is how many obligations the declared method LEFT and the
780/// automation closed — see [`TheoremCompileResult::discharged`]. It travels with the verdict
781/// rather than beside it, because a door that has the number and does not report it is how
782/// the two Surface A doors came to disclose different amounts about the same proof.
783fn prove_declared(
784    premises: &[ProofExpr],
785    goal: &ProofExpr,
786    definitions: &[logicaffeine_proof::verify::Definition],
787    declared: &DeclaredProof,
788) -> (logicaffeine_proof::verify::VerifiedProof, usize) {
789    let Some(script) = declared.script.as_deref() else {
790        return (
791            logicaffeine_proof::verify::prove_certify_check_with_defs(premises, goal, definitions),
792            0,
793        );
794    };
795    if !definitions.is_empty() {
796        return (
797            logicaffeine_proof::verify::VerifiedProof {
798                derivation: None,
799                proof_term: None,
800                kernel_ctx: Default::default(),
801                verified: false,
802                verification_error: Some(
803                    "a `Proof:` tactic script cannot see this document's `## Define` blocks — \
804                 the tactic state carries no definition environment. Either prove this \
805                 theorem with `Proof: Auto.` (which δ-unfolds the definitions) or inline \
806                 the definition"
807                        .to_string(),
808                ),
809            },
810            0,
811        );
812    }
813    logicaffeine_language::run_proof_sketch(
814        premises,
815        &declared.premise_names,
816        goal,
817        script,
818        declared.rule_name.as_deref(),
819    )
820}
821
822/// A parsed theorem block: premises and goal as owned (arena-free) `ProofExpr`s, the goal's
823/// display string, and whether the strategy is `Auto`. Factored out of
824/// [`compile_theorem_for_ui`] so the grounded grid problem can feed every trust tier and the
825/// benchmark, not just the kernel path.
826struct ParsedTheorem {
827    name: String,
828    premises: Vec<ProofExpr>,
829    goal: ProofExpr,
830    goal_string: String,
831    is_auto: bool,
832    /// An explicit `Proof:` tactic script (English-esque vernacular), if the block
833    /// gave one instead of `Auto`. Run by the tactic framework, kernel-certified.
834    script: Option<String>,
835    /// The INFERENCE-RULE name a one-word `Proof:` line gave
836    /// (`ProofStrategy::ByRule`). Only the diagnostic depends on it: a word the tactic
837    /// namespace does not carry is reported as a rule name rather than as a bad tactic.
838    rule_name: Option<String>,
839    /// Optional names for the premises (`Given (h): …`), parallel to `premises`, so a
840    /// script can refer to a premise as `h` rather than `hp0`.
841    premise_names: Vec<Option<String>>,
842    /// Whether the goal asks ("Who is in Florida?") rather than claims ("Some dog barks."):
843    /// a question is answered by its witnesses, a claim is proved.
844    asks: bool,
845}
846
847fn parse_theorem(input: &str) -> Result<ParsedTheorem, String> {
848    use logicaffeine_language::proof_convert::logic_expr_to_proof_expr;
849
850    let mut interner = Interner::new();
851    let mut lexer = Lexer::new(input, &mut interner);
852    let tokens = lexer.tokenize();
853
854    let mwe_trie = mwe::build_mwe_trie();
855    let tokens = mwe::apply_mwe_pipeline(tokens, &mwe_trie, &mut interner);
856
857    let type_registry = {
858        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
859        discovery.run()
860    };
861
862    let expr_arena = Arena::new();
863    let term_arena = Arena::new();
864    let np_arena = Arena::new();
865    let sym_arena = Arena::new();
866    let role_arena = Arena::new();
867    let pp_arena = Arena::new();
868
869    let ctx = AstContext::new(
870        &expr_arena,
871        &term_arena,
872        &np_arena,
873        &sym_arena,
874        &role_arena,
875        &pp_arena,
876    );
877
878    let mut world_state = drs::WorldState::new();
879    let mut parser = Parser::new(tokens, &mut world_state, &mut interner, ctx, type_registry);
880
881    let statements = parser.parse_program().map_err(|e| {
882        format!(
883            "Parse error: {}",
884            socratic_explanation(&e, &Interner::new())
885        )
886    })?;
887
888    let theorem = statements
889        .iter()
890        .find_map(|stmt| {
891            if let ast::Stmt::Theorem(t) = stmt {
892                Some(t)
893            } else {
894                None
895            }
896        })
897        .ok_or_else(|| "No theorem block found".to_string())?;
898
899    let premises: Vec<ProofExpr> = theorem
900        .premises
901        .iter()
902        .map(|p| logic_expr_to_proof_expr(p, &interner))
903        .collect();
904    let goal = logic_expr_to_proof_expr(theorem.goal, &interner);
905
906    let mut registry = SymbolRegistry::new();
907    let goal_string = theorem
908        .goal
909        .transpile(&mut registry, &interner, OutputFormat::SimpleFOL);
910
911    let DeclaredProof {
912        script,
913        rule_name,
914        premise_names,
915    } = declared_proof(theorem);
916
917    Ok(ParsedTheorem {
918        name: theorem.name.clone(),
919        premises,
920        goal,
921        goal_string,
922        is_auto: matches!(theorem.strategy, ast::theorem::ProofStrategy::Auto),
923        script,
924        rule_name,
925        premise_names,
926        asks: matches!(theorem.goal, ast::LogicExpr::Question { .. }),
927    })
928}
929
930/// A single theorem's verdict within a compiled formal development.
931#[derive(Debug, Clone)]
932pub struct TheoryTheoremResult {
933    pub name: String,
934    pub verified: bool,
935    pub error: Option<String>,
936}
937
938/// The result of compiling a program's formal development — its `## Axiom` declarations
939/// (a shared premise base) plus the theorems of its `## Theory` block, each discharged in
940/// citation order and kernel-certified by the multi-theorem driver.
941#[derive(Debug, Clone)]
942pub struct TheoryCompileResult {
943    pub theory_name: Option<String>,
944    pub axiom_count: usize,
945    /// The NAMES of every admitted axiom (standalone `## Axiom <name>` blocks and
946    /// `Axiom <name>` declarations in a `## Theory` body), in discovery order.
947    /// The inventory needs these to report axioms as named assumptions and to
948    /// reject a theorem/axiom name collision (G13-full) — a count alone cannot.
949    pub axiom_names: Vec<String>,
950    pub theorems: Vec<TheoryTheoremResult>,
951    pub parse_error: Option<String>,
952}
953
954impl TheoryCompileResult {
955    /// Whether every theorem in the development was kernel-certified (and it parsed).
956    pub fn all_verified(&self) -> bool {
957        self.parse_error.is_none()
958            && !self.theorems.is_empty()
959            && self.theorems.iter().all(|t| t.verified)
960    }
961}
962
963/// Compile a program's formal development end to end: collect every `## Axiom` (a shared
964/// premise base) and every `## Theory` block's `Axiom`/`Theorem` declarations, then prove
965/// the theorems in citation order, each kernel-certified by the multi-theorem driver. This
966/// is the seam that turns a Tarski-style source file into a verified development.
967pub fn compile_theory_for_ui(input: &str) -> TheoryCompileResult {
968    use logicaffeine_proof::development::parse_development;
969    use logicaffeine_proof::formula::parse_formula;
970    use logicaffeine_proof::verify::{prove_library_with_axioms, LibraryTheorem};
971
972    // Parse the program with the same wiring as `parse_theorem`.
973    let mut interner = Interner::new();
974    let mut lexer = Lexer::new(input, &mut interner);
975    let tokens = lexer.tokenize();
976    let mwe_trie = mwe::build_mwe_trie();
977    let tokens = mwe::apply_mwe_pipeline(tokens, &mwe_trie, &mut interner);
978    let type_registry = {
979        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
980        discovery.run()
981    };
982    let expr_arena = Arena::new();
983    let term_arena = Arena::new();
984    let np_arena = Arena::new();
985    let sym_arena = Arena::new();
986    let role_arena = Arena::new();
987    let pp_arena = Arena::new();
988    let ctx = AstContext::new(
989        &expr_arena,
990        &term_arena,
991        &np_arena,
992        &sym_arena,
993        &role_arena,
994        &pp_arena,
995    );
996    let mut world_state = drs::WorldState::new();
997    let mut parser = Parser::new(tokens, &mut world_state, &mut interner, ctx, type_registry);
998    let statements = match parser.parse_program() {
999        Ok(s) => s,
1000        Err(e) => {
1001            return TheoryCompileResult {
1002                theory_name: None,
1003                axiom_count: 0,
1004                axiom_names: Vec::new(),
1005                theorems: Vec::new(),
1006                parse_error: Some(format!(
1007                    "Parse error: {}",
1008                    socratic_explanation(&e, &Interner::new())
1009                )),
1010            }
1011        }
1012    };
1013
1014    // Collect the development: standalone `## Axiom` blocks + `## Theory` bodies.
1015    let mut axioms: Vec<ProofExpr> = Vec::new();
1016    let mut axiom_names: Vec<String> = Vec::new();
1017    let mut theorems: Vec<LibraryTheorem> = Vec::new();
1018    let mut theory_name: Option<String> = None;
1019
1020    for stmt in &statements {
1021        match stmt {
1022            ast::Stmt::Axiom(a) => match parse_formula(&a.formula) {
1023                Ok(expr) => {
1024                    axioms.push(expr);
1025                    axiom_names.push(a.name.clone());
1026                }
1027                Err(e) => {
1028                    return TheoryCompileResult {
1029                        theory_name,
1030                        axiom_count: axioms.len(),
1031                        axiom_names,
1032                        theorems: Vec::new(),
1033                        parse_error: Some(format!("Axiom '{}': {}", a.name, e)),
1034                    }
1035                }
1036            },
1037            ast::Stmt::Theory(t) => {
1038                if theory_name.is_none() {
1039                    theory_name = Some(t.name.clone());
1040                }
1041                if !t.body.trim().is_empty() {
1042                    match parse_development(&t.body) {
1043                        Ok(dev) => {
1044                            axiom_names.extend(dev.axioms.iter().map(|(n, _)| n.clone()));
1045                            axioms.extend(dev.axiom_exprs());
1046                            theorems.extend(dev.theorems);
1047                        }
1048                        Err(e) => {
1049                            return TheoryCompileResult {
1050                                theory_name,
1051                                axiom_count: axioms.len(),
1052                                axiom_names,
1053                                theorems: Vec::new(),
1054                                parse_error: Some(format!("Theory '{}': {}", t.name, e)),
1055                            }
1056                        }
1057                    }
1058                }
1059            }
1060            _ => {}
1061        }
1062    }
1063
1064    let results = prove_library_with_axioms(&axioms, &theorems);
1065    let theorem_results = theorems
1066        .iter()
1067        .zip(results)
1068        .map(|(t, r)| TheoryTheoremResult {
1069            name: t.name.clone(),
1070            verified: r.verified,
1071            error: r.verification_error,
1072        })
1073        .collect();
1074
1075    TheoryCompileResult {
1076        theory_name,
1077        axiom_count: axioms.len(),
1078        axiom_names,
1079        theorems: theorem_results,
1080        parse_error: None,
1081    }
1082}
1083
1084/// The GROUNDED, quantifier-free grid problem `(solver_input, goal)` for an `Auto` grid
1085/// theorem — the EXACT problem [`compile_theorem_for_ui`] solves, exposed so the trust tiers
1086/// (Untrusted CDCL / RUP / Kernel) and the benchmark all run the same input. `None` if the
1087/// theorem is not an `Auto` finite-domain grid.
1088pub fn grounded_grid_problem(input: &str) -> Option<(Vec<ProofExpr>, ProofExpr)> {
1089    let parsed = parse_theorem(input).ok()?;
1090    if !parsed.is_auto || !looks_like_grid(&parsed.premises) {
1091        return None;
1092    }
1093    let solver_input = prepare_premises_opts(&parsed.premises, true);
1094    let g = erase_tense(&parsed.goal);
1095    Some((solver_input, g))
1096}
1097
1098/// Compile a theorem block for UI display.
1099pub fn compile_theorem_for_ui(input: &str) -> TheoremCompileResult {
1100    let parsed = match parse_theorem(input) {
1101        Ok(p) => p,
1102        Err(e) => {
1103            return TheoremCompileResult {
1104                name: String::new(),
1105                premises: Vec::new(),
1106                goal: None,
1107                goal_string: None,
1108                derivation: None,
1109                verified: false,
1110                verification_error: None,
1111                answer: None,
1112                grid: None,
1113                error: Some(e),
1114                discharged: 0,
1115            };
1116        }
1117    };
1118    let ParsedTheorem {
1119        name,
1120        premises,
1121        goal,
1122        goal_string,
1123        is_auto,
1124        script,
1125        rule_name,
1126        premise_names,
1127        asks,
1128    } = parsed;
1129
1130    // The easter egg: when the premises take the grid form (declared bijection +
1131    // disjunctive closures), fill every cell the certified prover can force — no flag,
1132    // the structure alone triggers it. Attached to every grid result so the studio can
1133    // render the solved table alongside the headline goal.
1134    let grid = if is_auto && looks_like_grid(&premises) {
1135        solve_grid_from_premises(&premises, input)
1136    } else {
1137        None
1138    };
1139
1140    // How many obligations the DECLARED method left for the automation. Only the declared-
1141    // script route can leave any: `Auto` IS the automation, so its count is 0 by construction.
1142    let mut discharged = 0usize;
1143    let (derivation, verified, verification_error, answer) = if is_auto {
1144        // A wh-question goal ("Who is in Florida?") is an open ∃-form; the closed-goal
1145        // prover cannot discharge it and grinds a deep, futile search. Recognize the
1146        // question and ANSWER it by enumerating witnesses through the same certified no-Z3
1147        // path the puzzle uses — each candidate proved (or refuted) in ~1ms. A claim that
1148        // merely has an ∃ ("Some dog barks.") is proved like any other goal.
1149        if let (true, ProofExpr::Exists { variable, body }) = (asks, &goal) {
1150            let witnesses = answer_wh(&premises, variable, body);
1151            let verified = !witnesses.is_empty();
1152            let verr = (!verified)
1153                .then(|| "no individual in the domain satisfies the question".to_string());
1154            (None, verified, verr, Some(witnesses))
1155        } else {
1156            // A finite-domain GRID (a declared closure / "exactly one") is proved over
1157            // its GROUNDED, quantifier-free form, so the certified kernel can close it
1158            // in the browser (no Z3). An OPEN syllogism (Socrates: "every man is
1159            // mortal") is left untouched, keeping its `UniversalInst`/`ModusPonens`
1160            // trace. Both remain kernel-certified.
1161            let outcome = if looks_like_grid(&premises) {
1162                let g = erase_tense(&goal);
1163                // The incremental certified grid solver (trail propagation + DPLL) emits
1164                // a DerivationTree the kernel re-checks; it is faster and avoids the
1165                // general prover's re-saturation, and is the only path given the
1166                // FUNCTIONALITY exclusions. It is strictly additive: only a VERIFIED
1167                // solver tree is used, otherwise we fall back to the bounded backward
1168                // chainer (without functionality), so the solver can never regress.
1169                let solver_input = prepare_premises_opts(&premises, true);
1170                let solve = || {
1171                    let trace = std::env::var("LOGOS_TRACE").is_ok();
1172                    let t_solve = trace.then(std::time::Instant::now);
1173                    let tree = logicaffeine_proof::grid_solver::grid_prove(&solver_input, &g);
1174                    if let Some(t_solve) = t_solve {
1175                        let n = tree.as_ref().map(count_tree_nodes).unwrap_or(0);
1176                        eprintln!(
1177                            "[grid] solve+emit {:.2?} ({} tree nodes)",
1178                            t_solve.elapsed(),
1179                            n
1180                        );
1181                    }
1182                    let t_cert = trace.then(std::time::Instant::now);
1183                    let solved = tree
1184                        .map(|tree| {
1185                            logicaffeine_proof::verify::check_derivation(&solver_input, &g, tree)
1186                        })
1187                        .filter(|vp| vp.verified);
1188                    if let Some(t_cert) = t_cert {
1189                        eprintln!(
1190                            "[grid] kernel-certify {:.2?} (verified={})",
1191                            t_cert.elapsed(),
1192                            solved.is_some()
1193                        );
1194                    }
1195                    match solved {
1196                        Some(vp) => vp,
1197                        None => {
1198                            // The grid solver produced no certified tree. Before the
1199                            // expensive bounded chainer, ask the fast certified RUP tier
1200                            // whether the goal is even entailed — a non-entailed goal is
1201                            // decided in ~1ms instead of grinding a deep, futile search.
1202                            // (RUP runs the SAME `solver_input`, so a NotEntailed verdict is
1203                            // sound: the goal is not entailed by the premises.)
1204                            if matches!(
1205                                logicaffeine_proof::rup::entails_certified(&solver_input, &g),
1206                                Some(logicaffeine_proof::rup::Verdict::NotEntailed)
1207                            ) {
1208                                return logicaffeine_proof::verify::VerifiedProof {
1209                                    derivation: None,
1210                                    proof_term: None,
1211                                    kernel_ctx: Default::default(),
1212                                    verified: false,
1213                                    verification_error: Some(
1214                                        "goal is not entailed (RUP-certified)".to_string(),
1215                                    ),
1216                                };
1217                            }
1218                            let grounded = prepare_premises(&premises);
1219                            logicaffeine_proof::verify::prove_certify_check_bounded(
1220                                &grounded, &g, 60,
1221                            )
1222                        }
1223                    }
1224                };
1225                // A full multi-category grid's certified derivation recurses deeply
1226                // (case-analysis over every interdependent clue), so run the solve on a
1227                // generous stack — well past the default 8 MiB — on native targets.
1228                #[cfg(not(target_arch = "wasm32"))]
1229                {
1230                    std::thread::scope(|s| {
1231                        std::thread::Builder::new()
1232                            .stack_size(512 * 1024 * 1024)
1233                            .spawn_scoped(s, solve)
1234                            .expect("spawn grid-solve thread")
1235                            .join()
1236                            .expect("grid-solve thread panicked")
1237                    })
1238                }
1239                #[cfg(target_arch = "wasm32")]
1240                {
1241                    solve()
1242                }
1243            } else {
1244                logicaffeine_proof::verify::prove_certify_check(&premises, &goal)
1245            };
1246            (
1247                outcome.derivation,
1248                outcome.verified,
1249                outcome.verification_error,
1250                None,
1251            )
1252        }
1253    } else if script.is_some() {
1254        // An explicit `Proof:` line (English-esque vernacular): the SAME declared-method
1255        // driver every other Surface A door uses, run on a generous stack and
1256        // kernel-certified. (This door parses no `## Define` blocks, so its definition
1257        // environment is empty by construction.)
1258        let declared = DeclaredProof {
1259            script,
1260            rule_name,
1261            premise_names,
1262        };
1263        let run = || {
1264            let (vp, swept) = prove_declared(&premises, &goal, &[], &declared);
1265            (vp.derivation, vp.verified, vp.verification_error, swept)
1266        };
1267        #[cfg(not(target_arch = "wasm32"))]
1268        let (derivation, verified, verr, swept) = std::thread::scope(|s| {
1269            std::thread::Builder::new()
1270                .stack_size(256 * 1024 * 1024)
1271                .spawn_scoped(s, run)
1272                .expect("spawn proof-script thread")
1273                .join()
1274                .expect("proof-script thread panicked")
1275        });
1276        #[cfg(target_arch = "wasm32")]
1277        let (derivation, verified, verr, swept) = run();
1278        // A count is a fact about a PROOF. A sketch that did not certify has none, and
1279        // the prose door annotates only the certified arm — so reporting the sweep of a
1280        // failed run would make the two doors disagree in the other direction.
1281        discharged = if verified { swept } else { 0 };
1282        (derivation, verified, verr, None)
1283    } else {
1284        (None, false, None, None)
1285    };
1286
1287    TheoremCompileResult {
1288        name,
1289        premises,
1290        goal: Some(goal),
1291        goal_string: Some(goal_string),
1292        derivation,
1293        verified,
1294        verification_error,
1295        answer,
1296        grid,
1297        error: None,
1298        discharged,
1299    }
1300}
1301
1302fn count_tree_nodes(t: &logicaffeine_proof::DerivationTree) -> usize {
1303    1 + t.premises.iter().map(count_tree_nodes).sum::<usize>()
1304}
1305
1306// ═══════════════════════════════════════════════════════════════════
1307// Code Generation
1308// ═══════════════════════════════════════════════════════════════════
1309
1310/// Generate Rust code from LOGOS source — the Studio Code path. Mixed-document
1311/// aware: a source interleaving imperative code with Coq-style math
1312/// (`Definition`/`## Theorem:`/…) extracts the math into a bundled `mod proven` that
1313/// the imperative half calls into. Pure imperative source is a no-op partition.
1314#[cfg(feature = "codegen")]
1315pub fn generate_rust_code(source: &str) -> Result<String, ParseError> {
1316    let (imperative_src, math_src) = partition_mixed(source);
1317    let proven = match math_src.as_deref() {
1318        Some(math) => mixed_proven_module(math)?,
1319        None => None,
1320    };
1321    generate_rust_code_with_proven(&imperative_src, proven.as_deref())
1322}
1323
1324/// [`generate_rust_code`] with an already-extracted proven module bundled in.
1325#[cfg(feature = "codegen")]
1326pub fn generate_rust_code_with_proven(
1327    source: &str,
1328    proven: Option<&str>,
1329) -> Result<String, ParseError> {
1330    use logicaffeine_language::ast::stmt::{Expr, Stmt, TypeExpr};
1331    let library = crate::loader::LibraryProvenance::of(source);
1332
1333    let mut interner = Interner::new();
1334    let mut lexer = Lexer::new(source, &mut interner);
1335    let tokens = lexer.tokenize();
1336
1337    let mwe_trie = mwe::build_mwe_trie();
1338    let tokens = mwe::apply_mwe_pipeline(tokens, &mwe_trie, &mut interner);
1339
1340    let (type_registry, policy_registry) = {
1341        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
1342        let result = discovery.run_full();
1343        (result.types, result.policies)
1344    };
1345    let codegen_policies = policy_registry.clone();
1346
1347    let mut world_state = drs::WorldState::new();
1348    let expr_arena = Arena::new();
1349    let term_arena = Arena::new();
1350    let np_arena = Arena::new();
1351    let sym_arena = Arena::new();
1352    let role_arena = Arena::new();
1353    let pp_arena = Arena::new();
1354    let stmt_arena: Arena<Stmt> = Arena::new();
1355    let _compile_facts = crate::optimize::facts::scope();
1356    let imperative_expr_arena: Arena<Expr> = Arena::new();
1357    let type_expr_arena: Arena<TypeExpr> = Arena::new();
1358
1359    let ast_ctx = AstContext::with_types(
1360        &expr_arena,
1361        &term_arena,
1362        &np_arena,
1363        &sym_arena,
1364        &role_arena,
1365        &pp_arena,
1366        &stmt_arena,
1367        &imperative_expr_arena,
1368        &type_expr_arena,
1369    );
1370
1371    let mut parser = Parser::new(
1372        tokens,
1373        &mut world_state,
1374        &mut interner,
1375        ast_ctx,
1376        type_registry,
1377    );
1378    let stmts = parser.parse_program()?;
1379    let opt_flags = parser.program_opt_flags();
1380    let codegen_registry = parser.into_type_registry();
1381    let mut run_cfg =
1382        crate::optimization::OptimizationConfig::from_env().merged(&opt_flags);
1383    run_cfg.normalize();
1384    let resolved = crate::resolve_program::resolve_program(
1385        &stmts,
1386        crate::ast_map::Arenas {
1387            exprs: &imperative_expr_arena,
1388            stmts: &stmt_arena,
1389            types: &type_expr_arena,
1390        },
1391        &mut interner,
1392        run_cfg.is_on(crate::optimization::Opt::Comptime),
1393        library.functions(),
1394    );
1395    let stmts: Vec<Stmt> = match resolved {
1396        Some(rw) => rw.to_vec(),
1397        None => stmts,
1398    };
1399
1400    let type_env =
1401        crate::analysis::types::TypeEnv::infer_program(&stmts, &interner, &codegen_registry);
1402    let rust_code = crate::codegen::codegen_program_with_proven(
1403        &stmts,
1404        &codegen_registry,
1405        &codegen_policies,
1406        &interner,
1407        &type_env,
1408        &crate::optimization::OptimizationConfig::from_env(),
1409        "proven",
1410        proven,
1411    );
1412    Ok(rust_code)
1413}
1414
1415// ═══════════════════════════════════════════════════════════════════
1416// Interpreter (async)
1417// ═══════════════════════════════════════════════════════════════════
1418
1419/// Interpret LOGOS imperative code and return output lines.
1420///
1421/// Same engine dispatch as [`interpret_for_ui_sync`]: the bytecode VM runs
1422/// synchronous programs (with the tree-walker as the debug shadow oracle);
1423/// programs needing async (file I/O, sleep, mount) run on the tree-walker's
1424/// async executor.
1425/// The first Send/escape-analysis violation in `stmts`, packaged as a ready
1426/// rejection — or `None` if the program respects the message-passing + CRDT
1427/// memory model. This is the static concurrency gate (Phase 4): a program whose
1428/// concurrent branches share non-CRDT mutable state is refused *before* any tier
1429/// runs, so neither the VM nor the tree-walker executes a data race.
1430fn send_escape_rejection(
1431    stmts: &[logicaffeine_language::ast::stmt::Stmt],
1432) -> Option<InterpreterResult> {
1433    crate::concurrency::check_send_escape(stmts)
1434        .first()
1435        .map(|d| InterpreterResult {
1436            lines: Vec::new(),
1437            error: Some(d.message.clone()),
1438        })
1439}
1440
1441/// Reject a dimension-incoherent program (`2 meters + 1 gram`) BEFORE it runs, so the interpreter
1442/// tier matches the AOT compiler: a dimension mismatch is an analysis error on every tier, surfaced
1443/// before any output is produced — not a mid-execution failure. Mirrors `send_escape_rejection`.
1444fn send_dimension_rejection(
1445    stmts: &[logicaffeine_language::ast::stmt::Stmt],
1446    interner: &Interner,
1447) -> Option<InterpreterResult> {
1448    crate::analysis::dimension_check::DimensionChecker::new(interner)
1449        .check_program(stmts)
1450        .err()
1451        .map(|e| InterpreterResult {
1452            lines: Vec::new(),
1453            error: Some(e.message),
1454        })
1455}
1456
1457pub async fn interpret_for_ui(input: &str) -> InterpreterResult {
1458    interpret_for_ui_with_args(input, &[]).await
1459}
1460
1461/// Each run the IDE, a guide, an exercise or the REPL starts is a page load of its own: the document
1462/// its program paints starts empty, as a browser's does for a page it loads, so the nodes one run's
1463/// paint names are never taken for nodes an earlier run left behind.
1464fn begin_ui_run() {
1465    crate::semantics::dom::reset();
1466}
1467
1468/// The debug shadow oracle runs the program a second time. It paints a document of its own, so the
1469/// run the caller sees keeps the page its own engine drew, and the two runs' pages never meet.
1470#[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
1471fn in_a_document_of_its_own<T>(run: impl FnOnce() -> T) -> T {
1472    let shown = crate::semantics::dom::take();
1473    let out = run();
1474    crate::semantics::dom::restore(shown);
1475    out
1476}
1477
1478/// Like [`interpret_for_ui`], but supplies the program's argument vector to the
1479/// `args()` system native. `program_args` is the full argv (index 0 is the
1480/// program name), matching the compiled binary's `env::args()`.
1481pub async fn interpret_for_ui_with_args(input: &str, program_args: &[String]) -> InterpreterResult {
1482    begin_ui_run();
1483    // The synchronous dispatcher covers every non-async program; for async
1484    // ones it uses block_on, which would nest inside this future — so handle
1485    // the async case here with a real await.
1486    let needs_async = with_parsed_program(input, |parsed, interner| match parsed {
1487        Ok((stmts, _, _)) => crate::interpreter::needs_async(stmts, interner),
1488        Err(_) => false,
1489    });
1490    if needs_async && matches!(engine(), Engine::Jit | Engine::Vm) {
1491        if std::env::var_os("LOGOS_ENGINE_TRACE").is_some() {
1492            eprintln!("logos-engine: refused");
1493        }
1494        return InterpreterResult {
1495            lines: Vec::new(),
1496            error: Some(
1497                "the selected VM/JIT tier is sync-only; this program requires async execution"
1498                    .to_string(),
1499            ),
1500        };
1501    }
1502    if !needs_async {
1503        return interpret_for_ui_sync_with_args(input, program_args);
1504    }
1505
1506    // Match the sync path's preprocessing: wrap a bare script as `## Main`, then
1507    // demand-import the stdlib modules the program references. Without this an
1508    // async handler that calls a prelude function (http.lg's `plain`, net.lg's
1509    // `Message`, …) fails at runtime with "Unknown function".
1510    let implicit = implicit_main(input);
1511    let input = implicit.as_deref().unwrap_or(input);
1512    let prelude_src = crate::loader::apply_prelude(input);
1513    let input = prelude_src.as_ref();
1514    let library = crate::loader::LibraryProvenance::of(input);
1515
1516    use logicaffeine_language::ast::stmt::{Expr, Stmt, TypeExpr};
1517
1518    let mut interner = Interner::new();
1519    let mut lexer = Lexer::new(input, &mut interner);
1520    let tokens = lexer.tokenize();
1521
1522    let mwe_trie = mwe::build_mwe_trie();
1523    let mut tokens = mwe::apply_mwe_pipeline(tokens, &mwe_trie, &mut interner);
1524
1525    // Resolve the qualified escape hatch for cross-module calls (`Alias::fn` →
1526    // bare `fn`); no-op for single-file programs.
1527    let functions = crate::analysis::assemble::defined_function_names(input);
1528    crate::analysis::assemble::resolve_qualified_names(&mut tokens, &mut interner, &functions);
1529
1530    let (type_registry, policy_registry) = {
1531        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
1532        let result = discovery.run_full();
1533        (result.types, result.policies)
1534    };
1535
1536    let expr_arena = Arena::new();
1537    let term_arena = Arena::new();
1538    let np_arena = Arena::new();
1539    let sym_arena = Arena::new();
1540    let role_arena = Arena::new();
1541    let pp_arena = Arena::new();
1542    let stmt_arena: Arena<Stmt> = Arena::new();
1543    let _compile_facts = crate::optimize::facts::scope();
1544    let imperative_expr_arena: Arena<Expr> = Arena::new();
1545    let type_expr_arena: Arena<TypeExpr> = Arena::new();
1546
1547    let ctx = AstContext::with_types(
1548        &expr_arena,
1549        &term_arena,
1550        &np_arena,
1551        &sym_arena,
1552        &role_arena,
1553        &pp_arena,
1554        &stmt_arena,
1555        &imperative_expr_arena,
1556        &type_expr_arena,
1557    );
1558
1559    let mut world_state = drs::WorldState::new();
1560    let mut parser = Parser::new(tokens, &mut world_state, &mut interner, ctx, type_registry);
1561    let parsed = parser.parse_program();
1562    let opt_flags = parser.program_opt_flags();
1563    let type_registry_for_interp = parser.into_type_registry();
1564
1565    match parsed {
1566        Ok(stmts) => {
1567            let mut run_cfg =
1568                crate::optimization::OptimizationConfig::from_env().merged(&opt_flags);
1569            run_cfg.normalize();
1570            let resolved = crate::resolve_program::resolve_program(
1571                &stmts,
1572                crate::ast_map::Arenas {
1573                    exprs: &imperative_expr_arena,
1574                    stmts: &stmt_arena,
1575                    types: &type_expr_arena,
1576                },
1577                &mut interner,
1578                run_cfg.is_on(crate::optimization::Opt::Comptime),
1579                library.functions(),
1580            );
1581            let stmts: Vec<Stmt> = match resolved {
1582                Some(rw) => rw.to_vec(),
1583                None => stmts,
1584            };
1585            if let Some(rejection) = send_escape_rejection(&stmts) {
1586                return rejection;
1587            }
1588            // A program that uses channels/tasks AND needs async (e.g. networking) must run
1589            // on the cooperative scheduler — `interp.run` alone installs none, so a channel op
1590            // would panic "outside a scheduler context". The async drive loop services both
1591            // the channel ops and the network awaits (the latter over the host reactor). A
1592            // pure-channel program (no async) never reaches here; it takes the sync path.
1593            if crate::concurrency::uses_scheduler(&stmts) {
1594                return run_program_concurrent_streaming(
1595                    &stmts,
1596                    &type_registry_for_interp,
1597                    policy_registry,
1598                    &interner,
1599                    program_args,
1600                    None,
1601                    None,
1602                    None,
1603                    0,
1604                )
1605                .await;
1606            }
1607            let mut interp = crate::interpreter::Interpreter::new(&interner)
1608                .with_type_registry(&type_registry_for_interp)
1609                .with_policies(policy_registry)
1610                .with_program_args(program_args.to_vec());
1611            let run_result = interp.run(&stmts).await;
1612            let unhandled = interp.take_page_failure();
1613            InterpreterResult {
1614                error: run_result.err().or(unhandled),
1615                lines: interp.output,
1616            }
1617        }
1618        Err(e) => {
1619            let advice = socratic_explanation(&e, &interner);
1620            InterpreterResult {
1621                lines: vec![],
1622                error: Some(advice),
1623            }
1624        }
1625    }
1626}
1627
1628/// The execution front-end shared by every engine: lex → MWE → discovery →
1629/// parse. The tree-walker and the bytecode VM MUST both come through here so
1630/// they see the identical token stream, type registry, and policies — a
1631/// differential test that parses differently per engine is comparing two
1632/// different programs.
1633///
1634/// Parsed statements borrow stack-local arenas, so they are handed to the
1635/// closure rather than returned. A parse failure is delivered as
1636/// `Err(socratic advice text)` — also identical for both engines.
1637///
1638/// This private core also installs the file's `## No <opt>` decorators as the active config
1639/// (so the VM compiler's opt gates honor them) and hands the closure the `## Require` demands
1640/// so a Result-returning caller can enforce them. The public [`with_parsed_program`] /
1641/// [`with_parsed_program_checked`] wrappers select whether `## Require` is verified.
1642/// [`parse_seam_e`], with the failure already rendered as its Socratic message.
1643///
1644/// The overwhelming majority of callers want the sentence and nothing else. The few that need to
1645/// point AT the mistake — a dev-server overlay, a diagnostic with a caret — take the seam below
1646/// and keep the span.
1647fn parse_seam<R>(
1648    input: &str,
1649    body: impl for<'a> FnOnce(
1650        Result<
1651            (
1652                &'a [logicaffeine_language::ast::stmt::Stmt<'a>],
1653                &'a logicaffeine_language::analysis::TypeRegistry,
1654                logicaffeine_language::analysis::PolicyRegistry,
1655            ),
1656            String,
1657        >,
1658        &'a Interner,
1659        Vec<crate::optimization::Opt>,
1660    ) -> R,
1661) -> R {
1662    parse_seam_e(input, |parsed, interner, facts| {
1663        body(
1664            parsed.map_err(|e| socratic_explanation(&e, interner)),
1665            interner,
1666            facts.required,
1667        )
1668    })
1669}
1670
1671/// How a span of the text the parser saw maps back to the author's own text: the seam wraps a bare
1672/// script as `## Main` (a prefix) and then splices the stdlib modules the program uses (after any
1673/// leading prose). Both edits are undone here, once, so every span leaving the seam is a span of
1674/// the file the author wrote.
1675struct UserText {
1676    /// The `## Main\n` prefix the implicit-main wrap added, or 0.
1677    implicit_prefix: usize,
1678    /// The exact splice `apply_prelude_mapped` performed on the wrapped text.
1679    segments: Vec<crate::loader::PreludeSegment>,
1680}
1681
1682impl UserText {
1683    /// `span` in the author's text, or `None` when it lies in text the seam added.
1684    fn span(&self, span: crate::token::Span) -> Option<crate::token::Span> {
1685        let wrapped = crate::compile::prelude_user_span(&self.segments, span)?;
1686        if wrapped.start < self.implicit_prefix {
1687            return None;
1688        }
1689        Some(crate::token::Span::new(
1690            wrapped.start - self.implicit_prefix,
1691            wrapped.end - self.implicit_prefix,
1692        ))
1693    }
1694
1695    /// `span` in the author's text; a span in added text becomes the default (no location).
1696    fn span_or_default(&self, span: crate::token::Span) -> crate::token::Span {
1697        self.span(span).unwrap_or_default()
1698    }
1699}
1700
1701/// What the parser learned about a program besides its statements.
1702struct ParseFacts {
1703    /// The optimizations `## Require` demands.
1704    required: Vec<crate::optimization::Opt>,
1705    /// The LGX accessibility and structure findings, their spans in the author's text.
1706    findings: Vec<logicaffeine_language::lgx::check::Finding>,
1707    /// The value-semantics copy lint's findings, their spans in the author's text — see
1708    /// `value_copy_findings_of`.
1709    copy_findings: Vec<logicaffeine_language::lint::Finding>,
1710    /// Every tensor the program binds, as `(rows, cols)` — see `Parser::tensor_shapes`.
1711    tensor_shapes: std::collections::HashMap<logicaffeine_base::Symbol, (i64, i64)>,
1712    /// Every `Stmt::Site` marker's `(span, component, action)`, in the AUTHOR's own file
1713    /// coordinates — translated here, once, the same way `findings` is just below, so a runtime
1714    /// failure's location never needs a second, bespoke undoing of the implicit-`## Main`/stdlib
1715    /// splice (`FailureSite`'s own doc comment names that exact double-mapping shape as a past bug).
1716    failure_sites: Vec<logicaffeine_language::ast::stmt::FailureSite>,
1717    /// The map from the parsed text back to the author's.
1718    user_text: UserText,
1719}
1720
1721/// The parse seam, handing a failure over whole — message AND span — so a caller that points at
1722/// a location has one. [`parse_seam`] is the message-shaped wrapper most callers take.
1723
1724fn parse_seam_e<R>(
1725    input: &str,
1726    body: impl for<'a> FnOnce(
1727        Result<
1728            (
1729                &'a [logicaffeine_language::ast::stmt::Stmt<'a>],
1730                &'a logicaffeine_language::analysis::TypeRegistry,
1731                logicaffeine_language::analysis::PolicyRegistry,
1732            ),
1733            logicaffeine_language::error::ParseError,
1734        >,
1735        &'a Interner,
1736        ParseFacts,
1737    ) -> R,
1738) -> R {
1739    parse_seam_with(input, None, body)
1740}
1741
1742/// [`parse_seam_e`], and — under `mono` — the program handed on is the monomorphic one
1743/// ([`crate::monomorphize`]): every generic function and applied generic type made concrete, for
1744/// a backend that lowers only concrete code.
1745fn parse_seam_with<R>(
1746    input: &str,
1747    mono: Option<crate::monomorphize::Options>,
1748    body: impl for<'a> FnOnce(
1749        Result<
1750            (
1751                &'a [logicaffeine_language::ast::stmt::Stmt<'a>],
1752                &'a logicaffeine_language::analysis::TypeRegistry,
1753                logicaffeine_language::analysis::PolicyRegistry,
1754            ),
1755            logicaffeine_language::error::ParseError,
1756        >,
1757        &'a Interner,
1758        ParseFacts,
1759    ) -> R,
1760) -> R {
1761    use logicaffeine_language::ast::stmt::{Expr, Stmt, TypeExpr};
1762
1763    // A bare script (no `##` headers, imperative opening) runs as `## Main`.
1764    let implicit = implicit_main(input);
1765    let implicit_prefix = implicit
1766        .as_ref()
1767        .map_or(0, |wrapped| wrapped.len() - input.len());
1768    let input = implicit.as_deref().unwrap_or(input);
1769
1770    // Phase 10: auto-prepend the stdlib modules the program references (no-op when
1771    // it uses no stdlib vocabulary, so such programs stay byte-identical).
1772    let (prelude_src, segments) = crate::loader::apply_prelude_mapped(input);
1773    let user_text = UserText {
1774        implicit_prefix,
1775        segments,
1776    };
1777    let input = prelude_src.as_ref();
1778    let library = crate::loader::LibraryProvenance::of(input);
1779
1780    let mut interner = Interner::new();
1781    let mut lexer = Lexer::new(input, &mut interner);
1782    let tokens = lexer.tokenize();
1783
1784    let mwe_trie = mwe::build_mwe_trie();
1785    let mut tokens = mwe::apply_mwe_pipeline(tokens, &mwe_trie, &mut interner);
1786
1787    // Resolve the qualified escape hatch for cross-module calls (`Alias::fn` →
1788    // bare `fn`); no-op for single-file programs. Feeds the VM, JIT, wasm, isa,
1789    // and sync-interpreter tiers that share this seam.
1790    let functions = crate::analysis::assemble::defined_function_names(input);
1791    crate::analysis::assemble::resolve_qualified_names(&mut tokens, &mut interner, &functions);
1792
1793    let (type_registry, policy_registry) = {
1794        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
1795        let result = discovery.run_full();
1796        (result.types, result.policies)
1797    };
1798
1799    let expr_arena = Arena::new();
1800    let term_arena = Arena::new();
1801    let np_arena = Arena::new();
1802    let sym_arena = Arena::new();
1803    let role_arena = Arena::new();
1804    let pp_arena = Arena::new();
1805    let stmt_arena: Arena<Stmt> = Arena::new();
1806    let _compile_facts = crate::optimize::facts::scope();
1807    let imperative_expr_arena: Arena<Expr> = Arena::new();
1808    let type_expr_arena: Arena<TypeExpr> = Arena::new();
1809
1810    let ctx = AstContext::with_types(
1811        &expr_arena,
1812        &term_arena,
1813        &np_arena,
1814        &sym_arena,
1815        &role_arena,
1816        &pp_arena,
1817        &stmt_arena,
1818        &imperative_expr_arena,
1819        &type_expr_arena,
1820    );
1821
1822    let mut world_state = drs::WorldState::new();
1823    let (parsed, opt_flags, facts, type_registry_for_engines) = {
1824        let mut parser = Parser::new(tokens, &mut world_state, &mut interner, ctx, type_registry);
1825        let stmts = parser.parse_program();
1826        let flags = parser.program_opt_flags();
1827        let findings = parser
1828            .lgx_findings()
1829            .iter()
1830            .cloned()
1831            .map(|mut f| {
1832                f.span = user_text.span_or_default(f.span);
1833                f
1834            })
1835            .collect();
1836        let failure_sites = parser
1837            .failure_sites()
1838            .iter()
1839            .cloned()
1840            .map(|mut s| {
1841                s.span = user_text.span_or_default(s.span);
1842                s
1843            })
1844            .collect();
1845        let copy_findings = parser
1846            .value_copy_findings()
1847            .iter()
1848            .cloned()
1849            .map(|mut f| {
1850                f.span = user_text.span_or_default(f.span);
1851                f
1852            })
1853            .collect();
1854        let facts = ParseFacts {
1855            required: parser.required_optimizations(),
1856            findings,
1857            tensor_shapes: parser.tensor_shapes().clone(),
1858            failure_sites,
1859            copy_findings,
1860            user_text,
1861        };
1862        (stmts, flags, facts, parser.into_type_registry())
1863    };
1864
1865    let parsed =
1866        parsed.and_then(
1867            |stmts| match crate::analysis::refuse_retired_calls(&stmts, &interner) {
1868                Ok(()) => Ok(stmts),
1869                Err(refusal) => Err(logicaffeine_language::error::ParseError {
1870                    kind: logicaffeine_language::error::ParseErrorKind::Custom(refusal),
1871                    span: logicaffeine_language::token::Span::default(),
1872                }),
1873            },
1874        );
1875    // Under `mono`, the program as its concrete instances (see `parse_seam_with`).
1876    let parsed = match (parsed, mono) {
1877        (Ok(stmts), Some(opts)) => crate::monomorphize::monomorphize(
1878            &stmts,
1879            &type_registry_for_engines,
1880            &mut interner,
1881            crate::ast_map::Arenas {
1882                exprs: &imperative_expr_arena,
1883                stmts: &stmt_arena,
1884                types: &type_expr_arena,
1885            },
1886            opts,
1887        )
1888        .map(|m| (m.stmts, Some(m.registry)))
1889        .map_err(|message| logicaffeine_language::error::ParseError {
1890            kind: logicaffeine_language::error::ParseErrorKind::Custom(message),
1891            span: logicaffeine_language::token::Span::default(),
1892        }),
1893        (Ok(stmts), None) => Ok((stmts, None)),
1894        (Err(e), _) => Err(e),
1895    };
1896    match parsed {
1897        Ok((stmts, mono_registry)) => {
1898            let type_registry_for_engines = mono_registry.unwrap_or(type_registry_for_engines);
1899            // Strength-reduce accumulator recursion to a constant-stack `while`
1900            // loop so the VM and tree-walker match the AOT (and never hit the
1901            // call-depth limit on `Return n + f(n-1)`-shaped recursion).
1902            // Type-directed division: rewrite `Divide → ExactDivide` in Rational
1903            // contexts (default stays floor), then accumulator-TCO the resolved AST.
1904            // The constant Rational fold honors the `Opt::Comptime` toggle (env +
1905            // in-source `## No comptime`), consistent with the AOT and tiered paths.
1906            let mut run_cfg =
1907                crate::optimization::OptimizationConfig::from_env().merged(&opt_flags);
1908            run_cfg.normalize();
1909            // Install `## No` as the active config so the VM compiler's opt gates
1910            // (`NarrowVm`/`FastDiv`/`Borrow`) honor it too — the AOT path gets this via
1911            // `optimize_program`; the raw VM/wasm/isa seam needs it explicitly.
1912            crate::optimize::set_active_config(run_cfg);
1913            let resolved = crate::resolve_program::resolve_program(
1914                &stmts,
1915                crate::ast_map::Arenas {
1916                    exprs: &imperative_expr_arena,
1917                    stmts: &stmt_arena,
1918                    types: &type_expr_arena,
1919                },
1920                &mut interner,
1921                run_cfg.is_on(crate::optimization::Opt::Comptime),
1922                library.functions(),
1923            );
1924            let pre = resolved.unwrap_or(stmts.as_slice());
1925            match crate::tail_call::rewrite_accumulators(
1926                pre,
1927                &stmt_arena,
1928                &imperative_expr_arena,
1929                &mut interner,
1930            ) {
1931                Some(rw) => body(
1932                    Ok((rw, &type_registry_for_engines, policy_registry)),
1933                    &interner,
1934                    facts,
1935                ),
1936                None => body(
1937                    Ok((pre, &type_registry_for_engines, policy_registry)),
1938                    &interner,
1939                    facts,
1940                ),
1941            }
1942        }
1943        Err(e) => body(Err(e), &interner, facts),
1944    }
1945}
1946
1947/// The execution front-end shared by every engine (see `parse_seam`): lex → MWE → discovery →
1948/// parse, with the file's `## No` decorators installed as the active config. `## Require` is NOT
1949/// enforced here — this generic variant serves the differential-test seams and callers whose
1950/// return type can't carry a compile error; use [`with_parsed_program_checked`] for the emit
1951/// paths that must fail an unfired `## Require`.
1952pub fn with_parsed_program<R>(
1953    input: &str,
1954    f: impl for<'a> FnOnce(
1955        Result<
1956            (
1957                &'a [logicaffeine_language::ast::stmt::Stmt<'a>],
1958                &'a logicaffeine_language::analysis::TypeRegistry,
1959                logicaffeine_language::analysis::PolicyRegistry,
1960            ),
1961            String,
1962        >,
1963        &'a Interner,
1964    ) -> R,
1965) -> R {
1966    parse_seam(input, |parsed, interner, _required| f(parsed, interner))
1967}
1968
1969/// [`with_parsed_program`] that also hands over every tensor's `(rows, cols)` — the shape table the parser keeps
1970/// and the desugared statements do not (a declaration desugars to a flat `Seq` of `rows · cols` elements). The
1971/// spatial walk reads it to declare each tensor in the shape the program gives it.
1972pub fn with_parsed_tensor_program<R>(
1973    input: &str,
1974    f: impl for<'a> FnOnce(
1975        Result<
1976            (
1977                &'a [logicaffeine_language::ast::stmt::Stmt<'a>],
1978                &'a logicaffeine_language::analysis::TypeRegistry,
1979                logicaffeine_language::analysis::PolicyRegistry,
1980            ),
1981            String,
1982        >,
1983        &'a Interner,
1984        &std::collections::HashMap<logicaffeine_base::Symbol, (i64, i64)>,
1985    ) -> R,
1986) -> R {
1987    parse_seam_e(input, |parsed, interner, facts| {
1988        f(
1989            parsed.map_err(|e| socratic_explanation(&e, interner)),
1990            interner,
1991            &facts.tensor_shapes,
1992        )
1993    })
1994}
1995
1996/// [`with_parsed_program`] for a Result-returning compile (the `emit c`/`isa`/`wasm` backends):
1997/// installs `## No`, opens a `## Require` firing-trace around `f`, and after `f` succeeds fails
1998/// the compile on any demanded optimization that did not fire — the honest answer when a backend
1999/// (e.g. the VM tiers, which don't memoize) cannot provide a required optimization. `f`'s own
2000/// error propagates unchanged.
2001///
2002/// `f` is handed the parse Result RAW — spans still in the prelude-expanded text `f` actually
2003/// parsed, exactly like every backend's own `stmts` — and undone EXACTLY ONCE, at the single point
2004/// below where an error leaves this function. `f` may return the parse error unchanged (the
2005/// overwhelming majority: `let (stmts, ..) = parsed?;`) or a NEW error located at an AST span
2006/// `compile_with_oracle_located` or a resolver check built (also still prelude-coordinate,
2007/// unavoidably, since nothing between the parse and here ever undoes the splice) — both need the
2008/// SAME one undoing, so there is exactly one place to trust and it runs on whatever comes out,
2009/// not on what goes in. Undoing it going IN as well as coming OUT re-translated an already-correct
2010/// span a second time: the splice's stdlib segment is typically the largest run in the expanded
2011/// text, so almost any small, correct, already-undone offset falls inside where IT sits and maps
2012/// to "added text" — silently becoming `Span::default()` for any caller whose `f` simply forwards
2013/// `parsed`'s own error, which is the shape every current caller uses.
2014pub fn with_parsed_program_checked<T>(
2015    input: &str,
2016    f: impl for<'a> FnOnce(
2017        Result<
2018            (
2019                &'a [logicaffeine_language::ast::stmt::Stmt<'a>],
2020                &'a logicaffeine_language::analysis::TypeRegistry,
2021                logicaffeine_language::analysis::PolicyRegistry,
2022            ),
2023            logicaffeine_language::error::ParseError,
2024        >,
2025        &'a Interner,
2026    ) -> Result<T, crate::error::ParseError>,
2027) -> Result<T, crate::error::ParseError> {
2028    parse_seam_e(input, |parsed, interner, facts| {
2029        let gate = crate::optimize::DecoratorGate::for_required(facts.required);
2030        let user_text = facts.user_text;
2031        match f(parsed, interner) {
2032            Ok(t) => gate
2033                .verify()
2034                .map(|_| t)
2035                .map_err(|m| crate::error::ParseError {
2036                    kind: crate::error::ParseErrorKind::Custom(m),
2037                    span: crate::token::Span::default(),
2038                }),
2039            Err(mut e) => {
2040                gate.close();
2041                e.span = user_text.span_or_default(e.span);
2042                Err(e)
2043            }
2044        }
2045    })
2046}
2047
2048/// [`with_parsed_program`] over the program's monomorphic form ([`crate::monomorphize`]) — every
2049/// generic function and applied generic type made concrete — for a backend that lowers only
2050/// concrete code.
2051pub fn with_monomorphic_program<R>(
2052    input: &str,
2053    options: crate::monomorphize::Options,
2054    f: impl for<'a> FnOnce(
2055        Result<
2056            (
2057                &'a [logicaffeine_language::ast::stmt::Stmt<'a>],
2058                &'a logicaffeine_language::analysis::TypeRegistry,
2059                logicaffeine_language::analysis::PolicyRegistry,
2060            ),
2061            String,
2062        >,
2063        &'a Interner,
2064    ) -> R,
2065) -> R {
2066    parse_seam_with(input, Some(options), |parsed, interner, _facts| {
2067        f(
2068            parsed.map_err(|e| socratic_explanation(&e, interner)),
2069            interner,
2070        )
2071    })
2072}
2073
2074/// [`with_parsed_program_checked`] over the program's monomorphic form ([`crate::monomorphize`]) —
2075/// every generic function and applied generic type made concrete — for a backend that lowers only
2076/// concrete code.
2077pub fn with_monomorphic_program_checked<T>(
2078    input: &str,
2079    options: crate::monomorphize::Options,
2080    f: impl for<'a> FnOnce(
2081        Result<
2082            (
2083                &'a [logicaffeine_language::ast::stmt::Stmt<'a>],
2084                &'a logicaffeine_language::analysis::TypeRegistry,
2085                logicaffeine_language::analysis::PolicyRegistry,
2086            ),
2087            logicaffeine_language::error::ParseError,
2088        >,
2089        &'a Interner,
2090    ) -> Result<T, crate::error::ParseError>,
2091) -> Result<T, crate::error::ParseError> {
2092    parse_seam_with(input, Some(options), |parsed, interner, facts| {
2093        let gate = crate::optimize::DecoratorGate::for_required(facts.required);
2094        let user_text = facts.user_text;
2095        match f(parsed, interner) {
2096            Ok(t) => gate
2097                .verify()
2098                .map(|_| t)
2099                .map_err(|m| crate::error::ParseError {
2100                    kind: crate::error::ParseErrorKind::Custom(m),
2101                    span: crate::token::Span::default(),
2102                }),
2103            Err(mut e) => {
2104                gate.close();
2105                e.span = user_text.span_or_default(e.span);
2106                Err(e)
2107            }
2108        }
2109    })
2110}
2111
2112/// The accessibility and structure warnings `lgx/check.rs` computes for `input`.
2113///
2114/// ★ THE CHECKER RAN ON EVERY PARSE AND NOTHING READ IT. `img` without `alt`, a `button` that
2115/// announces nothing, an input with no label, a link with no href — all computed, all discarded,
2116/// because `Parser::lgx_findings()` had exactly one caller and it was a test. That is the failure
2117/// its own lock warns about ("a checker nobody runs is worse than no checker"), one layer up.
2118pub fn lgx_findings_of(input: &str) -> Vec<logicaffeine_language::lgx::check::Finding> {
2119    parse_seam_e(input, |_parsed, _interner, facts| facts.findings)
2120}
2121
2122/// The value-semantics copy lint's warnings for `input` — see `logicaffeine_language::lint`. Same
2123/// shape as [`lgx_findings_of`]: computed on every parse, worth nothing until something reads it.
2124pub fn value_copy_findings_of(input: &str) -> Vec<logicaffeine_language::lint::Finding> {
2125    parse_seam_e(input, |_parsed, _interner, facts| facts.copy_findings)
2126}
2127
2128/// Every [`Stmt::Site`](logicaffeine_language::ast::stmt::Stmt::Site) marker `input` parsed to, as
2129/// the `(span, component, action)` [`FailureSite`](logicaffeine_language::ast::stmt::FailureSite)
2130/// the marker's id indexes — in the author's own file coordinates, the implicit-`## Main` wrap and
2131/// the stdlib-prelude splice already undone (matching [`lgx_findings_of`]/[`parse_error_of`]'s own
2132/// treatment). The tree-walker's `current_site()` and a compiled program's `site_at` pc-lookup both
2133/// answer an id into THIS SAME table; whoever renders a runtime failure looks it up here and calls
2134/// [`FailureSite::render`](logicaffeine_language::ast::stmt::FailureSite::render) with the message.
2135pub fn failure_sites_of(input: &str) -> Vec<logicaffeine_language::ast::stmt::FailureSite> {
2136    parse_seam_e(input, |_parsed, _interner, facts| facts.failure_sites)
2137}
2138
2139/// The parse error for `input`, in the AUTHOR's own file coordinates — the implicit-`## Main` wrap
2140/// and the stdlib-prelude splice both undone, exactly as [`with_parsed_program_checked`] undoes
2141/// them for its callers — or `None` when `input` parses. A pure parse check with no `## Require`
2142/// gate: a caller that wants to render its OWN caret block (`largo run --interpret`, matching what
2143/// `largo check` already shows) takes the located error from here instead of formatting whatever
2144/// `Result::Err` variant happened to reach it.
2145pub fn parse_error_of(input: &str) -> Option<logicaffeine_language::error::ParseError> {
2146    parse_seam_e(input, |parsed, _interner, facts| {
2147        parsed.err().map(|mut e| {
2148            e.span = facts.user_text.span_or_default(e.span);
2149            e
2150        })
2151    })
2152}
2153
2154/// The `## Require <opt>` demands declared in `input` (a lightweight parse via `parse_seam`).
2155/// Empty for a program with no `## Require` decorators.
2156pub fn program_required_opts(input: &str) -> Vec<crate::optimization::Opt> {
2157    parse_seam(input, |_parsed, _interner, required| required)
2158}
2159
2160/// The tree-walk interpreter (`largo run --interpret`) is the raw differential tier — it applies
2161/// NO optimizations, so it cannot satisfy any `## Require <opt>`. Returns the honest error for the
2162/// first requirement (mirroring the compiled tiers' message), or `None` when there is none.
2163pub fn interpret_unsatisfiable_require(input: &str) -> Option<String> {
2164    program_required_opts(input).first().map(|opt| {
2165        let kw = opt.meta().keyword;
2166        format!(
2167            "`## Require {kw}` was declared, but the `{kw}` optimization did not fire — the \
2168             tree-walk interpreter (`--interpret`) applies no optimizations. Run the compiled \
2169             tier (`largo run` / `largo build` / `largo emit`) to satisfy it, or remove the \
2170             `## Require {kw}`."
2171        )
2172    })
2173}
2174
2175/// [`with_parsed_program`], but the statements pass through the RUN-PATH
2176/// optimizer (EXODIA D1: the Futamura residual — PE, GVN, LICM, closed-form,
2177/// deforestation, interval analysis, DCE) before reaching the closure. The
2178/// live `largo run` engines consume this; the differential seams stay on the
2179/// raw variant so optimizer correctness is itself differentially gated
2180/// (optimized-VM vs raw-tree-walker).
2181pub fn with_optimized_program<R>(
2182    input: &str,
2183    f: impl for<'a> FnOnce(
2184        Result<
2185            (
2186                &'a [logicaffeine_language::ast::stmt::Stmt<'a>],
2187                &'a logicaffeine_language::analysis::TypeRegistry,
2188                logicaffeine_language::analysis::PolicyRegistry,
2189            ),
2190            String,
2191        >,
2192        &'a Interner,
2193    ) -> R,
2194) -> R {
2195    with_optimized_program_scoped(input, None, f)
2196}
2197
2198/// [`with_optimized_program`], with the assembled project's file scope checked
2199/// on the same parsed AST before it is optimized.  Project runners use this to
2200/// avoid assembling and parsing the entire project a second time merely to
2201/// enforce import visibility.
2202pub fn with_optimized_program_scoped<R>(
2203    input: &str,
2204    scope: Option<&crate::analysis::ScopeInfo>,
2205    f: impl for<'a> FnOnce(
2206        Result<
2207            (
2208                &'a [logicaffeine_language::ast::stmt::Stmt<'a>],
2209                &'a logicaffeine_language::analysis::TypeRegistry,
2210                logicaffeine_language::analysis::PolicyRegistry,
2211            ),
2212            String,
2213        >,
2214        &'a Interner,
2215    ) -> R,
2216) -> R {
2217    // The run-path upfront tier is the env-configured mode (default Eager → T3, i.e.
2218    // today's behavior, bit-for-bit). `LOGOS_TIER_PROFILE`/`LOGOS_FORCE_TIER` select
2219    // Tiered/Baseline for the benchmark A/B and the T_optimize measurement (§12.1).
2220    let tier = crate::optimization::HotswapConfig::from_env().run_tier();
2221    with_optimized_program_tiered_scoped(input, tier, scope, f)
2222}
2223
2224/// [`with_optimized_program`] gated by an explicit hotness `tier` (HOTSWAP §4): the
2225/// statements pass through [`crate::optimize::optimize_for_run_tiered`] at `tier`.
2226/// `Tier::T3` reproduces `with_optimized_program` exactly; `Tier::T0` skips the
2227/// optimizer (the baseline tier). The accumulator→loop TCO rewrite is a LANGUAGE
2228/// SEMANTIC, not an optimization, so it runs at every tier — deep recursion stays
2229/// constant-stack regardless of the optimization tier.
2230pub fn with_optimized_program_tiered<R>(
2231    input: &str,
2232    tier: crate::optimization::Tier,
2233    f: impl for<'a> FnOnce(
2234        Result<
2235            (
2236                &'a [logicaffeine_language::ast::stmt::Stmt<'a>],
2237                &'a logicaffeine_language::analysis::TypeRegistry,
2238                logicaffeine_language::analysis::PolicyRegistry,
2239            ),
2240            String,
2241        >,
2242        &'a Interner,
2243    ) -> R,
2244) -> R {
2245    with_optimized_program_tiered_scoped(input, tier, None, f)
2246}
2247
2248fn with_optimized_program_tiered_scoped<R>(
2249    input: &str,
2250    tier: crate::optimization::Tier,
2251    scope: Option<&crate::analysis::ScopeInfo>,
2252    f: impl for<'a> FnOnce(
2253        Result<
2254            (
2255                &'a [logicaffeine_language::ast::stmt::Stmt<'a>],
2256                &'a logicaffeine_language::analysis::TypeRegistry,
2257                logicaffeine_language::analysis::PolicyRegistry,
2258            ),
2259            String,
2260        >,
2261        &'a Interner,
2262    ) -> R,
2263) -> R {
2264    use logicaffeine_language::ast::stmt::{Expr, Stmt, TypeExpr};
2265
2266    // A bare script (no `##` headers, imperative opening) runs as `## Main`.
2267    let implicit = implicit_main(input);
2268    let input = implicit.as_deref().unwrap_or(input);
2269
2270    // Phase 10: auto-prepend the stdlib modules the program references (no-op when
2271    // it uses no stdlib vocabulary, so such programs stay byte-identical).
2272    let prelude_src = crate::loader::apply_prelude(input);
2273    let input = prelude_src.as_ref();
2274    let library = crate::loader::LibraryProvenance::of(input);
2275
2276    let mut interner = Interner::new();
2277    let mut lexer = Lexer::new(input, &mut interner);
2278    let tokens = lexer.tokenize();
2279
2280    let mwe_trie = mwe::build_mwe_trie();
2281    let mut tokens = mwe::apply_mwe_pipeline(tokens, &mwe_trie, &mut interner);
2282
2283    // Resolve the qualified escape hatch for cross-module calls (`Alias::fn` →
2284    // bare `fn`); no-op for single-file programs. Feeds the VM, JIT, wasm, isa,
2285    // and sync-interpreter tiers that share this seam.
2286    let functions = crate::analysis::assemble::defined_function_names(input);
2287    crate::analysis::assemble::resolve_qualified_names(&mut tokens, &mut interner, &functions);
2288
2289    let (type_registry, policy_registry) = {
2290        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
2291        let result = discovery.run_full();
2292        (result.types, result.policies)
2293    };
2294
2295    let expr_arena = Arena::new();
2296    let term_arena = Arena::new();
2297    let np_arena = Arena::new();
2298    let sym_arena = Arena::new();
2299    let role_arena = Arena::new();
2300    let pp_arena = Arena::new();
2301    let stmt_arena: Arena<Stmt> = Arena::new();
2302    let _compile_facts = crate::optimize::facts::scope();
2303    let imperative_expr_arena: Arena<Expr> = Arena::new();
2304    let type_expr_arena: Arena<TypeExpr> = Arena::new();
2305
2306    let ctx = AstContext::with_types(
2307        &expr_arena,
2308        &term_arena,
2309        &np_arena,
2310        &sym_arena,
2311        &role_arena,
2312        &pp_arena,
2313        &stmt_arena,
2314        &imperative_expr_arena,
2315        &type_expr_arena,
2316    );
2317
2318    let mut world_state = drs::WorldState::new();
2319    let (parsed, opt_flags, tier_pins, type_registry_for_engines) = {
2320        let mut parser = Parser::new(tokens, &mut world_state, &mut interner, ctx, type_registry);
2321        let stmts = parser.parse_program();
2322        let flags = parser.program_opt_flags();
2323        let pins = parser.program_tier_pins();
2324        (stmts, flags, pins, parser.into_type_registry())
2325    };
2326
2327    match parsed {
2328        Ok(stmts) => {
2329            if let Some(scope) = scope {
2330                if let Err(why) = crate::analysis::check_scopes(&stmts, scope, &interner) {
2331                    return f(Err(why), &interner);
2332                }
2333            }
2334            // Respect file-level `## No <opt>` decorators on the run path too, so
2335            // optimization toggles behave consistently with the AOT compile.
2336            let mut run_cfg =
2337                crate::optimization::OptimizationConfig::from_env().merged(&opt_flags);
2338            run_cfg.normalize();
2339            // Tiered-optimizer pins: ambient env (`LOGOS_TIER_PIN`) overlaid by the
2340            // program's in-source `## Tier` decorators (the decorator wins).
2341            let mut hotswap = crate::optimization::HotswapConfig::from_env();
2342            hotswap.pins.overlay(&tier_pins);
2343            // Type-directed division (Divide → ExactDivide in Rational contexts) runs
2344            // BEFORE optimization so the optimizer sees ExactDivide (opaque, never
2345            // floor-folded), not a bare `7 / 2` it would fold to `3`.
2346            let resolved = crate::resolve_program::resolve_program(
2347                &stmts,
2348                crate::ast_map::Arenas {
2349                    exprs: &imperative_expr_arena,
2350                    stmts: &stmt_arena,
2351                    types: &type_expr_arena,
2352                },
2353                &mut interner,
2354                run_cfg.is_on(crate::optimization::Opt::Comptime),
2355                library.functions(),
2356            );
2357            let pre: Vec<_> = match resolved {
2358                Some(rw) => rw.to_vec(),
2359                None => stmts,
2360            };
2361            let optimized = crate::optimize::optimize_for_run_tiered(
2362                pre,
2363                &imperative_expr_arena,
2364                &stmt_arena,
2365                &mut interner,
2366                &run_cfg,
2367                &hotswap,
2368                tier,
2369            );
2370            // Accumulator recursion → constant-stack loop (matches the AOT and
2371            // the raw-parse engines).
2372            match crate::tail_call::rewrite_accumulators(
2373                &optimized,
2374                &stmt_arena,
2375                &imperative_expr_arena,
2376                &mut interner,
2377            ) {
2378                Some(rw) => f(
2379                    Ok((rw, &type_registry_for_engines, policy_registry)),
2380                    &interner,
2381                ),
2382                None => f(
2383                    Ok((&optimized, &type_registry_for_engines, policy_registry)),
2384                    &interner,
2385                ),
2386            }
2387        }
2388        Err(e) => {
2389            let advice = socratic_explanation(&e, &interner);
2390            f(Err(advice), &interner)
2391        }
2392    }
2393}
2394
2395/// Like [`with_optimized_program`], but the program runs through the
2396/// ARCHITECT pipeline (`optimize_program_v2`): equality saturation with
2397/// kernel-certified rewrites in place of GVN + LICM + closed-form. The
2398/// differential gates in `phase_exodia_architect.rs` hold this path to the
2399/// raw tree-walker's outcomes.
2400pub fn with_v2_optimized_program<R>(
2401    input: &str,
2402    f: impl for<'a> FnOnce(
2403        Result<
2404            (
2405                &'a [logicaffeine_language::ast::stmt::Stmt<'a>],
2406                &'a logicaffeine_language::analysis::TypeRegistry,
2407                logicaffeine_language::analysis::PolicyRegistry,
2408            ),
2409            String,
2410        >,
2411        &'a Interner,
2412    ) -> R,
2413) -> R {
2414    use logicaffeine_language::ast::stmt::{Expr, Stmt, TypeExpr};
2415
2416    // A bare script (no `##` headers, imperative opening) runs as `## Main`.
2417    let implicit = implicit_main(input);
2418    let input = implicit.as_deref().unwrap_or(input);
2419
2420    // Phase 10: auto-prepend the stdlib modules the program references (no-op when
2421    // it uses no stdlib vocabulary, so such programs stay byte-identical).
2422    let prelude_src = crate::loader::apply_prelude(input);
2423    let input = prelude_src.as_ref();
2424    let library = crate::loader::LibraryProvenance::of(input);
2425
2426    let mut interner = Interner::new();
2427    let mut lexer = Lexer::new(input, &mut interner);
2428    let tokens = lexer.tokenize();
2429
2430    let mwe_trie = mwe::build_mwe_trie();
2431    let mut tokens = mwe::apply_mwe_pipeline(tokens, &mwe_trie, &mut interner);
2432
2433    // Resolve the qualified escape hatch for cross-module calls (`Alias::fn` →
2434    // bare `fn`); no-op for single-file programs. Feeds the VM, JIT, wasm, isa,
2435    // and sync-interpreter tiers that share this seam.
2436    let functions = crate::analysis::assemble::defined_function_names(input);
2437    crate::analysis::assemble::resolve_qualified_names(&mut tokens, &mut interner, &functions);
2438
2439    let (type_registry, policy_registry) = {
2440        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
2441        let result = discovery.run_full();
2442        (result.types, result.policies)
2443    };
2444
2445    let expr_arena = Arena::new();
2446    let term_arena = Arena::new();
2447    let np_arena = Arena::new();
2448    let sym_arena = Arena::new();
2449    let role_arena = Arena::new();
2450    let pp_arena = Arena::new();
2451    let stmt_arena: Arena<Stmt> = Arena::new();
2452    let _compile_facts = crate::optimize::facts::scope();
2453    let imperative_expr_arena: Arena<Expr> = Arena::new();
2454    let type_expr_arena: Arena<TypeExpr> = Arena::new();
2455
2456    let ctx = AstContext::with_types(
2457        &expr_arena,
2458        &term_arena,
2459        &np_arena,
2460        &sym_arena,
2461        &role_arena,
2462        &pp_arena,
2463        &stmt_arena,
2464        &imperative_expr_arena,
2465        &type_expr_arena,
2466    );
2467
2468    let mut world_state = drs::WorldState::new();
2469    let (parsed, type_registry_for_engines) = {
2470        let mut parser = Parser::new(tokens, &mut world_state, &mut interner, ctx, type_registry);
2471        let parsed = parser.parse_program();
2472        (parsed, parser.into_type_registry())
2473    };
2474
2475    match parsed {
2476        Ok(stmts) => {
2477            let config = crate::optimization::OptimizationConfig::from_env();
2478            let resolved = crate::resolve_program::resolve_program(
2479                &stmts,
2480                crate::ast_map::Arenas {
2481                    exprs: &imperative_expr_arena,
2482                    stmts: &stmt_arena,
2483                    types: &type_expr_arena,
2484                },
2485                &mut interner,
2486                config.is_on(crate::optimization::Opt::Comptime),
2487                library.functions(),
2488            );
2489            let stmts: Vec<Stmt> = match resolved {
2490                Some(rw) => rw.to_vec(),
2491                None => stmts,
2492            };
2493            let optimized = crate::optimize::optimize_program(
2494                stmts,
2495                &imperative_expr_arena,
2496                &stmt_arena,
2497                &mut interner,
2498                &config,
2499            );
2500            f(
2501                Ok((&optimized, &type_registry_for_engines, policy_registry)),
2502                &interner,
2503            )
2504        }
2505        Err(e) => {
2506            let advice = socratic_explanation(&e, &interner);
2507            f(Err(advice), &interner)
2508        }
2509    }
2510}
2511
2512/// Interpret LOGOS imperative code synchronously (no async runtime needed).
2513///
2514/// The bytecode VM is the LIVE engine for the synchronous path (which is also
2515/// the browser/WASM path). The tree-walker remains fully wired as: the async
2516/// path (file I/O, sleep, mount), the shadow oracle in debug builds (every
2517/// program the corpus runs is differentially checked against it), and the
2518/// fallback for anything the VM compiler rejects.
2519pub fn interpret_for_ui_sync(input: &str) -> InterpreterResult {
2520    interpret_for_ui_sync_with_args(input, &[])
2521}
2522
2523/// In-process execution tier. All choices consume the same optimized program.
2524#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2525pub enum Engine {
2526    /// Preserve the product dispatcher: JIT/VM for synchronous programs and
2527    /// the tree-walker for programs requiring async or the scheduler.
2528    #[default]
2529    Auto,
2530    Jit,
2531    Vm,
2532    TreeWalker,
2533}
2534
2535thread_local! {
2536    static ENGINE: std::cell::Cell<Engine> = const { std::cell::Cell::new(Engine::Auto) };
2537}
2538
2539/// Select the tier used by subsequent in-process runs on this thread.
2540pub fn set_engine(engine: Engine) {
2541    ENGINE.with(|selected| selected.set(engine));
2542}
2543
2544fn engine() -> Engine {
2545    ENGINE.with(std::cell::Cell::get)
2546}
2547
2548#[cfg(not(target_arch = "wasm32"))]
2549thread_local! {
2550    /// Compiled-native functions to install into the next VM run on this thread
2551    /// (HOTSWAP §Axis-3). `largo run` loads a `.logos-native` bundle into this; the VM
2552    /// seam below drains it and installs each via `install_aot_native`, so a `native`-
2553    /// annotated function dispatches to `rustc -O3` machine code from its first call.
2554    /// Empty for every other caller — no AOT, behavior unchanged.
2555    static PENDING_AOT: std::cell::RefCell<Vec<(String, Box<dyn crate::vm::NativeFn>)>> =
2556        const { std::cell::RefCell::new(Vec::new()) };
2557}
2558
2559/// Queue compiled-native functions for the next VM run on this thread (HOTSWAP §Axis-3).
2560/// Consumed by the next `interpret_for_ui_*` VM run.
2561#[cfg(not(target_arch = "wasm32"))]
2562pub fn set_pending_aot_natives(natives: Vec<(String, Box<dyn crate::vm::NativeFn>)>) {
2563    PENDING_AOT.with(|p| *p.borrow_mut() = natives);
2564}
2565
2566/// Drain the pending compiled-native functions and install them into `vm`, resolving
2567/// each by name to its function index. No-op when none are queued.
2568#[cfg(not(target_arch = "wasm32"))]
2569fn install_pending_aot_natives(
2570    vm: &mut crate::vm::Vm,
2571    program: &crate::vm::CompiledProgram,
2572    interner: &Interner,
2573) {
2574    let pending = PENDING_AOT.with(|p| std::mem::take(&mut *p.borrow_mut()));
2575    for (name, nf) in pending {
2576        if let Some(fi) = program
2577            .fn_index
2578            .iter()
2579            .find(|(s, _)| interner.resolve(**s) == name)
2580            .map(|(_, i)| *i as usize)
2581        {
2582            vm.install_aot_native(fi, nf);
2583            if std::env::var_os("LOGOS_ENGINE_TRACE").is_some() {
2584                eprintln!("logos-engine: aot-native installed for '{name}'");
2585            }
2586        }
2587    }
2588}
2589
2590/// The bytecode the VM runs for `input`, as `largo run --interpret` compiles it: the run path's optimizer, the oracle
2591/// and the VM compiler. One section per function, `## Main` first, then `## To <name>` in code order, each instruction
2592/// at its pc. A source that does not parse, or that only the tree-walker runs, answers why.
2593pub fn vm_listing(input: &str) -> Result<String, String> {
2594    with_optimized_program(input, |parsed, interner| {
2595        let (stmts, type_registry, _policies) = parsed?;
2596        if crate::interpreter::needs_async(stmts, interner)
2597            || crate::concurrency::uses_scheduler(stmts)
2598        {
2599            return Err(
2600                "this program awaits or runs tasks, so it runs on the tree-walker, not the VM"
2601                    .to_string(),
2602            );
2603        }
2604        let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
2605        let program = crate::vm::Compiler::compile_with_oracle(
2606            stmts,
2607            interner,
2608            Some(type_registry),
2609            Some(oracle),
2610        )
2611        .map_err(|e| {
2612            format!(
2613                "the VM compiler does not take this program, so it runs on the tree-walker: {e:?}"
2614            )
2615        })?;
2616        let mut starts: Vec<(usize, String)> = program
2617            .functions
2618            .iter()
2619            .map(|f| (f.entry_pc, format!("## To {}", interner.resolve(f.name))))
2620            .collect();
2621        starts.sort();
2622        let lines = crate::vm::disasm::disassemble(&program);
2623        let width = lines.len().saturating_sub(1).to_string().len();
2624        let mut out = String::from("## Main\n");
2625        let mut next = starts.iter().peekable();
2626        for line in &lines {
2627            while let Some((pc, header)) = next.peek() {
2628                if *pc > line.pc {
2629                    break;
2630                }
2631                out.push_str(&format!("\n{header}\n"));
2632                next.next();
2633            }
2634            out.push_str(&format!("{:>width$}  {}\n", line.pc, line.text));
2635        }
2636        Ok(out)
2637    })
2638}
2639
2640/// Like [`interpret_for_ui_sync`], but supplies the program's argument vector
2641/// to the `args()` system native. `program_args` is the full argv (index 0 is
2642/// the program name), matching the compiled binary's `env::args()` — this is
2643/// what `largo run --interpret N` forwards so an args-driven `main.lg` runs the
2644/// same on the VM/JIT as on the native binary.
2645pub fn interpret_for_ui_sync_with_args(input: &str, program_args: &[String]) -> InterpreterResult {
2646    interpret_for_ui_sync_with_args_impl(input, program_args, None)
2647}
2648
2649/// Project-aware form of [`interpret_for_ui_sync_with_args`].  The scope gate
2650/// consumes the AST this execution already parsed, so explicit VM/JIT runs do
2651/// not pay for a separate front-end parse on every invocation.
2652pub fn interpret_for_ui_sync_with_args_scoped(
2653    input: &str,
2654    program_args: &[String],
2655    scope: &crate::analysis::ScopeInfo,
2656) -> InterpreterResult {
2657    interpret_for_ui_sync_with_args_impl(input, program_args, Some(scope))
2658}
2659
2660fn interpret_for_ui_sync_with_args_impl(
2661    input: &str,
2662    program_args: &[String],
2663    scope: Option<&crate::analysis::ScopeInfo>,
2664) -> InterpreterResult {
2665    begin_ui_run();
2666    // Diagnostic for benchmarking: with LOGOS_ENGINE_TRACE set, report which
2667    // engine actually ran a program to stderr, so a silent tree-walker fallback
2668    // is never mistaken for the VM+JIT.
2669    let trace = |engine: &str| {
2670        if std::env::var_os("LOGOS_ENGINE_TRACE").is_some() {
2671            eprintln!("logos-engine: {engine}");
2672        }
2673    };
2674    // The LIVE path runs the Futamura residual: both the VM and the debug
2675    // shadow oracle receive the SAME optimized program (two engines, one
2676    // program — the optimizer is differentially gated elsewhere against the
2677    // raw tree-walker).
2678    with_optimized_program_scoped(input, scope, |parsed, interner| match parsed {
2679        Ok((stmts, type_registry, policies)) => {
2680            if let Some(rejection) = send_escape_rejection(stmts) {
2681                return rejection;
2682            }
2683            if let Some(rejection) = send_dimension_rejection(stmts, interner) {
2684                return rejection;
2685            }
2686            let needs_async = crate::interpreter::needs_async(stmts, interner);
2687            let needs_scheduler = crate::concurrency::uses_scheduler(stmts);
2688            if needs_async || needs_scheduler {
2689                if !matches!(engine(), Engine::Auto | Engine::TreeWalker) {
2690                    let why = if needs_async {
2691                        "the selected VM/JIT tier is sync-only; this program requires async execution"
2692                    } else {
2693                        "the selected VM/JIT tier has no scheduler driver; this program requires the tree-walker scheduler"
2694                    };
2695                    trace("refused");
2696                    return InterpreterResult {
2697                        lines: Vec::new(),
2698                        error: Some(why.to_string()),
2699                    };
2700                }
2701                trace("treewalker (async)");
2702                return run_treewalker(
2703                    stmts,
2704                    type_registry,
2705                    policies,
2706                    interner,
2707                    true,
2708                    program_args,
2709                );
2710            }
2711            if engine() == Engine::TreeWalker {
2712                trace("treewalker");
2713                return run_treewalker(
2714                    stmts,
2715                    type_registry,
2716                    policies,
2717                    interner,
2718                    false,
2719                    program_args,
2720                );
2721            }
2722            if engine() == Engine::TreeWalker {
2723                trace("treewalker");
2724                return run_treewalker(
2725                    stmts,
2726                    type_registry,
2727                    policies,
2728                    interner,
2729                    false,
2730                    program_args,
2731                );
2732            }
2733            // Oracle range analysis (M9) over the EXACT snapshot being
2734            // compiled → bounds-check elimination in the JIT.
2735            let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
2736            match crate::vm::Compiler::compile_with_oracle(
2737                stmts,
2738                interner,
2739                Some(type_registry),
2740                Some(oracle),
2741            ) {
2742                Ok(program) => {
2743                    let mut vm = crate::vm::Vm::new(&program)
2744                        .with_policy_ctx(&policies, interner)
2745                        .with_program_args(program_args.to_vec());
2746                    // A budgeted run stays on the VM dispatch loop: JIT-tiered
2747                    // native code executes outside the STEPPED accounting, so a
2748                    // pure hot loop would escape its step budget entirely.
2749                    // Unbudgeted runs keep the full tier ladder.
2750                    let mut native = None;
2751                    if engine() == Engine::Jit && crate::interpreter::active_fuel().is_some() {
2752                        trace("refused");
2753                        return InterpreterResult {
2754                            lines: Vec::new(),
2755                            error: Some(
2756                                "the selected JIT tier cannot preserve --max-steps accounting; use --engine vm"
2757                                    .to_string(),
2758                            ),
2759                        };
2760                    }
2761                    if crate::interpreter::active_fuel().is_none()
2762                        && matches!(engine(), Engine::Auto | Engine::Jit)
2763                    {
2764                        if let Some(tier) = crate::vm::installed_native_tier() {
2765                            vm = vm.with_native_tier(tier);
2766                            native = Some(tier);
2767                        }
2768                    }
2769                    if engine() == Engine::Jit && native.is_none() {
2770                        trace("refused");
2771                        return InterpreterResult {
2772                            lines: Vec::new(),
2773                            error: Some(
2774                                "the selected JIT tier is unavailable on this build or platform"
2775                                    .to_string(),
2776                            ),
2777                        };
2778                    }
2779                    trace(if native.is_some() { "vm+jit" } else { "vm" });
2780                    // Compiled-native tier (HOTSWAP §Axis-3): install any AOT functions
2781                    // the run was given, so they dispatch to rustc -O3 machine code.
2782                    #[cfg(not(target_arch = "wasm32"))]
2783                    install_pending_aot_natives(&mut vm, &program, interner);
2784                    // A budgeted run (`--max-steps` / MCP `step_budget`) drives
2785                    // the resumable STEPPED monomorph and stops at the
2786                    // deterministic op where the shared fuel cell runs dry;
2787                    // the unbudgeted path is the untouched hot loop.
2788                    let error = crate::vm::drive_vm(&mut vm);
2789                    if let Some(tier) = native {
2790                        trace(&format!(
2791                            "native-tier {}: {}",
2792                            tier.engine_name(),
2793                            tier.compile_summary()
2794                        ));
2795                        let declines = tier.decline_summary();
2796                        if !declines.is_empty() {
2797                            trace(&format!(
2798                                "native-declines {}: {declines}",
2799                                tier.engine_name()
2800                            ));
2801                        }
2802                        let opts = tier.optimization_summary();
2803                        if !opts.is_empty() {
2804                            trace(&format!("native-opts {}: {opts}", tier.engine_name()));
2805                        }
2806                        let execution = tier.execution_summary();
2807                        if !execution.is_empty() {
2808                            trace(&format!(
2809                                "native-runtime {}: {execution}",
2810                                tier.engine_name()
2811                            ));
2812                        }
2813                    }
2814                    let result = InterpreterResult {
2815                        lines: vm.into_lines(),
2816                        error,
2817                    };
2818
2819                    // Debug-build shadow oracle: the SAME program runs on the
2820                    // tree-walker and the full outcome must match — this turns
2821                    // the entire existing test corpus into a differential
2822                    // suite. (Skipped on wasm to keep dev builds light, and
2823                    // under fuel: the VM already drained the shared cell, so
2824                    // the shadow would exhaust at step one and always diverge.
2825                    // Budgeted equivalence is fuel_budget.rs's job.)
2826                    #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
2827                    if crate::interpreter::active_fuel().is_none() {
2828                        let shadow = in_a_document_of_its_own(|| {
2829                            run_treewalker(
2830                                stmts,
2831                                type_registry,
2832                                policies.clone(),
2833                                interner,
2834                                false,
2835                                program_args,
2836                            )
2837                        });
2838                        assert_eq!(
2839                            (&result.lines, &result.error),
2840                            (&shadow.lines, &shadow.error),
2841                            "VM diverged from the tree-walker oracle for:\n{input}"
2842                        );
2843                    }
2844                    result
2845                }
2846                // The VM compiler rejects only constructs outside the parser's
2847                // reach; run them on the tree-walker rather than failing.
2848                Err(reason) => {
2849                    if engine() != Engine::Auto {
2850                        trace("refused");
2851                        InterpreterResult {
2852                            lines: Vec::new(),
2853                            error: Some(format!(
2854                                "the selected VM/JIT tier cannot compile this program: {reason}"
2855                            )),
2856                        }
2857                    } else {
2858                        trace("treewalker (vm-reject)");
2859                        run_treewalker(
2860                            stmts,
2861                            type_registry,
2862                            policies,
2863                            interner,
2864                            false,
2865                            program_args,
2866                        )
2867                    }
2868                }
2869            }
2870        }
2871        Err(advice) => InterpreterResult {
2872            lines: vec![],
2873            error: Some(advice),
2874        },
2875    })
2876}
2877
2878/// Baseline-tier interpret for the interactive UI (the Studio) — the cold-start
2879/// engine. Runs on the bytecode VM with NO run-path optimizer
2880/// (`with_parsed_program`, not `with_optimized_program`) and NO oracle
2881/// (`compile_with_types`, not `compile_with_oracle`), so there is no
2882/// optimize/analysis latency before execution. `largo run` and the benchmarks
2883/// keep [`interpret_for_ui`], which optimizes ahead of execution for peak
2884/// throughput. Output is identical — the VM is differentially gated against the
2885/// tree-walker on the SAME parsed statements (see the debug shadow-oracle assert
2886/// in [`interpret_for_ui_baseline_sync_with_args`]); only the startup latency
2887/// differs. This is the baseline half of the EXODIA tier split; promoting hot
2888/// code to the optimized path is a later step.
2889pub async fn interpret_for_ui_baseline(input: &str) -> InterpreterResult {
2890    interpret_for_ui_baseline_with_args(input, &[]).await
2891}
2892
2893/// Like [`interpret_for_ui_baseline`], but supplies the program's argument
2894/// vector to the `args()` system native.
2895pub async fn interpret_for_ui_baseline_with_args(
2896    input: &str,
2897    program_args: &[String],
2898) -> InterpreterResult {
2899    begin_ui_run();
2900    // Async programs (file I/O, sleep, mount) run on the tree-walker's async
2901    // executor regardless of tier — the VM is sync-only — so that case is
2902    // identical to the optimized entry (and must `await` rather than nest a
2903    // `block_on`); delegate it.
2904    let needs_async = with_parsed_program(input, |parsed, interner| match parsed {
2905        Ok((stmts, _, _)) => crate::interpreter::needs_async(stmts, interner),
2906        Err(_) => false,
2907    });
2908    if needs_async {
2909        return interpret_for_ui_with_args(input, program_args).await;
2910    }
2911    interpret_for_ui_baseline_sync_with_args(input, program_args)
2912}
2913
2914/// The synchronous baseline core: parse (UNoptimized) → bytecode VM (no oracle)
2915/// → run. Mirrors [`interpret_for_ui_sync_with_args`] exactly, minus
2916/// `optimize_for_run` and the oracle range analysis.
2917pub fn interpret_for_ui_baseline_sync_with_args(
2918    input: &str,
2919    program_args: &[String],
2920) -> InterpreterResult {
2921    begin_ui_run();
2922    let trace = |engine: &str| {
2923        if std::env::var_os("LOGOS_ENGINE_TRACE").is_some() {
2924            eprintln!("logos-engine: {engine}");
2925        }
2926    };
2927    with_parsed_program(input, |parsed, interner| match parsed {
2928        Ok((stmts, type_registry, policies)) => {
2929            if let Some(rejection) = send_escape_rejection(stmts) {
2930                return rejection;
2931            }
2932            if let Some(rejection) = send_dimension_rejection(stmts, interner) {
2933                return rejection;
2934            }
2935            if crate::interpreter::needs_async(stmts, interner)
2936                || crate::concurrency::uses_scheduler(stmts)
2937            {
2938                trace("treewalker (async)");
2939                return run_treewalker(
2940                    stmts,
2941                    type_registry,
2942                    policies,
2943                    interner,
2944                    true,
2945                    program_args,
2946                );
2947            }
2948            match crate::vm::Compiler::compile_with_types(stmts, interner, Some(type_registry)) {
2949                Ok(program) => {
2950                    let mut vm = crate::vm::Vm::new(&program)
2951                        .with_policy_ctx(&policies, interner)
2952                        .with_program_args(program_args.to_vec());
2953                    // A budgeted run stays on the VM dispatch loop: JIT-tiered
2954                    // native code executes outside the STEPPED accounting, so a
2955                    // pure hot loop would escape its step budget entirely.
2956                    // Unbudgeted runs keep the full tier ladder.
2957                    let mut native = None;
2958                    if crate::interpreter::active_fuel().is_none() {
2959                        if let Some(tier) = crate::vm::installed_native_tier() {
2960                            vm = vm.with_native_tier(tier);
2961                            native = Some(tier);
2962                        }
2963                    }
2964                    trace(if native.is_some() {
2965                        "vm+jit (baseline)"
2966                    } else {
2967                        "vm (baseline)"
2968                    });
2969                    // Compiled-native tier (HOTSWAP §Axis-3): install any AOT functions
2970                    // the run was given, so they dispatch to rustc -O3 machine code.
2971                    #[cfg(not(target_arch = "wasm32"))]
2972                    install_pending_aot_natives(&mut vm, &program, interner);
2973                    let error = vm.run().err();
2974                    if let Some(tier) = native {
2975                        trace(&format!(
2976                            "native-tier {}: {}",
2977                            tier.engine_name(),
2978                            tier.compile_summary()
2979                        ));
2980                        let declines = tier.decline_summary();
2981                        if !declines.is_empty() {
2982                            trace(&format!(
2983                                "native-declines {}: {declines}",
2984                                tier.engine_name()
2985                            ));
2986                        }
2987                        let opts = tier.optimization_summary();
2988                        if !opts.is_empty() {
2989                            trace(&format!("native-opts {}: {opts}", tier.engine_name()));
2990                        }
2991                        let execution = tier.execution_summary();
2992                        if !execution.is_empty() {
2993                            trace(&format!(
2994                                "native-runtime {}: {execution}",
2995                                tier.engine_name()
2996                            ));
2997                        }
2998                    }
2999                    let result = InterpreterResult {
3000                        lines: vm.into_lines(),
3001                        error,
3002                    };
3003
3004                    // The same debug differential net as the optimized path: the
3005                    // baseline VM and the tree-walker must agree on the SAME
3006                    // (unoptimized) statements. (Skipped on wasm to keep dev
3007                    // builds light.)
3008                    #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
3009                    {
3010                        let shadow = in_a_document_of_its_own(|| {
3011                            run_treewalker(
3012                                stmts,
3013                                type_registry,
3014                                policies.clone(),
3015                                interner,
3016                                false,
3017                                program_args,
3018                            )
3019                        });
3020                        assert_eq!(
3021                            (&result.lines, &result.error),
3022                            (&shadow.lines, &shadow.error),
3023                            "baseline VM diverged from the tree-walker oracle for:\n{input}"
3024                        );
3025                    }
3026                    result
3027                }
3028                // The VM compiler rejects only constructs outside the parser's
3029                // reach; run them on the tree-walker rather than failing.
3030                Err(_) => {
3031                    trace("treewalker (vm-reject)");
3032                    run_treewalker(
3033                        stmts,
3034                        type_registry,
3035                        policies,
3036                        interner,
3037                        false,
3038                        program_args,
3039                    )
3040                }
3041            }
3042        }
3043        Err(advice) => InterpreterResult {
3044            lines: vec![],
3045            error: Some(advice),
3046        },
3047    })
3048}
3049
3050/// Run a parsed program on the TREE-WALKER (the oracle engine). `force_async`
3051/// selects the async executor; otherwise the sync path is used.
3052/// Run a concurrent program on the deterministic scheduler: spawn the main block
3053/// as a task (which may spawn more), drive the scheduler to quiescence, and
3054/// collect the output merged through a shared callback.
3055fn run_program_concurrent<'a>(
3056    stmts: &'a [logicaffeine_language::ast::stmt::Stmt<'a>],
3057    type_registry: &logicaffeine_language::analysis::TypeRegistry,
3058    policies: logicaffeine_language::analysis::PolicyRegistry,
3059    interner: &'a Interner,
3060    program_args: &[String],
3061    vfs: Option<std::sync::Arc<dyn logicaffeine_system::fs::Vfs>>,
3062    stream: Option<crate::interpreter::OutputCallback>,
3063    seed: u64,
3064) -> InterpreterResult {
3065    use crate::concurrency::bridge::YieldState;
3066    use crate::concurrency::driver::InterpreterTask;
3067    use logicaffeine_runtime::{run_with_seed, RunOutcome, SchedSeed, SchedulerConfig};
3068    use std::cell::RefCell;
3069    use std::rc::Rc;
3070
3071    let output_sink: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
3072    let sink = output_sink.clone();
3073    // Collect every task's output for the final result, and — when streaming —
3074    // forward each line to the live callback as it is produced (the Studio's
3075    // real-time display).
3076    let callback: crate::interpreter::OutputCallback =
3077        Rc::new(RefCell::new(move |line: String| {
3078            if let Some(s) = &stream {
3079                (s.borrow_mut())(line.clone());
3080            }
3081            sink.borrow_mut().push(line);
3082        }));
3083    let err_sink: crate::concurrency::driver::ErrSink = Rc::new(RefCell::new(None));
3084
3085    let mut main = crate::interpreter::Interpreter::new(interner)
3086        .with_type_registry(type_registry)
3087        .with_policies(policies)
3088        .with_program_args(program_args.to_vec())
3089        .with_output_callback(callback);
3090    if let Some(v) = vfs {
3091        main = main.with_vfs(v);
3092    }
3093    let main_ys = Rc::new(RefCell::new(YieldState::new()));
3094    main.install_yield_state(main_ys.clone(), err_sink.clone());
3095
3096    let main_fut = Box::pin(async move { main.run(stmts).await });
3097    let main_task = InterpreterTask::new(main_fut, main_ys, Some(err_sink.clone()));
3098
3099    let (outcome, _trace) =
3100        run_with_seed(SchedulerConfig::default(), SchedSeed(seed), move |sched| {
3101            sched.spawn_main(Box::new(main_task));
3102        });
3103
3104    let mut error = err_sink.borrow().clone();
3105    if error.is_none() {
3106        match outcome {
3107            RunOutcome::Deadlock => {
3108                error = Some("deadlock: every task is blocked waiting".to_string());
3109            }
3110            // The synchronous scheduler has no reactor; a program that needs network I/O
3111            // must run on the async drive loop (it routes there via `needs_async`). Reaching
3112            // here means it was driven on the wrong tier — surface it instead of half-running.
3113            RunOutcome::WaitingForIo => {
3114                error = Some(
3115                    "networking requires the async runtime; this program was run on the \
3116                     synchronous scheduler"
3117                        .to_string(),
3118                );
3119            }
3120            RunOutcome::Done(_) => {}
3121        }
3122    }
3123    let lines = output_sink.borrow().clone();
3124    InterpreterResult { lines, error }
3125}
3126
3127/// A snapshot sink for the Studio's Tasks/Channels strip — invoked between scheduler
3128/// slices with the live task/channel state.
3129pub type ObserverCallback =
3130    std::rc::Rc<std::cell::RefCell<dyn FnMut(logicaffeine_runtime::SchedSnapshot)>>;
3131
3132/// Yield a macrotask so the host event loop (Dioxus) can repaint between scheduler
3133/// slices. On wasm this is a real `setTimeout(0)`; on native there is no event loop to
3134/// yield to, so it returns immediately and the drive loop continues — the output is
3135/// identical, only the interleaving with repaints differs.
3136async fn yield_macrotask() {
3137    #[cfg(target_arch = "wasm32")]
3138    {
3139        gloo_timers::future::TimeoutFuture::new(0).await;
3140    }
3141}
3142
3143/// Yield control back to the host async runtime once, so its reactor can advance a pending
3144/// network future before the scheduler re-polls the task that awaits it. Runtime-agnostic
3145/// (no tokio dependency): a future that wakes itself and returns `Pending` exactly once — the
3146/// same shape as `tokio::task::yield_now`, which lets the current-thread runtime poll its I/O
3147/// driver between turns. On wasm a `setTimeout(0)` lets the event loop fire the socket
3148/// callbacks. This is how a [`logicaffeine_runtime::RunOutcome::WaitingForIo`] is serviced.
3149async fn yield_to_reactor() {
3150    #[cfg(target_arch = "wasm32")]
3151    {
3152        gloo_timers::future::TimeoutFuture::new(0).await;
3153    }
3154    #[cfg(not(target_arch = "wasm32"))]
3155    {
3156        use std::future::Future;
3157        use std::pin::Pin;
3158        use std::task::{Context, Poll};
3159        struct YieldOnce(bool);
3160        impl Future for YieldOnce {
3161            type Output = ();
3162            fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
3163                if self.0 {
3164                    Poll::Ready(())
3165                } else {
3166                    self.0 = true;
3167                    cx.waker().wake_by_ref();
3168                    Poll::Pending
3169                }
3170            }
3171        }
3172        YieldOnce(false).await;
3173    }
3174}
3175
3176/// The browser-facing async driver for concurrent programs. Identical semantics to
3177/// [`run_program_concurrent`] (same deterministic scheduler, same seed, same output), but
3178/// it advances the scheduler in bounded slices and yields a macrotask between them so the
3179/// Studio repaints instead of freezing — and emits a [`logicaffeine_runtime::SchedSnapshot`]
3180/// to `observer` after each slice to drive the Tasks/Channels strip.
3181#[allow(clippy::too_many_arguments)]
3182async fn run_program_concurrent_streaming<'a>(
3183    stmts: &'a [logicaffeine_language::ast::stmt::Stmt<'a>],
3184    type_registry: &logicaffeine_language::analysis::TypeRegistry,
3185    policies: logicaffeine_language::analysis::PolicyRegistry,
3186    interner: &'a Interner,
3187    program_args: &[String],
3188    vfs: Option<std::sync::Arc<dyn logicaffeine_system::fs::Vfs>>,
3189    stream: Option<crate::interpreter::OutputCallback>,
3190    observer: Option<ObserverCallback>,
3191    seed: u64,
3192) -> InterpreterResult {
3193    use crate::concurrency::bridge::YieldState;
3194    use crate::concurrency::driver::InterpreterTask;
3195    use logicaffeine_runtime::{Chooser, RunOutcome, SchedSeed, Scheduler, SchedulerConfig};
3196    use std::cell::RefCell;
3197    use std::rc::Rc;
3198
3199    // The slice budget: how many scheduler steps to run before yielding a macrotask. Large
3200    // enough that a quiescent program finishes in one slice; small enough that a busy one
3201    // still repaints. It does not affect output (the scheduler is deterministic).
3202    const SLICE_STEPS: usize = 256;
3203
3204    let output_sink: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
3205    let sink = output_sink.clone();
3206    let callback: crate::interpreter::OutputCallback =
3207        Rc::new(RefCell::new(move |line: String| {
3208            if let Some(s) = &stream {
3209                (s.borrow_mut())(line.clone());
3210            }
3211            sink.borrow_mut().push(line);
3212        }));
3213    let err_sink: crate::concurrency::driver::ErrSink = Rc::new(RefCell::new(None));
3214
3215    let mut main = crate::interpreter::Interpreter::new(interner)
3216        .with_type_registry(type_registry)
3217        .with_policies(policies)
3218        .with_program_args(program_args.to_vec())
3219        .with_output_callback(callback);
3220    if let Some(v) = vfs {
3221        main = main.with_vfs(v);
3222    }
3223    let main_ys = Rc::new(RefCell::new(YieldState::new()));
3224    main.install_yield_state(main_ys.clone(), err_sink.clone());
3225
3226    let main_fut = Box::pin(async move { main.run(stmts).await });
3227    let main_task = InterpreterTask::new(main_fut, main_ys, Some(err_sink.clone()));
3228
3229    let mut sched = Scheduler::new(SchedulerConfig::default(), Chooser::record(SchedSeed(seed)));
3230    sched.spawn_main(Box::new(main_task));
3231
3232    let outcome = loop {
3233        match sched.run_slice(SLICE_STEPS) {
3234            Some(RunOutcome::WaitingForIo) => {
3235                // A task is awaiting external I/O (a network op). Let the host reactor make
3236                // progress, then re-poll the parked tasks — they re-drive their network
3237                // futures, which now observe completion.
3238                if let Some(ob) = &observer {
3239                    (ob.borrow_mut())(sched.snapshot());
3240                }
3241                yield_to_reactor().await;
3242                sched.wake_io();
3243            }
3244            Some(o) => break o,
3245            None => {
3246                if let Some(ob) = &observer {
3247                    (ob.borrow_mut())(sched.snapshot());
3248                }
3249                yield_macrotask().await;
3250            }
3251        }
3252    };
3253
3254    let mut error = err_sink.borrow().clone();
3255    if error.is_none() {
3256        if let RunOutcome::Deadlock = outcome {
3257            error = Some("deadlock: every task is blocked waiting".to_string());
3258        }
3259    }
3260    let lines = output_sink.borrow().clone();
3261    InterpreterResult { lines, error }
3262}
3263
3264/// Parse `input` and run its concurrent program on the **tree-walker** scheduler
3265/// under an explicit `seed` — the seeded sibling of the default
3266/// `run_program_concurrent` entry, used by the cross-tier seeded differential.
3267pub fn run_treewalker_concurrent_seeded(input: &str, seed: u64) -> InterpreterResult {
3268    with_parsed_program(input, |parsed, interner| match parsed {
3269        Ok((stmts, type_registry, policies)) => run_program_concurrent(
3270            stmts,
3271            type_registry,
3272            policies,
3273            interner,
3274            &[],
3275            None,
3276            None,
3277            seed,
3278        ),
3279        Err(advice) => InterpreterResult {
3280            lines: vec![],
3281            error: Some(advice),
3282        },
3283    })
3284}
3285
3286/// Run a concurrent program on the **bytecode VM** under the deterministic
3287/// scheduler (T11): compile to opcodes, then drive the main `Vm` (and any
3288/// spawned per-task VMs) through `run_until_block` via a `VmTask`. This is the
3289/// VM analog of `run_program_concurrent`; the default routing still sends
3290/// concurrent programs to the tree-walker, so this is the explicit VM entry used
3291/// to exercise and (Phase 5c) differentially compare the VM concurrency tier.
3292pub fn run_vm_concurrent(input: &str) -> InterpreterResult {
3293    run_vm_concurrent_seeded(input, 0)
3294}
3295
3296/// [`run_vm_concurrent`] under an explicit scheduler `seed` — the VM sibling of
3297/// [`run_treewalker_concurrent_seeded`] for the cross-tier seeded differential.
3298pub fn run_vm_concurrent_seeded(input: &str, seed: u64) -> InterpreterResult {
3299    run_vm_concurrent_traced(input, seed).0
3300}
3301
3302/// [`run_vm_concurrent_seeded`], also returning the recorded scheduling trace —
3303/// the seam the `.replay` failure artifact captures its schedule through.
3304pub fn run_vm_concurrent_traced(
3305    input: &str,
3306    seed: u64,
3307) -> (InterpreterResult, logicaffeine_runtime::SchedTrace) {
3308    run_vm_concurrent_traced_with_config(
3309        input,
3310        logicaffeine_runtime::SchedulerConfig::default(),
3311        seed,
3312    )
3313}
3314
3315/// Run a concurrent program on the VM under an EXPLICIT [`SchedulerConfig`](logicaffeine_runtime::SchedulerConfig) — the same knob surface the AOT
3316/// bytecode-walker's stepped scheduler exposes ([`crate::codegen_c::concurrency::SchedulerKnobs`]). This is
3317/// the oracle side of the cross-tier knob equivalence: `AOT-at-knobs-K == VM-at-knobs-K`. The default-config
3318/// wrapper is [`run_vm_concurrent`].
3319///
3320/// [`SchedulerConfig`]: logicaffeine_runtime::SchedulerConfig
3321pub fn run_vm_concurrent_with_config(
3322    input: &str,
3323    config: logicaffeine_runtime::SchedulerConfig,
3324    seed: u64,
3325) -> InterpreterResult {
3326    run_vm_concurrent_traced_with_config(input, config, seed).0
3327}
3328
3329/// [`run_vm_concurrent_traced`] under an explicit [`SchedulerConfig`](logicaffeine_runtime::SchedulerConfig) (the config-parameterized core both
3330/// the default-config and knobbed entry points delegate to).
3331///
3332/// [`SchedulerConfig`]: logicaffeine_runtime::SchedulerConfig
3333pub fn run_vm_concurrent_traced_with_config(
3334    input: &str,
3335    config: logicaffeine_runtime::SchedulerConfig,
3336    seed: u64,
3337) -> (InterpreterResult, logicaffeine_runtime::SchedTrace) {
3338    use crate::concurrency::vm_driver::VmTask;
3339    use logicaffeine_runtime::{run_with_seed, RunOutcome, SchedSeed};
3340    use std::cell::RefCell;
3341    use std::rc::Rc;
3342
3343    with_parsed_program(input, |parsed, interner| match parsed {
3344        Ok((stmts, type_registry, policies)) => {
3345            let empty_trace = || logicaffeine_runtime::SchedTrace {
3346                seed: SchedSeed(seed),
3347                choices: Vec::new(),
3348            };
3349            let program =
3350                match crate::vm::Compiler::compile_with_types(stmts, interner, Some(type_registry))
3351                {
3352                    Ok(p) => p,
3353                    Err(e) => {
3354                        return (
3355                            InterpreterResult {
3356                                lines: vec![],
3357                                error: Some(e),
3358                            },
3359                            empty_trace(),
3360                        )
3361                    }
3362                };
3363            let output: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
3364            let err_sink: crate::concurrency::driver::ErrSink = Rc::new(RefCell::new(None));
3365            let mut vm = crate::vm::Vm::new(&program).with_policy_ctx(&policies, interner);
3366            // Task bodies tier exactly like the main program: a hot integer loop
3367            // inside a task JIT-compiles. Concurrency ops are JIT-ineligible (not
3368            // integer ops ⇒ never region-selected), so a tiered region is
3369            // yield-free and a task only ever suspends on the bytecode path.
3370            // Spawned children inherit this tier via `spawn_task_vm`.
3371            #[cfg(not(target_arch = "wasm32"))]
3372            if let Some(tier) = crate::vm::installed_native_tier() {
3373                vm = vm.with_native_tier(tier);
3374            }
3375            let main_task = VmTask::new(vm, output.clone(), Some(err_sink.clone()));
3376            let (outcome, trace) = run_with_seed(config, SchedSeed(seed), move |sched| {
3377                sched.spawn_main(Box::new(main_task));
3378            });
3379            let mut error = err_sink.borrow().clone();
3380            if error.is_none() {
3381                if let RunOutcome::Deadlock = outcome {
3382                    error = Some("deadlock: every task is blocked waiting".to_string());
3383                }
3384            }
3385            let lines = output.borrow().clone();
3386            (InterpreterResult { lines, error }, trace)
3387        }
3388        Err(advice) => {
3389            let trace = logicaffeine_runtime::SchedTrace {
3390                seed: logicaffeine_runtime::SchedSeed(seed),
3391                choices: Vec::new(),
3392            };
3393            (
3394                InterpreterResult {
3395                    lines: vec![],
3396                    error: Some(advice),
3397                },
3398                trace,
3399            )
3400        }
3401    })
3402}
3403
3404/// One cooperative poll interval for the VM net runner — a short async sleep so the relay delivers
3405/// (and, in the browser, the event loop runs) between `Await` polls. Mirrors the tree-walker's.
3406async fn vm_net_poll_tick() {
3407    #[cfg(not(target_arch = "wasm32"))]
3408    logicaffeine_system::tokio::time::sleep(std::time::Duration::from_millis(2)).await;
3409    #[cfg(target_arch = "wasm32")]
3410    gloo_timers::future::TimeoutFuture::new(2).await;
3411}
3412
3413/// Service one suspended VM networking request through the shared [`NetInbox`] — the SAME inbox the
3414/// tree-walker uses, so the wire encode/decode is identical and a `Send`/`Await` produces the same
3415/// value on both tiers. `Connect`/`Listen` do the async relay I/O; `Send`/`Stream` encode + publish;
3416/// `Await` drains-and-takes (yielding between polls) until the peer's message arrives.
3417async fn service_vm_net_block(
3418    vm: &mut crate::vm::Vm<'_>,
3419    netbox: &mut crate::concurrency::net_inbox::NetInbox,
3420    tcpbox: &mut crate::concurrency::tcp_registry::TcpRegistry,
3421    req: crate::vm::VmBlock,
3422) -> Result<(), String> {
3423    use crate::concurrency::marshal::{self};
3424    use crate::interpreter::RuntimeValue;
3425    use crate::vm::{Value, VmBlock};
3426    match req {
3427        // tcp.lg natives: rebuild the operand values and run the SAME value-level
3428        // exec the tree-walker calls — one implementation, both tiers.
3429        VmBlock::Tcp(kind, payloads) => {
3430            let op = crate::concurrency::tcp_registry::TcpOp::from_code(kind)
3431                .ok_or_else(|| format!("vm: unknown tcp op code {kind}"))?;
3432            let vals: Vec<RuntimeValue> = payloads.into_iter().map(marshal::rebuild).collect();
3433            let result = tcpbox.exec_values(op, vals).await?;
3434            vm.deliver_resume(Value::from_runtime(result));
3435            Ok(())
3436        }
3437        VmBlock::NetConnect(url_payload) => {
3438            let raw = marshal::rebuild(url_payload).to_display_string();
3439            let url = crate::concurrency::net_inbox::relay_url(&raw)?;
3440            // OFFLINE mode: `Connect` is a single-node local no-op (mirrors the tree-walker's offline
3441            // `Connect`), so the VM net oracle agrees with it. A relay-connected driver dials for real.
3442            if !crate::concurrency::net_inbox::net_is_offline() {
3443                let net = logicaffeine_system::net::Net::connect(&url)
3444                    .await
3445                    .map_err(|e| format!("Connect to relay '{url}' failed: {e}"))?;
3446                netbox.net = Some(net);
3447            }
3448            vm.deliver_resume(Value::nothing());
3449            Ok(())
3450        }
3451        VmBlock::NetListen(topic_payload) => {
3452            let raw = marshal::rebuild(topic_payload).to_display_string();
3453            let topic = logicaffeine_system::addr::canonical_topic(&raw);
3454            let hs_topic = crate::concurrency::net_inbox::handshake_topic_for(&topic);
3455            // LOCAL/OFFLINE mode (no relay): declare the inbox identity locally, skip the relay
3456            // subscribe — mirrors the tree-walker's offline `Listen` so both tiers agree.
3457            if let Some(net) = netbox.net.as_mut() {
3458                net.subscribe(&topic).await?;
3459                // Also receive peers' capability handshakes on our dedicated handshake topic (kept off
3460                // the data topic so they never interleave with messages).
3461                net.subscribe(&hs_topic).await?;
3462            }
3463            netbox.inbox = Some(std::rc::Rc::new(topic));
3464            vm.deliver_resume(Value::nothing());
3465            Ok(())
3466        }
3467        VmBlock::NetSend(to_payload, msg_payload) => {
3468            let topic = crate::concurrency::net_inbox::peer_topic(&marshal::rebuild(to_payload))?;
3469            // Advertise our surface to this peer on first contact — on its HANDSHAKE topic, never the
3470            // data topic — so it can negotiate back. Absorbed by the peer's drain, invisible to data.
3471            if let Some(hs) = netbox.first_contact_handshake(&topic) {
3472                netbox.publish(
3473                    &crate::concurrency::net_inbox::handshake_topic_for(&topic),
3474                    hs,
3475                )?;
3476            }
3477            let value = marshal::rebuild(msg_payload);
3478            let from = netbox
3479                .inbox
3480                .as_ref()
3481                .map(|t| t.to_string())
3482                .unwrap_or_default();
3483            // The negotiated maximal crush — byte-identical to the tree-walker's plain send (both call
3484            // `encode_negotiated` with the same program registry). Type-id fires only on a matching
3485            // peer epoch, so a raw / different-program peer still gets the plain encoding.
3486            let bytes =
3487                netbox.encode_negotiated(&from, &value, &topic, netbox.my_registry.clone())?;
3488            netbox.publish(&topic, bytes)?;
3489            vm.deliver_resume(Value::nothing());
3490            Ok(())
3491        }
3492        VmBlock::NetStream(to_payload, values_payload) => {
3493            let topic = crate::concurrency::net_inbox::peer_topic(&marshal::rebuild(to_payload))?;
3494            if let Some(hs) = netbox.first_contact_handshake(&topic) {
3495                netbox.publish(
3496                    &crate::concurrency::net_inbox::handshake_topic_for(&topic),
3497                    hs,
3498                )?;
3499            }
3500            let list = marshal::rebuild(values_payload);
3501            let items = match &list {
3502                RuntimeValue::List(rc) => rc.borrow().to_values(),
3503                other => vec![other.clone()],
3504            };
3505            let from = netbox
3506                .inbox
3507                .as_ref()
3508                .map(|t| t.to_string())
3509                .unwrap_or_default();
3510            let blob = marshal::frame_stream_message(&from, &items)?;
3511            netbox.publish(&topic, blob)?;
3512            vm.deliver_resume(Value::nothing());
3513            Ok(())
3514        }
3515        VmBlock::NetAwait(from_payload, stream) => {
3516            let want = crate::concurrency::net_inbox::peer_topic(&marshal::rebuild(from_payload))?;
3517            if netbox.inbox.is_none() {
3518                return Err(crate::concurrency::net_inbox::AWAIT_WITHOUT_LISTEN.to_string());
3519            }
3520            // OFFLINE (no relay): drain our own loopback outbox (the `Send … to <self>` delivered
3521            // locally) rather than requiring a relay — the VM net oracle mirrors the tree-walker.
3522            loop {
3523                let got = if stream {
3524                    netbox.try_take_stream(&want)
3525                } else {
3526                    netbox.try_take_message(&want, false)
3527                };
3528                if let Some(v) = got {
3529                    vm.deliver_resume(Value::from_runtime(v));
3530                    return Ok(());
3531                }
3532                // No type-id registry: the VM net runner sends self-describing (no `shared` dial),
3533                // so an empty registry decodes everything correctly.
3534                netbox.drain(netbox.my_registry.clone());
3535                let got = if stream {
3536                    netbox.try_take_stream(&want)
3537                } else {
3538                    netbox.try_take_message(&want, false)
3539                };
3540                if let Some(v) = got {
3541                    vm.deliver_resume(Value::from_runtime(v));
3542                    return Ok(());
3543                }
3544                vm_net_poll_tick().await;
3545            }
3546        }
3547        VmBlock::NetMakePeer(addr_payload) => {
3548            let raw = marshal::rebuild(addr_payload).to_display_string();
3549            let topic = logicaffeine_system::addr::canonical_topic(&raw);
3550            vm.deliver_resume(Value::from_runtime(RuntimeValue::Peer(std::rc::Rc::new(
3551                topic,
3552            ))));
3553            Ok(())
3554        }
3555        VmBlock::NetSync(topic_payload, current_payload) => {
3556            let topic = marshal::rebuild(topic_payload).to_display_string();
3557            let current = marshal::rebuild(current_payload);
3558            // Encode the counter (Int) or counter-struct as the relay wire form; `None` ⇒ nothing
3559            // to publish yet. Then merge whatever has arrived since the last sync point.
3560            let publish_bytes = crate::semantics::arith::crdt_to_wire(&current);
3561            // LOCAL/OFFLINE mode: single-node sync is a no-op — the local CRDT value stands (mirrors
3562            // the tree-walker's offline `Sync`). A relay-connected node publishes + merges.
3563            let merged = if let Some(net) = netbox.net.as_mut() {
3564                net.subscribe(&topic).await?;
3565                if let Some(bytes) = publish_bytes {
3566                    net.publish(&topic, bytes)?;
3567                }
3568                let incoming = net.drain();
3569                let mut merged = current;
3570                for (_t, data) in incoming {
3571                    merged = crate::semantics::arith::crdt_merge_wire(merged, &data);
3572                }
3573                merged
3574            } else {
3575                current
3576            };
3577            vm.deliver_resume(Value::from_runtime(merged));
3578            Ok(())
3579        }
3580        // `Op::Sleep` always yields `VmBlock::Sleep`, whichever async driver resumes it — a plain
3581        // sequential program with a bare `Sleep` (no channels/tasks, no networking) reaches THIS
3582        // driver too, because `run_strict_vm` refuses any `Sleep` as needing the async runtime and
3583        // the dispatcher's only other fallback is the concurrency scheduler's virtual clock, which a
3584        // program with no tasks never drives. Mirrors the tree-walker's own non-scheduled
3585        // `Stmt::Sleep` arm: a real timer, tokio's reactor when one is current (this driver runs
3586        // under `futures::executor::block_on`, which has none, so the fallback is what actually
3587        // fires), a blocking thread sleep otherwise, `gloo_timers` on wasm. `as_ticks` already
3588        // reports a Duration-valued Sleep in nanoseconds, the unit `Duration::from_nanos` wants.
3589        VmBlock::Sleep(ticks) => {
3590            if ticks > 0 {
3591                #[cfg(not(target_arch = "wasm32"))]
3592                {
3593                    let dur = std::time::Duration::from_nanos(ticks);
3594                    match logicaffeine_system::tokio::runtime::Handle::try_current() {
3595                        Ok(_) => logicaffeine_system::tokio::time::sleep(dur).await,
3596                        Err(_) => std::thread::sleep(dur),
3597                    }
3598                }
3599                #[cfg(target_arch = "wasm32")]
3600                {
3601                    let millis = (ticks / 1_000_000) as u32;
3602                    if millis > 0 {
3603                        gloo_timers::future::TimeoutFuture::new(millis).await;
3604                    }
3605                }
3606            }
3607            vm.deliver_resume(Value::nothing());
3608            Ok(())
3609        }
3610        _ => Err(
3611            "run_vm_net_async services only peer-networking blocks; this program mixes \
3612                  channels/tasks with networking, which the VM net runner does not yet drive"
3613                .to_string(),
3614        ),
3615    }
3616}
3617
3618/// Run a peer-networking program on the BYTECODE VM — the historical name for
3619/// [`run_vm_io_async`], kept so existing locks keep reading naturally.
3620pub async fn run_vm_net_async(input: &str) -> InterpreterResult {
3621    run_vm_io_async(input).await
3622}
3623
3624/// The bytecode-tier HTTP accept loop for a `Serve` statement — the byte-for-byte
3625/// analogue of the tree-walker's `serve_http_concurrent`. It owns the SAME
3626/// `Listener` + `FuturesUnordered` overlap machinery: every connection is an
3627/// OWNED future driven inline (the VM is `!Send`, nothing is spawned), overlapped
3628/// with the accept future by `select!`, keep-alive per the shared
3629/// `request_wants_keep_alive` law, at most `MAX_INFLIGHT` in flight, a parse
3630/// error → 400 + close.
3631///
3632/// The ONLY difference from the interpreter is the handler dispatch: each request
3633/// re-enters `handler` AS VM BYTECODE via [`crate::vm::Vm::call_handler_bytecode`]
3634/// (a fresh child VM at the handler's entry, fed the marshaled `Request` value),
3635/// then reads back its `Response` through the SHARED
3636/// [`crate::interpreter::Interpreter::value_to_http_response`] marshaling. A
3637/// handler failure (runtime error, nested-IO suspension, or a non-`Response`
3638/// return) answers a 500 for THAT request and keeps serving — a bad request
3639/// never takes the server down. The loop never returns except on a fatal bind
3640/// error; the host aborts the task to stop it.
3641#[cfg(not(target_arch = "wasm32"))]
3642async fn serve_vm_accept_loop(
3643    vm: &crate::vm::Vm<'_>,
3644    port: u16,
3645    handler: u16,
3646) -> Result<(), String> {
3647    use futures::stream::{FuturesUnordered, StreamExt};
3648    use logicaffeine_system::http::server::{
3649        internal_error, read_error_response, Conn, Listener, ReadError,
3650    };
3651    use logicaffeine_system::http::wire::{request_wants_keep_alive, HttpRequest, HttpResponse};
3652    use logicaffeine_system::http::{
3653        service_unavailable, shutdown_requested, Admission, Lifecycle, LifecycleConfig,
3654    };
3655    use std::time::Duration;
3656
3657    enum Step {
3658        Request(Conn, Result<HttpRequest, ReadError>),
3659        Closed,
3660    }
3661    type StepFut<'a> = std::pin::Pin<Box<dyn std::future::Future<Output = Step> + 'a>>;
3662
3663    /// Read one request under the configured body cap and read deadline — the
3664    /// same bounds the tree-walker and the native engines apply, so a slow or
3665    /// oversized peer is refused identically on every tier.
3666    async fn read_bounded(
3667        conn: &mut Conn,
3668        max_body: usize,
3669        deadline: Duration,
3670    ) -> Option<Result<HttpRequest, ReadError>> {
3671        match logicaffeine_system::tokio::time::timeout(
3672            deadline,
3673            conn.read_request_capped(max_body),
3674        )
3675        .await
3676        {
3677            Ok(read) => Some(read),
3678            Err(_) => None,
3679        }
3680    }
3681
3682    fn read_step<'a>(mut conn: Conn, max_body: usize, deadline: Duration) -> StepFut<'a> {
3683        Box::pin(async move {
3684            match read_bounded(&mut conn, max_body, deadline).await {
3685                Some(read) => Step::Request(conn, read),
3686                None => Step::Closed,
3687            }
3688        })
3689    }
3690
3691    fn write_step<'a>(
3692        mut conn: Conn,
3693        resp: HttpResponse,
3694        keep_alive: bool,
3695        max_body: usize,
3696        deadline: Duration,
3697    ) -> StepFut<'a> {
3698        Box::pin(async move {
3699            if conn.write_response_conn(&resp, keep_alive).await.is_err() || !keep_alive {
3700                return Step::Closed;
3701            }
3702            match read_bounded(&mut conn, max_body, deadline).await {
3703                Some(read) => Step::Request(conn, read),
3704                None => Step::Closed,
3705            }
3706        })
3707    }
3708
3709    // The ONE deployment/dev-proxy seam: `LOGOS_HOST` names the interface (default
3710    // loopback) and `LOGOS_PORT` (then `PORT`) overrides the program's port —
3711    // composed into the whole address by `env_bind_address`, shared with the
3712    // interpreter + AOT tiers so no tier drifts.
3713    let port = logicaffeine_system::http::server::env_port_override(port);
3714    let addr = logicaffeine_system::http::server::env_bind_address(port);
3715    let listener = Listener::bind(&addr)
3716        .await
3717        .map_err(|e| format!("Serve: cannot bind {addr}: {e}"))?;
3718    let bound = listener.local_addr().map_err(|e| format!("Serve: {e}"))?;
3719    logicaffeine_system::http::server::announce_serving(bound);
3720
3721    // The SAME lifecycle the tree-walker and the compiled tier get, read from the
3722    // SAME place, so the three tiers cannot drift.
3723    let lifecycle = Lifecycle::new(LifecycleConfig::from_env());
3724    lifecycle.set_ready(true);
3725    let cfg = lifecycle.config();
3726    let (max_body, read_deadline, max_inflight) =
3727        (cfg.max_body, cfg.read_deadline, cfg.max_inflight);
3728
3729    let shutdown = shutdown_requested();
3730    futures::pin_mut!(shutdown);
3731    let mut draining = false;
3732    let mut inflight: FuturesUnordered<StepFut> = FuturesUnordered::new();
3733    loop {
3734        if draining && inflight.is_empty() {
3735            return Ok(());
3736        }
3737        logicaffeine_system::tokio::select! {
3738            accepted = listener.accept(), if !draining && inflight.len() < max_inflight => {
3739                if let Ok(conn) = accepted {
3740                    inflight.push(read_step(conn, max_body, read_deadline));
3741                }
3742            }
3743            _ = &mut shutdown, if !draining => {
3744                lifecycle.set_ready(false);
3745                draining = true;
3746            }
3747            Some(step) = inflight.next() => {
3748                match step {
3749                    Step::Request(conn, Ok(req)) => {
3750                        let keep_alive = request_wants_keep_alive(&req);
3751                        if let Some(resp) = lifecycle.probe_response(&req.path) {
3752                            inflight.push(write_step(conn, resp, keep_alive, max_body, read_deadline));
3753                            continue;
3754                        }
3755                        let guard = match lifecycle.admit() {
3756                            Admission::Admit(g) => g,
3757                            Admission::NotReady | Admission::Overloaded => {
3758                                inflight.push(write_step(conn, service_unavailable(), false, max_body, read_deadline));
3759                                continue;
3760                            }
3761                        };
3762                        let request_value = crate::interpreter::Interpreter::http_request_to_value(&req);
3763                        // Re-enter the handler as VM bytecode; its `Show` output is
3764                        // dropped to stderr like the interpreter's (a running server
3765                        // never surfaces `lines`).
3766                        let (result, _handler_output) =
3767                            vm.call_handler_bytecode(handler, request_value);
3768                        let resp = match result {
3769                            Ok(value) => match crate::interpreter::Interpreter::value_to_http_response(&value) {
3770                                Ok(resp) => resp,
3771                                Err(e) => {
3772                                    eprintln!("Serve: handler error: {e}");
3773                                    internal_error()
3774                                }
3775                            },
3776                            Err(e) => {
3777                                eprintln!("Serve: handler error: {e}");
3778                                internal_error()
3779                            }
3780                        };
3781                        drop(guard);
3782                        lifecycle.notify_slot_freed();
3783                        inflight.push(write_step(conn, resp, keep_alive, max_body, read_deadline));
3784                    }
3785                    Step::Request(conn, Err(ReadError::Parse(ref e))) => {
3786                        // The SHARED read-error law, the same one the tree-walker and both
3787                        // native engines apply: a declared body over the limit is 413 so the
3788                        // client knows to send less, and everything else is 400. Answering a
3789                        // flat 400 here made this tier disagree with its own oracle.
3790                        inflight.push(write_step(conn, read_error_response(e), false, max_body, read_deadline));
3791                    }
3792                    Step::Request(_, Err(_)) | Step::Closed => {}
3793                }
3794            }
3795        }
3796    }
3797}
3798
3799/// Run an IO program (peer networking and/or tcp.lg sockets) on the BYTECODE VM (single task, no
3800/// channels): drive the resumable VM and service each `VmBlock::Net*`/`VmBlock::Tcp` through the
3801/// shared `NetInbox`/`TcpRegistry` — the SAME seams the tree-walker uses — so networking and
3802/// sockets run byte-identically on both tiers. The cross-tier locks prove they agree.
3803pub async fn run_vm_io_async(input: &str) -> InterpreterResult {
3804    use logicaffeine_language::ast::stmt::{Expr, Stmt, TypeExpr};
3805
3806    // The stdlib prelude splices exactly as on the tree-walker path — the tcp.lg
3807    // native declarations (and any other referenced modules) must exist on BOTH
3808    // tiers or the differential is meaningless.
3809    let input = crate::loader::apply_prelude(input);
3810    let library = crate::loader::LibraryProvenance::of(input.as_ref());
3811    let input: &str = &input;
3812    let mut interner = Interner::new();
3813    let mut lexer = Lexer::new(input, &mut interner);
3814    let tokens = lexer.tokenize();
3815    let mwe_trie = mwe::build_mwe_trie();
3816    let tokens = mwe::apply_mwe_pipeline(tokens, &mwe_trie, &mut interner);
3817    let (type_registry, policy_registry) = {
3818        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
3819        let result = discovery.run_full();
3820        (result.types, result.policies)
3821    };
3822    let expr_arena = Arena::new();
3823    let term_arena = Arena::new();
3824    let np_arena = Arena::new();
3825    let sym_arena = Arena::new();
3826    let role_arena = Arena::new();
3827    let pp_arena = Arena::new();
3828    let stmt_arena: Arena<Stmt> = Arena::new();
3829    let _compile_facts = crate::optimize::facts::scope();
3830    let imperative_expr_arena: Arena<Expr> = Arena::new();
3831    let type_expr_arena: Arena<TypeExpr> = Arena::new();
3832    let ctx = AstContext::with_types(
3833        &expr_arena,
3834        &term_arena,
3835        &np_arena,
3836        &sym_arena,
3837        &role_arena,
3838        &pp_arena,
3839        &stmt_arena,
3840        &imperative_expr_arena,
3841        &type_expr_arena,
3842    );
3843    let mut world_state = drs::WorldState::new();
3844    let mut parser = Parser::new(tokens, &mut world_state, &mut interner, ctx, type_registry);
3845    let stmts = match parser.parse_program() {
3846        Ok(s) => s,
3847        Err(e) => {
3848            return InterpreterResult {
3849                lines: vec![],
3850                error: Some(socratic_explanation(&e, &Interner::new())),
3851            }
3852        }
3853    };
3854    let opt_flags = parser.program_opt_flags();
3855    let type_registry_for_vm = parser.into_type_registry();
3856    let mut run_cfg =
3857        crate::optimization::OptimizationConfig::from_env().merged(&opt_flags);
3858    run_cfg.normalize();
3859    let resolved = crate::resolve_program::resolve_program(
3860        &stmts,
3861        crate::ast_map::Arenas {
3862            exprs: &imperative_expr_arena,
3863            stmts: &stmt_arena,
3864            types: &type_expr_arena,
3865        },
3866        &mut interner,
3867        run_cfg.is_on(crate::optimization::Opt::Comptime),
3868        library.functions(),
3869    );
3870    let stmts: Vec<Stmt> = match resolved {
3871        Some(rw) => rw.to_vec(),
3872        None => stmts,
3873    };
3874    let program = match crate::vm::Compiler::compile_with_types(
3875        &stmts,
3876        &interner,
3877        Some(&type_registry_for_vm),
3878    ) {
3879        Ok(p) => p,
3880        Err(e) => {
3881            return InterpreterResult {
3882                lines: vec![],
3883                error: Some(e),
3884            }
3885        }
3886    };
3887    let mut vm = crate::vm::Vm::new(&program).with_policy_ctx(&policy_registry, &interner);
3888    let mut netbox = crate::concurrency::net_inbox::NetInbox::new();
3889    let mut tcpbox = crate::concurrency::tcp_registry::TcpRegistry::new();
3890    // Build the wire type registry from the analysis types — IDENTICALLY to the tree-walker's
3891    // `build_wire_type_registry` (both derive from the same analysis table) — so two same-program peers
3892    // advertise matching registry epochs and may elide type NAMES from the wire (type-id).
3893    {
3894        let mut structs: Vec<(String, Vec<String>)> = Vec::new();
3895        let mut enums: Vec<(String, Vec<String>)> = Vec::new();
3896        for (name_sym, type_def) in type_registry_for_vm.iter_types() {
3897            // Skip a compiler-provided struct (`HttpError`/`File`) the program never declared —
3898            // every program's analysis table carries both, so leaving them in would advertise a
3899            // non-zero epoch (and inflate the registry) for a program with no types of its own.
3900            if type_registry_for_vm.is_builtin_struct(*name_sym) {
3901                continue;
3902            }
3903            let type_name = interner.resolve(*name_sym).to_string();
3904            match type_def {
3905                crate::analysis::registry::TypeDef::Struct { fields, .. } => {
3906                    structs.push((
3907                        type_name,
3908                        fields
3909                            .iter()
3910                            .map(|f| interner.resolve(f.name).to_string())
3911                            .collect(),
3912                    ));
3913                }
3914                crate::analysis::registry::TypeDef::Enum { variants, .. } => {
3915                    enums.push((
3916                        type_name,
3917                        variants
3918                            .iter()
3919                            .map(|v| interner.resolve(v.name).to_string())
3920                            .collect(),
3921                    ));
3922                }
3923                _ => {}
3924            }
3925        }
3926        netbox.set_registry(
3927            crate::concurrency::marshal::WireTypeRegistry::new(structs).with_enums(enums),
3928        );
3929    }
3930    let mut lines: Vec<String> = Vec::new();
3931    let mut error = None;
3932    loop {
3933        let step = vm.run_until_block();
3934        lines.extend(vm.drain_lines());
3935        match step {
3936            Ok(crate::vm::VmStep::Done(_)) => break,
3937            Ok(crate::vm::VmStep::Blocked) => {
3938                let req = match vm.take_pending() {
3939                    Some(r) => r,
3940                    None => break,
3941                };
3942                // `Serve` owns the accept loop: it never resumes the top-level VM
3943                // (the loop runs until the host aborts the task), so it is driven
3944                // HERE rather than through `service_vm_net_block`. The loop only
3945                // returns on a fatal bind error — a served response never
3946                // surfaces through `lines` (a running server never completes),
3947                // exactly as on the tree-walker.
3948                if let crate::vm::VmBlock::Serve(port, handler) = req {
3949                    #[cfg(not(target_arch = "wasm32"))]
3950                    {
3951                        if let Err(e) = serve_vm_accept_loop(&vm, port, handler).await {
3952                            error = Some(e);
3953                        }
3954                    }
3955                    #[cfg(target_arch = "wasm32")]
3956                    {
3957                        let _ = (port, handler);
3958                        error = Some(
3959                            "serve: networking is unavailable on the wasm32 target".to_string(),
3960                        );
3961                    }
3962                    break;
3963                }
3964                if let Err(e) = service_vm_net_block(&mut vm, &mut netbox, &mut tcpbox, req).await {
3965                    error = Some(e);
3966                    break;
3967                }
3968            }
3969            Ok(crate::vm::VmStep::Paused) => break,
3970            Err(e) => {
3971                error = Some(e);
3972                break;
3973            }
3974        }
3975    }
3976    InterpreterResult { lines, error }
3977}
3978
3979/// [`run_vm_concurrent_seeded`] under the **work-stealing M:N driver**: `workers`
3980/// OS-thread workers poll task bodies in parallel while one coordinator owns the
3981/// scheduler and applies channel ops + flushes output in deterministic pick
3982/// order. The observable result is byte-identical to the cooperative driver at the
3983/// same seed (`diff_cooperative_eq_workstealing_seeded`) — the difference is that
3984/// task bodies genuinely run on multiple cores.
3985///
3986/// The executor uses scoped threads, so each worker *borrows* the one shared,
3987/// immutable program (+ policies + interner) — no clone, no leak. Only a `Send`
3988/// `SpawnDesc` crosses a worker boundary; the worker rebuilds the `!Send` task
3989/// body locally from it.
3990#[cfg(not(target_arch = "wasm32"))]
3991pub fn run_vm_workstealing_seeded(input: &str, seed: u64, workers: usize) -> InterpreterResult {
3992    use crate::concurrency::vm_driver::VmTask;
3993    use logicaffeine_runtime::{
3994        run_workstealing_seeded, RunOutcome, SchedSeed, SchedulerConfig, SpawnDesc, Task,
3995    };
3996
3997    with_parsed_program(input, |parsed, interner| match parsed {
3998        Ok((stmts, type_registry, policies)) => {
3999            let program =
4000                match crate::vm::Compiler::compile_with_types(stmts, interner, Some(type_registry))
4001                {
4002                    Ok(p) => p,
4003                    Err(e) => {
4004                        return InterpreterResult {
4005                            lines: vec![],
4006                            error: Some(e),
4007                        }
4008                    }
4009                };
4010            // Build a worker-local task body from a `Send` descriptor. Workers run
4011            // the bytecode path: the native JIT tier is per-thread state (its code
4012            // cache is `!Sync`), so no shared tier is installed across workers.
4013            // Tiering is output-preserving, so this stays byte-identical to the
4014            // cooperative (tiered) driver; per-worker JIT is a future optimization.
4015            // The parallelism is the task bodies running on separate cores, which
4016            // the bytecode interpreter already delivers. The main task runs the
4017            // top-level program (`Vm::new` positions there); a spawned task is
4018            // positioned at its function via `setup_task`.
4019            let build = |desc: SpawnDesc| -> Box<dyn Task<'_> + '_> {
4020                let mut vm = crate::vm::Vm::new(&program).with_policy_ctx(&policies, interner);
4021                if !desc.is_main {
4022                    vm.setup_task(desc.func, &desc.args);
4023                }
4024                Box::new(VmTask::work_stealing(vm, None))
4025            };
4026            let main = SpawnDesc {
4027                func: 0,
4028                args: vec![],
4029                priority: 0,
4030                is_main: true,
4031            };
4032            let config = SchedulerConfig::default().with_workers(workers.max(1));
4033            let result = run_workstealing_seeded(config, SchedSeed(seed), main, build);
4034            let error = match result.outcome {
4035                RunOutcome::Deadlock => Some("deadlock: every task is blocked waiting".to_string()),
4036                _ => None,
4037            };
4038            InterpreterResult {
4039                lines: result.output,
4040                error,
4041            }
4042        }
4043        Err(advice) => InterpreterResult {
4044            lines: vec![],
4045            error: Some(advice),
4046        },
4047    })
4048}
4049
4050/// Run a program on the synchronous tree-walker and return its global
4051/// bindings as sorted `(name, type, value)` rows — the REPL's `:vars`
4052/// inspection. Returns `None` for programs the sync walker can't host
4053/// (async/concurrent) or that fail to parse or run.
4054pub fn repl_global_bindings(
4055    input: &str,
4056    program_args: &[String],
4057) -> Option<Vec<(String, String, String)>> {
4058    with_parsed_program(input, |parsed, interner| match parsed {
4059        Ok((stmts, type_registry, policies)) => {
4060            if crate::interpreter::needs_async(stmts, interner)
4061                || crate::concurrency::uses_scheduler(stmts)
4062            {
4063                return None;
4064            }
4065            let mut interp = crate::interpreter::Interpreter::new(interner)
4066                .with_type_registry(type_registry)
4067                .with_policies(policies)
4068                .with_program_args(program_args.to_vec());
4069            interp.run_sync(stmts).ok()?;
4070            Some(interp.global_bindings())
4071        }
4072        Err(_) => None,
4073    })
4074}
4075
4076pub(crate) fn run_treewalker<'a>(
4077    stmts: &'a [logicaffeine_language::ast::stmt::Stmt<'a>],
4078    type_registry: &logicaffeine_language::analysis::TypeRegistry,
4079    policies: logicaffeine_language::analysis::PolicyRegistry,
4080    interner: &'a Interner,
4081    force_async: bool,
4082    program_args: &[String],
4083) -> InterpreterResult {
4084    if crate::concurrency::uses_scheduler(stmts) {
4085        return run_program_concurrent(
4086            stmts,
4087            type_registry,
4088            policies,
4089            interner,
4090            program_args,
4091            Some(std::sync::Arc::new(logicaffeine_system::fs::MemVfs::new())),
4092            None,
4093            0,
4094        );
4095    }
4096    let mut interp = crate::interpreter::Interpreter::new(interner)
4097        .with_type_registry(type_registry)
4098        .with_policies(policies)
4099        .with_program_args(program_args.to_vec())
4100        .with_vfs(std::sync::Arc::new(logicaffeine_system::fs::MemVfs::new()));
4101    let run_result = if force_async {
4102        futures::executor::block_on(interp.run(stmts))
4103    } else {
4104        interp.run_sync(stmts)
4105    };
4106    // ★ AN UNHANDLED ACTION FAILURE IS THE PROGRAM'S ERROR, reported once the run has finished
4107    // rather than thrown when it happened. Thrown, it would stop a `Replay` at its first trap;
4108    // dropped, an author gets a button that silently does nothing. A real error the program raised
4109    // outranks it — that one stopped the run, and it is the one that explains the rest.
4110    let unhandled = interp.take_page_failure();
4111    InterpreterResult {
4112        error: run_result.err().or(unhandled),
4113        lines: interp.output,
4114    }
4115}
4116
4117/// Interpret LOGOS imperative code with streaming output.
4118///
4119/// The `on_output` callback is called each time `Show` executes, allowing
4120/// real-time output display like a REPL. The callback receives the output line.
4121///
4122/// # Example
4123/// ```no_run
4124/// use std::rc::Rc;
4125/// use std::cell::RefCell;
4126/// # use logicaffeine_compile::interpret_streaming;
4127///
4128/// # fn main() {}
4129/// # async fn example() {
4130/// # let source = "## Main\nShow \"hello\".";
4131/// let lines = Rc::new(RefCell::new(Vec::new()));
4132/// let lines_clone = lines.clone();
4133///
4134/// interpret_streaming(source, Rc::new(RefCell::new(move |line: String| {
4135///     lines_clone.borrow_mut().push(line);
4136/// }))).await;
4137/// # }
4138/// ```
4139pub async fn interpret_streaming<F>(
4140    input: &str,
4141    on_output: std::rc::Rc<std::cell::RefCell<F>>,
4142) -> InterpreterResult
4143where
4144    F: FnMut(String) + 'static,
4145{
4146    interpret_streaming_with_vfs(input, on_output, None).await
4147}
4148
4149/// Like [`interpret_streaming`], but routes the interpreter's file I/O
4150/// (`Write`/`Read`/`Mount`) to `vfs`. The browser Studio passes its `WebVfs`
4151/// here so the standard-library I/O vocabulary works against OPFS/IndexedDB; a
4152/// `None` vfs leaves file I/O reporting "VFS not initialized" as before. The
4153/// clone-per-task model means concurrent tasks inherit the same VFS handle.
4154pub async fn interpret_streaming_with_vfs<F>(
4155    input: &str,
4156    on_output: std::rc::Rc<std::cell::RefCell<F>>,
4157    vfs: Option<std::sync::Arc<dyn logicaffeine_system::fs::Vfs>>,
4158) -> InterpreterResult
4159where
4160    F: FnMut(String) + 'static,
4161{
4162    interpret_streaming_impl(input, on_output, vfs, None).await
4163}
4164
4165/// Like [`interpret_streaming_with_vfs`], but also emits a [`logicaffeine_runtime::SchedSnapshot`]
4166/// to `observer` after each scheduler slice — the Studio's Tasks/Channels strip subscribes
4167/// here to show a concurrent program's live task and channel state as it runs.
4168pub async fn interpret_streaming_with_vfs_observer<F>(
4169    input: &str,
4170    on_output: std::rc::Rc<std::cell::RefCell<F>>,
4171    vfs: Option<std::sync::Arc<dyn logicaffeine_system::fs::Vfs>>,
4172    observer: ObserverCallback,
4173) -> InterpreterResult
4174where
4175    F: FnMut(String) + 'static,
4176{
4177    interpret_streaming_impl(input, on_output, vfs, Some(observer)).await
4178}
4179
4180async fn interpret_streaming_impl<F>(
4181    input: &str,
4182    on_output: std::rc::Rc<std::cell::RefCell<F>>,
4183    vfs: Option<std::sync::Arc<dyn logicaffeine_system::fs::Vfs>>,
4184    observer: Option<ObserverCallback>,
4185) -> InterpreterResult
4186where
4187    F: FnMut(String) + 'static,
4188{
4189    use crate::interpreter::OutputCallback;
4190    use logicaffeine_language::ast::stmt::{Expr, Stmt, TypeExpr};
4191    begin_ui_run();
4192
4193    let mut interner = Interner::new();
4194    let mut lexer = Lexer::new(input, &mut interner);
4195    let tokens = lexer.tokenize();
4196
4197    let mwe_trie = mwe::build_mwe_trie();
4198    let mut tokens = mwe::apply_mwe_pipeline(tokens, &mwe_trie, &mut interner);
4199
4200    // Resolve the qualified escape hatch for cross-module calls (`Alias::fn` →
4201    // bare `fn`); no-op for single-file programs.
4202    let functions = crate::analysis::assemble::defined_function_names(input);
4203    crate::analysis::assemble::resolve_qualified_names(&mut tokens, &mut interner, &functions);
4204
4205    let (type_registry, policy_registry) = {
4206        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
4207        let result = discovery.run_full();
4208        (result.types, result.policies)
4209    };
4210
4211    let expr_arena = Arena::new();
4212    let term_arena = Arena::new();
4213    let np_arena = Arena::new();
4214    let sym_arena = Arena::new();
4215    let role_arena = Arena::new();
4216    let pp_arena = Arena::new();
4217    let stmt_arena: Arena<Stmt> = Arena::new();
4218    let _compile_facts = crate::optimize::facts::scope();
4219    let imperative_expr_arena: Arena<Expr> = Arena::new();
4220    let type_expr_arena: Arena<TypeExpr> = Arena::new();
4221
4222    let ctx = AstContext::with_types(
4223        &expr_arena,
4224        &term_arena,
4225        &np_arena,
4226        &sym_arena,
4227        &role_arena,
4228        &pp_arena,
4229        &stmt_arena,
4230        &imperative_expr_arena,
4231        &type_expr_arena,
4232    );
4233
4234    let mut world_state = drs::WorldState::new();
4235    let mut parser = Parser::new(tokens, &mut world_state, &mut interner, ctx, type_registry);
4236    let parsed = parser.parse_program();
4237    let opt_flags = parser.program_opt_flags();
4238    let type_registry_for_interp = parser.into_type_registry();
4239
4240    match parsed {
4241        Ok(stmts) => {
4242            let mut run_cfg =
4243                crate::optimization::OptimizationConfig::from_env().merged(&opt_flags);
4244            run_cfg.normalize();
4245            let resolved = crate::resolve_program::resolve_program(
4246                &stmts,
4247                crate::ast_map::Arenas {
4248                    exprs: &imperative_expr_arena,
4249                    stmts: &stmt_arena,
4250                    types: &type_expr_arena,
4251                },
4252                &mut interner,
4253                run_cfg.is_on(crate::optimization::Opt::Comptime),
4254                &crate::loader::library_owned_functions(input),
4255            );
4256            let stmts: Vec<Stmt> = match resolved {
4257                Some(rw) => rw.to_vec(),
4258                None => stmts,
4259            };
4260            if let Some(rejection) = send_escape_rejection(&stmts) {
4261                return rejection;
4262            }
4263            // Create the callback wrapper that calls the user's callback
4264            let callback: OutputCallback =
4265                std::rc::Rc::new(std::cell::RefCell::new(move |line: String| {
4266                    (on_output.borrow_mut())(line);
4267                }));
4268
4269            // Concurrent programs run on the deterministic scheduler — the browser
4270            // concurrency path — driven in slices that yield a macrotask between them so
4271            // the UI repaints, streaming each line as it is produced and emitting a
4272            // snapshot to the observer (if any). (Without this, a concurrency op would
4273            // `yield_request` with no scheduler installed and panic.)
4274            if crate::concurrency::uses_scheduler(&stmts) {
4275                return run_program_concurrent_streaming(
4276                    &stmts,
4277                    &type_registry_for_interp,
4278                    policy_registry,
4279                    &interner,
4280                    &[],
4281                    vfs,
4282                    Some(callback),
4283                    observer,
4284                    0,
4285                )
4286                .await;
4287            }
4288
4289            let mut interp = crate::interpreter::Interpreter::new(&interner)
4290                .with_type_registry(&type_registry_for_interp)
4291                .with_policies(policy_registry)
4292                .with_output_callback(callback);
4293            if let Some(v) = vfs {
4294                interp = interp.with_vfs(v);
4295            }
4296
4297            match interp.run(&stmts).await {
4298                Ok(()) => InterpreterResult {
4299                    lines: interp.output,
4300                    error: None,
4301                },
4302                Err(e) => InterpreterResult {
4303                    lines: interp.output,
4304                    error: Some(e),
4305                },
4306            }
4307        }
4308        Err(e) => {
4309            let advice = socratic_explanation(&e, &interner);
4310            InterpreterResult {
4311                lines: vec![],
4312                error: Some(advice),
4313            }
4314        }
4315    }
4316}
4317
4318// ═══════════════════════════════════════════════════════════════════
4319// Theorem Verification (Kernel-certified)
4320// ═══════════════════════════════════════════════════════════════════
4321
4322use crate::kernel;
4323use logicaffeine_language::ast::Stmt;
4324use logicaffeine_language::proof_convert::logic_expr_to_proof_expr;
4325
4326/// Phase 78: Verify a theorem with full kernel certification.
4327///
4328/// Pipeline:
4329/// 1. Parse theorem block
4330/// 2. Extract symbols and build kernel context
4331/// 3. Run proof engine
4332/// 4. Certify derivation tree to kernel term
4333/// 5. Type-check the term
4334/// 6. Return (proof_term, context)
4335pub fn verify_theorem(input: &str) -> Result<(kernel::Term, kernel::Context), ParseError> {
4336    let (proof_exprs, goal_expr, definitions, declared) = theorem_problem_declared(input)?;
4337
4338    // === STEPS 3-6: Prove → certify → type-check (the one canonical pipeline), BY THE
4339    // METHOD THE BLOCK DECLARED — see `prove_declared`. ===
4340    let (outcome, _) = prove_declared(&proof_exprs, &goal_expr, &definitions, &declared);
4341    if outcome.verified {
4342        Ok((
4343            outcome
4344                .proof_term
4345                .expect("a verified outcome always carries a proof term"),
4346            outcome.kernel_ctx,
4347        ))
4348    } else {
4349        Err(ParseError {
4350            kind: logicaffeine_language::error::ParseErrorKind::Custom(
4351                outcome
4352                    .verification_error
4353                    .unwrap_or_else(|| "Theorem verification failed".to_string()),
4354            ),
4355            span: logicaffeine_language::token::Span::default(),
4356        })
4357    }
4358}
4359
4360/// An English theorem proved, with its FOL and a human-readable PROOF TRACE — the
4361/// "English in → proof out, see the trace" path. Parsing yields the premises and
4362/// goal as FOL; the kernel-certified backward chainer yields the derivation, which
4363/// renders as an indented step-by-step proof.
4364#[derive(Debug, Clone)]
4365pub struct TheoremTrace {
4366    /// Whether the goal was proved (kernel-certified).
4367    pub verified: bool,
4368    /// The premises, rendered as FOL — what the English compiled to.
4369    pub premises: Vec<String>,
4370    /// The goal, rendered as FOL.
4371    pub goal: String,
4372    /// The derivation rendered as an indented proof trace (`└─ [Rule] conclusion`
4373    /// per step). `None` when no derivation was found.
4374    pub trace: Option<String>,
4375    /// The verification error, when proving failed.
4376    pub error: Option<String>,
4377}
4378
4379/// Prove an English `## Theorem` block and return its FOL plus a rendered PROOF
4380/// TRACE. Unlike [`verify_theorem`] (which returns the raw kernel term), this
4381/// surfaces the derivation tree so the proof steps are visible.
4382pub fn prove_theorem_trace(input: &str) -> Result<TheoremTrace, ParseError> {
4383    let (proof_exprs, goal_expr, definitions, declared) = theorem_problem_declared(input)?;
4384    let (outcome, _) = prove_declared(&proof_exprs, &goal_expr, &definitions, &declared);
4385    Ok(TheoremTrace {
4386        verified: outcome.verified,
4387        premises: proof_exprs.iter().map(|p| p.to_string()).collect(),
4388        goal: goal_expr.to_string(),
4389        trace: outcome.derivation.as_ref().map(|d| d.display_tree()),
4390        error: outcome.verification_error,
4391    })
4392}
4393
4394/// Build an INDEPENDENTLY RE-CHECKABLE certificate for a proved English `## Theorem`.
4395///
4396/// A `largo prove` ✓ is a boolean the caller must trust the prover for. A
4397/// [`kernel::certificate::TheoremCertificate`] is instead a portable artifact — the
4398/// kernel proof term, the goal it proves, and the theorem's DISCLOSED environment delta
4399/// (its declared vocabulary + stated premises as hypotheses) — that a third party can
4400/// re-verify with nothing but the kernel, by TYPE-CHECKING the term, never by re-running
4401/// proof search.
4402///
4403/// Returns `Ok(None)` when the theorem block parses but is NOT kernel-certified (an
4404/// unproved goal has no proof term, so no certificate exists — the honest outcome).
4405/// Only a genuine kernel derivation yields a certificate; there is no finite-enumeration
4406/// path here that could mint one.
4407pub fn theorem_certificate(
4408    input: &str,
4409) -> Result<Option<kernel::certificate::TheoremCertificate>, ParseError> {
4410    let (proof_exprs, goal_expr, definitions, declared) = theorem_problem_declared(input)?;
4411    let (outcome, _) = prove_declared(&proof_exprs, &goal_expr, &definitions, &declared);
4412    // A derivation alone is NOT a proof: only a `verified` outcome carries a
4413    // kernel-certified proof term, and only that becomes a certificate.
4414    if !outcome.verified {
4415        return Ok(None);
4416    }
4417    let Some(proof_term) = outcome.proof_term else {
4418        return Ok(None);
4419    };
4420    let name = english_theorem_name(input);
4421    Ok(Some(build_theorem_certificate(
4422        &name,
4423        proof_term,
4424        &outcome.kernel_ctx,
4425    )))
4426}
4427
4428/// The display name of an English `## Theorem: Name` block (mirrors the CLI's namer).
4429fn english_theorem_name(input: &str) -> String {
4430    input
4431        .lines()
4432        .find(|l| l.trim_start().starts_with("## Theorem"))
4433        .and_then(|l| l.split_once(':'))
4434        .map(|(_, name)| name.trim().to_string())
4435        .filter(|n| !n.is_empty())
4436        .unwrap_or_else(|| "theorem".to_string())
4437}
4438
4439/// Assemble a [`kernel::certificate::TheoremCertificate`] from a proved theorem's kernel
4440/// proof term and its proving context. The certificate's claimed type is the term's
4441/// inferred type in that context; its disclosed delta is EVERY declaration/definition the
4442/// context holds beyond the standard prelude — the theorem's own vocabulary and premises.
4443///
4444/// The prelude baseline is subtracted so the delta carries ONLY the theorem-specific
4445/// assumptions, in the open, and the checker rebuilds the trusted prelude itself.
4446pub(crate) fn build_theorem_certificate(
4447    name: &str,
4448    proof_term: kernel::Term,
4449    ctx: &kernel::Context,
4450) -> kernel::certificate::TheoremCertificate {
4451    use kernel::certificate::{CertDeclaration, CertDefinition, TheoremCertificate};
4452
4453    // The trusted baseline: the standard prelude. Anything in `ctx` NOT in the baseline is
4454    // the theorem's disclosed delta.
4455    let baseline = kernel::prelude::StandardLibrary::context();
4456
4457    let declarations: Vec<CertDeclaration> = ctx
4458        .iter_declarations()
4459        .filter(|(n, _)| baseline.get_global(n).is_none())
4460        .map(|(n, ty)| CertDeclaration {
4461            name: n.to_string(),
4462            ty: ty.clone(),
4463        })
4464        .collect();
4465    let definitions: Vec<CertDefinition> = ctx
4466        .iter_definitions()
4467        .filter(|(n, _, _)| baseline.get_global(n).is_none())
4468        .map(|(n, ty, body)| CertDefinition {
4469            name: n.to_string(),
4470            ty: ty.clone(),
4471            body: body.clone(),
4472        })
4473        .collect();
4474
4475    // The claimed type is what the term actually proves in the full context. If the term
4476    // somehow fails to type-check here it is not a real proof; a bogus fallback type would
4477    // simply be rejected by the independent re-checker, never silently accepted.
4478    let claimed_type = kernel::infer_type(ctx, &proof_term)
4479        .unwrap_or_else(|_| kernel::Term::Global("False".to_string()));
4480
4481    TheoremCertificate::new(name, proof_term, claimed_type, declarations, definitions)
4482}
4483
4484// ═══════════════════════════════════════════════════════════════════
4485// Proof / Math → Rust extraction (the Curry-Howard "Forge", UI-facing)
4486// ═══════════════════════════════════════════════════════════════════
4487
4488/// Names the user defined — present in `ctx` but absent from a fresh kernel
4489/// context (i.e. excluding the StandardLibrary baseline). Inductives are listed
4490/// before definitions so the extracted module reads top-down; StandardLibrary
4491/// items are pulled in by [`extract_math_rust`] only when transitively needed.
4492fn user_defined_entries(ctx: &kernel::Context) -> Vec<String> {
4493    let base = Baseline::new();
4494
4495    let mut entries = Vec::new();
4496    for (name, _) in ctx.iter_inductives() {
4497        // A user inductive extracts as an enum only if every constructor field is
4498        // a concrete Rust type. Dependent/indexed families (e.g. `Eq<Nat,n,…>`,
4499        // value-indexed proof types) and opaque/primitive types are skipped.
4500        if !base.owns_inductive(name) && inductive_is_emittable(ctx, name) {
4501            entries.push(name.to_string());
4502        }
4503    }
4504    for (name, ty, body) in ctx.iter_definitions() {
4505        // Only data-typed definitions whose body references nothing inextractable
4506        // (no Prop proofs, no axioms/tactics like `syn_diag`/`try_auto`) extract to
4507        // runnable Rust — so we never emit Rust that references undefined symbols.
4508        if !base.owns_definition(name, ty, body)
4509            && type_is_emittable(ctx, ty, &[])
4510            && crate::extraction::is_extractable(ctx, name)
4511        {
4512            entries.push(name.to_string());
4513        }
4514    }
4515    // The module lists its items by name, whatever order they were declared in.
4516    entries.sort();
4517    entries.dedup();
4518    entries
4519}
4520
4521/// Whether a kernel type extracts to a concrete Rust type: a mapped primitive, a
4522/// user inductive with emittable constructors (→ enum), a declared type parameter
4523/// (`generics`), or a function/application built from those. `Sort` (Prop/Type),
4524/// logical/opaque types, and undeclared type variables are not.
4525fn type_is_emittable(ctx: &kernel::Context, ty: &kernel::Term, generics: &[String]) -> bool {
4526    use kernel::Term;
4527    match ty {
4528        Term::Global(name) => {
4529            crate::extraction::primitive_rust_type(name).is_some()
4530                || (ctx.is_inductive(name)
4531                    && !ctx.get_constructors(name).is_empty()
4532                    && !crate::extraction::is_logical_type(name))
4533        }
4534        // A type variable is only a real Rust type if it's a declared generic of
4535        // the enclosing inductive — never in a bare definition type.
4536        Term::Var(v) => generics.iter().any(|g| g == v),
4537        Term::Pi {
4538            param_type,
4539            body_type,
4540            ..
4541        } => {
4542            type_is_emittable(ctx, param_type, generics)
4543                && type_is_emittable(ctx, body_type, generics)
4544        }
4545        Term::App(f, a) => {
4546            type_is_emittable(ctx, f, generics) && type_is_emittable(ctx, a, generics)
4547        }
4548        _ => false,
4549    }
4550}
4551
4552/// The leading `: Type` parameters of an inductive (its Rust generics).
4553fn inductive_generics(ctx: &kernel::Context, ind: &str) -> Vec<String> {
4554    use kernel::Term;
4555    let mut names = Vec::new();
4556    let mut cur = match ctx.get_global(ind) {
4557        Some(t) => t,
4558        None => return names,
4559    };
4560    while let Term::Pi {
4561        param,
4562        param_type,
4563        body_type,
4564    } = cur
4565    {
4566        if matches!(param_type.as_ref(), Term::Sort(_)) {
4567            names.push(param.clone());
4568            cur = body_type;
4569        } else {
4570            break;
4571        }
4572    }
4573    names
4574}
4575
4576/// A user inductive is emittable iff it has constructors and every constructor
4577/// *field* (after the leading type parameters) is itself an emittable type.
4578fn inductive_is_emittable(ctx: &kernel::Context, ind: &str) -> bool {
4579    use kernel::Term;
4580    let ctors = ctx.get_constructors(ind);
4581    if ctors.is_empty() || crate::extraction::is_logical_type(ind) {
4582        return false;
4583    }
4584    let generics = inductive_generics(ctx, ind);
4585    for (_, ty) in &ctors {
4586        let mut cur = *ty;
4587        for _ in 0..generics.len() {
4588            if let Term::Pi { body_type, .. } = cur {
4589                cur = body_type;
4590            } else {
4591                break;
4592            }
4593        }
4594        while let Term::Pi {
4595            param_type,
4596            body_type,
4597            ..
4598        } = cur
4599        {
4600            if !type_is_emittable(ctx, param_type, &generics) {
4601                return false;
4602            }
4603            cur = body_type;
4604        }
4605    }
4606    true
4607}
4608
4609/// Extract every user-defined inductive and definition in `ctx` into one Rust
4610/// module — the "compile my math to Rust" path for the Math studio. Shared and
4611/// StandardLibrary dependencies are pulled in only when a user definition
4612/// transitively needs them, and are emitted exactly once.
4613pub fn extract_math_rust(ctx: &kernel::Context) -> Result<String, String> {
4614    let entries = user_defined_entries(ctx);
4615    if entries.is_empty() {
4616        return Ok("// nothing defined yet — add a Definition or Inductive".to_string());
4617    }
4618    let module = extract_math_module(ctx)?;
4619    let checks: Vec<(String, Vec<kernel::Term>)> = property_checks(ctx)
4620        .into_iter()
4621        .map(|(n, _, p)| (n, p))
4622        .collect();
4623    // The "compiled mathematical object" runs and proves itself.
4624    Ok(format!(
4625        "{module}{}",
4626        math_demo_main(ctx, &entries, &checks)
4627    ))
4628}
4629
4630/// Extract every user-defined inductive/definition in `ctx` into one Rust module —
4631/// types, functions, and `check_*` property fns from proven theorems — WITHOUT a
4632/// demo `main`. This is the linkable artifact bundled into an imperative program's
4633/// `mod proven`; [`extract_math_rust`] wraps it with a self-verifying `main` for the
4634/// standalone Math compile.
4635pub fn extract_math_module(ctx: &kernel::Context) -> Result<String, String> {
4636    let entries = user_defined_entries(ctx);
4637    if entries.is_empty() {
4638        return Ok("// nothing defined yet — add a Definition or Inductive".to_string());
4639    }
4640    let refs: Vec<&str> = entries.iter().map(|s| s.as_str()).collect();
4641    let mut module = crate::extraction::extract_programs(ctx, &refs).map_err(|e| e.to_string())?;
4642    // Proven theorems → runnable property checks over the extracted functions
4643    // (e.g. `∀n. add Zero n = n` → `fn check_…(n) -> bool { add(Zero, n) == n }`).
4644    // Appended in sorted order so the module is byte-identical across recompiles.
4645    let mut check_names: std::collections::HashSet<String> = std::collections::HashSet::new();
4646    for (name, check_fn, _) in property_checks(ctx) {
4647        module.push_str(&check_fn);
4648        check_names.insert(name);
4649    }
4650    // Honest notes for proof-irrelevant theorems (Gödel, consistency, `True`, …): a
4651    // definition whose TYPE is a proposition is a *proof*, and by Curry-Howard a proof
4652    // of a Prop has no computational content — so it has no runnable form. The
4653    // constructive dependencies it uses are still extracted above; the note explains
4654    // why the theorem itself isn't a function. Sorted for deterministic output.
4655    let base = Baseline::new();
4656    let mut notes: Vec<String> = Vec::new();
4657    for (name, ty, body) in ctx.iter_definitions() {
4658        if base.owns_definition(name, ty, body) || check_names.contains(name) {
4659            continue;
4660        }
4661        if def_type_is_proposition(ty) {
4662            let name = ctx.written_name(name);
4663            notes.push(format!(
4664                "// note: `{name}` is a proof of a proposition — proof-irrelevant (no \
4665                 computational content), so it has no runnable form; any constructive \
4666                 definitions it relies on are extracted above.\n"
4667            ));
4668        }
4669    }
4670    notes.sort();
4671    for n in notes {
4672        module.push_str(&n);
4673    }
4674    Ok(module)
4675}
4676
4677/// Whether a definition's type is a proposition — i.e. the definition is a *proof*
4678/// (proof-irrelevant), not computational data. Peels any `∀` (Pi) binders, then
4679/// checks whether the head of the result is a logical/proof type (`Eq`/`And`/`True`/
4680/// `Syntax`/`Derivation`/…). Used to emit honest notes for theorems with no runnable form.
4681fn def_type_is_proposition(ty: &kernel::Term) -> bool {
4682    use kernel::Term;
4683    let mut cur = ty;
4684    while let Term::Pi { body_type, .. } = cur {
4685        cur = body_type;
4686    }
4687    let mut head = cur;
4688    while let Term::App(f, _) = head {
4689        head = f;
4690    }
4691    matches!(head, Term::Global(n) if crate::extraction::is_logical_type(n))
4692}
4693
4694/// Proven theorems → runnable property checks: `(name, check_fn_source, param_types)`,
4695/// sorted by name for deterministic emission. A theorem yields a check iff
4696/// [`crate::extraction::emit_property_check`] produces a runnable predicate over the
4697/// extracted functions (it quantifies only over data types).
4698fn property_checks(ctx: &kernel::Context) -> Vec<(String, String, Vec<kernel::Term>)> {
4699    let base = Baseline::new();
4700    let mut checks: Vec<(String, String, Vec<kernel::Term>)> = Vec::new();
4701    for (name, ty, body) in ctx.iter_definitions() {
4702        if base.owns_definition(name, ty, body) {
4703            continue;
4704        }
4705        if let Some(check_fn) = crate::extraction::emit_property_check(ctx, name, ty) {
4706            checks.push((name.to_string(), check_fn, pi_param_types(ty)));
4707        }
4708    }
4709    checks.sort_by(|a, b| a.0.cmp(&b.0));
4710    checks
4711}
4712
4713/// The StandardLibrary baseline: what a fresh `Repl::new()` declares, and AS WHAT.
4714///
4715/// A NAME is not an identity. `add_zero`, `mul_zero`, `le_add_mono`, `Nat_add` — the prelude's
4716/// integer laws and structural arithmetic — are all perfectly ordinary names for a user's own
4717/// theorem, and compared by name alone a user's
4718/// `Definition add_zero : Eq MyNat (my_add MZero MZero) MZero` IS the prelude's
4719/// `∀a:Int. a + 0 = a`: it vanishes from the extracted module with no `check_add_zero` and not
4720/// even the honest note that would say why. The comparison that holds is the one the trust
4721/// door already makes about an axiom footprint — a name the rebuilt prelude declares AT THE
4722/// SAME TYPE AND BODY is the prelude's; anything else at that name was introduced by this run.
4723///
4724/// INDUCTIVES are compared by name, because in this kernel a redeclared inductive is not a
4725/// second declaration: its constructors are APPENDED to the same family (which is why
4726/// `distinct_constructors` exists), so there is no rival declaration to compare against.
4727struct Baseline {
4728    inductives: std::collections::HashSet<String>,
4729    definitions: std::collections::HashMap<String, (kernel::Term, kernel::Term)>,
4730}
4731
4732impl Baseline {
4733    fn new() -> Self {
4734        let baseline = kernel::interface::Repl::new();
4735        let base = baseline.context();
4736        Self {
4737            inductives: base.iter_inductives().map(|(n, _)| n.to_string()).collect(),
4738            definitions: base
4739                .iter_definitions()
4740                .map(|(n, ty, body)| (n.to_string(), (ty.clone(), body.clone())))
4741                .collect(),
4742        }
4743    }
4744
4745    /// Is `name` the prelude's inductive (not a user type that reuses the spelling)?
4746    fn owns_inductive(&self, name: &str) -> bool {
4747        self.inductives.contains(name)
4748    }
4749
4750    /// Is the definition `name : ty := body` the prelude's own, rather than a user
4751    /// declaration that happens to share its spelling?
4752    fn owns_definition(&self, name: &str, ty: &kernel::Term, body: &kernel::Term) -> bool {
4753        self.definitions
4754            .get(name)
4755            .is_some_and(|(bty, bbody)| bty == ty && bbody == body)
4756    }
4757}
4758
4759/// Whether a term applies the `div`/`mod` arithmetic builtins (whose extracted Rust
4760/// `/`/`%` panics on a zero divisor) — used to skip them in the self-verifying demo.
4761fn term_uses_div_or_mod(term: &kernel::Term) -> bool {
4762    use kernel::Term;
4763    match term {
4764        Term::Global(n) => n == "div" || n == "mod",
4765        Term::App(f, a) => term_uses_div_or_mod(f) || term_uses_div_or_mod(a),
4766        Term::Lambda {
4767            param_type, body, ..
4768        } => term_uses_div_or_mod(param_type) || term_uses_div_or_mod(body),
4769        Term::Pi {
4770            param_type,
4771            body_type,
4772            ..
4773        } => term_uses_div_or_mod(param_type) || term_uses_div_or_mod(body_type),
4774        Term::Fix { body, .. } => term_uses_div_or_mod(body),
4775        Term::Match {
4776            discriminant,
4777            motive,
4778            cases,
4779        } => {
4780            term_uses_div_or_mod(discriminant)
4781                || term_uses_div_or_mod(motive)
4782                || cases.iter().any(term_uses_div_or_mod)
4783        }
4784        _ => false,
4785    }
4786}
4787
4788/// A self-verifying demo `main`: each value/function result is `assert_eq!`d
4789/// against `kernel::normalize` (the kernel's evaluator) and printed; each proven
4790/// theorem's property check is run on a sample and asserted.
4791fn math_demo_main(
4792    ctx: &kernel::Context,
4793    entries: &[String],
4794    checks: &[(String, Vec<kernel::Term>)],
4795) -> String {
4796    use kernel::Term;
4797    let mut lines = Vec::new();
4798    for name in entries {
4799        let Some(body) = ctx.get_definition_body(name) else {
4800            continue; // an inductive, not a definition
4801        };
4802        // The Rust item a key was emitted as, and the name its author wrote, which a key that a
4803        // shadow minted is not.
4804        let (item, written) = (
4805            crate::extraction::rust_global(ctx, name),
4806            ctx.written_name(name),
4807        );
4808        // Skip exercising a def that uses `div`/`mod`: the demo samples Int as 0, and
4809        // `n / n` / `n % n` at n=0 is a compile-time divide-by-zero panic (and the
4810        // kernel leaves div-by-0 stuck, diverging from Rust's panic). The function is
4811        // still EXTRACTED — just not run in the self-verifying demo.
4812        if term_uses_div_or_mod(body) {
4813            continue;
4814        }
4815        if matches!(body, Term::Lambda { .. } | Term::Fix { .. }) {
4816            // A function: apply it to kernel-built sample arguments.
4817            let Some(ty) = ctx.get_definition_type(name) else {
4818                continue;
4819            };
4820            let params = pi_param_types(ty);
4821            let samples: Option<Vec<Term>> = params.iter().map(|p| sample_value(ctx, p)).collect();
4822            let Some(samples) = samples else { continue }; // can't sample → skip
4823            if samples.is_empty() {
4824                continue;
4825            }
4826            let args_rust: Vec<String> = samples
4827                .iter()
4828                .map(|s| crate::extraction::emit_value(ctx, s))
4829                .collect();
4830            let mut app = Term::Global(name.clone());
4831            for s in &samples {
4832                app = Term::App(Box::new(app), Box::new(s.clone()));
4833            }
4834            let expected = crate::extraction::emit_value(ctx, &kernel::normalize(ctx, &app));
4835            let call = format!("{}({})", item, args_rust.join(", "));
4836            lines.push(format!("    assert_eq!({call}, {expected});"));
4837            lines.push(format!("    println!(\"{written}(..) = {{:?}}\", {call});"));
4838        } else {
4839            // A value: evaluate and self-verify.
4840            let expected = crate::extraction::emit_value(ctx, &kernel::normalize(ctx, body));
4841            lines.push(format!("    assert_eq!({item}(), {expected});"));
4842            lines.push(format!("    println!(\"{written} = {{:?}}\", {item}());"));
4843        }
4844    }
4845    // Run each proven theorem's property check on a sample and assert it holds.
4846    for (name, param_types) in checks {
4847        let samples: Option<Vec<kernel::Term>> =
4848            param_types.iter().map(|p| sample_value(ctx, p)).collect();
4849        let Some(samples) = samples else { continue };
4850        let args: Vec<String> = samples
4851            .iter()
4852            .map(|s| crate::extraction::emit_value(ctx, s))
4853            .collect();
4854        let (item, written) = (
4855            crate::extraction::rust_global(ctx, name),
4856            ctx.written_name(name),
4857        );
4858        let call = format!("check_{}({})", item, args.join(", "));
4859        lines.push(format!(
4860            "    assert!({call}, \"theorem {written} failed on sample\");"
4861        ));
4862        lines.push(format!(
4863            "    println!(\"\\u{{2713}} {written} holds (checked on a sample)\");"
4864        ));
4865    }
4866    if lines.is_empty() {
4867        return "\nfn main() {}\n".to_string();
4868    }
4869    format!("\nfn main() {{\n{}\n}}\n", lines.join("\n"))
4870}
4871
4872/// The parameter types of a (possibly curried) function type `A -> B -> C`.
4873fn pi_param_types(ty: &kernel::Term) -> Vec<kernel::Term> {
4874    use kernel::Term;
4875    let mut params = Vec::new();
4876    let mut cur = ty;
4877    while let Term::Pi {
4878        param_type,
4879        body_type,
4880        ..
4881    } = cur
4882    {
4883        params.push((**param_type).clone());
4884        cur = body_type;
4885    }
4886    params
4887}
4888
4889/// A small sample value of a type, for the demo (a primitive zero, or the first
4890/// nullary constructor of an inductive). `None` if we can't build one cheaply.
4891fn sample_value(ctx: &kernel::Context, ty: &kernel::Term) -> Option<kernel::Term> {
4892    use kernel::{Literal, Term};
4893    match ty {
4894        Term::Global(name) => match name.as_str() {
4895            "Int" => Some(Term::Lit(Literal::Int(0))),
4896            "Float" => Some(Term::Lit(Literal::Float(0.0))),
4897            "Text" => Some(Term::Lit(Literal::Text(String::new()))),
4898            // First nullary constructor of a user inductive (Zero, Yes, MNil, …).
4899            _ if ctx.is_inductive(name) => ctx
4900                .get_constructors(name)
4901                .into_iter()
4902                .find(|(_, cty)| !matches!(cty, Term::Pi { .. }))
4903                .map(|(cname, _)| Term::Global(cname.to_string())),
4904            _ => None,
4905        },
4906        _ => None,
4907    }
4908}
4909
4910/// Compile a Math-mode SOURCE program (the editor text) to a Rust module: split
4911/// it into vernacular statements, run them into a fresh kernel, then extract every
4912/// user-defined inductive/definition. This is the exact pipeline the Studio's
4913/// Math "🦀 Compile" button drives, exposed as one function so it is testable.
4914pub fn extract_math_rust_from_source(input: &str) -> String {
4915    let mut repl = kernel::interface::Repl::new();
4916    // Batch execution groups mutually-recursive inductives declared as separate
4917    // statements into one mutual block (see `Repl::execute_batch`); errors on individual
4918    // statements (e.g. `Check`/`Eval`) are ignored — only the resulting
4919    // definitions/inductives matter for extraction.
4920    let stmts = parse_math_statements(input);
4921    let _ = repl.execute_batch(&stmts);
4922    match extract_math_rust(repl.context()) {
4923        Ok(rust) => rust,
4924        Err(e) => format!("// extraction error: {e}"),
4925    }
4926}
4927
4928/// Like [`extract_math_rust_from_source`], but produces the main-less module (the
4929/// linkable artifact bundled into an imperative program's `mod proven`).
4930pub fn extract_math_module_from_source(input: &str) -> String {
4931    let mut repl = kernel::interface::Repl::new();
4932    // Batch execution groups mutually-recursive inductives (`Tree`↔`Forest`) declared as
4933    // separate statements into one mutual block, so a forward reference between them
4934    // registers instead of failing its universe check. A source with no forward
4935    // references behaves exactly as the per-statement loop did.
4936    let stmts = parse_math_statements(input);
4937    let _ = repl.execute_batch(&stmts);
4938    match extract_math_module(repl.context()) {
4939        Ok(rust) => rust,
4940        Err(e) => format!("// extraction error: {e}"),
4941    }
4942}
4943
4944/// IMPLICIT MAIN: a source with no `##` headers whose first non-blank line
4945/// reads as an imperative statement runs as its own `## Main` body, so a bare
4946/// script runs rather than parsing as logic prose.
4947/// Natural-language documents (no statement-keyword opening) are untouched.
4948/// Returns the wrapped source, or `None` when the input is not a bare script.
4949pub fn implicit_main(source: &str) -> Option<String> {
4950    if source.lines().any(|l| l.trim_start().starts_with("##")) {
4951        return None;
4952    }
4953    let first = source.lines().find(|l| !l.trim().is_empty())?;
4954    const STATEMENT_HEADS: &[&str] = &[
4955        "Let ",
4956        "Show ",
4957        "Set ",
4958        "If ",
4959        "While ",
4960        "Repeat ",
4961        "Push ",
4962        "Pop ",
4963        "Add ",
4964        "Remove ",
4965        "Call ",
4966        "Return ",
4967        "Increase ",
4968        "Decrease ",
4969        "Break",
4970        "Inspect ",
4971        "Assert ",
4972    ];
4973    let t = first.trim_start();
4974    if STATEMENT_HEADS.iter().any(|h| t.starts_with(h)) {
4975        Some(format!("## Main\n{}", source))
4976    } else {
4977        None
4978    }
4979}
4980
4981/// Partition a possibly-MIXED document into its imperative and math streams.
4982///
4983/// A mixed document interleaves the language's blocks with the kernel's vernacular: Coq-style
4984/// sentences (`Definition`/`Inductive`/`Axiom`/`Theorem`/`Lemma`/`Fixpoint`) and literate
4985/// `## Theorem:`/`## Lemma:` blocks in the kernel's own form, the name followed by `Statement:`.
4986/// The math feeds the Forge (extracted into `mod proven`); the imperative blocks compile
4987/// normally and call into it.
4988///
4989/// What the language reads never reaches the kernel: `## To`/`## A X is one of` stay
4990/// imperative, an English `## Theorem:` (`Given:`/`Prove:`) is the proof engine's
4991/// (`opens_kernel_statement`), and a block the language reads as text owns its body to the
4992/// next header (`language_reads_as_text`), even where a line opens with a kernel keyword.
4993///
4994/// Returns `(imperative_src, Some(math_src))` when math is present, or
4995/// `(source.to_string(), None)` for a pure imperative program — so that path is a
4996/// guaranteed no-op (byte-identical compile). In `imperative_src` the math lines are
4997/// BLANKED (kept as empty lines), not deleted, so imperative line numbers — and thus
4998/// error spans — stay aligned with the original source.
4999pub fn partition_mixed(source: &str) -> (String, Option<String>) {
5000    if let Some(wrapped) = implicit_main(source) {
5001        return (wrapped, None);
5002    }
5003    let lines: Vec<&str> = source.lines().collect();
5004    let mut is_math = vec![false; lines.len()];
5005    let mut i = 0;
5006    let mut any = false;
5007    let mut in_text_block = false;
5008    while i < lines.len() {
5009        let t = lines[i].trim();
5010        if let Some(header) = t.strip_prefix("##") {
5011            in_text_block = language_reads_as_text(header);
5012        }
5013        if in_text_block || !is_math_block_start(t) {
5014            i += 1;
5015            continue;
5016        }
5017        let literate = t.starts_with("## Theorem:") || t.starts_with("## Lemma:");
5018        if literate && !opens_kernel_statement(&lines, i) {
5019            i += 1;
5020            continue;
5021        }
5022        any = true;
5023        if literate {
5024            // Literate theorem: header + indented / `Statement:` / `Proof:` lines.
5025            is_math[i] = true;
5026            i += 1;
5027            while i < lines.len() {
5028                let nt = lines[i].trim();
5029                let indented = lines[i].starts_with(' ') || lines[i].starts_with('\t');
5030                if nt.is_empty() {
5031                    is_math[i] = true;
5032                    i += 1;
5033                    continue;
5034                }
5035                if indented || nt.starts_with("Statement:") || nt.starts_with("Proof:") {
5036                    is_math[i] = true;
5037                    i += 1;
5038                    if nt.starts_with("Proof:") && nt.ends_with('.') {
5039                        break;
5040                    }
5041                } else {
5042                    break;
5043                }
5044            }
5045        } else {
5046            // Coq-style statement: accumulate until a line ending with `.`. Defensive:
5047            // a `## ` block header (e.g. `## Main`, `## To`) ends the math block even
5048            // if the terminating `.` is missing/unterminated, so a malformed Definition
5049            // never swallows the imperative code that follows it.
5050            let mut ended = t.ends_with('.');
5051            is_math[i] = true;
5052            i += 1;
5053            while !ended && i < lines.len() {
5054                if lines[i].trim_start().starts_with("## ") {
5055                    break;
5056                }
5057                is_math[i] = true;
5058                ended = lines[i].trim().ends_with('.');
5059                i += 1;
5060            }
5061        }
5062    }
5063    if !any {
5064        return (source.to_string(), None);
5065    }
5066    let imp: Vec<&str> = lines
5067        .iter()
5068        .enumerate()
5069        .map(|(j, l)| if is_math[j] { "" } else { *l })
5070        .collect();
5071    let math: Vec<&str> = lines
5072        .iter()
5073        .enumerate()
5074        .filter(|(j, _)| is_math[*j])
5075        .map(|(_, l)| *l)
5076        .collect();
5077    (imp.join("\n"), Some(math.join("\n")))
5078}
5079
5080fn is_math_block_start(trimmed: &str) -> bool {
5081    const COQ: [&str; 6] = [
5082        "Definition ",
5083        "Inductive ",
5084        "Axiom ",
5085        "Theorem ",
5086        "Lemma ",
5087        "Fixpoint ",
5088    ];
5089    COQ.iter().any(|k| trimmed.starts_with(k))
5090        || trimmed.starts_with("## Theorem:")
5091        || trimmed.starts_with("## Lemma:")
5092}
5093
5094/// Whether the block header `header` (the text after `##`) opens a block the language reads as
5095/// raw text — `## Axiom` and `## Theory`, whose bodies the parser captures whole
5096/// (`collect_block_text`) up to the next block header.
5097fn language_reads_as_text(header: &str) -> bool {
5098    let word = header
5099        .trim_start()
5100        .split(|c: char| c.is_whitespace() || c == ':')
5101        .next()
5102        .unwrap_or("");
5103    matches!(word.to_ascii_lowercase().as_str(), "axiom" | "theory")
5104}
5105
5106/// Whether the literate block whose header is `lines[at]` is the kernel's: its name followed by
5107/// the kernel's `Statement:`, on the header line or the first line after it — the one form the
5108/// kernel's literate parser reads. Any other body (`Given:`/`Prove:`) is the proof engine's
5109/// English theorem, which the language reads.
5110fn opens_kernel_statement(lines: &[&str], at: usize) -> bool {
5111    let header = lines[at].trim();
5112    let after_colon = header
5113        .split_once(':')
5114        .map_or("", |(_, rest)| rest)
5115        .trim_start();
5116    let after_name = after_colon
5117        .split_once(char::is_whitespace)
5118        .map_or("", |(_, rest)| rest)
5119        .trim_start();
5120    let next = if after_name.is_empty() {
5121        lines[at + 1..]
5122            .iter()
5123            .map(|l| l.trim())
5124            .find(|l| !l.is_empty())
5125            .unwrap_or("")
5126    } else {
5127        after_name
5128    };
5129    next.strip_prefix("Statement")
5130        .is_some_and(|rest| rest.trim_start().starts_with(':'))
5131}
5132
5133/// Extract a mixed document's math stream into a bundleable `mod proven` body, or
5134/// `Ok(None)` if it has no public items to call into (e.g. only vacuous proofs) — so
5135/// we never emit a `use proven::*;` over an empty module.
5136///
5137/// Unlike standalone math extraction, this ALSO emits a `Showable` impl for each
5138/// non-generic proven enum, so imperative `Show <proven value>` works. `Showable`
5139/// lives in `logicaffeine_system` (in scope inside `mod proven` via `use super::*;`),
5140/// which is ONLY linked when bundled into an imperative program — hence it is added
5141/// here, not in `extract_math_module` (whose output must also compile standalone, dep-free).
5142///
5143/// A statement the kernel REFUSES refuses the program, in the kernel's own words and naming the
5144/// statement. Dropping it and extracting the rest leaves the imperative half calling a
5145/// `check_*` that was never emitted, and the reader is told "Unknown function" three layers
5146/// away from the refusal that caused it.
5147pub(crate) fn mixed_proven_module(math_src: &str) -> Result<Option<String>, ParseError> {
5148    let mut repl = kernel::interface::Repl::new();
5149    // Batch execution groups mutually-recursive inductives (see `Repl::execute_batch`).
5150    let stmts = parse_math_statements(math_src);
5151    for (stmt, outcome) in stmts.iter().zip(repl.execute_batch(&stmts)) {
5152        if let Err(refusal) = outcome {
5153            return Err(ParseError {
5154                kind: crate::error::ParseErrorKind::Custom(format!(
5155                    "the kernel refused the math statement `{}`: {refusal}",
5156                    stmt.trim()
5157                )),
5158                span: crate::token::Span::default(),
5159            });
5160        }
5161    }
5162    let ctx = repl.context();
5163    let mut rust = match extract_math_module(ctx) {
5164        Ok(r) => r,
5165        Err(_) => return Ok(None),
5166    };
5167    if !(rust.contains("pub fn") || rust.contains("pub enum") || rust.contains("pub struct")) {
5168        return Ok(None);
5169    }
5170    // Show-verb integration: bridge each non-generic proven enum to the runtime
5171    // `Showable` trait (via Debug). Sorted for deterministic output.
5172    let base = Baseline::new();
5173    let mut inds: Vec<String> = Vec::new();
5174    for (name, _) in ctx.iter_inductives() {
5175        if !base.owns_inductive(name)
5176            && inductive_is_emittable(ctx, name)
5177            && inductive_generics(ctx, name).is_empty()
5178        {
5179            inds.push(name.to_string());
5180        }
5181    }
5182    inds.sort();
5183    for ind in inds {
5184        let ind = crate::extraction::rust_global(ctx, &ind);
5185        rust.push_str(&format!(
5186            "impl Showable for {ind} {{ fn format_show(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {{ write!(f, \"{{:?}}\", self) }} }}\n"
5187        ));
5188    }
5189    Ok(Some(rust))
5190}
5191
5192/// Split a Math-mode program into complete vernacular statements.
5193///
5194/// Handles both Coq-style (period-terminated) and the Literate forms
5195/// (`## To …` functions, `## Theorem:` blocks, `A X is either …` inductives).
5196pub fn parse_math_statements(code: &str) -> Vec<String> {
5197    let mut statements = Vec::new();
5198    let lines: Vec<&str> = code.lines().collect();
5199    let mut i = 0;
5200
5201    while i < lines.len() {
5202        let line = lines[i];
5203        let trimmed = line.trim();
5204
5205        // Skip empty lines and comments
5206        if trimmed.is_empty() || trimmed.starts_with("--") {
5207            i += 1;
5208            continue;
5209        }
5210
5211        // Literate function definition: "## To ..."
5212        if trimmed.starts_with("## To ") {
5213            let mut block = String::new();
5214            block.push_str(trimmed);
5215            i += 1;
5216
5217            while i < lines.len() {
5218                let next_line = lines[i];
5219                let next_trimmed = next_line.trim();
5220
5221                if next_trimmed.is_empty() {
5222                    i += 1;
5223                    continue;
5224                }
5225                if next_trimmed.starts_with("--") {
5226                    i += 1;
5227                    continue;
5228                }
5229
5230                let is_indented = next_line.starts_with(' ') || next_line.starts_with('\t');
5231                let is_continuation = next_trimmed.starts_with("Consider ")
5232                    || next_trimmed.starts_with("When ")
5233                    || next_trimmed.starts_with("Yield ");
5234
5235                if is_indented || is_continuation {
5236                    block.push(' ');
5237                    block.push_str(next_trimmed);
5238                    i += 1;
5239                } else {
5240                    break;
5241                }
5242            }
5243
5244            statements.push(block);
5245            continue;
5246        }
5247
5248        // Literate theorem: "## Theorem: ..." (header + Statement: + Proof:)
5249        if trimmed.starts_with("## Theorem:") {
5250            let mut block = String::new();
5251            block.push_str(trimmed);
5252            i += 1;
5253
5254            while i < lines.len() {
5255                let next_line = lines[i];
5256                let next_trimmed = next_line.trim();
5257
5258                if next_trimmed.is_empty() {
5259                    i += 1;
5260                    continue;
5261                }
5262                if next_trimmed.starts_with("--") {
5263                    i += 1;
5264                    continue;
5265                }
5266
5267                let is_indented = next_line.starts_with(' ') || next_line.starts_with('\t');
5268                let is_theorem_part =
5269                    next_trimmed.starts_with("Statement:") || next_trimmed.starts_with("Proof:");
5270
5271                if is_indented || is_theorem_part {
5272                    block.push('\n');
5273                    block.push_str(next_line);
5274                    i += 1;
5275                    if next_trimmed.starts_with("Proof:") && next_trimmed.ends_with('.') {
5276                        break;
5277                    }
5278                } else {
5279                    break;
5280                }
5281            }
5282
5283            statements.push(block);
5284            continue;
5285        }
5286
5287        // Literate inductive: "A X is either..." / "An X is either..."
5288        if (trimmed.starts_with("A ") || trimmed.starts_with("An "))
5289            && trimmed.contains(" is either")
5290        {
5291            if trimmed.ends_with('.') && !trimmed.trim_end_matches('.').ends_with(':') {
5292                statements.push(trimmed.to_string());
5293                i += 1;
5294                continue;
5295            }
5296
5297            let mut block = String::new();
5298            block.push_str(trimmed);
5299            i += 1;
5300
5301            while i < lines.len() {
5302                let next_line = lines[i];
5303                let next_trimmed = next_line.trim();
5304
5305                if next_trimmed.is_empty() {
5306                    i += 1;
5307                    continue;
5308                }
5309                if next_trimmed.starts_with("--") {
5310                    i += 1;
5311                    continue;
5312                }
5313
5314                let is_indented = next_line.starts_with(' ') || next_line.starts_with('\t');
5315                let looks_like_variant = next_trimmed.starts_with("a ")
5316                    || next_trimmed
5317                        .chars()
5318                        .next()
5319                        .map(|c| c.is_uppercase())
5320                        .unwrap_or(false);
5321
5322                if is_indented
5323                    || (looks_like_variant
5324                        && !next_trimmed.starts_with("A ")
5325                        && !next_trimmed.starts_with("An "))
5326                {
5327                    if !block.ends_with(':') {
5328                        block.push_str(" or ");
5329                    } else {
5330                        block.push(' ');
5331                    }
5332                    block.push_str(next_trimmed.trim_end_matches('.'));
5333                    i += 1;
5334                } else {
5335                    break;
5336                }
5337            }
5338
5339            if !block.ends_with('.') {
5340                block.push('.');
5341            }
5342            statements.push(block);
5343            continue;
5344        }
5345
5346        // Traditional Coq-style: accumulate until period
5347        let mut current_stmt = String::new();
5348        while i < lines.len() {
5349            let line = lines[i];
5350            let trimmed = line.trim();
5351
5352            if trimmed.is_empty() || trimmed.starts_with("--") {
5353                i += 1;
5354                continue;
5355            }
5356
5357            if !current_stmt.is_empty() {
5358                current_stmt.push(' ');
5359            }
5360            current_stmt.push_str(trimmed);
5361            i += 1;
5362
5363            if trimmed.ends_with('.') {
5364                break;
5365            }
5366        }
5367
5368        if !current_stmt.is_empty() {
5369            statements.push(current_stmt);
5370        }
5371    }
5372
5373    statements
5374}
5375
5376/// Compile a Logic-mode input to runnable Rust.
5377///
5378/// A `## Theorem:` block becomes a **model-checker** for `premises ⊨ goal`; a
5379/// plain sentence becomes a model-checker for that formula — a self-contained
5380/// `Model` + `holds(&Model) -> bool` + demo `main` you can compile and run
5381/// ([`crate::extraction::fol_model`]). The finite-domain *puzzle* (Simon grid) is
5382/// the exception: it would run the full solver synchronously and freeze the page,
5383/// so it bails with a note (use Execute to solve it).
5384pub fn extract_logic_rust(input: &str) -> Result<String, String> {
5385    extract_logic_impl(input, true)
5386}
5387
5388/// Why Logic's Compile has no Rust to give for `input`, or `None` when it has one: a finite-domain
5389/// puzzle is solved by Execute, and extracting it would run the whole solver — the same test
5390/// [`extract_logic_rust`] makes before it bails.
5391pub fn logic_compile_note(input: &str) -> Option<&'static str> {
5392    match theorem_proof_exprs(input) {
5393        Ok((premises, _)) if looks_like_grid(&premises) => {
5394            Some("A finite-domain puzzle is solved by Execute \u{2014} compiling it would run the whole solver to extract it.")
5395        }
5396        _ => None,
5397    }
5398}
5399
5400/// Like [`extract_logic_rust`], but emits NO demo `main` — the linkable form bundled
5401/// into an imperative program's `mod proven` (which has its own `main`). Produces the
5402/// `World` + `holds` (+ `Monitor`) library items only.
5403pub fn extract_logic_module(input: &str) -> Result<String, String> {
5404    extract_logic_impl(input, false)
5405}
5406
5407fn extract_logic_impl(input: &str, emit_main: bool) -> Result<String, String> {
5408    use crate::extraction::fol_model::{fol_to_model_checker, fol_to_model_checker_module};
5409    let emit = |premises: &[logicaffeine_proof::ProofExpr],
5410                goal: &logicaffeine_proof::ProofExpr,
5411                english: &str,
5412                fol: &str| {
5413        if emit_main {
5414            fol_to_model_checker(premises, goal, english, fol)
5415        } else {
5416            fol_to_model_checker_module(premises, goal, english, fol)
5417        }
5418    };
5419
5420    // A `## Theorem:` block: model-check `premises ⊨ goal` — unless it is a grid
5421    // puzzle (bail before the solver runs, see above).
5422    if let Ok((premises, goal)) = theorem_proof_exprs(input) {
5423        if looks_like_grid(&premises) {
5424            return Ok("// this is a finite-domain puzzle — run it with Execute. \
5425                Compiling it to Rust would run the full solver synchronously."
5426                .to_string());
5427        }
5428        let fol = if premises.is_empty() {
5429            goal.to_string()
5430        } else {
5431            format!(
5432                "{} ⊢ {}",
5433                premises
5434                    .iter()
5435                    .map(|p| p.to_string())
5436                    .collect::<Vec<_>>()
5437                    .join(", "),
5438                goal
5439            )
5440        };
5441        return Ok(emit(&premises, &goal, input, &fol));
5442    }
5443
5444    // A plain sentence: model-check the single formula.
5445    let proof = compile_for_proof(input);
5446    if let Some(expr) = proof.proof_expr {
5447        let fol = proof
5448            .logic_string
5449            .clone()
5450            .unwrap_or_else(|| expr.to_string());
5451        return Ok(emit(&[], &expr, input, &fol));
5452    }
5453
5454    Ok("// could not parse this input into a logical formula to compile".to_string())
5455}
5456
5457/// Ask the Z3 oracle whether a theorem's premises semantically entail its goal.
5458///
5459/// Same `## Theorem:` block format as [`verify_theorem`], but the answer is an
5460/// [`SmtVerdict`](logicaffeine_proof::oracle::SmtVerdict) over the standard
5461/// translation (modal frame axioms, similarity relations, lattice axioms) —
5462/// **not** a kernel-certified proof. Use this for entailment questions the
5463/// monotonic kernel cannot express (modality, counterfactuals, mereology).
5464/// Assemble the lexicon-derived [`SmtTheory`](logicaffeine_proof::oracle::SmtTheory)
5465/// for a theorem: every mentioned predicate the lexicon tags as a MASS noun
5466/// becomes a cumulative (Link-lattice) predicate.
5467#[cfg(feature = "verification")]
5468fn smt_theory_for(
5469    premises: &[ProofExpr],
5470    goal: Option<&ProofExpr>,
5471) -> logicaffeine_proof::oracle::SmtTheory {
5472    let mut exprs: Vec<ProofExpr> = premises.to_vec();
5473    if let Some(g) = goal {
5474        exprs.push(g.clone());
5475    }
5476    let cumulative_predicates = logicaffeine_proof::oracle::predicate_names(&exprs)
5477        .into_iter()
5478        .filter(|name| logicaffeine_language::lexicon::is_mass_noun(name))
5479        .collect();
5480    logicaffeine_proof::oracle::SmtTheory {
5481        cumulative_predicates,
5482    }
5483}
5484
5485#[cfg(feature = "verification")]
5486pub fn check_theorem_smt(
5487    input: &str,
5488) -> Result<logicaffeine_proof::oracle::SmtVerdict, ParseError> {
5489    let (proof_exprs, goal_expr) = theorem_proof_exprs(input)?;
5490    let theory = smt_theory_for(&proof_exprs, Some(&goal_expr));
5491    Ok(logicaffeine_proof::oracle::oracle_entails_with_theory(
5492        &proof_exprs,
5493        &goal_expr,
5494        &theory,
5495    ))
5496}
5497
5498/// Ask the Z3 oracle whether a theorem's premises are jointly satisfiable
5499/// (the goal is parsed but ignored).
5500///
5501/// Every non-entailment claim in the test suite pairs with this check so an
5502/// inconsistent premise set cannot fake a `NotEntailed` via vacuity.
5503#[cfg(feature = "verification")]
5504pub fn check_theorem_premises_consistent(
5505    input: &str,
5506) -> Result<logicaffeine_proof::oracle::SmtConsistency, ParseError> {
5507    let (proof_exprs, _goal) = theorem_proof_exprs(input)?;
5508    let theory = smt_theory_for(&proof_exprs, None);
5509    Ok(logicaffeine_proof::oracle::oracle_consistent_with_theory(
5510        &proof_exprs,
5511        &theory,
5512    ))
5513}
5514
5515/// Ask the defeasible (non-monotonic) layer whether a theorem's premises
5516/// defeasibly entail its goal: generics and implicatures license cancellable
5517/// inferences via circumscription over per-rule abnormality predicates.
5518///
5519/// The verdict is **not kernel-certified** and is strictly weaker than
5520/// classical entailment — a defeated default reads as `NotEntailed` while the
5521/// premise set stays [`SmtConsistency::Consistent`].
5522#[cfg(feature = "verification")]
5523pub fn check_theorem_defeasible(
5524    input: &str,
5525) -> Result<logicaffeine_proof::oracle::SmtVerdict, ParseError> {
5526    let (proof_exprs, goal, defaults, _definitions, _declared) = theorem_problem(input, true)?;
5527    let theory = smt_theory_for(&proof_exprs, Some(&goal));
5528    Ok(crate::defeasible::defeasible_entails(
5529        &proof_exprs,
5530        &goal,
5531        &defaults,
5532        &theory,
5533    ))
5534}
5535
5536/// Consistency under the defeasible layer: defaults defeated by exceptions
5537/// must NOT read as contradictions.
5538#[cfg(feature = "verification")]
5539pub fn check_theorem_defeasible_consistent(
5540    input: &str,
5541) -> Result<logicaffeine_proof::oracle::SmtConsistency, ParseError> {
5542    let (proof_exprs, _goal, defaults, _definitions, _declared) = theorem_problem(input, true)?;
5543    let theory = smt_theory_for(&proof_exprs, None);
5544    Ok(crate::defeasible::defeasible_consistent(
5545        &proof_exprs,
5546        &defaults,
5547        &theory,
5548    ))
5549}
5550
5551/// Parse a `## Theorem:` block and convert its premises and goal to
5552/// [`ProofExpr`]s — the shared front half of [`verify_theorem`] and
5553/// `check_theorem_smt`.
5554/// Parse a `## Theorem` document and convert its premises and goal to
5555/// [`ProofExpr`]. Public so a puzzle solver can obtain the parsed-FOL premises
5556/// (the Given clues/declarations) and feed them to the entailment oracle.
5557pub fn theorem_proof_exprs(input: &str) -> Result<(Vec<ProofExpr>, ProofExpr), ParseError> {
5558    let (premises, goal, _defaults, _definitions, _declared) = theorem_problem(input, false)?;
5559    Ok((premises, goal))
5560}
5561
5562/// Like [`theorem_proof_exprs`] but also returns the document's `## Define`
5563/// blocks (Rung 0a) lowered to proof-layer definitions, so the prover can
5564/// δ-unfold them. This is the entry the kernel-certified theorem path uses.
5565pub fn theorem_proof_exprs_with_defs(
5566    input: &str,
5567) -> Result<
5568    (
5569        Vec<ProofExpr>,
5570        ProofExpr,
5571        Vec<logicaffeine_proof::verify::Definition>,
5572    ),
5573    ParseError,
5574> {
5575    let (premises, goal, _defaults, definitions, _declared) = theorem_problem(input, false)?;
5576    Ok((premises, goal, definitions))
5577}
5578
5579/// [`theorem_proof_exprs_with_defs`] plus the `Proof:` line the block DECLARED — the entry
5580/// every kernel-certified Surface A door uses, so none of them can prove a theorem by a
5581/// method its author did not write (see [`prove_declared`]).
5582fn theorem_problem_declared(
5583    input: &str,
5584) -> Result<
5585    (
5586        Vec<ProofExpr>,
5587        ProofExpr,
5588        Vec<logicaffeine_proof::verify::Definition>,
5589        DeclaredProof,
5590    ),
5591    ParseError,
5592> {
5593    let (premises, goal, _defaults, definitions, declared) = theorem_problem(input, false)?;
5594    Ok((premises, goal, definitions, declared))
5595}
5596
5597/// The `uses` dependency graph (Rung 0b) for an English document: its `## Define`
5598/// blocks plus the theorem's premises and goal, lowered and analyzed. Each node
5599/// is a definition or the theorem; each edge is a `uses`. This is the structure
5600/// a `mathscrapes` node/edge compiles into.
5601pub fn theorem_dependency_graph(
5602    input: &str,
5603) -> Result<logicaffeine_proof::verify::DependencyGraph, ParseError> {
5604    let (premises, goal, definitions) = theorem_proof_exprs_with_defs(input)?;
5605    Ok(logicaffeine_proof::verify::dependency_graph(
5606        &definitions,
5607        &premises,
5608        &goal,
5609    ))
5610}
5611
5612/// ANSWER a wh-question theorem ("Given: … Prove: Who is a lawyer?"). A wh-goal
5613/// converts to ∃x.φ(x); the ANSWER is the witness. We find it the same way the
5614/// puzzle is meant to be solved — by the GENERAL kernel-certified prover, applied
5615/// per candidate: enumerate the domain individuals named in the premises and prove
5616/// each candidate goal φ(c); the c's that prove are the answer (usually one, for a
5617/// puzzle with a unique solution). No question-specific reasoning — every step is
5618/// the same `prove_certify_check` that proves Socrates.
5619pub fn answer_question(input: &str) -> Result<Vec<String>, ParseError> {
5620    let (premises, goal) = theorem_proof_exprs(input)?;
5621    match &goal {
5622        ProofExpr::Exists { variable, body } => Ok(answer_wh(&premises, variable, body)),
5623        _ => Err(ParseError {
5624            kind: logicaffeine_language::error::ParseErrorKind::Custom(
5625                "Prove goal is not a question (expected a wh-question ∃-form)".to_string(),
5626            ),
5627            span: logicaffeine_language::token::Span::default(),
5628        }),
5629    }
5630}
5631
5632/// The witnesses of a wh-question `∃var. body(var)`: enumerate the domain individuals
5633/// named in the premises and keep those `c` for which `body(c)` is entailed by the
5634/// certified no-Z3 path. Shared by [`answer_question`] and the studio entry
5635/// [`compile_theorem_for_ui`], so a wh-goal never reaches the closed-goal search.
5636fn answer_wh(premises: &[ProofExpr], var: &str, body: &ProofExpr) -> Vec<String> {
5637    let mut candidates: Vec<String> = Vec::new();
5638    for p in premises {
5639        collect_constants(p, &mut candidates);
5640    }
5641    candidates.sort();
5642    candidates.dedup();
5643    // Prepare the premise set ONCE (tense-erase + finite-domain grounding) — it is
5644    // identical for every candidate cell, so doing it per candidate would re-ground the
5645    // whole grid N times. This is the optimization that keeps bigger puzzles tractable.
5646    let trace = std::env::var("LOGOS_TRACE").is_ok();
5647    let t0 = trace.then(std::time::Instant::now);
5648    let prepared = prepare_premises(premises);
5649    if let Some(t0) = t0 {
5650        eprintln!(
5651            "[answer] {} premises → prepared ({} clauses) in {:.2?}; {} candidates",
5652            premises.len(),
5653            prepared.len(),
5654            t0.elapsed(),
5655            candidates.len()
5656        );
5657    }
5658    let mut answers = Vec::new();
5659    for c in &candidates {
5660        let tc = trace.then(std::time::Instant::now);
5661        let candidate_goal =
5662            logicaffeine_language::proof_convert::instantiate_var_with_constant(body, var, c);
5663        let ok = candidate_entailed_prepared(&prepared, &candidate_goal);
5664        if let Some(tc) = tc {
5665            eprintln!("[answer]   {:<14} {} ({:.2?})", c, ok, tc.elapsed());
5666        }
5667        if ok {
5668            answers.push(c.clone());
5669        }
5670    }
5671    if let Some(t0) = t0 {
5672        eprintln!("[answer] total {:.2?} → {:?}", t0.elapsed(), answers);
5673    }
5674    answers
5675}
5676
5677/// SOLVE the whole grid for the studio (the form-recognized easter egg): re-parse the
5678/// theorem and, if it is a finite-domain grid, fill every cell the certified prover can
5679/// force. `None` for a non-grid theorem.
5680pub fn solve_grid(input: &str) -> Option<SolvedGrid> {
5681    let parsed = parse_theorem(input).ok()?;
5682    if !looks_like_grid(&parsed.premises) {
5683        return None;
5684    }
5685    solve_grid_from_premises(&parsed.premises, input)
5686}
5687
5688/// One category closure `∀x(RowSort(x) → d₁ ∨ … ∨ dₙ)`: the bound variable, its row
5689/// sort, and each disjunct paired with the value it contributes.
5690struct GridClosure {
5691    var: String,
5692    row_sort: String,
5693    disjuncts: Vec<(String, ProofExpr)>,
5694}
5695
5696/// Split a (possibly nested) disjunction into its leaf disjuncts.
5697fn flatten_or<'a>(e: &'a ProofExpr, out: &mut Vec<&'a ProofExpr>) {
5698    match e {
5699        ProofExpr::Or(l, r) => {
5700            flatten_or(l, out);
5701            flatten_or(r, out);
5702        }
5703        other => out.push(other),
5704    }
5705}
5706
5707/// The unary SORT predicate guarding `var` (`Trip(x)` → "trip"), if the antecedent is
5708/// one — possibly under conjunction.
5709fn antecedent_sort(e: &ProofExpr, var: &str) -> Option<String> {
5710    let is_var =
5711        |t: &ProofTerm| matches!(t, ProofTerm::Variable(v) | ProofTerm::BoundVarRef(v) if v == var);
5712    match e {
5713        ProofExpr::Predicate { name, args, .. } if args.len() == 1 && is_var(&args[0]) => {
5714            Some(name.clone())
5715        }
5716        ProofExpr::And(l, r) => antecedent_sort(l, var).or_else(|| antecedent_sort(r, var)),
5717        _ => None,
5718    }
5719}
5720
5721/// The value a disjunct contributes for `var`: the constant argument of a binary relation
5722/// (`in(x, Florida)` → "Florida") or the predicate name of a unary one (`cycling(x)` →
5723/// "cycling"). `None` if the disjunct is not a simple predicate over `var`.
5724fn disjunct_value(d: &ProofExpr, var: &str) -> Option<String> {
5725    let is_var =
5726        |t: &ProofTerm| matches!(t, ProofTerm::Variable(v) | ProofTerm::BoundVarRef(v) if v == var);
5727    match d {
5728        ProofExpr::Predicate { name, args, .. } => match args.as_slice() {
5729            [a] if is_var(a) => Some(name.clone()),
5730            [a, ProofTerm::Constant(c)] if is_var(a) => Some(c.clone()),
5731            [ProofTerm::Constant(c), a] if is_var(a) => Some(c.clone()),
5732            _ => None,
5733        },
5734        _ => None,
5735    }
5736}
5737
5738/// Extract one [`GridClosure`] per disjunctive-closure premise (`∀x(Trip(x) → A ∨ B ∨
5739/// …)`). These closures ARE the grid's columns — the antecedent names the rows, the
5740/// disjuncts name the cells.
5741fn extract_grid_closures(premises: &[ProofExpr]) -> Vec<GridClosure> {
5742    fn from_forall(e: &ProofExpr, out: &mut Vec<GridClosure>) {
5743        if let ProofExpr::ForAll { variable, body } = e {
5744            match body.as_ref() {
5745                ProofExpr::Implies(ante, cons) => {
5746                    let mut leaves = Vec::new();
5747                    flatten_or(cons, &mut leaves);
5748                    let disjuncts: Vec<(String, ProofExpr)> = leaves
5749                        .iter()
5750                        .filter_map(|d| disjunct_value(d, variable).map(|v| (v, (*d).clone())))
5751                        .collect();
5752                    if let Some(row_sort) = antecedent_sort(ante, variable) {
5753                        // Only a closure whose every disjunct is a clean predicate over the
5754                        // row var defines a column (guards against a stray non-grid ∀).
5755                        if !disjuncts.is_empty() && disjuncts.len() == leaves.len() {
5756                            out.push(GridClosure {
5757                                var: variable.clone(),
5758                                row_sort,
5759                                disjuncts,
5760                            });
5761                        }
5762                    }
5763                }
5764                ProofExpr::ForAll { .. } => from_forall(body, out),
5765                _ => {}
5766            }
5767        }
5768    }
5769    let mut out = Vec::new();
5770    for p in premises {
5771        from_forall(&erase_tense(p), &mut out);
5772    }
5773    out
5774}
5775
5776/// Title-case a lowercased sort name for a column/row header ("trip" → "Trip").
5777fn title_case(s: &str) -> String {
5778    let mut chars = s.chars();
5779    match chars.next() {
5780        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
5781        None => String::new(),
5782    }
5783}
5784
5785/// A human header for a category column: the declared sort whose domain covers the
5786/// column's values (case-insensitive), else a positional fallback.
5787fn grid_column_label(
5788    values: &[String],
5789    sorts: &std::collections::HashMap<String, Vec<ProofTerm>>,
5790    idx: usize,
5791) -> String {
5792    let want: Vec<String> = values.iter().map(|v| v.to_lowercase()).collect();
5793    let mut keys: Vec<&String> = sorts.keys().collect();
5794    keys.sort();
5795    for k in keys {
5796        let dom: std::collections::HashSet<String> = sorts[k]
5797            .iter()
5798            .filter_map(|t| match t {
5799                ProofTerm::Constant(c) => Some(c.to_lowercase()),
5800                _ => None,
5801            })
5802            .collect();
5803        if !dom.is_empty() && want.iter().all(|v| dom.contains(v)) {
5804            return title_case(k);
5805        }
5806    }
5807    format!("Category {}", idx + 1)
5808}
5809
5810/// A coarse stem that bridges a gerund surface form and the base form it normalizes to
5811/// (`"Cycling"` and `"Cycle"` → `"cycl"`), so a grid value can be matched back to the word
5812/// the user actually wrote. Strips a trailing `-ing` then a trailing `-e`; leaves
5813/// already-base words (constants, years, names) effectively unchanged.
5814fn category_stem(s: &str) -> String {
5815    let mut w = s.to_lowercase();
5816    if w.len() > 5 && w.ends_with("ing") {
5817        w.truncate(w.len() - 3);
5818    }
5819    if w.len() > 3 && w.ends_with('e') {
5820        w.truncate(w.len() - 1);
5821    }
5822    w
5823}
5824
5825/// Map each grid value back to the SURFACE word the user wrote. Category values
5826/// normalize to a base form in the FOL (a relation's constant like `Florida` survives, but
5827/// a gerund activity becomes `Cycle`); the original word ("cycling") lives only in the
5828/// input text. Key the input words by stem and recover them. First occurrence wins, so the
5829/// declaration's spelling is preferred.
5830fn surface_form_map(input: &str) -> std::collections::HashMap<String, String> {
5831    let mut map = std::collections::HashMap::new();
5832    for word in input.split(|c: char| !c.is_alphanumeric()) {
5833        if !word.is_empty() {
5834            map.entry(category_stem(word))
5835                .or_insert_with(|| word.to_string());
5836        }
5837    }
5838    map
5839}
5840
5841/// Fill the grid from already-parsed premises: rows are the row sort's domain, columns
5842/// are the disjunctive closures, and each cell is the disjunct value the certified no-Z3
5843/// prover entails for that row (or `None` if undetermined). Same engine `answer_question`
5844/// uses per cell, swept across the whole table.
5845fn solve_grid_from_premises(premises: &[ProofExpr], input: &str) -> Option<SolvedGrid> {
5846    let closures = extract_grid_closures(premises);
5847    if closures.is_empty() {
5848        return None;
5849    }
5850    let untensed: Vec<ProofExpr> = premises.iter().map(erase_tense).collect();
5851    let sorts = logicaffeine_proof::grounding::sort_domains(&untensed);
5852    let row_sort = closures[0].row_sort.clone();
5853    let rows: Vec<String> = sorts
5854        .get(&row_sort)
5855        .map(|dom| {
5856            dom.iter()
5857                .filter_map(|t| match t {
5858                    ProofTerm::Constant(c) => Some(c.clone()),
5859                    _ => None,
5860                })
5861                .collect()
5862        })
5863        .unwrap_or_default();
5864    if rows.is_empty() {
5865        return None;
5866    }
5867    // Ground ONCE, with functionality, exactly as the fast certified grid path does — the
5868    // exclusion lemmas let RUP decide each non-entailed candidate in ~1ms.
5869    let prepared = prepare_premises_opts(premises, true);
5870    let surface = surface_form_map(input);
5871    let display = |v: &str| {
5872        surface
5873            .get(&category_stem(v))
5874            .cloned()
5875            .unwrap_or_else(|| v.to_string())
5876    };
5877    let mut columns = Vec::new();
5878    for clo in &closures {
5879        if clo.row_sort != row_sort {
5880            continue;
5881        }
5882        let values: Vec<String> = clo.disjuncts.iter().map(|(v, _)| display(v)).collect();
5883        let mut cells = Vec::with_capacity(rows.len());
5884        for r in &rows {
5885            let mut found = None;
5886            for (label, dj) in &clo.disjuncts {
5887                let atom = erase_tense(
5888                    &logicaffeine_language::proof_convert::instantiate_var_with_constant(
5889                        dj, &clo.var, r,
5890                    ),
5891                );
5892                if candidate_entailed_prepared(&prepared, &atom) {
5893                    found = Some(display(label));
5894                    break;
5895                }
5896            }
5897            cells.push(found);
5898        }
5899        let label = grid_column_label(&values, &sorts, columns.len());
5900        columns.push(GridColumn {
5901            label,
5902            values,
5903            cells,
5904        });
5905    }
5906    Some(SolvedGrid {
5907        row_label: title_case(&row_sort),
5908        rows,
5909        columns,
5910    })
5911}
5912
5913/// Prepare the premise set for the per-candidate solve, ONCE.
5914///
5915/// A logic grid is FINITE and STATIC, so we (1) ERASE TENSE — a grid is one static
5916/// scenario; the past-tense clue wrappers ("one WAS in Connecticut") carry no
5917/// information — and (2) GROUND the finite domain SORT-AWARE: each guarded quantifier
5918/// expands over its sort's declared domain (∀x(Trip(x)→…) over the four trips, not the
5919/// whole universe). The result is quantifier-free (decidable — neither our kernel nor
5920/// Z3 can instantiate ∀/∃ forever) and identical for every cell, so the per-cell
5921/// entailment check below sees a finite, decidable problem.
5922///
5923/// This is GENERAL over any declared finite-domain grid: the domains come from the
5924/// English declarations the parser produced (`sort_domains`), never from puzzle
5925/// knowledge. Grounding the KERNEL path (not just the Z3 path) is what lets the
5926/// certified prover close a full multi-category grid in the browser.
5927/// Does this premise set describe a finite-domain GRID — a declared bijection with a
5928/// closure (`∀x(Sort(x) → A ∨ B ∨ …)`) or an "exactly one" — as opposed to an open
5929/// syllogism? Only grids are grounded before proving (so Socrates keeps its
5930/// `UniversalInst` trace). Structural, never keyed to a particular puzzle.
5931fn looks_like_grid(premises: &[ProofExpr]) -> bool {
5932    fn has_disjunctive_closure(e: &ProofExpr) -> bool {
5933        match e {
5934            ProofExpr::ForAll { body, .. } => match body.as_ref() {
5935                ProofExpr::Implies(_, c) => matches!(c.as_ref(), ProofExpr::Or(..)),
5936                ProofExpr::ForAll { .. } => has_disjunctive_closure(body),
5937                _ => false,
5938            },
5939            ProofExpr::Temporal { body, .. } => has_disjunctive_closure(body),
5940            _ => false,
5941        }
5942    }
5943    !logicaffeine_proof::grounding::at_most_one_lemmas(premises).is_empty()
5944        || premises.iter().any(has_disjunctive_closure)
5945}
5946
5947fn prepare_premises(premises: &[ProofExpr]) -> Vec<ProofExpr> {
5948    prepare_premises_opts(premises, false)
5949}
5950
5951/// `prepare_premises`, optionally adding the bijection's FUNCTIONALITY half
5952/// (`∀x(Li → ¬Lj)`: a row takes at most one value per category). Functionality is
5953/// given ONLY to the incremental grid solver — it propagates the exclusions cheaply —
5954/// never to the re-saturating backward chainer, which it would slow to a crawl.
5955fn prepare_premises_opts(premises: &[ProofExpr], with_functionality: bool) -> Vec<ProofExpr> {
5956    let mut untensed: Vec<ProofExpr> = premises.iter().map(erase_tense).collect();
5957    // "Exactly one φ" ⟹ pairwise "at most one φ": the existence form grounds to a
5958    // disjunction the certified kernel cannot use directly; its entailed pairwise
5959    // uniqueness grounds to the conjunctive exclusion rules unit propagation runs on.
5960    let lemmas = logicaffeine_proof::grounding::at_most_one_lemmas(&untensed);
5961    untensed.extend(lemmas);
5962    // Definite-description clues ("the Florida trip is the hunting trip", "the trip with
5963    // Yvonne wasn't in Kentucky") name a unique row by a singleton value; rewrite them
5964    // to row-indexed implications the solver propagates, instead of an existential whose
5965    // grounding explodes to a row-disjunction.
5966    let defns = logicaffeine_proof::grounding::definite_property_implications(&untensed);
5967    untensed.extend(defns);
5968    if with_functionality {
5969        let func = logicaffeine_proof::grounding::functionality_lemmas(&untensed);
5970        untensed.extend(func);
5971        // HIDDEN SINGLE: the column closures (`⋁_r In(r, v)`) — the existence half of each
5972        // "exactly one" that `compile` otherwise drops. With functionality they let the
5973        // solver force a value's last remaining row, deepening the ROOT fixpoint so more
5974        // cells take the linear prove_var exit instead of search.
5975        let cols = logicaffeine_proof::grounding::column_closure_lemmas(&untensed);
5976        untensed.extend(cols);
5977    }
5978    let fallback = logicaffeine_proof::grounding::domain_constants(&untensed);
5979    let mut sorts = logicaffeine_proof::grounding::sort_domains(&untensed);
5980    bind_occasion_synonyms_to_row_domain(&untensed, &mut sorts);
5981    let grounded: Vec<ProofExpr> = untensed
5982        .iter()
5983        .map(|p| logicaffeine_proof::grounding::ground_sorted(p, &sorts, &fallback))
5984        .collect();
5985    // Discharge the now-true sort facts (`Trip(Alpha)`, …) so propagation runs on pure
5986    // value-literals: a closure becomes a bare disjunction, an at-most-one a one-step
5987    // exclusion rule. This is what keeps the full-grid search tractable.
5988    let discharged = logicaffeine_proof::grounding::discharge_unary_facts(&grounded);
5989    // Fold trivial reflexive identities: a grounded `∃x∃y` of-pair's diagonal
5990    // (`x = y = c`) carries `¬(c = c) = False`, so that disjunct drops.
5991    logicaffeine_proof::grounding::simplify_trivial_identities(&discharged)
5992}
5993
5994/// Does the premise set entail the candidate answer goal?
5995///
5996/// Without `verification`: the KERNEL-CERTIFIED prover over the GROUNDED, tense-erased
5997/// grid. Grounding made the problem quantifier-free, so the kernel's case-split +
5998/// reductio strategies close each cell with a real proof term — no Z3, runs in WASM.
5999/// The bounded depth makes an unentailed cell fail fast rather than search to the hilt.
6000#[cfg(not(feature = "verification"))]
6001fn candidate_entailed_prepared(prepared: &[ProofExpr], goal: &ProofExpr) -> bool {
6002    let g = erase_tense(goal);
6003    // FAST certified tier first: the CDCL+RUP engine decides the grounded grid in ~1ms with
6004    // an independently-checked proof (and answers a NON-entailed candidate just as fast,
6005    // where the kernel path degenerates to a deep futile search). Fall back to the bounded
6006    // kernel chainer only when the problem isn't purely propositional (RUP returns `None`).
6007    match logicaffeine_proof::rup::entails_certified(prepared, &g) {
6008        Some(logicaffeine_proof::rup::Verdict::Entailed) => return true,
6009        Some(logicaffeine_proof::rup::Verdict::NotEntailed) => return false,
6010        None => {}
6011    }
6012    logicaffeine_proof::verify::prove_certify_check_bounded(prepared, &g, 100).verified
6013}
6014
6015/// OCCASION soft-typing for the finite-domain solve.
6016///
6017/// In a logic grid the row entity is described by several OCCASION-sort head nouns
6018/// — "the hunting VACATION", "the Florida TRIP", "the 2004 HOLIDAY" — where the
6019/// modifier does the referring and the head is a soft type ([`Sort::is_occasion`],
6020/// the same principle [`drs::DiscourseModel::resolve_definite_by_modifier`] uses for
6021/// coreference). Only ONE of these head nouns is declared with a domain
6022/// (`Trip(Alpha)…`); the synonyms carry no domain, so an occasion guard like
6023/// `Vacation(x)` would ground over the WHOLE universe and a phantom non-row constant
6024/// (`Florida`, `2003`, …) could satisfy a synonym-headed clue. Point every
6025/// occasion-sorted guard at the shared row domain (the union of the declared
6026/// occasion-sort domains).
6027///
6028/// This is NOT global synonymy — no `Vacation ↔ Trip` axiom is asserted and "a work
6029/// trip" never collapses; the binding fires only for occasion-SORTED head predicates
6030/// inside the grounded solve, leaving ordinary parsing untouched.
6031fn bind_occasion_synonyms_to_row_domain(
6032    premises: &[ProofExpr],
6033    sorts: &mut std::collections::HashMap<String, Vec<logicaffeine_proof::ProofTerm>>,
6034) {
6035    use logicaffeine_language::lexicon::lookup_sort;
6036    use logicaffeine_proof::ProofTerm;
6037    let is_occasion = |n: &str| lookup_sort(n).map_or(false, |s| s.is_occasion());
6038
6039    // The shared row domain: the union of every declared occasion-sort domain. In a
6040    // grid there is one row sort with a domain (`Trip`); its synonyms have none.
6041    let mut row_domain: Vec<ProofTerm> = Vec::new();
6042    for (name, dom) in sorts.iter() {
6043        if is_occasion(name) {
6044            for c in dom {
6045                if !row_domain.contains(c) {
6046                    row_domain.push(c.clone());
6047                }
6048            }
6049        }
6050    }
6051    if row_domain.is_empty() {
6052        return;
6053    }
6054
6055    // Every occasion-sorted guard that appears in the premises but lacks its own
6056    // declared domain inherits the row domain.
6057    let mut names = HashSet::new();
6058    for p in premises {
6059        collect_unary_predicate_names(p, &mut names);
6060    }
6061    for name in names {
6062        if is_occasion(&name) {
6063            sorts.entry(name).or_insert_with(|| row_domain.clone());
6064        }
6065    }
6066}
6067
6068/// Collect every UNARY predicate name appearing anywhere in `e` — the candidate sort
6069/// guards the occasion-binding inspects.
6070fn collect_unary_predicate_names(e: &ProofExpr, out: &mut HashSet<String>) {
6071    match e {
6072        ProofExpr::Predicate { name, args, .. } if args.len() == 1 => {
6073            out.insert(name.clone());
6074        }
6075        ProofExpr::And(l, r)
6076        | ProofExpr::Or(l, r)
6077        | ProofExpr::Implies(l, r)
6078        | ProofExpr::Iff(l, r) => {
6079            collect_unary_predicate_names(l, out);
6080            collect_unary_predicate_names(r, out);
6081        }
6082        ProofExpr::Counterfactual {
6083            antecedent,
6084            consequent,
6085        } => {
6086            collect_unary_predicate_names(antecedent, out);
6087            collect_unary_predicate_names(consequent, out);
6088        }
6089        ProofExpr::Not(x)
6090        | ProofExpr::ForAll { body: x, .. }
6091        | ProofExpr::Exists { body: x, .. }
6092        | ProofExpr::Temporal { body: x, .. }
6093        | ProofExpr::Modal { body: x, .. } => collect_unary_predicate_names(x, out),
6094        _ => {}
6095    }
6096}
6097
6098#[cfg(feature = "verification")]
6099fn candidate_entailed_prepared(prepared: &[ProofExpr], goal: &ProofExpr) -> bool {
6100    // The candidate goal is a ground predicate (no quantifiers) — just erase tense.
6101    let g = erase_tense(goal);
6102    // FAST certified tier first: the CDCL+RUP engine decides the grounded grid in ~1ms with
6103    // an independently-checked proof. Only if it can't encode the problem do we fall back to
6104    // the bounded kernel chainer, then Z3.
6105    match logicaffeine_proof::rup::entails_certified(prepared, &g) {
6106        Some(logicaffeine_proof::rup::Verdict::Entailed) => return true,
6107        Some(logicaffeine_proof::rup::Verdict::NotEntailed) => return false,
6108        None => {}
6109    }
6110    if logicaffeine_proof::verify::prove_certify_check_bounded(prepared, &g, 40).verified {
6111        return true;
6112    }
6113    matches!(
6114        logicaffeine_proof::oracle::oracle_entails(prepared, &g),
6115        logicaffeine_proof::oracle::SmtVerdict::Entailed
6116    )
6117}
6118
6119/// Strip `Temporal` wrappers throughout a [`ProofExpr`] — a logic grid is one
6120/// static scenario, so tense carries no information and would otherwise block the
6121/// oracle from forcing values across past-tense clues.
6122fn erase_tense(e: &ProofExpr) -> ProofExpr {
6123    match e {
6124        ProofExpr::Temporal { body, .. } => erase_tense(body),
6125        ProofExpr::And(l, r) => ProofExpr::And(Box::new(erase_tense(l)), Box::new(erase_tense(r))),
6126        ProofExpr::Or(l, r) => ProofExpr::Or(Box::new(erase_tense(l)), Box::new(erase_tense(r))),
6127        ProofExpr::Implies(l, r) => {
6128            ProofExpr::Implies(Box::new(erase_tense(l)), Box::new(erase_tense(r)))
6129        }
6130        ProofExpr::Iff(l, r) => ProofExpr::Iff(Box::new(erase_tense(l)), Box::new(erase_tense(r))),
6131        ProofExpr::Not(x) => ProofExpr::Not(Box::new(erase_tense(x))),
6132        ProofExpr::ForAll { variable, body } => ProofExpr::ForAll {
6133            variable: variable.clone(),
6134            body: Box::new(erase_tense(body)),
6135        },
6136        ProofExpr::Exists { variable, body } => ProofExpr::Exists {
6137            variable: variable.clone(),
6138            body: Box::new(erase_tense(body)),
6139        },
6140        other => other.clone(),
6141    }
6142}
6143
6144fn collect_constants(e: &ProofExpr, out: &mut Vec<String>) {
6145    use logicaffeine_proof::ProofTerm;
6146    fn term(t: &ProofTerm, out: &mut Vec<String>) {
6147        match t {
6148            ProofTerm::Constant(s) => out.push(s.clone()),
6149            ProofTerm::Function(_, args) | ProofTerm::Group(args) => {
6150                args.iter().for_each(|a| term(a, out))
6151            }
6152            _ => {}
6153        }
6154    }
6155    match e {
6156        ProofExpr::Predicate { args, .. } => args.iter().for_each(|a| term(a, out)),
6157        ProofExpr::Identity(a, b) => {
6158            term(a, out);
6159            term(b, out);
6160        }
6161        ProofExpr::And(l, r)
6162        | ProofExpr::Or(l, r)
6163        | ProofExpr::Implies(l, r)
6164        | ProofExpr::Iff(l, r) => {
6165            collect_constants(l, out);
6166            collect_constants(r, out);
6167        }
6168        ProofExpr::Not(x) => collect_constants(x, out),
6169        ProofExpr::ForAll { body, .. }
6170        | ProofExpr::Exists { body, .. }
6171        | ProofExpr::Temporal { body, .. } => collect_constants(body, out),
6172        ProofExpr::Term(t) => term(t, out),
6173        _ => {}
6174    }
6175}
6176
6177/// Lower a `## Define` block (Rung 0a) to a proof-layer definition: the LHS
6178/// predicate supplies the (normalized) definiendum name and parameter symbols,
6179/// the RHS is the definiens. Both sides pass through the SAME
6180/// `logic_expr_to_proof_expr` + interner as theorem premises and goals, so the
6181/// definiendum name and parameters match the predicate occurrences the prover
6182/// sees. Returns `None` if the LHS is not a predicate application.
6183fn lower_definition(
6184    def: &logicaffeine_language::ast::DefinitionBlock,
6185    interner: &Interner,
6186) -> Option<logicaffeine_proof::verify::Definition> {
6187    use logicaffeine_language::proof_convert::logic_expr_to_proof_expr;
6188    let (name, params) = match logic_expr_to_proof_expr(def.definiendum, interner) {
6189        ProofExpr::Predicate { name, args, .. } => {
6190            let params = args
6191                .iter()
6192                .filter_map(|t| match t {
6193                    ProofTerm::Constant(n) | ProofTerm::Variable(n) => Some(n.clone()),
6194                    _ => None,
6195                })
6196                .collect();
6197            (name, params)
6198        }
6199        _ => return None,
6200    };
6201    let definiens = logic_expr_to_proof_expr(def.definiens, interner);
6202    Some(logicaffeine_proof::verify::Definition {
6203        name,
6204        params,
6205        definiens,
6206    })
6207}
6208
6209/// [`theorem_proof_exprs`] with optional DEFEASIBLE conversion: premises keep
6210/// their generics/implicatures as abnormality-guarded defaults (returned for
6211/// the circumscription pass); the goal always converts strictly. Also returns
6212/// the document's `## Define` blocks lowered to proof-layer definitions (Rung 0a).
6213fn theorem_problem(
6214    input: &str,
6215    defeasible: bool,
6216) -> Result<
6217    (
6218        Vec<ProofExpr>,
6219        ProofExpr,
6220        Vec<logicaffeine_language::proof_convert::DefaultRule>,
6221        Vec<logicaffeine_proof::verify::Definition>,
6222        DeclaredProof,
6223    ),
6224    ParseError,
6225> {
6226    // === STEP 1: Parse ===
6227    let mut interner = Interner::new();
6228    let mut lexer = Lexer::new(input, &mut interner);
6229    let tokens = lexer.tokenize();
6230
6231    let mwe_trie = mwe::build_mwe_trie();
6232    let tokens = mwe::apply_mwe_pipeline(tokens, &mwe_trie, &mut interner);
6233
6234    let type_registry = {
6235        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
6236        discovery.run()
6237    };
6238
6239    let expr_arena = Arena::new();
6240    let term_arena = Arena::new();
6241    let np_arena = Arena::new();
6242    let sym_arena = Arena::new();
6243    let role_arena = Arena::new();
6244    let pp_arena = Arena::new();
6245
6246    let ctx = AstContext::new(
6247        &expr_arena,
6248        &term_arena,
6249        &np_arena,
6250        &sym_arena,
6251        &role_arena,
6252        &pp_arena,
6253    );
6254
6255    let mut world_state = drs::WorldState::new();
6256    let mut parser = Parser::new(tokens, &mut world_state, &mut interner, ctx, type_registry);
6257    if defeasible {
6258        // The defeasible layer reasons over the pragmatic channel too:
6259        // scalar implicatures become guarded defaults.
6260        parser.set_pragmatic_mode(true);
6261    }
6262    let statements = parser.parse_program()?;
6263
6264    let theorem = statements
6265        .iter()
6266        .find_map(|stmt| {
6267            if let Stmt::Theorem(t) = stmt {
6268                Some(t)
6269            } else {
6270                None
6271            }
6272        })
6273        .ok_or_else(|| ParseError {
6274            kind: logicaffeine_language::error::ParseErrorKind::Custom(
6275                "No theorem block found in input".to_string(),
6276            ),
6277            span: logicaffeine_language::token::Span::default(),
6278        })?;
6279
6280    // === STEP 2: Convert premises and goal to ProofExpr ===
6281    let mut defaults = Vec::new();
6282    let proof_exprs: Vec<ProofExpr> = theorem
6283        .premises
6284        .iter()
6285        .map(|premise| {
6286            if defeasible {
6287                logicaffeine_language::proof_convert::logic_expr_to_proof_expr_defeasible(
6288                    premise,
6289                    &interner,
6290                    &mut defaults,
6291                )
6292            } else {
6293                logic_expr_to_proof_expr(premise, &interner)
6294            }
6295        })
6296        .collect();
6297    let goal_expr = logic_expr_to_proof_expr(theorem.goal, &interner);
6298
6299    // Rung 0a: collect every `## Define` block in the document, lowered to a
6300    // proof-layer definition the prover can δ-unfold.
6301    let definitions: Vec<logicaffeine_proof::verify::Definition> = statements
6302        .iter()
6303        .filter_map(|stmt| match stmt {
6304            Stmt::Definition(d) => lower_definition(d, &interner),
6305            _ => None,
6306        })
6307        .collect();
6308
6309    Ok((
6310        proof_exprs,
6311        goal_expr,
6312        defaults,
6313        definitions,
6314        declared_proof(theorem),
6315    ))
6316}