tpt-syntaxis

Rust

Maths. Rust + Lean 4 engine that discovers, verifies, minimizes, and publishes novel theorems — symbolic search by default, AI-assisted when you want it.

0 stars0 forks0 watchersApache License 2.0

Languages

Rust98.7%Lean0.7%Just0.6%
README

TPT Syntaxis

AI-optional, 100% Rust mathematical discovery engine powered by Lean 4.

TPT Syntaxis automatically discovers, verifies, minimizes, and publishes novel mathematical theorems. It combines formal verification (Lean 4 kernel as the sole source of truth) with high-performance Rust computation and optional heuristic AI search via OpenRouter.

Conjecture Generation → Proof Search → Lean Kernel Verification → Minimize + Audit → Publication
       (AI Compass)      (Symbolic +       (Absolute)            (Compression)     (Mathlib PR /
                         Compass)                                                  arXiv / Journal)

Table of Contents


Getting Started

5 minutes from zero to discovering your first theorem.

Prerequisites

ToolVersionPurposeInstall
Rust1.85+Core languagerustup.rs
Lean 4v4.12+Proof verificationElan
JustlatestCommand runnercargo install just

For AI mode only:

ToolPurposeInstall
OpenRouter API keyLLM accessopenrouter.ai

Installation

# 1. Clone the repository
git clone https://github.com/tpt-solutions/tpt-syntaxis.git
cd tpt-syntaxis

# 2. Install Rust toolchain (pinned in rust-toolchain.toml)
rustup toolchain install stable

# 3. Install Lean via Elan (pinned in lean-toolchain)
curl https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh -sSf | sh

# 4. Install Just command runner
cargo install just

# 5. Build everything
# NOTE: this project depends on Mathlib (see lakefile.lean). The first build
# fetches Mathlib and its prebuilt .olean cache via `lake exe cache get` — a
# multi-gigabyte download. Subsequent builds are incremental and much faster.
just build

First Run

# Run in symbolic mode (zero API cost, fully deterministic)
just run

# Output: TPT Syntaxis starts, discovers theorems using symbolic search
# The symbolic backend tries tactics like norm_num, simp, ring over goals
# Start the review dashboard
just dashboard

# Open http://127.0.0.1:3000 in your browser
# Review discovered theorems, accept/reject/flag for submission

Using AI Mode

# Set your OpenRouter API key
export OPENROUTER_API_KEY="your-key-here"

# Edit config.toml to enable AI mode
# Set backend = "hybrid" in [discovery] section

# Run with AI-guided search
just run

Three Modes

ModeHow It WorksWhen to UseCost
SymbolicBeam search over simp-lemma matches + power tactics (norm_num, ring, omega, linarith, aesop), kernel-verified before recordingLaptop, offline, deterministicZero
AILLM guesses tactics based on semantic understandingAbstract, creative leapsAPI calls
HybridAI compass suggests strategy; symbolic engine grinds subgoalsDefault for serious discoveryAPI calls

Key insight: Even in AI mode, the Lean kernel is the sole source of truth. The AI can hallucinate freely — if it suggests a non-existent lemma, Lean rejects it and the engine moves on. The AI never writes trusted proof code.


Using the CLI

The tpt command provides full access to all capabilities:

# Install the CLI
cargo install tpt-syntaxis-cli

# Solve a theorem goal
tpt solve --goal "1 + 1 = 2" --mode symbolic
tpt solve --goal "a + b = b + a" --mode hybrid

# Search for similar theorems
tpt search "commutativity" --mode hybrid --top-k 5

# Minimize a proof (compress verbose proofs)
tpt minimize --file proof.lean

# Audit a proof for safety
tpt audit "add_zero" --axioms "Nat.add_zero"

# Manage sorry bounties
tpt bounties --file bounties.json

# Show version
tpt version

CLI Examples

$ tpt solve --goal "1 + 1 = 2" --mode symbolic
Solving: 1 + 1 = 2
Mode: symbolic

Suggested tactics:
  1. norm_num
  2. simp [Nat.add_zero]
  3. omega
  4. ring
  5. linarith

$ tpt minimize --file proof.lean
Minimizing proof in: proof.lean

Original: 8 steps
Minimized: 2 steps
Compression: 75%

Minimized proof:
theorem add_zero (a : Nat) : a + 0 = a := by
  simp [Nat.add_zero]
  done

Using the Dashboard

The dashboard provides a web-based review interface for discovered theorems.

# Start the dashboard
just dashboard

# Open http://127.0.0.1:3000

Dashboard Features

PageWhat It Shows
Home (/)Stats cards + theorem list with accept/reject/flag buttons, search panel with a 🎲 "Surprise Me" random-goal action
Theorem Detail (/theorems/:id)Statement, original proof, minimized proof, Mathlib diff
Tactic Profile (/theorems/:id/profile)Timing breakdown per tactic step
Proof Tree (/theorems/:id/tree)ASCII visualization of proof structure
Suggestions (/theorems/:id/suggest)Recommended tactics + similar theorems
Discover Goals (/discover)Category cards (Arithmetic, Number Theory, Topology, etc.) — pick one to run a random search scoped to that category
Sorry Hunt (/sorry-hunt)Lists sorrys found in the Lean sources; pick one to use its statement as a search goal
Coverage (/coverage)Mathlib coverage statistics
Stats (/stats)Overall dashboard statistics
Settings (/settings)Configure the OpenRouter API key for AI/Hybrid mode

Dashboard Actions

  • Accept — Mark theorem as verified and ready for submission
  • Reject — Discard (not significant enough, incorrect, etc.)
  • Flag for Submission — Queue for Mathlib PR / arXiv / journal

Architecture

┌──────────────────────────────────────────────────────────────┐
│                        TPT Syntaxis                          │
├──────────────────────────────────────────────────────────────┤
│                                                              │
│  ┌──────────────┐    ┌──────────────┐    ┌──────────────┐   │
│  │  Conjecture   │───▶│ Proof Search │───▶│ Lean Kernel  │   │
│  │  Generator    │    │ (Symbolic +  │    │ Verification │   │
│  │  (AI Compass) │    │  Compass)    │    │ (Absolute)   │   │
│  └──────────────┘    └──────────────┘    └──────┬───────┘   │
│         ▲                                        │          │
│         │          ┌──────────────┐    ┌─────────▼────────┐ │
│         └──────────│  Mathlib PR  │◀───│ Minimize + Audit │ │
│                    │  / Journal   │    └──────────────────┘ │
│                    └──────────────┘                          │
└──────────────────────────────────────────────────────────────┘

The Trust Stack

┌─────────────────────────────────────────────────────────────┐
│  Human Interpretation                                        │  Subjective
│  "Is this theorem interesting?"                              │
├─────────────────────────────────────────────────────────────┤
│  Statement Correctness                                       │  Human must verify
│  "Does the Lean code say what we think it says?"             │  definitions match
├─────────────────────────────────────────────────────────────┤
│  Lean Kernel Verification                                    │  Machine-checked
│  "Is the proof logically valid?"                             │  GUARANTEED
├─────────────────────────────────────────────────────────────┤
│  Lean Kernel Source Code (~6,000 lines)                      │  Heavily audited
│  "Is the kernel itself trustworthy?"                         │  by the community
└─────────────────────────────────────────────────────────────┘

Discovery Pipeline

StageActorOutput
1. Conjecture GenerationAI Compass + Symbolic GeneratorList of candidate theorems
2. Proof SearchHybrid backend (Symbolic + Compass)Raw proof (possibly ugly)
3. Kernel VerificationLean 4Binary: accepted or rejected
4. Proof Minimizationtpt-syntaxis-minimizeClean, compressed proof
5. Significance Filtertpt-syntaxis-auditRating: Trivial → OpenProblem
6. Proof Audittpt-syntaxis-auditAxiom list + warnings
7. Human ReviewDashboardAccept / Reject / Submit
8. Publicationtpt-syntaxis-publishMathlib PR / arXiv / Journal

Workspace Crates

CratePurposeKey Types
tpt-syntaxis-bridgeLean 4 LSP/JSON-RPC interfaceLeanServer, LeanTacticState
tpt-syntaxis-coreOrchestrator, Search Compass, algorithmsMctsSearch, SearchCompass, DiscoveryBackend
tpt-syntaxis-forgeRust math FFI (SMT, linear algebra)SatSolver, Matrix, is_prime
tpt-syntaxis-extractData pipeline, Mathlib extractionMathlibIndex, VectorIndex, LeanParser
tpt-syntaxis-minimizeProof compressionMinimizer, TacticProof, TacticVerifier
tpt-syntaxis-auditAxiom checking, significance filteringAuditor, Significance, AxiomChecker
tpt-syntaxis-publishMathlib PRs, arXiv, journal formattingMathlibPrCreator, ArxivFormatter, SorryBountyBoard
tpt-syntaxis-dashboardWeb review UI (axum + HTMX)Routes, handlers, templates
tpt-syntaxis-cliCommand-line interface (tpt binary)Cli, Commands
tpt-syntaxis-profileTactic profiling, timingProfiler, ProofProfile, TacticStats
tpt-syntaxis-vizProof tree SVG/ASCII/JSONProofTree, ProofTreeNode
tpt-syntaxis-coverageMathlib coverage analysisCoverageAnalyzer, DependencyGraph
tpt-syntaxis-suggestTactic recommendation engineRecommender, Recommendation
tpt-syntaxis-crossproveLean/Coq/Isabelle translationCrossProver, TacticTranslator

Crate Dependency Graph

tpt-syntaxis-crossprove (standalone)
tpt-syntaxis-forge (standalone)
tpt-syntaxis-extract (standalone)
    ↓
tpt-syntaxis-minimize → tpt-syntaxis-bridge
tpt-syntaxis-audit → tpt-syntaxis-extract
tpt-syntaxis-profile → tpt-syntaxis-minimize
tpt-syntaxis-viz → tpt-syntaxis-minimize
tpt-syntaxis-coverage → tpt-syntaxis-extract
tpt-syntaxis-suggest → tpt-syntaxis-extract, tpt-syntaxis-core
    ↓
tpt-syntaxis-core → tpt-syntaxis-bridge, tpt-syntaxis-forge, tpt-syntaxis-extract,
                     tpt-syntaxis-minimize, tpt-syntaxis-audit
    ↓
tpt-syntaxis-publish → tpt-syntaxis-core, tpt-syntaxis-audit
tpt-syntaxis-dashboard → all above
tpt-syntaxis-cli → all above

Configuration

Edit config.toml to configure the system:

[discovery]
backend = "hybrid"  # "symbolic" | "ai" | "hybrid"

[ai.openrouter]
api_key = "${OPENROUTER_API_KEY}"
conjecture_model = "anthropic/claude-3.5-sonnet"
tactic_model = "meta-llama/llama-3.1-405b-instruct"
compass_model = "deepseek/deepseek-r1"
base_url = "https://openrouter.ai/api/v1"

[ai.parameters]
temperature = 0.7
max_tokens = 1024

[search]
max_branches = 16
beam_width = 5
timeout_seconds = 300

[publish]
mathlib_repo = "leanprover-community/mathlib4"
auto_pr_on_open_problem = true

[dashboard]
host = "127.0.0.1"
port = 3000

Environment Variables

VariableRequiredDescription
OPENROUTER_API_KEYFor AI/Hybrid modeAPI key from openrouter.ai

Examples

Run the examples to see each capability in action:

# Solve a simple theorem
cargo run --example solve_simple

# Build a Mathlib index and search
cargo run --example index_mathlib

# Minimize a verbose proof
cargo run --example minimize_proof

# Audit a proof for safety
cargo run --example audit_proof

# Render a proof tree
cargo run --example proof_tree

# Profile tactic execution
cargo run --example tactic_profile

# Get tactic recommendations
cargo run --example recommend_tactics

# Generate a coverage report
cargo run --example coverage_report

# Translate Lean proof to Coq/Isabelle
cargo run --example translate_proof

Example: Solving a Theorem

use tpt_syntaxis_core::backend::{SymbolicBackend, DiscoveryBackend};
use tpt_syntaxis_bridge::LeanTacticState;

#[tokio::main]
async fn main() {
    let backend = SymbolicBackend::new();
    let state = LeanTacticState {
        goals: vec![tpt_syntaxis_bridge::LeanGoal {
            name: None,
            hypothesis: vec![],
            target: "1 + 1 = 2".to_string(),
        }],
        messages: vec![],
        tactic_pos: None,
    };

    let suggestions = backend.suggest_tactics(&state, 5).await.unwrap();
    for (i, tactic) in suggestions.iter().enumerate() {
        println!("{}. {}", i + 1, tactic);
    }
    // Output:
    // 1. simp [Nat.add_zero]
    // 2. norm_num
    // 3. omega
    // 4. ring
    // 5. linarith
}

Example: Minimizing a Proof

use tpt_syntaxis_minimize::{TacticProof, Minimizer};

let code = r#"theorem add_zero (a : Nat) : a + 0 = a := by
  have h : a + 0 = a := by simp [Nat.add_zero]
  exact h
  done"#;

let proof = TacticProof::parse(code);
let minimizer = Minimizer::new();
let result = minimizer.minimize(&proof).unwrap();

// Original: 4 steps → Minimized: 2 steps (50% compression)

How It Works

1. Conjecture Generation

The system generates candidate theorems using:

  • Symbolic patterns: Commutativity, associativity, identity elements
  • AI Compass (hybrid mode): LLM suggests strategy metadata — never tactic code
  • Mathlib gaps: Targets unresolved sorry statements

2. Proof Search

Two search algorithms explore the tactic space:

  • Production MCTS: PUCT selection, transposition tables, time budgets, progressive widening, heuristic rollouts
  • Beam Search: Top-K branch exploration with heuristic scoring

The DiscoveryBackend trait provides tactic suggestions:

#[async_trait]
pub trait DiscoveryBackend: Send + Sync {
    async fn suggest_tactics(&self, state: &LeanTacticState, n: usize)
        -> Result<Vec<String>>;
    fn estimate_value(&self, state: &LeanTacticState) -> f64;
    fn state_hash(&self, state: &LeanTacticState) -> u64;
}

3. Kernel Verification

The search backends propose candidate tactic sequences using cheap heuristics — they never touch the real elaborator. Before a candidate is ever recorded as a discovery, tpt-syntaxis-core::verify compiles it as a real theorem (lake env lean against the project's Mathlib dependency) and only accepts it if the Lean 4 kernel actually checks it. A heuristic "success" that doesn't survive this step is discarded, never recorded — the kernel is the sole source of truth, not the search's own opinion of itself.

4. Proof Minimization

Raw proofs (often hundreds of brute-forced steps) are compressed:

  1. Parse into individual tactic steps
  2. Try replacing N-step windows with single power tactics
  3. Verify each replacement via TacticVerifier
  4. Recurse until no further compression

5. Significance Classification

Discoveries are classified into five tiers:

TierCriteriaAction
Trivial≤ 2 steps, standard tacticsLog only
KnownVariantSlight rewording of existing theoremLog only
NovelButSimpleNew, follows from known resultsDashboard review
NovelAndDeepNew, non-obvious strategy requiredPriority review
OpenProblemResolved a known Mathlib sorryPriority submission

6. Publication

Approved discoveries are formatted and submitted:

  • Mathlib PR: GitHub API integration with standard PR template
  • arXiv preprint: LaTeX formatted for cs.LO / math.LO
  • Journal submission: Templates for JFR, LMCS, JAR

For Developers

Development Setup

# Clone and build
git clone https://github.com/anthropics/tpt-syntaxis.git
cd tpt-syntaxis
just build

# Run all tests (100+ tests)
just test

# Lint
just clippy
just fmt-check

Build Commands

CommandDescription
just buildBuild everything (Lean + Rust)
just build-rustBuild Rust workspace only
just build-leanBuild Lean project only
just testRun all Rust tests
just test-leanRun Lean tests
just clippyRun clippy with warnings as errors
just fmtFormat all code
just fmt-checkCheck formatting without modifying
just runRun the discovery engine
just dashboardStart the review dashboard
just publish-dry-runVerify crates.io publishing
just cleanClean build artifacts

Architecture Principles

  • 100% Rust — no Python, no Node.js anywhere in the toolchain
  • AI is optional — symbolic mode runs with zero API calls, zero cost, fully deterministic
  • Lean kernel is the sole source of truth — no component bypasses it
  • AI never writes proof code — only tactic suggestions or compass metadata
  • Human-in-the-loop — no auto-publish bypass; dashboard gates all publication

CI/CD

GitHub Actions runs on every push:

  1. cargo fmt --all -- --check
  2. cargo clippy --workspace -- -D warnings
  3. cargo test --workspace
  4. lake build + lake env lean --run lean-src/Main.lean
  5. cargo publish --dry-run (PRs only)

Tag-triggered release workflow publishes to crates.io in dependency order.


License

MIT OR Apache-2.0