Coding assistants · Research feature

SpecForge: Recursive Self-Improvement for Coding Agents via Behavioral Specifications

The agent generates code from these specifications, runs it against verified tests, and revises the specifications based on failures.

Adapted from research by Yutong Cheng, Haifeng Chen, Peng Gao and colleagues.

arXiv preprint revision · 2026-10-11 · Attribution & reuse
In this article
Editorial illustration of linked workflow.

Editor’s introduction

The agent generates code from these specifications, runs it against verified tests, and revises the specifications based on failures. This process creates a self-improvement loop, but it faces a key challenge: output coupling, where improving one code component inadvertently breaks others due to interdependencies. The researchers introduce SpecForge, a framework that manages this complexity through state selection, dependency-aware refinement, and diversified failure exploration. The framework demonstrates stable progress across five backbone models, achieving a 94.9% solve rate with one model and outperforming baselines by 5.7 percentage points on average. The improved specifications also enhance the agent’s ability to perform tasks outside the loop, such as cross-language translation and new feature development. The evidence shows that specification refinement can lead to broader capability gains, though the study does not evaluate long-term stability beyond a few iterations or real-world deployment scenarios.

Introduction

Large language models are increasingly used as autonomous coding agents. Systems such as Cursor, Codex, and Claude Code can generate code, implement new features, and modify existing software with limited human intervention. Their effectiveness, however, depends heavily on how well they understand the behavior of the codebase they work with. This understanding is essential for tasks such as repository-level code generation, legacy system migration, cross-language reimplementation, and new-feature implementation. One way to provide such understanding is through behavioral specifications: natural-language code documentation that describes what individual program entities (e.g., functions, classes, and methods) do, including their inputs, outputs, and important behavioral constraints. Unlike traditional documentation intended primarily for human readers, these specifications serve as actionable knowledge that coding agents can use to generate and modify code. Importantly, because specifications are expressed in natural language, agents can also revise them based on feedback, creating an opportunity for self-improvement without changing the underlying language model.

This motivates specification-mediated recursive self-improvement (RSI), in which a coding agent iteratively improves its own behavioral specifications using feedback from code generation and execution, without modifying the underlying model weights. Starting from initial specifications, the agent generates code conditioned on these specifications alone and evaluates the generated implementations through unit tests. Test failures reveal missing or ambiguous behavioral information, which the agent uses to refine the specifications. The refined specifications then guide the next round of code generation, forming a recursive self-improvement loop. In our setting, the tests are automatically generated from the reference implementation and validated through execution, retaining only tests that pass. This provides reliable, execution-grounded feedback without requiring human annotations. Importantly, the objective is not to improve the reconstructed code itself, but to produce more accurate behavioral specifications. Their quality is measured not by readability or similarity to human-written documentation, but by whether an agent can reconstruct behaviorally correct code from them. The resulting specifications capture reusable knowledge of the existing codebase, which can support downstream tasks such as cross-language translation and new-feature implementation, even when no reference implementation of the desired output is available.

Despite its promise, specification-based RSI faces a fundamental challenge: program entities are not independent. Existing language-space optimization methods, such as MIPROv2, GEPA, and ACE, demonstrate that language models can improve their own context through iterative refinement and feedback. However, directly applying this approach to behavioral specifications is difficult because changes to one entity can affect the behavior of others. We refer to this phenomenon as output coupling. It arises in two ways. First, dependency coupling occurs when the correctness of a caller depends on the behavior of its callees. Refining a caller before its callees are correctly specified can therefore produce misleading feedback. Second, generation coupling occurs because a coding model may condition on the entire specification bundle, so modifying one specification can change how other entities are generated, even without direct dependencies. Consequently, an update that fixes one entity may break another, creating a whack-a-mole effect: improvements are repeatedly undone by subsequent refinements, and the optimization process may oscillate rather than converge. For recursive self-improvement to be effective, it must therefore address three requirements: preserving previous progress, respecting dependencies between entities, and handling noisy or incomplete feedback during refinement.

Setup

Benchmark. We evaluate SpecForge on DevEval+, a benchmark for evaluating behavioral specifications through code reconstruction and execution-based verification across modules with complex inter-entity dependencies. It consists of 20 Python modules, 247 entities, and 760 test cases. The modules are drawn from DevEval and supplemented with additional GitHub repositories to broaden domain coverage, including finance, biological analysis, and signal processing. DevEval+ is structurally nontrivial, with an average dependency depth of 4.2, making it a suitable testbed for studying output coupling under repository-scale generation (full details in Appendix H).

Across all methods, final performance is evaluated with ground-truth test suites that remain hidden from the search procedure. During optimization, methods receive only LLM-generated tests. Additional details on test generation appear in §J, while implementation details and prompts for all baselines are provided in §G. Additional experiments, such as the fidelity of the self-generated improvement signal (§E) and module-level case studies (§D), are included in the Appendix.

New Feature Implementation

Whereas cross-language translation evaluates specifications on re-implementing existing code in a different language, real-world development more often requires implementing new functionality atop an existing codebase, with specifications of the existing code as guidance. We therefore evaluate on SWE-Dev, a benchmark in which an LLM must implement new functions—specified by a Product Requirements Document (PRD)—within real open-source packages, validated against developer-written test suites.

Experimental Setup. We select 10 packages from SWE-Dev, comprising 27 feature-implementation instances (15 easy and 12 hard). For each package, we run all four methods on the existing source code to produce behavioral specifications of the current codebase; these specifications are then provided as context when the LLM implements new functions. We compare two conditions, which share the stubbed source and differ only in the accompanying text (Appendix I): (i) Spec+Source: stubs paired with the signature and docstring of each target function, plus the specifications of the existing codebase produced by each of the four methods; (ii) PRD+Source: stubs paired with the default PRD provided by the SWE-Dev benchmark. We report Pass@1 following SWE-Dev’s evaluation protocol, broken down by difficulty level.

Recursive Self-Improvement. Self-improving LLM systems differ first in the substrate into which an improvement is written. Weight-space methods write into model parameters: the model is fine-tuned on data it generated itself, on rewards derived from its own outputs, or on rewards from a grounded environment. The gain is amortized across tasks, but it cannot be read, diffed, or reverted. Context-space methods keep the weights frozen and write into the harness instead, through verbal self-refinement, prompt search and textual gradients, experience memory, skill and tool synthesis, or search over the whole scaffold; at the frontier, the procedure that performs the update is itself rewritten. The improvement signal ranges from the model’s own judgment to external verifiers such as tests, compilers, and environments. SpecForge is a context-space method with an execution-based improvement signal and a fixed update procedure. The key difficulty in such a recursive self-improvement loop is that behavioral specifications are inherently coupled through the code generated from them, so that an improvement to one can cause a global regression and make the iterative process oscillate.

Coding Agents. Coding is among the most rapidly advancing capabilities of LLM agents, in large part because code is executable, verifiable, and searchable: a candidate can be run, checked against tests, and improved by search. Agents such as Cursor, Codex, and Claude Code now resolve issues and implement features across entire repositories. The same property is carrying agents beyond conventional software, wherever the artifact can be expressed as a program or other interpretable text: games, explanatory videos rendered from animation code, 3D scenes written as Blender scripts, and symbolic music. SpecForge is complementary to these agents: it supplies behavioral specifications that a coding agent can condition on, which in our experiments improve cross-language translation and new-feature implementation (§4.5).

Code Documentation. Documentation generation has evolved from template-based heuristics through neural summarization to modern LLM-based repository-level approaches. RepoAgent extracts structural patterns from repositories to generate API references with hierarchical organization, while DocAgent employs retrieval-augmented generation to produce context-aware explanations grounded in relevant code snippets. Both optimize for subjective quality metrics—clarity, completeness, and helpfulness—evaluated through human assessment or proxy metrics like BLEU scores against reference documentation. These approaches uniformly assume documentation serves human developers and measure quality through readability heuristics rather than downstream task performance. See Appendix K for further related work.

Conclusion

We presented SpecForge, a multi-frontier tree search framework that makes specification-mediated self-improvement stable and compounding. A frozen coding agent improves by rewriting the behavioral specifications in its harness from the failures of the code it writes from them; unlike documentation written for human readers, a specification is judged only through the code it induces. Within this formulation, the central challenge is output coupling: because generated entities are behaviorally interdependent, locally beneficial refinements can trigger global regressions, rendering standard monolithic or sequential refinement unstable. SpecForge addresses this challenge through Pareto-guided frontier preservation, dependency-constrained entity selection, and error-diversified expansion, enabling stable progress under coupled search dynamics. Empirically, it consistently outperforms strong baselines on DevEval+, exhibits superior search efficiency and robustness, and produces specifications that improve downstream performance in both cross-language translation and new-feature implementation, indicating that what the loop improves is reusable knowledge of the codebase rather than a fit to the tests that guided it.

Why Multi-Frontier Search Escapes Certain Frontier-Local Optima

A central role of the Pareto archive in SpecForge is to prevent the search from collapsing onto a single refinement trajectory too early. We formalize this benefit through the notion of frontier-local optimality: a state may be locally saturated with respect to its currently eligible refinements, while another non-dominated state still exposes a different eligibility frontier from which progress remains possible.

The importance of this criterion is that it preserves states with complementary strengths across entities rather than only the current best state under a scalar score. Such states can induce different solved sets and therefore different eligibility frontiers.

This assumption states that one archived frontier may be saturated while another still contains a productive move. It is natural in our setting because eligibility is induced by the solved subset, and different trajectories typically solve different subsets of entities.

Construction of the signal

Test oracles are obtained by executing LLM-proposed inputs on the reference implementation to derive the expected outputs (§J); output correctness is therefore guaranteed by construction. The only residual imperfection lies in input quality: some generated inputs may be redundant, exercise overlapping code paths, or fail to cover critical edge cases. Error-diversified expansion (§3.3) is designed for precisely this kind of imperfection: by conditioning each child on a different subset of failing tests rather than on the full test set, it bounds the influence of any individual weak or redundant test.

Commercial Agents

We evaluate Cursor and Claude Code under four configurations: (1) Base: generate specifications for all entities in a single session; (2) +Topo: provide the dependency graph as context for one-shot specification generation; (3) +Test: prompt the agent to generate test cases from its specifications, then iteratively refine code until tests pass, with a budget of 50 manual action approvals (agents typically terminate before exhausting the budget); (4) +Topo+Test: combine both strategies. Cursor supports Gemini-2.5-Flash, Gemini-3.1-Pro, and Claude-4.5-Sonnet but not Qwen3-235B-A22B or GPT-4o; Claude Code only supports Claude models. Prompts are provided in Appendix F.6.

Prompt Optimization Methods

Critically, both methods optimize the specification bundle monolithically—they cannot attribute failures to individual entities or reason about inter-entity dependencies. This design choice is intentional: it evaluates whether state-of-the-art prompt optimization can succeed without the structural decomposition that SpecForge introduces.

From GitHub

To increase structural complexity and domain coverage, we collected 10 additional modules from open-source GitHub repositories: interpreter, croniter, peakutils, pyfaidx, lexer, schedule, patternpy, schema, parser, and streaming-indicators. The data collection process consists of two phases: repository selection and quality assurance.

In the quality assurance phase, two authors independently set up the environment for each candidate repository and executed its test suite to verify functionality. Following this sanity check, annotators reviewed each test case for correctness and quality, verifying that tests accurately capture intended behavior rather than implementation quirks. Repositories were included only with unanimous agreement on test suite quality.

How the PRD is generated

The PRD shipped with each instance is written by GPT-4o in two parts. A module-level description is synthesized from the test file. A function-level description of each target is obtained by augmenting the target’s original docstring with implementation-level details, with the prompt conditioned on the full code of its file, including the target function itself. The PRD concatenates the module description with, for each target, its signature, the augmented docstring, and a list of related functions (DEPENDENCIES). The PRD is therefore derived from the tests and the reference implementation, and it describes only the functions to be implemented: existing functions that the targets call appear in the dependency list by name only, without any description of their behavior.

Specification generation and masking

Each method generates specifications on the complete package, so that the codebase is executable, as it is in real development before a feature is added, and every entity has a reference behavior from which SpecForge can derive test oracles. Deleting the target functions from a complete module beforehand would leave the module unable to run, since the remaining code still references them, which would rule out execution-based optimization methods such as SpecForge. Before the implementation step, we remove the specifications of the target functions. No method observes the instance’s evaluation test file.

Additional results analysis

The two conditions trade task-specific information against codebase-level information. The PRD describes the target functions in detail but says nothing about the behavior of the existing code they build on; the Spec+Source conditions describe the target functions only minimally but describe the whole existing module. New features are rarely self-contained: SWE-Dev targets call into existing functions, constants, and exception types, and a correct implementation must use them exactly as they behave. For example, in the vulture configuration task, the PRD requires _check_input_config to validate values against DEFAULTS and to raise InputError, but never states which keys DEFAULTS contains or how InputError is constructed. We refer to this missing knowledge as the semantic gap of the PRD. The experiment therefore asks whether a better semantic understanding of the existing module lets an agent implement a high-quality feature from only the minimal information that defines it. Because the PRD condition receives strictly more target-specific information, derived from the reference implementation, the comparison is conservative for the Spec+Source conditions.

Overview

SpecForge operates as a self-improving framework where the search is guided by LLM-generated test cases rather than ground-truth tests. This design choice reflects realistic deployment scenarios where comprehensive test suites may not exist. The key insight is that even imperfect tests provide valuable diagnostic signals—test failures reveal knowledge gaps in the specifications, enabling targeted refinement.

Two additional filters are applied post-validation: (i) tests that reach the target entity only via transitive calls to other functions are discarded, ensuring each retained test directly exercises its target; and (ii) tests with identical normalized inputs and assertions are deduplicated. This ensures test correctness by construction: every retained test is consistent with the reference implementation and contributes a distinct diagnostic signal.

Behavioral specifications as vertical knowledge

Behavioral specifications can be viewed as a form of vertical knowledge: repository-specific facts about what each program entity does, which are absent from a model’s weights and must be supplied to it at inference time. A broad line of work studies how such domain knowledge is acquired, structured, and used by LLMs. In cyber threat intelligence (CTI), LLMs have been used to construct knowledge graphs from unstructured threat reports, retrieval-augmented LLMs have been benchmarked over heterogeneous CTI sources, and CTI corpora have been organized into agent-native scaffolds for direct consumption by agents. Related efforts parse hybrid system logs into structured templates and translate natural language into first-order logic that symbolic reasoners can consume, and documentation optimized as repository-specific playbooks for coding agents brings this view to software. These works share the premise that knowledge should be represented in the form its consumer can use. They differ from SpecForge in how the representation is judged and improved: knowledge graphs, retrieval corpora, and parsers are typically constructed once and evaluated by extraction or answer accuracy, whereas SpecForge treats the knowledge artifact itself as the object of recursive improvement, judges it by the behavior it induces in the consuming agent, and revises it until that behavior is verified correct.