Spaces:
Sleeping
Sleeping
Commit History
-
Repo cleanup: dead code out, test isolation fix, real README
p4r5kpftnp-cmd- Remove src/lmm_client.py and src/proof_agent.py — MVP-era relics with zero production importers since the provider routing moved into rag_chain. Their tests go with them (including the proof_agent default-model regression test, obsolete with the module deleted). - Fix sys.modules pollution in test_manual_bug_fixes.py: it installed MagicMocks at lean_verifier/retriever/rag_chain at import time and never restored them, poisoning every test module imported later during discovery (alphabetical order put 6 files after it). Mocks are now installed only around the langgraph_agent import and restored in a finally block; the mock-built langgraph_agent is evicted too. - Replace the 344-line MVP design doc README (Ollama-era, described the since-removed reranker) with an accurate project README: architecture diagram, RAG details with real numbers, model matrix, local-run quickstart, honest small-sample benchmark table, project layout, CI notes. HF Spaces frontmatter un…16fb4fc -
RAFT-style prompting: distractor-aware framing + usage citations
p4r5kpftnp-cmdApplies the core insight of RAFT (Retrieval-Augmented Fine-Tuning) at the prompt level, no fine-tuning required: 1. Retrieved lemmas are now framed as optional hints that "MAY BE IRRELEVANT" with an explicit instruction to ignore unhelpful ones. By default LLMs treat provided context as something they must use — exactly the distractor trap RAFT measures. 2. The model must open its code block with a citation comment (`-- used: Nat.add_comm` / `-- used: none`). Forcing a citation reduces hallucinated lemma names, and the generate node logs it ("[rag] lemmas cited as used: ..."), turning every run into labeled (retrieved, actually-used) feedback — seed data for a future retrieval eval harness. 3. Premises render as a fenced ```lean block with the fully-qualified name in a `--` comment above each declaration (page_content often carries only the short name, but `exact`/`rw` need the full one). Previously they were prose bullets. 4. Prompt reordered: code…f4afb6d -
Retrieval fixes: robust nprobe tuning + goals-only query
p4r5kpftnp-cmd1. nprobe: set via faiss.extract_index_ivf() instead of attribute assignment on the top-level index. FAISS silently ignores nprobe set on wrapper indexes (IndexIDMap etc.), so reaching the IVF layer directly guards against a future wrap making the tuning a no-op. Verified the persisted index defaults to nprobe=16 and load bumps it to 32. Non-IVF indexes and test doubles are tolerated (RuntimeError / TypeError respectively) since search-breadth tuning must never break index loading. 2. Retrieval query: goals only, newline-joined. Previously the retrieve node space-joined goals + Lean error messages into one string. The LeanDojo ByT5 encoder was trained on canonical proof states ("h : T\n⊢ goal"); error text is off-distribution noise that skews the embedding. Errors still reach the LLM through the generation prompt — they just no longer pollute retrieval. With no open goals (pure syntax error) the query is empty and the retriever returns [], whi…1dc8f6a
-
Swap MiniLM retriever for LeanDojo's ByT5 premise encoder
p4r5kpftnp-cmdReplaces the general-English `all-MiniLM-L6-v2` embedder with `kaiyuy/leandojo-lean4-retriever-byt5-small` — a ByT5 encoder fine-tuned on (proof_state, used_premise) pairs from Mathlib. Semantic retrieval now returns directly-relevant lemmas (`Nat.add_comm`, `Nat.add_assoc`, …) where the old setup returned irrelevant matches. What changed: - New `src/byt5_embedder.py` — LangChain Embeddings wrapper around the ByT5 encoder (mean-pooled + L2-normalized). - New `scripts/build_leandojo_index.py` — downloads the 181k pre-computed premise embeddings + dictionary from the LeanDojo HuggingFace repo and builds an IVFPQ FAISS index. IVFPQ compresses ~1 GB flat embeddings to ~17 MB with ~95% recall, keeping us under GitHub's free LFS quota. - `src/retriever.py` — drops BM25 ensemble and the generic `ms-marco-MiniLM-L-6-v2` cross-encoder reranker. The LeanDojo encoder is already domain-specialized; the generic rerank was reordering correct premises below irrelevant ones (verifie…d05440d
-
Pin ruff to 0.15.14 and re-sort imports
p4r5kpftnp-cmdThe lint job failed because `pip install ruff` pulled 0.15.x while the local run used an old 0.1.6 — newer ruff sorts import blocks differently, so 3 files tripped I001 only in CI. Pinned the workflow to ruff==0.15.14 and re-ran `ruff check --fix` (import re-sorting in langgraph_agent.py, retriever.py, test_state_machine_fuzz.py). 98 tests still pass.01cdf65 -
Add CI/CD: GitHub Actions workflow + ruff config
p4r5kpftnp-cmdNew .github/workflows/ci.yml with three jobs: - lint: ruff check on every push/PR (fast, no project deps) - test: pytest over the ~98-test suite on every push/PR - deploy: on push to main only, pushes to the HF Space (gated on an HF_TOKEN secret — skips cleanly if the secret isn't set) Supporting changes to make the suite CI-green: - ruff.toml: line-length 120; ignore E402 (sys.path.insert-before-import is intentional in tests/scripts) and E741; exclude web/, data/, .claude/. - Fixed test isolation: test_proof_agent.py and test_app_fuzz.py permanently overwrote sys.modules["langgraph_agent"] with a mock and never restored it, poisoning every later test file (31 failures in a full run). They now restore sys.modules after importing their target. - test_retriever_fuzz.py: force a fresh `retriever` import so a cached real module from another test file can't shadow its mocks. - test_lean_verifier.py: skipUnless(`lean` on PATH) so the 3 real-Lean tests skip on CI r…6cf7e7c
-
Add Claude CLI provider for Pro-token billing
p4r5kpftnp-cmdNew `ClaudeCliChat` LangChain wrapper that shells out to `claude -p` for each LLM call. Routes through the user's local Claude Code installation and bills against their Pro subscription tokens instead of API credits. Model name prefix routing in _make_llm: - `claude-cli-*` -> ClaudeCliChat (subprocess to `claude -p`) - `claude-*` -> Anthropic API (needs api_key) - everything else -> Groq Example: python3 scripts/benchmark.py \ --problems-dir problems \ --model claude-cli-opus \ --retries 3 Tradeoff: each subprocess adds ~5-15s startup overhead vs the API, but cost is zero (covered by Pro). Good for cheap local benchmarks; the Anthropic API path is still preferred for the live Space.a8eac5b -
Speed up proof generation: cache components, smaller max_tokens, two-stage retry
p4r5kpftnp-cmdThree targeted speedups for the live Space: 1. Cache LeanEnvironment + MathLibRetriever module-level in app.py. Each solve_proof call used to spawn a fresh Lean REPL (5-15s cold) and reload the 200MB FAISS index. Now both are built once on first use and shared across requests. LeanEnvironment grew a threading.Lock so concurrent verifies serialize at the Lean step but parallelize everywhere else. 2. Lower LLM max_tokens from 1024 -> 512. Most Lean proofs are 1-5 lines; the cap rarely bites and the smaller window is ~20-30% faster. 3. Two-stage retry. On Groq, attempt 0 now uses llama-3.1-8b-instant (~3-5x faster than 70b); subsequent attempts escalate to whichever model the user picked in the dropdown. Skipped when the user explicitly picks 8b or any Claude model. LangGraphAgent gained optional `fast_model`, `lean_env`, and `retriever` parameters so callers can opt into the new behavior; defaults preserve the old per-call construction for scripts/run_agent…df04431 -
Add Claude API support (users supply their own key)
p4r5kpftnp-cmdUsers can now pick a Claude model (Opus 4.7, Sonnet 4.6, Haiku 4.5) from the model dropdown and paste their own Anthropic API key into a password field above the editors. Groq remains the default (using the Space's GROQ_API_KEY env var). Implementation: - `RAGProofChain` picks provider from model name prefix: `claude-*` → ChatAnthropic, everything else → ChatGroq - `api_key` parameter threaded through LangGraphAgent → RAGProofChain so user-provided keys reach the LangChain client directly (never set as an env var, so concurrent calls don't clobber each other) - `solve_proof` validates: Claude models require the key field; Groq models still rely on the Space's env var - New deps: `langchain-anthropic` - Test mocks accept **kwargs so the existing fuzz/concurrent suites still pass with the new constructor signature The Anthropic key is sent over HTTPS to the Space backend then to Anthropic; it is not stored on disk and is not logged.1145e92 -
Merge pull request #8 from ray5th/worktree-agent-a0c1e62025fb04462
Unverified signatureFuzz retriever query handling (+ fix missing input guards)2e7766e -
Merge pull request #7 from ray5th/worktree-agent-a5d6c683e40e73f66
Unverified signatureFuzz state machine + retries (+ fix empty LLM output bug)c84133e -
Fix 4 bugs found in manual code review
p4r5kpftnp-cmd +1: Claude Sonnet 4.6Bugs (all real, all in code paths the live HF Space hits): 1. `_count_theorem_blocks` keyword tuple had mismatched trailing spaces in `src/langgraph_agent.py`. `theorem\nfoo` returned 0 (false negative — would mis-reject valid LLM output as "dropped theorem"); `examplelike` returned 1 (false positive). Replaced with regex requiring a whitespace or end-of-line boundary. 2. `_extract_lean_code` did `text.split("\`\`\`lean")[1]` which leaks the trailing tag suffix when the LLM uses `\`\`\`lean4` (a common variant). Old output: "4\nfoo := rfl". New: proper regex match requiring whitespace/newline after the lean tag, with optional digit suffix. 3. `_read_file` / `_write_file` used the platform default encoding, which is ASCII on minimal Docker images. Lean source uses ∀ ∃ ℕ unicode. Forced encoding="utf-8" on both. Matches the fix already applied to app.py's tempfile/open calls. 4. `proof_agent.py` still defaulted to `"qwen3-vl:4b"` (a stale Ollama model…1808386 -
Fix 4 bugs found by stress-test agents + add fuzz/concurrent test suites
p4r5kpftnp-cmd +1: Claude Sonnet 4.6Bugs fixed: - src/lmm_client.py: chat() crashed with IndexError when Groq returned empty choices (content filter / quota). Now returns "" gracefully. - src/lean_verifier.py: verify_proof("") crashed with pydantic ValidationError (Command requires min_length=1). Now returns a clean failure result. - src/lean_verifier.py: LeanServer.run exceptions propagated up, killing the agent retry loop on transient disconnects. Now caught and surfaced as "Lean server error: <msg>" inside the failure result. - app.py: tempfile and open() use platform default encoding, which can blow up on non-UTF-8 locales for Lean source containing ∀ ℕ ∃ etc. Forced UTF-8 on both ends. Tests added (all using stdlib unittest + mocks, no Lean/Groq needed): - tests/test_app_fuzz.py — 11 fuzz cases for app.solve_proof (empty, whitespace, 100KB input, unicode, missing GROQ_API_KEY, agent raising, temp-file cleanup, etc.) - tests/test_concurrent_solve.py — 4 stress cases for concurrent invocations; ve…b42c3ef -
Gracefully skip RAG when FAISS index is missing
p4r5kpftnp-cmd +1: Claude Sonnet 4.6The HF Spaces Docker image ships without a pre-built Mathlib FAISS index (building it requires Mathlib installed, which is too heavy for the build). Previously the retriever raised RuntimeError on the first proof attempt, breaking the app entirely. Now retrieve() detects the missing index, prints a one-time warning, and returns []. The LangGraph agent continues without RAG context, falling back to the LLM's training knowledge of Mathlib. This is a graceful degradation — proofs may be lower quality without retrieval, but the app works. To re-enable RAG, run `python scripts/build_index.py` to build the index (requires Lean+Mathlib installed locally). Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>41f9289 -
Fuzz retriever query handling (fix missing input guards)
p4r5kpftnp-cmd +1: Claude Opus 4.7Adds tests/test_retriever_fuzz.py covering MathLibRetriever.retrieve and __init__ across degenerate inputs (empty, whitespace, 5000-char, special chars, Lean unicode, None, non-string) and index-dir failure modes (missing, garbage). Heavy deps (HuggingFaceEmbeddings, FAISS, HuggingFaceCrossEncoder) are mocked before the module is imported so the suite is hermetic. Bug found and fixed: - retrieve(None) (and any non-string) was silently passed to the LangChain retriever where it surfaced as an opaque error far from the call site. Now raises TypeError up front. - Empty/whitespace queries fell through to the embedding model which returns noisy near-neighbours; they now short-circuit to []. - Unbounded query length could pin the embedder; capped at 2000 chars. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>1c701bb -
Fuzz state machine + fix empty-LLM-output bug
p4r5kpftnp-cmd +1: Claude Opus 4.7Adds tests/test_state_machine_fuzz.py covering should_continue (status x attempt x max_retries corpus), make_generate_node (identical/empty/ whitespace/dropped/added-theorem/valid outputs), and make_verify_node (success and failure transitions, solved_at_attempt tracking). Fixes a latent bug in make_generate_node: _sanitize_imports unconditionally prepends "import Mathlib", so an empty/whitespace-only LLM response produced a non-empty new_code and slipped past the "no changes" guard, silently writing a stub file and never marking status="failed". The empty-output check now runs on the extracted payload before sanitization. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>ec7552d
-
Add Hugging Face Spaces deployment with Groq API
p4r5kpftnp-cmd +1: Claude Sonnet 4.6- Replace Ollama/local LLM with Groq API (langchain-groq + groq SDK) - Default model changed to llama-3.3-70b-versatile across all LLM clients - Add Gradio web UI (app.py) as the HF Spaces entry point - Add Dockerfile with Ubuntu 22.04 + Lean 4 via elan, Mathlib pre-warmed - Update requirements.txt: remove ollama/langchain-ollama, add groq/langchain-groq/gradio Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>c2ebdf5
-
Add MiniF2F benchmark harness and improve proof agent robustness
p4r5kpftnp-cmd +1: Claude Sonnet 4.6- scripts/benchmark.py: new benchmark runner against MiniF2F-valid (244 problems); reports pass@k for k=1..max_retries, avg attempts-to-solve, avg wall-clock time, and writes a per-problem CSV for ablation analysis - langgraph_agent.py: track solved_at_attempt in ProofState; expose solve_file_detailed() returning {success, solved_at_attempt, total_attempts}; add _count_theorem_blocks() guard that rejects LLM responses that silently drop theorem statements (false-success bug) - rag_chain.py: rewrite system prompt with tactic reference, common mistakes section, and seven few-shot examples; escape curly braces in Lean implicit-arg syntax so LangChain doesn't treat them as template variables (KeyError crash) - problems/lecture{4-7}_problems.lean: verified Lean 4 solutions for 11 problems drawn from course lecture notes (Lectures 4-7) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>8c51ce7 -
Fix LLM hallucinated imports and slow thinking mode
p4r5kpftnp-cmd +1: Claude Sonnet 4.6- langgraph_agent.py: add _sanitize_imports() which strips all LLM-generated import lines and replaces them with `import Mathlib`. LLMs consistently hallucinate non-existent Lean paths (e.g. Mathlib.TacticLibrary.Peel) that break compilation; the correct import for any Mathlib proof is always `import Mathlib`. - rag_chain.py: tighten system prompt with explicit rules (keep imports, no spurious `open`, prefer simple tactics). Add num_predict=1024 cap and think=False to disable chain-of-thought mode on qwen3/gemma3 models — without this, models spend 20+ minutes generating reasoning tokens before the actual answer. Tested: simple_add.lean (n + 0 = n) solved in 2 attempts with gemma3:12b, verified by Lean REPL. Proof: `simp`. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>ef4afaa
-
Fix import paths and Mathlib auto-detection for LangChain 1.x
p4r5kpftnp-cmd +1: Claude Sonnet 4.6EnsembleRetriever and CrossEncoderReranker moved to langchain_classic in LangChain 1.x — update retriever.py imports accordingly. MathLibCorpus now searches lean-interact's TempRequireProject cache (.lake/packages/mathlib) for Mathlib source and prefers the Mathlib/ subdirectory to avoid import-only root files returning zero declarations. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>5543636 -
Add LangChain/LangGraph RAG pipeline for retrieval-augmented proof generation
p4r5kpftnp-cmd +1: Claude Sonnet 4.6- src/mathlib_corpus.py: walks Mathlib4 .lean source files and extracts theorem/lemma/def declarations as LangChain Documents - src/retriever.py: MathLibRetriever — FAISS + BM25 hybrid retrieval via EnsembleRetriever (60/40), reranked with CrossEncoder; index persisted to data/mathlib_index/ for reuse across runs - src/rag_chain.py: RAGProofChain — LangChain LCEL chain (ChatPromptTemplate | OllamaLLM | StrOutputParser) that injects retrieved lemma context into each proof-generation call - src/langgraph_agent.py: LangGraphAgent — replaces the plain Python retry loop with a proper state machine (verify → retrieve → generate → verify); exposes the same solve_file() API - src/proof_agent.py: thin backward-compatible wrapper around LangGraphAgent - scripts/build_index.py: one-time offline script to build and save the FAISS index from Mathlib4 source - scripts/run_agent.py: updated to use LangGraphAgent directly - requirements.txt: add faiss-cpu, rank-bm25, sentence-transform…3ac681e
-
rework
p4r5kpftnp-cmd4562b5e
-
Initial commit: Agentic Lean 4 Theorem Prover
p4r5kpftnp-cmd- src/lean_env.py: Lean compiler wrapper + error parser - src/retriever.py: FAISS index build and Mathlib4 RAG retrieval - src/agent.py: Claude-powered agentic proof loop with self-correction - src/cli.py: Rich interactive CLI - extract_mathlib.py: Mathlib4 lemma extractor - requirements.txt, README.md, .env.example4a3b0d0