Lean4Agent: Formal Modeling and Verification for Agent Workflow and Trajectory

Ruida Wang, Jerry Huang, Pengcheng Wang, Xuanqing Liu, Luyang Kong, Tong Zhang

TL;DR

Just as mathematicians invented formal proof assistants because natural language gets dangerously slippery over long proofs, multi-step AI agents desperately need a "compiler" for their logic. Lean4Agent brings the Lean4 theorem prover to AI workflows—mathematically catching subtle logical flaws before an agent runs a single token, and pinpointing the exact step where things broke when a run fails so the agent can systematically fix its own playbook.

What Problem Does This Paper Address?

Building an LLM agent to handle long-horizon tasks—like resolving complex GitHub issues—feels a bit like writing software without a compiler. You string together natural language prompts, loops, and tool calls, cross your fingers, and hit run. Because natural language is ambiguous, errors compound quietly over dozens of steps.

Existing ways to verify agents are fragmented. Asking another LLM to judge an output ("LLM-as-judge") is prone to hallucinations and overconfidence. Meanwhile, traditional formal checks—like temporal logic or SMT solvers—lack the expressiveness to handle complex, data-dependent higher-order reasoning. Until now, there hasn't been a unified mathematical framework to verify both an agent's static blueprint (its workflow) and its actual runtime behavior (its trajectory).

Methods

The authors turn to Lean4, an expressive formal language based on dependent type theory (where types can depend on actual values, allowing rich mathematical specifications). Their framework, Lean4Agent, has two core engines:

Figure 1: Lean4Agent Framework: The Lean4Agent framework consists of two main components. (a) FormalAgentLib is a three-layer Lean4 library for formally modeling and verifying agent behaviors. Layer 1 verifies the structural correctness of the workflow through a workflow graph. Layer 2 develops a predicate (pred.) system to model pre- and post-conditions of agent executions and verify the semantic self-consistency using LLMExec assumptions. Layer 3 localizes the violated step in the workflow by applying Lean, external programs, and LLM-as-judge to check the execution trajectory. (b) LeanEvolve uses verification results to refine workflows, and it builds formal-guided workflow evolution with the pure-LLM evolve add-on to further enhance its capabilities.
  1. FormalAgentLib (The Verifier): An extensible three-layer Lean4 library:
  2. Layer 1 (Structural): Acts like a basic compiler, checking graph reachability and ensuring variables aren't read before they are written.
  3. Layer 2 (Static Semantic): Translates natural language instructions into formal pre- and post-conditions (Hoare-style logic contracts) using an LLM annotator. Assuming an LLM can execute single short steps locally (LLMExec), Lean4 proves whether the overall multi-step workflow is semantically self-contained—including invisible "implicit" variables like conversation history.
  4. Layer 3 (Trajectory): Inspects actual runtime logs against those step-level contracts—using Lean propositions, Python validators, and LLM judges—to localize the exact step where a failure occurred.
  5. LeanEvolve (The Debugger): When a verified workflow still fails a real-world task, LeanEvolve uses Layer 3's localized diagnostics (plus environment feedback like unit test errors) to surgically rewrite the flawed step in the workflow. For tasks allowing multiple attempts, it pairs this formal-guided repair with a "pure-LLM" rewrite mode for broader, creative exploration.

Datasets

The authors didn't introduce new benchmarks, instead selecting subsets of two existing datasets to test contrasting agent skills across five models (GPT-5.2, GLM-5, Kimi-K2.5, Gemma-4-31B, and Qwen-3.5-27B):

  • SWE-Bench-Verified (50 hard problems): Real-world GitHub issues that take human engineers over an hour to solve, testing LLM-intensive exploration and coding.
  • ELAIP-Bench (100 problems): Expert-level multiple-choice questions from recent AI papers, testing workflow-intensive systematic reading and evidence retrieval.

Key Insights and Ideas

  • Catching invisible context bugs before deployment: FormalAgentLib catches subtle design flaws humans easily miss. For instance, it flagged a software workflow where context-isolated steps tried to reference evidence from prior conversational turns that wasn't actually passed along. In paper-reading workflows, graph-level predicates caught "anchoring bias"—where evaluating multiple-choice options sequentially in the same context polluted later judgments. Removing graph-level predicates caused 13 out of 21 defective workflows on ELAIP-Bench to slip through undetected!
  • Smaller models lean harder on good blueprints: Formal workflow verification helped across the board, but smaller models saw massive jumps (Gemma-4-31B jumped 27.33% on SWE-Bench when using verified workflows vs. unverified ones), showing weaker agents are heavily sensitive to structural and semantic guardrails.
  • Imperfect translators still build solid proofs: Having an LLM translate messy English steps into formal Lean predicates had a low 2.47% error rate across 1,460 annotations. Crucially, manually fixing all 36 errors changed zero workflow-level pass/fail verdicts—mostly because local annotation quirks get caught or absorbed by global formal propagation.

Key Results

  • Static Verification Pays Off: Workflows passing Layer-2 verification outperformed failing ones by an average of 14.80% on SWE-Bench and 9.07% on ELAIP-Bench (11.94% overall average).
  • Surgical Self-Improvement: Adding LeanEvolve boosted verified SWE-Bench accuracy by an additional 7.47% on average across all five models (e.g., lifting GPT-5.2 to 70.67% and Qwen-3.5-27B by +10.67%).
  • Formal Guidance Beats Blind Rewriting: On ELAIP-Bench failed trajectories, formal-guided evolution solved 7.00% more cases on average than pure-LLM workflow rewriting, proving that pinpointing the exact broken contract beats guessing which prompt to tweak.

Limitations and Future Work

Passing static verification doesn't guarantee an agent will always get the right answer—only that its blueprint is logically self-contained under local execution assumptions. Furthermore, properties outside Lean's decidable core (like checking live URLs or vague natural language variables) still fall back on Python scripts and LLM-as-judge modules at runtime, and high API costs prevented full evaluation on models like Claude-Opus-4.6. Looking ahead, the authors envision using Lean4Agent's formal feedback loops as a foundation for training verifiable, self-improving autonomous agents.

Summary updated

BibTeX
@inproceedings{wang2026lean,
  author = {Ruida WANG and Jerry Huang and Pengcheng Wang and Xuanqing Liu and Luyang Kong and Tong Zhang},
  title = {{Lean4Agent: Formal Modeling and Verification for Agent Workflow and Trajectory}},
  booktitle = {Advances in Neural Information Processing Systems},
  year = {2026},
  url = {https://openreview.net/forum?id=HBViYASFJz},
}
Figure