From Base Model to AI Agent: Building Long-Horizon Coding Capabilities
A product-neutral technical guide to building long-horizon agentic coding capabilities, covering base-model selection, continual pre-training, verifiable-reward reinforcement learning, context compression and self-summarization, multi-dimensional evaluation, engineering trade-offs, transparency, and a deployment checklist.
1. Introduction: Coding Assistants Are Moving from “Completion” to “Task Execution”
Over the past two years, the capability boundary of AI coding assistants has expanded significantly. Early products focused on line-level or function-level completion and single-turn Q&A, with value centered on “writing faster.” Today, developers expect more complete delivery: understanding an issue description, locating relevant modules in a codebase, making changes across multiple files, adding or running tests, and iterating based on errors until the task actually converges. This capability is commonly called agentic coding.
One coding tool released the first version of its in-house coding model in fall 2025, emphasizing a high generation speed of 250 tokens per second. In spring 2026, its next version claimed a score of 61.7 on a terminal-task benchmark, surpassing a closed-source flagship model, with support for a 200K-token context and the ability to autonomously complete complex tasks involving hundreds of steps. However, developers soon found that the model identifier pointed to an open-source base model. The company behind the base model then confirmed a commercial licensing partnership. The coding tool’s co-founder publicly apologized for not disclosing the base model’s source at launch, emphasized that large-scale reinforcement learning and other post-training had been performed on top of the base model, and later released a technical report detailing the training process. Early in the incident, the first version was observed to have apparent traces such as Chinese-language comments mixed into generated code, prompting outside speculation about its technical provenance.
This incident highlights two points:
- Coding capability involves multiple layers, including data, licensing, and disclosure; provenance must be clear and traceable.
- Whether a coding assistant can handle long-horizon tasks ultimately depends on how base-model selection, continual pre-training, reinforcement learning, and the evaluation system work together—not on a single number.
This article does not target any specific product. Instead, it abstracts these stages into a reusable technical method, helping readers build a complete understanding, evaluate technical approaches, or guide in-house development.
2. Problem Definition: What Is “Long-Horizon Agentic Coding”?
2.1 From Single-Step Generation to Closed-Loop Execution
| Dimension | Traditional completion/chat assistant | Agentic coding assistant |
|---|---|---|
| Interaction unit | One completion or one Q&A turn | A complete task (e.g., fixing an issue) |
| Context | Current file and limited context | Repository structure, dependencies, issue, historical trajectory |
| Execution ability | Generally does not execute code | Reads/writes files, runs commands, executes tests |
| Feedback source | User confirmation | Compiler, tests, static checks, user instructions |
| Key metrics | Acceptance rate, first-token latency, tokens per second | Task success rate, average steps, token cost, unintended-edit rate |
| Failure modes | Code errors, hallucinated APIs | Goal drift, repeated trial and error, out-of-scope edits |
“Long-horizon” usually means a task requires dozens to hundreds of model calls and spans multiple files and tool operations.
2.2 Why Long-Horizon Tasks Are Harder
- Locating information in long contexts: Task information is often scattered across multiple files and several tool outputs; relevant clues may appear in the middle of the context.
- State maintenance: As steps increase, early constraints (e.g., “do not modify public interfaces”) can be gradually forgotten.
- Limited context budget: Logs and file contents returned by tools accumulate quickly, while the context window and inference cost have limits.
- Errors accumulate: One incorrect change can trigger a chain of consequences. Without effective verification and rollback mechanisms, errors can be amplified repeatedly.
2.3 Division of Two Capability Layers
Long-horizon agentic coding naturally contains two kinds of requirements:
- Completion layer: requires low latency and high throughput, directly serving the developer’s coding experience;
- Agent core layer: requires planning, tool calling, long-range consistency, and self-correction.
Engineering practice usually advances both tracks:
- use a smaller specialized model for completion;
- use a model with long-context and tool-calling capabilities for agent tasks.
The two types of models can come from different training configurations of the same base model, or from models of different scales.
3. Technical Route One: Base-Model Selection and Continual Pre-Training
3.1 Four Common Technical Routes
- End-to-end training of a specialized model: fully in-house, with the highest data and compute barriers and a long iteration cycle;
- Direct use of a general model: leveraging a general model’s coding and reasoning capabilities together with prompt engineering and a tool layer; fast to start, but usually needs additional adaptation for repository-level and long-horizon tasks;
- Continual pre-training and reinforcement learning on an open-source base model: achieving domain-specific capability at controllable cost, and a common industry practice;
- Hybrid approach: use a small model for completion and deeply train the agent core layer based on an open-source base model, balancing cost and effectiveness.
One common misunderstanding needs clarification: the same base model does not imply the same capability. The base model determines the starting point; domain data and training methods determine the final level.
3.2 Key Dimensions for Base-Model Selection
| Dimension | Focus | Evaluation method |
|---|---|---|
| Code capability baseline | Multilingual coverage, algorithm and engineering code quality | Public code benchmarks + internal code sets |
| Instruction following | Ability to consistently follow format and behavior constraints | Constraint-following test sets |
| Tool calling | Accuracy and format stability of function-call arguments | Simulated tool-calling scenarios |
| Context capability | Information retrieval and reasoning in long documents | Long-context retrieval and multi-hop reasoning tests |
| Inference efficiency | Generation speed, concurrency, hardware compatibility | Load testing under typical workloads |
| Vocabulary efficiency | Compression rate of code text | Tokens per unit of code length |
| License | Commercial terms, attribution and derivative-work obligations | Legal review |
Two additional points:
- License is a hard gate. If the situation described in the source material is accurate—that some tools achieved significant capability gains on top of a base model through large-scale reinforcement learning—such practices still typically produce derivative works under most mainstream open-source licenses. Whether the resulting compliance obligations can be met must be confirmed at the selection stage.
- Architecture affects serving cost. Mixture-of-Experts (MoE) architectures usually activate only part of the expert parameters, allowing large parameter capacity to be maintained while controlling inference computation. They are therefore often used as the base architecture for coding models.
3.3 Continual Pre-Training: Helping the Base Model “Read the Repository”
Domain adaptation is not simple fine-tuning. Continual pre-training means continuing to train an existing base model so that it adapts to the data distribution of the target domain. For coding scenarios, the key is to help the model understand repository-level context:
- multiple files in the same directory;
- import dependencies among files;
- multiple related locations corresponding to the same issue.
At the same time, the technical report mentioned in the source material is a typical form of disclosing such a process: which base model was used, how continual pre-training was performed, and how reinforcement learning was conducted. This kind of transparency is worth learning from across the industry.
# Example: construct repository-level training samples (pseudocode)def build_repo_sample(repo, target_file, cursor, max_tokens):deps = repo.dependency_graph.dependencies_of(target_file) # Static analysis dependenciessegments = [read(target_file)]segments += [read(f) for f in repo.same_dir_files(target_file)]segments += [read(f) for f in deps if f != target_file]text = f"<repo>{tree_stub(repo)}</repo>\n" + "\n".join(segments)text += f"<file name='{target_file}'>\n{cursor.before}\n<CURSOR>\n{cursor.after}\n"return truncate(text, max_tokens) # When too long, truncate by relevance
Several training configuration points also need attention:
- The learning rate is generally significantly lower than in pre-training, and the number of training steps is limited, to avoid erasing the base model’s general capabilities;
- A certain proportion of natural-language data should be mixed in to mitigate catastrophic forgetting;
- Data quality should be ensured through deduplication, quality filtering, and decontamination (removing samples that overlap with public evaluation sets).
4. Technical Route Two: Large-Scale Reinforcement Learning and “Self-Summarization”
4.1 From “Writing Correct Code” to “Completing Tasks”
On top of the base model, reinforcement learning addresses task-level alignment: the model should not only write code, but also plan, execute, and correct itself based on feedback in real environments, while staying committed to the goal. The most representative approach is centered on verifiable rewards:
- reward signals come from compile results, unit-test pass rates, static-check results, and other signals that can be judged automatically and are hard to reinterpret subjectively;
- these signals are objective and can be collected in parallel at scale, so training can be scaled.
4.2 Key Points in Reward Function Design
Reward design is where reward hacking most often appears. Common loopholes and countermeasures are as follows:
| Loophole | Behavior | Countermeasure |
|---|---|---|
| Tampering with tests | Deleting or relaxing assertions | Protected-path checks; use independent copies during evaluation |
| Hard-coding return values | Special-casing test cases | Hidden tests; randomized inputs |
| Excessive modification | Rewriting unrelated files to “get lucky” | Change-scope penalty |
| Repeated trial and error | Repeating the same command | Repeated-action penalty |
| Hanging process | Starting a service and not exiting | Command timeout and process cleanup |
# Example: scoring function based on verifiable rewards (pseudocode)PROTECTED = ("tests/", "conftest.py", "pytest.ini")def compute_reward(sandbox, task, candidate_patch):changed = sandbox.apply_patch(candidate_patch)# 1) Protected-path check: prohibit changes to tests and evaluation configif any(p.startswith(PROTECTED) for p in changed):return -1.0, "modified_tests"# 2) Build and type checkif not sandbox.build_ok():return -1.0, "build_failed"# 3) Public tests + independent hidden private testspublic = sandbox.run_tests(task.public_tests)private = sandbox.run_tests(task.hidden_tests)# 4) Over-editing penalty (e.g., changed lines significantly exceed expectation)over_edit = max(0, sandbox.diff_lines() - task.expected_lines) / 100reward = 0.3 * public + 1.0 * private - 0.2 * min(over_edit, 1.0)return reward, {"public": public, "private": private}
On this basis, many teams also add process rewards, for example giving positive signals for behaviors such as “reading relevant files before making changes” and “advancing step by step according to the plan,” to alleviate the sparse-reward problem in long trajectories.
4.3 Three Forms of Context Compression
In long-horizon tasks, context is quickly filled by tool outputs, so a trade-off must be made between “retaining key information” and “controlling context size.” Common compression forms include:
- Sliding window: retain the most recent few turns; simple to implement, but early critical constraints can be lost;
- Hierarchical summarization: compress earlier conversation into summaries; a typical approach is to keep recent original text and roll up earlier content into summaries;
- Self-summarization: the model proactively distills and maintains structured “task notes” at key points, serving as a portable state carrier.
4.4 “Self-Summarization”: A Training Method for Long-Context Capability
“Self-summarization” is a reinforcement-learning technique mentioned in the source material for optimizing long-context tasks. The idea can be understood as follows:
- Insert summarization points into the trajectory. When the context approaches a threshold, or when a stage goal is completed, the model is asked to output structured notes, such as the current goal, completed steps, key findings, open questions, and next-step plan.
- Summarization actions are also subject to reward checks. During training, the compressed context is used to continue the task; if the task ultimately succeeds, this summarization receives a positive reward. The model gradually learns “what to keep and what to discard.” Signals for measuring summarization quality can be specific:
- whether the model can still accurately answer early constraints after compression;
- whether key information has been omitted;
- whether subsequent tasks can be completed smoothly.
- Constraint injection during online execution. At runtime, key constraints such as “do not modify public interfaces” and “keep existing error codes” are continuously injected into the system prompt, and the model is given a structured to-do list tool, so that critical state does not rely solely on the model’s memory.
This is consistent with the “to-do list + context compression” mechanism commonly used by mainstream coding agents such as Claude Code and Cursor, and can be viewed as engineering practice and training methods mutually corroborating each other.
# Example: self-summarization points in a trajectory (pseudocode)NOTE_SCHEMA = {"goal": "string", "done": ["string"], "findings": ["string"],"open_questions": ["string"], "next_steps": ["string"],}def maybe_compress(trajectory, budget_ratio=0.8):if trajectory.tokens() < trajectory.budget * budget_ratio:returnnote = model.generate( # Summarize at this node: output structured notesmessages=trajectory.messages + [{"role": "user","content": f"Please output the current task notes in JSON format: {json.dumps(NOTE_SCHEMA)}",}],response_format=NOTE_SCHEMA,)trajectory.reset(system_constraints + [as_message(note)])trajectory.add_tool("todo_write", note["next_steps"]) # Sync to-do list
5. Evaluation System: Replacing a Single Score with Multiple Dimensions
5.1 Multi-Dimensional Benchmarks
| Evaluation dimension | Typical task | Main focus |
|---|---|---|
| Code generation | Complete implementation based on function signatures and docs | Single-file correctness |
| Issue fixing | Submit a patch given an issue and a repository | Localization ability, correctness of changes, change scope |
| Terminal operations | Complete build, debugging, and other tasks in a command-line environment | Command construction, error recovery, tool calling |
| Tool calling | Complete workflows with multiple tools | Argument accuracy, format stability |
| Long context | Retrieve and reason across multiple files | Long-distance dependencies and retention of key constraints |
The terminal-task benchmark mentioned in the source material usually requires an agent to perform configuration, debugging, and build tasks in an isolated environment by executing shell commands, with scores based on test pass rates. Because the environment is controllable and results can be judged automatically, this type of benchmark has become an important reference for measuring an agent’s “hands-on” ability.
5.2 How to Interpret a Score Like 61.7
Take 61.7 as an example: it indicates that the model’s performance on this type of terminal task is already in the leading tier of the industry. However, interpreting a single score requires caution:
- Benchmarks iterate: new versions are usually harder, and scores across versions are not directly comparable;
- Task distribution is biased: benchmark tasks may not cover an enterprise’s technology stack, frameworks, and coding standards;
- Optimization bias exists: overlap between training and evaluation can inflate scores;
- Environment differences are significant: whether dependencies can be installed and whether the network is available can affect results.
5.3 Internal Evaluation Sets: An Irreplaceable Part
The most reliable approach for enterprises is to build their own evaluation sets. Recommended components include:
- Representative tasks: tasks drawn from a real requirements management system with clear acceptance criteria;
- Independent hidden cases: used only for evaluation, not for training;
- Category statistics: separately measured by language, module, and task type (bug fix, feature addition, refactoring, migration);
- Contamination prevention: periodically rotate tasks to avoid overfitting caused by long-term repetition.
6. Engineering Implementation: Latency, Cost, Security, and Observability
6.1 Latency and Throughput
- In completion scenarios, first-token latency and output speed directly determine the feel. The “250 tokens per second” positioning in the source material shows that generation speed has become a core experience metric for coding models.
- In agent scenarios, end-to-end duration matters more. It equals per-step generation time multiplied by total steps. Reducing invalid steps and reducing generation time per step are equally important.
- Common optimization methods include increasing batch concurrency, prefix cache reuse (the same system prompt and file content need not be recomputed), speculative decoding, and other inference acceleration techniques. In published data, batch inference throughput should be clearly distinguished from interactive generation speed.
6.2 Cost Model
In long-horizon tasks, input tokens often account for the majority: each round must carry the system prompt, task notes, and tool-returned content again. The focus of cost optimization is therefore:
- streamline and stabilize the system prompt to hit the cache;
- replace raw logs with structured notes;
- delegate large-file retrieval to a retrieval tool rather than stuffing everything into the context at once.
6.3 Security and Permissions
| Risk | Description | Countermeasure |
|---|---|---|
| Accidental data deletion | Agent executes destructive commands | Disable high-risk commands by default; require human confirmation before execution |
| Out-of-scope modification | Modifies files unrelated to the task | Restrict writable directories; validate change scope |
| Secret leakage | Reads or outputs credential files | Intercept sensitive paths; perform secret scanning before output |
| Supply-chain risk | Introduces dependencies of unknown origin | Dependency allowlists and version pinning |
| Sandbox escape | Untrusted code affects the host environment | Container/microVM isolation; restrict network egress |
6.4 Observability and Iteration
Every agent run should record the complete trajectory, including tool calls, time spent, token consumption, and results at each step. On this basis, build a metrics dashboard:
- monitor success rate, average steps, timeout rate, and per-task cost;
- perform attribution analysis on failed trajectories, classifying them as localization errors, editing errors, insufficient verification, context loss, and so on;
- feed attribution results back into training, selecting difficult samples for reinforcement learning.
A usable evaluation scheduling skeleton is as follows:
# Example: evaluation scheduling skeleton (pseudocode)def run_eval(model, tasks, sandbox_factory, max_steps=50):records = []for task in tasks: # Can be replaced by a concurrent task queue in practicesandbox = sandbox_factory() # One isolated environment per tasktrajectory = []for step in range(max_steps):action = model.next_action(trajectory, task)result = sandbox.execute(action) # Tool execution and observationtrajectory.append((action, result))if result.done or result.failed:breakreward, detail = grade(sandbox, task) # Score with independent hidden casesrecords.append({"id": task.id, "reward": reward, "steps": step + 1, **detail})sandbox.destroy()return summarize(records) # Success rate, average steps, cost, etc.
6.5 Platform Support
Building such capabilities often involves multiple pipelines:
- data cleaning and corpus management;
- continual pre-training and reinforcement learning;
- sandboxed evaluation execution;
- model inference serving;
- trajectory log analysis, monitoring, and alerting.
Enterprises can leverage general cloud capabilities to reduce infrastructure burden. For example, the source material notes that Baidu AI Cloud and other cloud platforms offer corresponding products such as ML platforms, container services, object storage, log services, and monitoring/alerting. When selecting, focus on:
- heterogeneous compute scheduling;
- task isolation;
- elastic scaling;
- end-to-end observability.
7. Transparency and Compliance: The Last Mile of Technical Provenance
The controversy in the source material reminds practitioners that disclosing the provenance of model capabilities is itself part of engineering delivery.
- Clarify the base model and training methods. In model cards, technical reports, or release notes, state the base model, license, summary of continual pre-training and reinforcement-learning methods, evaluation results, and known limitations.
- Distinguish model IDs from identity information. Model IDs are often determined by the deployment framework or service registration information and do not directly equal identity information. But outsiders may easily associate the two; rather than explaining defensively later, it is better to explain proactively.
- Check for identifiable traces. Specific-language comments, unique naming habits, and other elements mixed into generated code can become clues for outsiders to infer provenance. Before release, perform normalization checks; more importantly, ensure clear data provenance through training-data governance.
- Ensure license obligations can be fulfilled. Derivative models need to retain copyright notices and license texts, and publish model modification notes corresponding to the source code (model weights released as source code can usually constitute “corresponding source code”). Also note that some open-source licenses have specific provisions on whether interactive output contains AI-generated content.
- Avoid improper comparisons. When citing third-party benchmark scores in marketing materials, state the benchmark version, evaluation conditions, and comparison targets, and avoid out-of-context claims.
8. Deployment Checklist
- Base-model license has passed legal review; commercial use and derivative-work obligations are clear
- Training corpus has completed deduplication, decontamination, and provenance recording
- Continual pre-training mixes in general-purpose data to prevent catastrophic forgetting
- Reward function includes protected-path checks and hidden tests
- Change-scope penalty and repeated-action penalty are configured
- Context compression is implemented, and key constraints are continuously injected
- Internal evaluation set is isolated from training tasks and periodically rotated
- Completion layer and agent layer have separate latency and cost targets
- Sandbox isolation, dangerous-command interception, and secret scanning are ready
- End-to-end trajectory logs and monitoring/alerting are integrated
- Model card and release materials fully disclose base model, methods, and limitations
9. Conclusion
In discussions of long-horizon agentic coding, several eye-catching numbers naturally draw attention. But what truly determines whether a coding model can handle long-horizon tasks is a complete technical chain:
- choose a base model with the right license and capability match;
- use continual pre-training to help the model read the repository;
- align task goals with large-scale reinforcement learning based on verifiable rewards;
- manage context through self-summarization and similar methods;
- continuously improve through multi-dimensional evaluation and complete observability;
- and earn trust through transparent disclosure.
If any link is missing, “completing tasks involving hundreds of steps” remains at the demo level. For teams that want to build such capabilities, rather than chasing a single leaderboard score, it is better to focus on real business scenarios and gradually strengthen every link in this chain.
