SPP commited on
Commit
ed428ff
·
0 Parent(s):

Q.E.D — initial submission

Browse files
Files changed (5) hide show
  1. README.md +94 -0
  2. back.py +264 -0
  3. back_modal.py +145 -0
  4. front.py +572 -0
  5. requirements.txt +8 -0
README.md ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Q.E.D
3
+ emoji: ⊢
4
+ colorFrom: green
5
+ colorTo: gray
6
+ sdk: gradio
7
+ app_file: front.py
8
+ pinned: true
9
+ license: mit
10
+ short_description: LLM-guided formal verification — AI proposes tactics, Lean's kernel certifies the proof
11
+ tags:
12
+ - track:wood
13
+ - sponsor:modal
14
+ - achievement:offbrand
15
+ - achievement:best-demo
16
+ - gradio
17
+ - lean4
18
+ - formal-verification
19
+ - agents
20
+ - build-small-hackathon
21
+ ---
22
+
23
+ # ⊢ Q.E.D
24
+
25
+ An LLM-guided formal verification agent. You give it a theorem statement in Lean 4; it finds a proof that **Lean's kernel certifies as formally correct**.
26
+
27
+ Unlike a chatbot saying "yes, that's true," Lean's kernel is a proof-checker that either accepts or rejects every logical step against its axioms. No hallucinations. No approximations. The result is machine-checked mathematics.
28
+
29
+ ## Demo
30
+
31
+ 📹 **[DEMO VIDEO: paste URL here]**
32
+
33
+ 🐦 **[SOCIAL POST: paste URL here]**
34
+
35
+ ## What it does
36
+
37
+ The agent runs a propose → verify → learn loop, using a 27B LLM (well under the 32B limit) to propose Lean 4 proof tactics, Lean's kernel to verify each one, and the kernel's error messages fed back verbatim into the next prompt:
38
+
39
+ ```
40
+ theorem
41
+ → propose 3 tactic candidates (27B LLM via Modal)
42
+ → verify each in live Lean 4 REPL (Modal container)
43
+ → kernel rejects? → error text fed back to LLM
44
+ → kernel accepts? → advance proof state
45
+ → repeat until complete or stuck
46
+ ```
47
+
48
+ Key behaviours:
49
+
50
+ - **Fallback layer** — deterministic tactics (`rfl`, `norm_num`, `simp`, `omega`, `contradiction`, `assumption`) are tried at each step before the LLM is called.
51
+ - **Stuck-state detector** — if the same proof state recurs 3 times, or 3 consecutive steps all fail, the agent concludes "not provable as stated" and returns a clean verdict instead of looping indefinitely. This correctly identifies false theorems.
52
+ - **No cache on demo runs** — every run executes the full live loop so the propose→verify→learn steps are always visible.
53
+
54
+ **Model**: one model, Qwen3-27B quantized (Q4_K_M GGUF) served via llama.cpp. 27B < 32B. ✓
55
+
56
+ ## Best Use of Modal
57
+
58
+ Two Modal deployments power the app:
59
+
60
+ | App | What it runs |
61
+ |---|---|
62
+ | `lean-proof-agent` | FastAPI app with a persistent Lean 4 REPL. `min_containers=1` keeps it warm so there is zero cold-start delay. Runs the full agent loop and orchestrates the LLM calls. |
63
+ | `llama-server` | llama.cpp HTTP server running **Qwen3-27B (Q4_K_M)** on a Modal GPU. Receives the current proof state as context, returns tactic candidates. |
64
+
65
+ Why Modal specifically:
66
+
67
+ - Lean 4 requires a **persistent REPL process** with the full toolchain installed and pre-warmed — not something you can spin up per-request. Modal containers hold that state across calls.
68
+ - `min_containers=1` means the Lean server is **always alive**, which is critical for a live demo with ~30-second proof runs.
69
+ - The LLM needs a GPU. Modal's on-demand GPU allocation means no dedicated hardware to maintain.
70
+ - The two apps are **independently scaled**: REPL is CPU-bound, LLM is GPU-bound.
71
+
72
+ ## Off Brand — custom UI
73
+
74
+ The frontend is not stock Gradio. Every proof run produces a **live-rendered SVG proof tree** built from the agent's search trace: goal-state nodes connected by tactic edges, failed branches in red, the accepted path in green, a terminal QED node. It runs in the browser with zero JS dependencies — generated server-side and injected as HTML.
75
+
76
+ The overall aesthetic is a dark mathematical terminal: JetBrains Mono, GitHub-dark palette (`#0d1117` background, `#2ea043` green accent), styled to match the proof tree's colour scheme.
77
+
78
+ ## Best Agent — agent loop design
79
+
80
+ The proof search is a genuine multi-step agentic loop with external tool use and error-driven self-correction:
81
+
82
+ - **Propose**: LLM generates 3 tactic candidates given the current proof state and the previous kernel error (if any)
83
+ - **Verify**: Lean's formal kernel checks each candidate — this is ground truth, not a heuristic
84
+ - **Learn**: the exact kernel error message is injected back into the next LLM prompt
85
+ - **Decide**: best partial-progress result is selected; all-failed steps increment a failure counter
86
+ - **Conclude**: stuck-state detector fires a deliberate "not provable" verdict rather than hitting the step limit
87
+
88
+ The agent correctly proves true theorems and correctly identifies false ones — both happen live on every run.
89
+
90
+ ## Try it
91
+
92
+ Load any example theorem and click **⊢ Prove**. The step walkthrough shows every LLM candidate, which ones the kernel rejected, the error fed back, and the tactic that advanced the proof.
93
+
94
+ Each completed proof includes a pre-filled link to [live.lean-lang.org](https://live.lean-lang.org/) so you can paste it into Lean's web kernel and see "Goals accomplished!" yourself.
back.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import modal
2
+ import hashlib
3
+ from fastapi import FastAPI
4
+ from pydantic import BaseModel
5
+
6
+ app = modal.App("lean-proof-agent")
7
+
8
+ image = (
9
+ modal.Image.debian_slim()
10
+ .apt_install("curl", "git", "build-essential")
11
+ .pip_install("lean-interact", "requests", "fastapi")
12
+ .run_commands(
13
+ "curl https://elan.lean-lang.org/elan-init.sh -sSf | sh -s -- -y --default-toolchain leanprover/lean4:v4.14.0",
14
+ )
15
+ .env({"PATH": "/root/.elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"})
16
+
17
+ .run_commands(
18
+ 'python -c "from lean_interact import LeanREPLConfig; LeanREPLConfig()"'
19
+ )
20
+ )
21
+
22
+
23
+
24
+
25
+
26
+ LLAMA_ENDPOINT = "https://no-name13--llama-server-serve.modal.run/v1/chat/completions"
27
+
28
+ web_app = FastAPI()
29
+
30
+ class ProveRequest(BaseModel):
31
+ theorem: str
32
+ max_steps: int = 20
33
+ use_fallbacks: bool = True
34
+ show_reasoning: bool = True # when True, skip cache read so the full agent loop always runs
35
+
36
+ class StepLog(BaseModel):
37
+ step: int
38
+ goal: str
39
+ candidates: list[str]
40
+ chosen: str
41
+ status: str
42
+ error: str | None = None
43
+
44
+ class ProveResponse(BaseModel):
45
+ success: bool
46
+ stuck: bool = False
47
+ tactics: list[str]
48
+ steps: list[StepLog]
49
+ message: str
50
+
51
+
52
+ @app.function(
53
+ image=image,
54
+ timeout=300,
55
+ min_containers=1,
56
+ )
57
+ @modal.asgi_app()
58
+ def fastapi_app():
59
+ from lean_interact import LeanServer, LeanREPLConfig, Command, ProofStep
60
+ from lean_interact.interface import LeanError
61
+ import requests
62
+
63
+ config = LeanREPLConfig()
64
+ server = LeanServer(config)
65
+
66
+ FALLBACK_TACTICS = ["rfl", "norm_num", "simp", "omega", "contradiction", "assumption"]
67
+ NUM_CANDIDATES = 3
68
+ lemma_cache: dict[str, list[str]] = {}
69
+
70
+
71
+ def ask_model(goal_state, last_error=None, num_candidates=3):
72
+ error_context = ""
73
+ if last_error:
74
+ error_context = (
75
+ f"\nThe previous tactic failed with this error:\n{last_error}\n"
76
+ f"IMPORTANT: if the error says 'major premise type is not an inductive type', "
77
+ f"it means you must use `intro` to bring variables into context BEFORE using `induction`.\n"
78
+ )
79
+ prompt = (
80
+ f"You are a Lean 4 theorem prover. Given this proof state:\n\n{goal_state}\n"
81
+ f"{error_context}\n"
82
+ f"Suggest the next single tactic. Output ONLY the tactic, no backticks, no explanation.\n"
83
+ f"RULES:\n"
84
+ f"- do NOT use `omega`, `decide`, `tauto`\n"
85
+ f"- do NOT use `apply Nat.add_comm` (using a named library lemma as a shortcut)\n"
86
+ f"- ALLOWED closing tactics — use these freely when they fit:\n"
87
+ f" `exact h` or `exact ⟨h1, h2⟩` (provide a proof term directly)\n"
88
+ f" `contradiction` (when context contains P and ¬P)\n"
89
+ f" `assumption` (when goal matches a hypothesis exactly)\n"
90
+ f" `absurd h1 h2` (derive False from h1 : P and h2 : ¬P)\n"
91
+ f"- always use fresh, distinct variable names when introducing (e.g. `intro n`, `intro P`, `intro Q`) — never reuse a name already present in the context\n"
92
+ f"- if the goal starts with `∀`, always use `intro` first before anything else\n"
93
+ f"- when using induction, always provide full case syntax:\n"
94
+ f" induction n with\n | zero => simp\n | succ n ih => simp [ih]"
95
+ )
96
+
97
+ tactics = []
98
+ for _ in range(num_candidates):
99
+ try:
100
+ payload = {
101
+ "model": "any",
102
+ "messages": [{"role": "user", "content": prompt}],
103
+ "max_tokens": 200,
104
+ "stream": False,
105
+ "temperature": 0.8,
106
+ "chat_template_kwargs": {"enable_thinking": False}
107
+ }
108
+ resp = requests.post(LLAMA_ENDPOINT, json=payload, timeout=30)
109
+ resp.raise_for_status()
110
+ tactic = resp.json()["choices"][0]["message"]["content"].strip().strip("`").strip()
111
+ if tactic and tactic not in tactics:
112
+ tactics.append(tactic)
113
+ except Exception:
114
+ break
115
+ return tactics
116
+
117
+ def try_tactic(tactic, proof_state_id):
118
+ result = server.run(ProofStep(tactic=tactic, proof_state=proof_state_id))
119
+ if isinstance(result, LeanError):
120
+ return None, result.message
121
+ return result, None
122
+
123
+ def try_fallbacks(proof_state_id, enabled):
124
+ if not enabled:
125
+ return None, None
126
+ for tactic in FALLBACK_TACTICS:
127
+ result, _ = try_tactic(tactic, proof_state_id)
128
+ if result is not None and "sorry" not in result.proof_status:
129
+ return result, tactic
130
+ return None, None
131
+
132
+ @web_app.post("/prove", response_model=ProveResponse)
133
+ def prove(req: ProveRequest):
134
+ steps = []
135
+ response = server.run(Command(cmd=f"{req.theorem} := by sorry"))
136
+
137
+ if not response.sorries:
138
+ if any(m.data == "Goals accomplished!" for m in response.messages):
139
+ return ProveResponse(success=True, tactics=[], steps=[], message="Proved trivially!")
140
+ return ProveResponse(success=False, tactics=[], steps=[], message="Could not get initial proof state")
141
+
142
+ proof_state_id = response.sorries[0].proof_state
143
+ current_goals = [response.sorries[0].goal]
144
+
145
+ goal_hash = hashlib.md5(current_goals[0].encode()).hexdigest()
146
+ if not req.show_reasoning and goal_hash in lemma_cache:
147
+ cached = lemma_cache[goal_hash]
148
+ return ProveResponse(
149
+ success=True, tactics=cached, steps=[],
150
+ message=f"Proved from cache ({len(cached)} tactic(s))!"
151
+ )
152
+
153
+ tactics = []
154
+ last_error = None
155
+ visited = set()
156
+ llm_ever_responded = False
157
+ consecutive_failures = 0 # all_failed steps in a row
158
+ goal_seen: dict[str, int] = {} # goal text → times seen
159
+ STUCK_THRESHOLD = 3
160
+
161
+ for step in range(req.max_steps):
162
+ goal_text = "\n".join(current_goals)
163
+ if not goal_text.strip():
164
+ break
165
+
166
+ # Stuck-state detection: same goal returning, or consecutive dead ends
167
+ goal_seen[goal_text] = goal_seen.get(goal_text, 0) + 1
168
+ if goal_seen[goal_text] >= STUCK_THRESHOLD or consecutive_failures >= STUCK_THRESHOLD:
169
+ return ProveResponse(
170
+ success=False, stuck=True, tactics=tactics, steps=steps,
171
+ message=(
172
+ "Search stuck — the same goal state recurred with no progress. "
173
+ "This theorem is likely not provable in the current theory: "
174
+ "it may require classical logic (Law of Excluded Middle), "
175
+ "or a tactic the agent is constrained from using."
176
+ ),
177
+ )
178
+
179
+ result, fallback_tactic = try_fallbacks(proof_state_id, req.use_fallbacks)
180
+ if result is not None:
181
+ tactics.append(fallback_tactic)
182
+ steps.append(StepLog(
183
+ step=step, goal=goal_text,
184
+ candidates=[fallback_tactic], chosen=fallback_tactic,
185
+ status=result.proof_status
186
+ ))
187
+ if result.proof_status == "Completed":
188
+ lemma_cache[goal_hash] = list(tactics)
189
+ return ProveResponse(success=True, tactics=tactics, steps=steps,
190
+ message=f"Proved in {step+1} steps!")
191
+ proof_state_id = result.proof_state
192
+ current_goals = result.goals
193
+ last_error = None
194
+ consecutive_failures = 0
195
+ continue
196
+
197
+ candidates = ask_model(goal_text, last_error=last_error, num_candidates=NUM_CANDIDATES)
198
+ if not candidates:
199
+ steps.append(StepLog(
200
+ step=step, goal=goal_text,
201
+ candidates=[], chosen="",
202
+ status="model_unavailable", error="LLM endpoint cold/unavailable — retrying"
203
+ ))
204
+ continue # don't count toward stuck-state; just burn a step and retry
205
+
206
+ llm_ever_responded = True
207
+ best_result = None
208
+ best_tactic = None
209
+ step_error = None
210
+
211
+ for tactic in candidates:
212
+ key = (proof_state_id, tactic)
213
+ if key in visited:
214
+ continue
215
+ visited.add(key)
216
+ result, error = try_tactic(tactic, proof_state_id)
217
+ if result is None:
218
+ last_error = error
219
+ step_error = error
220
+ continue
221
+ if "sorry" in result.proof_status:
222
+ last_error = "That tactic left sorry holes. Provide the full proof of each case inline."
223
+ continue
224
+ if result.proof_status == "Completed":
225
+ tactics.append(tactic)
226
+ steps.append(StepLog(
227
+ step=step, goal=goal_text,
228
+ candidates=candidates, chosen=tactic,
229
+ status="Completed"
230
+ ))
231
+ lemma_cache[goal_hash] = list(tactics)
232
+ return ProveResponse(success=True, tactics=tactics, steps=steps,
233
+ message=f"Proved in {step+1} steps!")
234
+ if best_result is None or len(result.goals) < len(best_result.goals):
235
+ best_result = result
236
+ best_tactic = tactic
237
+
238
+ if best_result is not None:
239
+ tactics.append(best_tactic)
240
+ steps.append(StepLog(
241
+ step=step, goal=goal_text,
242
+ candidates=candidates, chosen=best_tactic,
243
+ status=best_result.proof_status
244
+ ))
245
+ proof_state_id = best_result.proof_state
246
+ current_goals = best_result.goals
247
+ last_error = None
248
+ consecutive_failures = 0
249
+ else:
250
+ consecutive_failures += 1
251
+ steps.append(StepLog(
252
+ step=step, goal=goal_text,
253
+ candidates=candidates, chosen="",
254
+ status="all_failed", error=step_error
255
+ ))
256
+
257
+ fail_msg = (
258
+ "LLM endpoint warming up — fallback tactics only. Failed within max steps."
259
+ if not llm_ever_responded
260
+ else "Failed within max steps"
261
+ )
262
+ return ProveResponse(success=False, tactics=tactics, steps=steps, message=fail_msg)
263
+
264
+ return web_app
back_modal.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import modal
2
+ import subprocess
3
+
4
+ app = modal.App("llama-server")
5
+
6
+ MINUTES = 60
7
+ GPU_CONFIG = "A100-40GB"
8
+ cache_dir = "/root/.cache/llama.cpp"
9
+
10
+ #REPO_ID = "google/gemma-4-31B-it-qat-q4_0-gguf"
11
+ #MODEL_FILE = "gemma-4-31B_q4_0-it.gguf"
12
+ #MMPROJ_FILE = "gemma-4-31B-it-mmproj.gguf"
13
+
14
+
15
+ REPO_ID = "unsloth/Qwen3.6-27B-GGUF"
16
+ MODEL_FILE = "Qwen3.6-27B-Q4_K_M.gguf"
17
+
18
+
19
+ cuda_tag = "12.4.0-devel-ubuntu22.04"
20
+
21
+ model_cache = modal.Volume.from_name("llamacpp-cache", create_if_missing=True)
22
+
23
+ image = (
24
+ modal.Image.from_registry(f"nvidia/cuda:{cuda_tag}", add_python="3.11")
25
+ .apt_install(
26
+ "git",
27
+ "build-essential",
28
+ "cmake",
29
+ "curl",
30
+ "libcurl4-openssl-dev",
31
+ "libssl-dev",
32
+ )
33
+ .run_commands("git clone https://github.com/ggerganov/llama.cpp && cd llama.cpp && git pull origin master")
34
+ .run_commands(
35
+ "cmake llama.cpp -B llama.cpp/build "
36
+ "-DBUILD_SHARED_LIBS=OFF -DGGML_CUDA=ON -DLLAMA_CURL=ON -DLLAMA_OPENSSL=ON"
37
+ )
38
+ .run_commands(
39
+ "cmake --build llama.cpp/build --config Release -j "
40
+ "--target llama-server "
41
+ )
42
+ .run_commands("cp llama.cpp/build/bin/llama-server /usr/local/bin/")
43
+ .entrypoint([])
44
+ )
45
+
46
+ download_image = (
47
+ modal.Image.debian_slim(python_version="3.11")
48
+ .pip_install("huggingface_hub[hf_transfer]==0.26.2")
49
+ .env({"HF_HUB_ENABLE_HF_TRANSFER": "1"})
50
+ )
51
+
52
+
53
+ @app.function(
54
+ image=download_image,
55
+ volumes={cache_dir: model_cache},
56
+ timeout=20 * MINUTES,
57
+ )
58
+ def download_model():
59
+ from huggingface_hub import hf_hub_download
60
+
61
+ for filename in [MODEL_FILE]: #, MMPROJ_FILE
62
+ hf_hub_download(
63
+ repo_id=REPO_ID,
64
+ filename=filename,
65
+ local_dir=cache_dir,
66
+ )
67
+
68
+ model_cache.commit()
69
+
70
+
71
+ @app.function(
72
+ image=image,
73
+ gpu=GPU_CONFIG,
74
+ volumes={cache_dir: model_cache},
75
+ timeout=60 * MINUTES,
76
+ max_containers=1,
77
+ min_containers=1, #← for judging so that judges can start with a warm container
78
+ )
79
+
80
+ @modal.web_server(port=8080, startup_timeout=5 * MINUTES)
81
+ def serve():
82
+ import shutil
83
+ import os
84
+ import urllib.request
85
+ import json
86
+ import time
87
+
88
+ local_model = f"/tmp/{MODEL_FILE}"
89
+ #local_mmproj = f"/tmp/{MMPROJ_FILE}"
90
+
91
+ if not os.path.exists(local_model):
92
+ print("Copying model to local storage...", flush=True)
93
+ shutil.copy2(f"{cache_dir}/{MODEL_FILE}", local_model)
94
+
95
+ #shutil.copy2(f"{cache_dir}/{MMPROJ_FILE}", local_mmproj)
96
+ print("Copy complete.", flush=True)
97
+
98
+ subprocess.Popen([
99
+ "llama-server",
100
+ "-m",local_model ,
101
+ # "--mmproj", local_mmproj,
102
+ "--host", "0.0.0.0",
103
+ "--port", "8080",
104
+ "--ctx-size", "4096",
105
+ "-ngl", "999",
106
+ "--flash-attn","on",
107
+ "-np","1",
108
+ "-b", "2048",
109
+ "-ub", "512",
110
+ "--cache-type-k", "q8_0",
111
+ "--cache-type-v", "q8_0",
112
+ "-t", "8",
113
+ #"--no-mmap", ← loads weight into ram/not needed because of tmp
114
+ #"--no-warmup", skip empty run
115
+ ])
116
+
117
+ # wait for server ready
118
+ for _ in range(60):
119
+ try:
120
+ urllib.request.urlopen("http://localhost:8080/health")
121
+ break
122
+ except Exception:
123
+ time.sleep(5)
124
+
125
+ # fire a real request to compile actual CUDA graphs
126
+ payload = json.dumps({
127
+ "model": "any",
128
+ "messages": [{"role": "user", "content": "hi"}],
129
+ "max_tokens": 10,
130
+ "chat_template_kwargs": {"enable_thinking": False}
131
+ }).encode()
132
+ req = urllib.request.Request(
133
+ "http://localhost:8080/v1/chat/completions",
134
+ data=payload,
135
+ headers={"Content-Type": "application/json"}
136
+ )
137
+ urllib.request.urlopen(req)
138
+ print("Warmup complete.", flush=True)
139
+
140
+
141
+
142
+
143
+ @app.local_entrypoint()
144
+ def main():
145
+ download_model.remote()
front.py ADDED
@@ -0,0 +1,572 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import urllib.parse
2
+ import gradio as gr
3
+ import requests
4
+
5
+ MODAL_ENDPOINT = "https://no-name13--lean-proof-agent-fastapi-app.modal.run"
6
+
7
+ # ── Example theorems ──────────────────────────────────────────────────────────
8
+ # Lead with add_comm_nat (induction / multi-step) so the agent loop is visible.
9
+ # Keep zero_add as the simple contrast. False theorem always last.
10
+ EXAMPLES = [
11
+ (
12
+ "theorem add_comm_nat : ∀ n m : Nat, n + m = m + n",
13
+ "∀ n m · n + m = m + n — addition is commutative",
14
+ "provable",
15
+ ),
16
+ (
17
+ "theorem reverse_reverse : ∀ (α : Type) (l : List α), l.reverse.reverse = l",
18
+ "∀ α l · reverse(reverse l) = l — reversing a list twice is identity",
19
+ "provable",
20
+ ),
21
+ (
22
+ "theorem zero_add : ∀ n : Nat, 0 + n = n",
23
+ "∀ n · 0 + n = n — zero is the left identity for addition",
24
+ "provable",
25
+ ),
26
+ (
27
+ "theorem currying : ∀ P Q R : Prop, (P ∧ Q → R) ↔ (P → Q → R)",
28
+ "∀ P Q R · (P∧Q→R) ↔ (P→Q→R) — currying",
29
+ "provable",
30
+ ),
31
+ (
32
+ "theorem de_morgan_and : ∀ P Q : Prop, ¬(P ∧ Q) ↔ ¬P ∨ ¬Q",
33
+ "∀ P Q · ¬(P∧Q) ↔ ¬P∨¬Q — De Morgan's law",
34
+ "provable",
35
+ ),
36
+ # FALSE theorem — the stuck detector concludes "not provable" within a few steps.
37
+ (
38
+ "theorem cannot_prove : ∀ n : Nat, n + 1 = n",
39
+ "∀ n · n+1 = n — FALSE: the agent correctly cannot prove this ✗",
40
+ "unprovable",
41
+ ),
42
+ ]
43
+
44
+ EXAMPLE_LOOKUP = {lean.strip(): (desc, kind) for lean, desc, kind in EXAMPLES}
45
+
46
+ TACTIC_EXPLANATIONS = {
47
+ "intro": "introduces a universally quantified variable or hypothesis into the local context",
48
+ "induction": "applies structural induction — splits into base case (zero) and inductive step (succ)",
49
+ "simp": "simplifies the goal using a library of known equalities and lemmas",
50
+ "rfl": "closes the goal when both sides are definitionally equal",
51
+ "omega": "decision procedure for linear arithmetic — automatically solves goals about integers/naturals",
52
+ "rw": "rewrites the goal using an equation",
53
+ "exact": "closes the goal by providing an exact proof term",
54
+ "apply": "applies a lemma whose conclusion matches the goal",
55
+ "constructor": "splits a conjunction (∧) or iff (↔) goal into its two parts",
56
+ "cases": "case-splits on a hypothesis or value",
57
+ "norm_num": "solves numeric goals like 2 + 2 = 4 or 3 ∣ 6",
58
+ "contradiction": "closes the goal when context contains P and ¬P (a direct contradiction)",
59
+ "assumption": "closes the goal when it matches a hypothesis in the local context exactly",
60
+ "tauto": "closes propositional tautologies automatically",
61
+ }
62
+
63
+ # ── Dark theme — mathematical / formal-proof terminal aesthetic ───────────────
64
+ # Wraps in try/except so a theme API mismatch never breaks the app.
65
+ CUSTOM_CSS = """
66
+ /* ── Base ───────────────────────────────────────────────── */
67
+ body, .gradio-container { background: #0d1117 !important; color: #c9d1d9 !important; }
68
+ .contain, .gap, .row { background: #0d1117 !important; }
69
+
70
+ /* ── Panels ─────────────────────────────────────────────── */
71
+ .block.padded, .block {
72
+ background: #161b22 !important;
73
+ border: 1px solid #30363d !important;
74
+ border-radius: 8px !important;
75
+ }
76
+ .form { background: #161b22 !important; }
77
+
78
+ /* ── All text — catch-all first, then specifics ──────────── */
79
+ * { color: #c9d1d9; }
80
+
81
+ /* ── Headings ────────────────────────────────────────────── */
82
+ h1, h2, h3, h4 { color: #e6edf3 !important; }
83
+ h1 { border-bottom: 1px solid #21262d; padding-bottom: 6px; }
84
+
85
+ /* ── Labels (component titles, slider/checkbox labels) ────── */
86
+ label, .label-wrap, .label-wrap span,
87
+ span.text-gray-500, span.text-sm,
88
+ .block > .label-wrap > span { color: #b0bec5 !important; }
89
+
90
+ /* ── Body text, lists, paragraphs ───────────────────────── */
91
+ p, li, em, span { color: #c9d1d9 !important; }
92
+ a { color: #58a6ff !important; }
93
+ strong, b { color: #e6edf3 !important; }
94
+
95
+ /* ── Slider ──────────────────────────────────────────────── */
96
+ input[type=range] { accent-color: #2ea043 !important; }
97
+ .range-input span, .range-input output,
98
+ input[type=range] + span, .slider-container span { color: #c9d1d9 !important; }
99
+
100
+ /* ── Checkbox ─────────────────────────��──────────────────── */
101
+ input[type=checkbox] { accent-color: #2ea043 !important; }
102
+ .checkbox-label, .checkbox-label span { color: #c9d1d9 !important; }
103
+
104
+ /* ── Inputs ──────────────────────────────────────────────── */
105
+ textarea, input[type=text], input[type=number] {
106
+ background: #0d1117 !important;
107
+ color: #e6edf3 !important;
108
+ border: 1px solid #30363d !important;
109
+ border-radius: 6px !important;
110
+ font-family: 'JetBrains Mono', 'Fira Code', ui-monospace, monospace !important;
111
+ }
112
+ textarea::placeholder { color: #484f58 !important; }
113
+
114
+ /* ── Primary button ──────────────────────────────────────── */
115
+ button.primary {
116
+ background: #1a3a1a !important;
117
+ border: 1px solid #2ea043 !important;
118
+ color: #3fb950 !important;
119
+ font-weight: bold !important;
120
+ letter-spacing: 0.05em !important;
121
+ transition: all 0.15s ease !important;
122
+ }
123
+ button.primary:hover {
124
+ background: #2ea043 !important;
125
+ color: #fff !important;
126
+ box-shadow: 0 0 10px #2ea04355 !important;
127
+ }
128
+
129
+ /* ── Secondary / example buttons ────────────────────────── */
130
+ button.secondary, button[variant=secondary] {
131
+ background: #21262d !important;
132
+ border: 1px solid #30363d !important;
133
+ color: #c9d1d9 !important;
134
+ font-size: 0.8em !important;
135
+ transition: all 0.12s ease !important;
136
+ }
137
+ button.secondary:hover { border-color: #3fb950 !important; color: #3fb950 !important; }
138
+
139
+ /* ── Code blocks ─────────────────────────────────────────── */
140
+ code {
141
+ background: #161b22 !important;
142
+ color: #79c0ff !important;
143
+ border: 1px solid #30363d !important;
144
+ border-radius: 4px !important;
145
+ padding: 2px 5px !important;
146
+ }
147
+ pre {
148
+ background: #161b22 !important;
149
+ border: 1px solid #30363d !important;
150
+ border-radius: 6px !important;
151
+ }
152
+ pre code { color: #c9d1d9 !important; border: none !important; padding: 0 !important; }
153
+
154
+ /* ── Markdown output ─────────────────────────────────────── */
155
+ .output-markdown, .output-markdown * { color: #c9d1d9 !important; }
156
+ .output-markdown h1, .output-markdown h2,
157
+ .output-markdown h3 { color: #e6edf3 !important; }
158
+ .output-markdown strong, .output-markdown b { color: #e6edf3 !important; }
159
+ .output-markdown a { color: #58a6ff !important; }
160
+ .output-markdown code { color: #79c0ff !important; }
161
+ .output-markdown hr { border-color: #30363d !important; }
162
+
163
+ /* ── Description italic below theorem input ──────────────── */
164
+ .prose em, .prose i, em, i { color: #8fb8d8 !important; }
165
+ """
166
+
167
+ try:
168
+ _theme = gr.themes.Base(
169
+ primary_hue=gr.themes.colors.green,
170
+ neutral_hue=gr.themes.colors.zinc,
171
+ font=[gr.themes.GoogleFont("JetBrains Mono"), "ui-monospace", "monospace"],
172
+ font_mono=[gr.themes.GoogleFont("JetBrains Mono"), "ui-monospace", "monospace"],
173
+ )
174
+ except Exception:
175
+ _theme = None
176
+
177
+
178
+ # ── Verdict banner — three states, dark-theme colours ────────────────────────
179
+
180
+ def build_verdict_banner(success: bool, stuck: bool, english_desc: str = "") -> str:
181
+ font = "font-family:'JetBrains Mono','Fira Code',ui-monospace,monospace;"
182
+
183
+ if success:
184
+ desc_html = (
185
+ f'<div style="font-size:1.0em;color:#7ee787;margin:6px 0 10px;">'
186
+ f'<em>{english_desc}</em></div>'
187
+ ) if english_desc else ""
188
+ return (
189
+ f'<div style="background:#0d2818;border:2px solid #2ea043;border-radius:8px;'
190
+ f'padding:16px 22px;margin:10px 0;{font}">'
191
+ f'<div style="font-size:1.8em;font-weight:bold;color:#3fb950;letter-spacing:2px;margin-bottom:6px;">'
192
+ f'&#10003; FORMALLY VERIFIED</div>'
193
+ f'{desc_html}'
194
+ f'<div style="font-size:0.82em;color:#7ee787;line-height:1.75;'
195
+ f'border-top:1px solid #1a4a1a;padding-top:10px;margin-top:8px;">'
196
+ f'The AI proposed proof tactics. <strong style="color:#a0e8a0;">Lean 4\'s formal kernel</strong> '
197
+ f'checked every logical step against its axioms and accepted the proof.<br><br>'
198
+ f'<strong style="color:#3fb950;">This cannot be faked.</strong> '
199
+ f'Unlike a chatbot saying "yes, that\'s true," Lean\'s kernel rejects any gap in reasoning '
200
+ f'— no exceptions, no hallucinations. The proof below is machine-checked mathematics.'
201
+ f'</div></div>'
202
+ )
203
+
204
+ if stuck:
205
+ desc_html = (
206
+ f'<div style="font-size:1.0em;color:#e3b341;margin:6px 0 10px;">'
207
+ f'<em>{english_desc}</em></div>'
208
+ ) if english_desc else ""
209
+ return (
210
+ f'<div style="background:#1c1400;border:2px solid #d29922;border-radius:8px;'
211
+ f'padding:16px 22px;margin:10px 0;{font}">'
212
+ f'<div style="font-size:1.7em;font-weight:bold;color:#e3b341;letter-spacing:1px;margin-bottom:6px;">'
213
+ f'&#9888; NOT PROVABLE AS STATED</div>'
214
+ f'{desc_html}'
215
+ f'<div style="font-size:0.82em;color:#c9a227;line-height:1.75;'
216
+ f'border-top:1px solid #3a2800;padding-top:10px;margin-top:8px;">'
217
+ f'The agent detected it was stuck: the same goal state recurred with no progress.<br><br>'
218
+ f'<strong style="color:#e3b341;">This is a deliberate conclusion, not a failure.</strong> '
219
+ f'The claim as written cannot be proven — it may be mathematically false, '
220
+ f'or require axioms and tactics outside the current mode. '
221
+ f'Recognising when something is unprovable is part of what a formal proof agent does.'
222
+ f'</div></div>'
223
+ )
224
+
225
+ return (
226
+ f'<div style="background:#1c0a0a;border:2px solid #c62828;border-radius:8px;'
227
+ f'padding:16px 22px;margin:10px 0;{font}">'
228
+ f'<div style="font-size:1.6em;font-weight:bold;color:#f85149;margin-bottom:8px;">'
229
+ f'&#10007; SEARCH INCOMPLETE</div>'
230
+ f'<div style="font-size:0.82em;color:#c9d1d9;line-height:1.7;">'
231
+ f'The agent exhausted its step budget without completing the proof. '
232
+ f'Partial progress is shown below — try increasing the step limit or picking a simpler theorem.'
233
+ f'</div></div>'
234
+ )
235
+
236
+
237
+ # ── SVG proof tree — DO NOT MODIFY ───────────────────────────────────────────
238
+
239
+ def build_proof_tree_svg(steps: list, tactics: list, success: bool,
240
+ stuck: bool = False, claim: str = "") -> str:
241
+ if not steps:
242
+ return ""
243
+
244
+ NODE_W, NODE_H = 300, 44
245
+ STEP_H = 140
246
+ SVG_W = 820
247
+ CX = SVG_W // 2
248
+
249
+ n = len(steps)
250
+ title_h = 72 if claim else 52
251
+ SVG_H = title_h + (n + (1 if (success or stuck) else 0)) * STEP_H + NODE_H + 20
252
+
253
+ def esc(s):
254
+ return str(s).replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;')
255
+
256
+ def trunc(s, maxn=36):
257
+ s = str(s).replace('\n', ' ').strip()
258
+ return s[:maxn] + '…' if len(s) > maxn else s
259
+
260
+ out = []
261
+ out.append(f'<svg xmlns="http://www.w3.org/2000/svg" width="{SVG_W}" height="{SVG_H}">')
262
+ out.append(f'<rect width="{SVG_W}" height="{SVG_H}" fill="#030c04" rx="8"/>')
263
+ out.append('<defs>')
264
+ for mid, col in [('ahg', '#00e639'), ('ahr', '#f38ba8'), ('ahgr', '#6c7086'), ('aha', '#e6a817')]:
265
+ out.append(
266
+ f'<marker id="{mid}" markerWidth="8" markerHeight="6" refX="7" refY="3" orient="auto">'
267
+ f'<polygon points="0 0,8 3,0 6" fill="{col}"/></marker>'
268
+ )
269
+ out.append('</defs>')
270
+
271
+ if success:
272
+ title, tc = "Proof Tree — ✓ Verified", "#00e639"
273
+ elif stuck:
274
+ title, tc = "Proof Tree — ⚠ Concluded: Not Provable", "#e6a817"
275
+ else:
276
+ title, tc = "Proof Tree — ✗ Incomplete", "#f38ba8"
277
+
278
+ out.append(
279
+ f'<text x="{CX}" y="28" text-anchor="middle" '
280
+ f'font-family="monospace" font-size="14" font-weight="bold" fill="{tc}">{esc(title)}</text>'
281
+ )
282
+
283
+ if claim:
284
+ out.append(
285
+ f'<text x="{CX}" y="47" text-anchor="middle" '
286
+ f'font-family="monospace" font-size="10" fill="#70b870">'
287
+ f'Claim: {esc(trunc(claim, 74))}</text>'
288
+ )
289
+
290
+ legend_y = title_h - 10
291
+ for lx, col, label in [(20, '#00e639', 'successful path'), (168, '#f38ba8', 'failed attempt')]:
292
+ out.append(f'<line x1="{lx}" y1="{legend_y}" x2="{lx+20}" y2="{legend_y}" stroke="{col}" stroke-width="2"/>')
293
+ out.append(
294
+ f'<text x="{lx+24}" y="{legend_y+4}" font-family="monospace" font-size="9" fill="{col}">{label}</text>'
295
+ )
296
+
297
+ for i, step in enumerate(steps):
298
+ cy = title_h + i * STEP_H + NODE_H // 2
299
+ chosen = step.get('chosen', '')
300
+ candidates = step.get('candidates', [])
301
+ status = step.get('status', '')
302
+ goal = step.get('goal', '')
303
+ failed = [c for c in candidates if c != chosen]
304
+
305
+ on_path = bool(chosen) and status != 'all_failed'
306
+ if on_path and success:
307
+ bg, border = '#001a00', '#00e639'
308
+ elif status == 'all_failed':
309
+ bg, border = '#1a0000', '#f38ba8'
310
+ else:
311
+ bg, border = '#050f05', '#2a5a2a'
312
+
313
+ nx, ny = CX - NODE_W // 2, cy - NODE_H // 2
314
+ out.append(
315
+ f'<rect x="{nx}" y="{ny}" width="{NODE_W}" height="{NODE_H}" '
316
+ f'rx="5" fill="{bg}" stroke="{border}" stroke-width="1.5"/>'
317
+ )
318
+ out.append(
319
+ f'<text x="{CX}" y="{cy+5}" text-anchor="middle" '
320
+ f'font-family="monospace" font-size="10" fill="#98c898">'
321
+ f'{esc(trunc(f"Step {i}: {goal}"))}</text>'
322
+ )
323
+
324
+ for j, fc in enumerate(failed):
325
+ bx = CX + NODE_W // 2 + 55 + j * 75
326
+ by = cy + STEP_H // 3
327
+ out.append(
328
+ f'<line x1="{CX+NODE_W//2}" y1="{cy}" x2="{bx}" y2="{by}" '
329
+ f'stroke="#f38ba8" stroke-width="1.5" stroke-dasharray="4,3" marker-end="url(#ahr)"/>'
330
+ )
331
+ mx = (CX + NODE_W // 2 + bx) // 2 + 3
332
+ my = (cy + by) // 2 - 3
333
+ out.append(
334
+ f'<text x="{mx}" y="{my}" font-family="monospace" font-size="8" fill="#f38ba8">'
335
+ f'{esc(trunc(fc, 18))}</text>'
336
+ )
337
+ out.append(f'<circle cx="{bx}" cy="{by}" r="7" fill="#1a0000" stroke="#f38ba8" stroke-width="1"/>')
338
+ out.append(
339
+ f'<text x="{bx}" y="{by+4}" text-anchor="middle" '
340
+ f'font-family="monospace" font-size="9" fill="#f38ba8">✗</text>'
341
+ )
342
+
343
+ next_cy = title_h + (i + 1) * STEP_H + NODE_H // 2
344
+ if on_path:
345
+ color, mid = ('#00e639', 'ahg') if success else ('#6c7086', 'ahgr')
346
+ out.append(
347
+ f'<line x1="{CX}" y1="{cy+NODE_H//2}" x2="{CX}" y2="{next_cy-NODE_H//2}" '
348
+ f'stroke="{color}" stroke-width="2" marker-end="url(#{mid})"/>'
349
+ )
350
+ ly = (cy + NODE_H // 2 + next_cy - NODE_H // 2) // 2
351
+ out.append(
352
+ f'<text x="{CX+6}" y="{ly}" font-family="monospace" font-size="9" fill="{color}">'
353
+ f'{esc(trunc(chosen, 28))}</text>'
354
+ )
355
+ elif status == 'all_failed':
356
+ out.append(
357
+ f'<line x1="{CX}" y1="{cy+NODE_H//2}" x2="{CX}" y2="{cy+NODE_H//2+28}" '
358
+ f'stroke="#f38ba8" stroke-width="1.5" stroke-dasharray="4,3"/>'
359
+ )
360
+
361
+ if success or stuck:
362
+ cy = title_h + n * STEP_H + NODE_H // 2
363
+ nx, ny = CX - NODE_W // 2, cy - NODE_H // 2
364
+ if success:
365
+ node_fill, node_stroke = '#002800', '#00e639'
366
+ node_text, node_col = '✓ QED — Goals accomplished!', '#00ff41'
367
+ else:
368
+ node_fill, node_stroke = '#201000', '#e6a817'
369
+ node_text, node_col = '⚠ Concluded: not provable as stated', '#f5c842'
370
+ out.append(
371
+ f'<rect x="{nx}" y="{ny}" width="{NODE_W}" height="{NODE_H}" '
372
+ f'rx="5" fill="{node_fill}" stroke="{node_stroke}" stroke-width="2"/>'
373
+ )
374
+ out.append(
375
+ f'<text x="{CX}" y="{cy+5}" text-anchor="middle" '
376
+ f'font-family="monospace" font-size="11" font-weight="bold" fill="{node_col}">'
377
+ f'{esc(node_text)}</text>'
378
+ )
379
+
380
+ out.append('</svg>')
381
+ return f'<div style="overflow-x:auto;padding:8px">{"".join(out)}</div>'
382
+
383
+
384
+ # ── Step walkthrough ──────────────────────────────────────────────────────────
385
+
386
+ def explain_tactic(tactic: str) -> str:
387
+ for key, explanation in TACTIC_EXPLANATIONS.items():
388
+ if tactic.strip().startswith(key):
389
+ return f"*`{key}` — {explanation}*"
390
+ return ""
391
+
392
+
393
+ def make_playground_url(theorem_stmt: str, tactics: list) -> str:
394
+ proof_lines = [f"{theorem_stmt} := by"] + [
395
+ f" {line}" for t in tactics for line in t.strip().split("\n")
396
+ ]
397
+ code = "\n".join(proof_lines)
398
+ return "https://live.lean-lang.org/#code=" + urllib.parse.quote(code)
399
+
400
+
401
+ def format_steps(steps: list, tactics: list, stuck: bool = False,
402
+ theorem_stmt: str = "") -> str:
403
+ if not steps:
404
+ return ""
405
+ out = ["### Agent loop: propose → verify → learn\n"]
406
+ for s in steps:
407
+ goal = s['goal']
408
+ chosen = s.get('chosen', '')
409
+ candidates = s.get('candidates', [])
410
+ status = s.get('status', '')
411
+ error = s.get('error', '')
412
+ step_num = s['step']
413
+
414
+ out.append(f"---\n**Step {step_num}** — current goal:")
415
+ out.append(f"```\n{goal}\n```")
416
+
417
+ if not candidates:
418
+ out.append("⚠️ *LLM endpoint warming up — no candidates available at this step*")
419
+ else:
420
+ rejected = [c for c in candidates if c != chosen]
421
+ out.append(f"\U0001f916 **LLM proposed:** `{'`, `'.join(candidates)}`")
422
+ for r in rejected:
423
+ out.append(f"- ❌ `{r}` — Lean kernel rejected")
424
+ if error and rejected:
425
+ short_err = error.replace('\n', ' ')[:120]
426
+ out.append(f"- \U0001f4e2 *Kernel error fed back to agent:* `{short_err}`")
427
+ if chosen and status != 'all_failed':
428
+ exp = explain_tactic(chosen)
429
+ out.append(f"- ✅ `{chosen}` — Lean kernel accepted")
430
+ if exp:
431
+ out.append(f" {exp}")
432
+ out.append(f"- *Result:* `{status}`")
433
+ elif status == 'all_failed':
434
+ out.append("- ❌ All candidates rejected — feeding errors back, trying next step")
435
+
436
+ out.append("")
437
+
438
+ if stuck:
439
+ out.append(
440
+ "---\n⚠️ **Search concluded** — the same goal state recurred with no progress.\n"
441
+ "The claim could not be proven. It may be mathematically false, "
442
+ "or require axioms and tactics outside the current mode."
443
+ )
444
+ elif tactics:
445
+ proof_lines = ["by"] + [f" {line}" for t in tactics for line in t.strip().split("\n")]
446
+ proof_block = "\n".join(proof_lines)
447
+ out.append("---\n### Complete proof\n")
448
+ out.append("```lean4")
449
+ out.append(proof_block)
450
+ out.append("```")
451
+ out.append("\n---\n### Verify it yourself")
452
+ if theorem_stmt:
453
+ url = make_playground_url(theorem_stmt, tactics)
454
+ out.append(
455
+ f"[**▶ Open in Lean 4 web playground ↗**]({url})\n\n"
456
+ "The proof is pre-filled and ready to run. "
457
+ "The kernel outputs **\"Goals accomplished!\"** or rejects it if anything is wrong. "
458
+ "**It cannot be convinced. It cannot be fooled.**"
459
+ )
460
+ else:
461
+ out.append(
462
+ "Paste the proof above into [live.lean-lang.org ↗](https://live.lean-lang.org/). "
463
+ "The kernel outputs **\"Goals accomplished!\"** — or rejects it if anything is wrong."
464
+ )
465
+
466
+ return "\n".join(out)
467
+
468
+
469
+ # ── Main proof handler ────────────────────────────────────────────────────────
470
+
471
+ def prove_theorem(theorem: str, max_steps: int, use_fallbacks: bool):
472
+ if not theorem.strip():
473
+ yield "Please enter a theorem statement.", "", ""
474
+ return
475
+
476
+ yield "⏳ Sending to proof agent on Modal…", "", ""
477
+
478
+ lookup = EXAMPLE_LOOKUP.get(theorem.strip())
479
+ english_desc = lookup[0] if lookup else ""
480
+
481
+ try:
482
+ resp = requests.post(
483
+ f"{MODAL_ENDPOINT}/prove",
484
+ json={
485
+ "theorem": theorem,
486
+ "max_steps": max_steps,
487
+ "use_fallbacks": use_fallbacks,
488
+ "show_reasoning": True, # always run live loop, skip cache read
489
+ },
490
+ timeout=280,
491
+ )
492
+ data = resp.json()
493
+ except requests.exceptions.Timeout:
494
+ yield "❌ Request timed out. Try a simpler theorem or fewer max steps.", "", ""
495
+ return
496
+ except Exception as e:
497
+ yield f"❌ Error contacting proof agent: {e}", "", ""
498
+ return
499
+
500
+ warmup_note = ""
501
+ msg = data.get("message", "")
502
+ if "warming up" in msg.lower() or "unavailable" in msg.lower():
503
+ warmup_note = "⚠️ LLM endpoint warming up (cold start) — proof attempted with fallback tactics only.\n\n"
504
+
505
+ success = data["success"]
506
+ stuck = data.get("stuck", False)
507
+
508
+ banner = build_verdict_banner(success, stuck, english_desc)
509
+ details = format_steps(
510
+ data["steps"], data["tactics"],
511
+ stuck=stuck, theorem_stmt=theorem.strip()
512
+ )
513
+ svg_html = build_proof_tree_svg(
514
+ data["steps"], data["tactics"], success, stuck=stuck, claim=english_desc
515
+ )
516
+ yield warmup_note + banner, details, svg_html
517
+
518
+
519
+ # ── UI ────────────────────────────────────────────────────────────────────────
520
+
521
+ _blocks_kwargs: dict = dict(title="Q.E.D", css=CUSTOM_CSS)
522
+ if _theme is not None:
523
+ _blocks_kwargs["theme"] = _theme
524
+
525
+ with gr.Blocks(**_blocks_kwargs) as demo:
526
+ gr.Markdown("""
527
+ # ⊢ Q.E.D
528
+ **∀ theorem → ∃ proof** — LLM-guided formal verification, powered by Modal.
529
+
530
+ Enter a theorem in Lean 4 syntax (∀ ∃ ¬ ∧ ∨ → ↔ ℕ ℤ α all supported).
531
+ The agent proposes tactics, Lean's kernel verifies each step, and kernel errors feed back into the next proposal.
532
+ Watch it **prove** a true theorem — or **correctly conclude** a false one is unprovable.
533
+ """)
534
+
535
+ with gr.Row():
536
+ with gr.Column(scale=2):
537
+ theorem_input = gr.Textbox(
538
+ label="Theorem statement",
539
+ placeholder="theorem my_thm : ∀ n : Nat, 0 + n = n",
540
+ value=EXAMPLES[0][0],
541
+ lines=3,
542
+ )
543
+ desc_display = gr.Markdown(
544
+ value=f"*{EXAMPLES[0][1]}*",
545
+ label="",
546
+ )
547
+ with gr.Row():
548
+ max_steps = gr.Slider(5, 30, value=20, step=1, label="Max steps")
549
+ use_fallbacks = gr.Checkbox(value=True, label="Use fallback tactics (ω, simp…)")
550
+ prove_btn = gr.Button("⊢ Prove", variant="primary")
551
+
552
+ with gr.Column(scale=1):
553
+ gr.Markdown("**Examples** — click to load\n\n*∀ provable ones first, then a false one ↓*")
554
+ for lean_stmt, english_desc, kind in EXAMPLES:
555
+ btn = gr.Button(english_desc, size="sm")
556
+ btn.click(
557
+ fn=lambda lean=lean_stmt, d=english_desc: (lean, f"*{d}*"),
558
+ outputs=[theorem_input, desc_display],
559
+ )
560
+
561
+ banner_out = gr.HTML(label="Verdict")
562
+ steps_out = gr.Markdown(label="Agent loop walkthrough")
563
+ tree_out = gr.HTML(label="Proof search tree")
564
+
565
+ prove_btn.click(
566
+ fn=prove_theorem,
567
+ inputs=[theorem_input, max_steps, use_fallbacks],
568
+ outputs=[banner_out, steps_out, tree_out],
569
+ )
570
+
571
+ demo.queue()
572
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ gradio==6.18.0
2
+ requests==2.34.2
3
+ modal==1.5.0
4
+ fastapi==0.136.3
5
+ uvicorn==0.49.0
6
+ lean-interact==0.11.4
7
+ pydantic==2.13.4
8
+ huggingface-hub==1.19.0