AI Agent Autonomous Debugging and PR Submission: A Technical Practice
This article explores how to build an AI agent that autonomously debugs issues in real repositories and submits pull requests that pass tests. It covers task tiering across model capability levels, a seven-stage closed-loop workflow with budget constraints, evaluation approaches that weigh both pass rate and cost, reliability guardrails such as sandboxing and evidence trails, and ways to integrate agents into existing CI/CD pipelines. Readers will find practical guidance on task cards, escalation strategies, and observability for turning autonomous repair into a stable engineering capability.
1. Background: Why “Being Able to Write Code” Is Not the Same as “Delivering a Fix”
In the daily rhythm of software development, fixing defects is rarely the hardest coding task, but it is often the most context-consuming one. Developers must first locate the relevant modules in the repository, understand the historical design intent, reproduce the issue, form a hypothesis, validate it, add tests, and finally submit the change. Most of the real time cost goes into “understanding and validation” rather than typing.
Over the past couple of years, the capability boundary of AI coding tools has moved from “completing a single line of code” to “executing multi-step operations in a real repository.” As a result, the industry has seen an agent-centric programming paradigm emerge: the model no longer just outputs snippets, but is placed inside a loop where it can read files, execute commands, run tests, observe results, and iterate. This kind of loop is commonly called an Agent Loop, and its key characteristics are visible state, rollback-able actions, and measurable results.
It is worth emphasizing that the criteria for evaluating this capability are changing. In the past we only looked at whether the “final answer was correct”; now we care more about three things: task completion rate, the resource cost required to complete a single task, and whether the output can go directly into the existing development workflow (for example, whether it can pass the CI pipeline). Together, these three determine whether an agent can move from “demo” to “daily use.”
2. The Engineering Value of Model Tiering: Allocating Compute by Task Difficulty and Call Frequency
In real-world adoption, a common mistake is “using the strongest model for every task.” A more mature approach is to establish a task-tiering strategy that routes work of different difficulty and frequency to models with different capability levels and cost structures. This tiering typically includes three roles:
- Flagship tier: aimed at the highest-difficulty, research-oriented, exploratory tasks, such as algorithm validation, complex performance bottleneck analysis, and cross-system architecture reasoning. These tasks are called infrequently, but each call carries high value.
- Mid-tier: aimed at agentic coding, computer operation, and high-frequency professional work, suitable for scenarios that require repeated calls, long loops, and multi-turn tool use. It is the workhorse of day-to-day development automation.
- Lightweight tier: aimed at short tasks such as format conversion, comment generation, simple classification, and log summarization, emphasizing throughput and response speed.
The value of tiering is not just saving money, but keeping the “cost of failure” within an acceptable range. In long-loop tasks, a single wrong hypothesis can lead to dozens of wasted tool calls; putting these tasks on a tier with lower per-call cost that has been optimized for agent loops noticeably improves the overall input-output ratio. In engineering practice, this is usually paired with a “prompt caching” mechanism: repeatedly used content such as system prompts, repository conventions, and long context is cached and reused, further reducing the marginal cost of each call.
3. Closed-Loop Design: Seven Stages of Autonomous Agent Debugging
To make an agent truly “diagnose and fix autonomously,” you need to break the process into observable stages and set exit conditions for each one.
- Task intake and constraint fixing. Write the defect description, reproduction steps, and acceptance criteria into a structured task card, making explicit the “directories that must not be modified,” the “test suite that must pass,” and the “code style constraints.”
- Repository context construction. Retrieve relevant files, call chains, configuration, and dependencies to generate a compact context package, rather than stuffing the entire repository into the window.
- Reproduction and observation. Run a minimal reproduction script, collect logs, stack traces, and monitoring metrics, and form a comparable “issue fingerprint.”
- Hypothesis generation and ranking. Have the model output multiple candidate root causes and rank them by “verification cost,” validating the cheapest hypothesis first.
- Change implementation. Modify code with a minimal-change principle, avoiding opportunistic refactoring, so the diff stays readable and reviewable.
- Validation and regression. Run targeted tests first, then regression tests over the affected scope; on failure, loop back to step 4.
- Submission and delivery. Generate a change description, impact analysis, and test evidence, then let the pipeline decide whether it passes after submission.
A sample task card structure can be written as:
task:goal: "Fix the exception thrown when a paginated query returns an empty result"constraints:- "Do not change public interface signatures"- "Keep the existing log format"acceptance:- "All targeted test cases pass"- "Regression test cases for related modules pass"budget:max_iterations: 12max_tool_calls: 80
The budget field is critical. Without a budget, an autonomous loop easily falls into a state of “repeated trial and error without converging,” wasting resources and slowing delivery.
4. Evaluation Perspective: From “Score” to “Score + Cost”
Agent benchmarks in the industry are making cost a first-class metric. Long-horizon task evaluation grounded in real repositories is a typical example: the model must enter the codebase, independently complete tasks that require multiple steps, and is ultimately measured by test pass rate. The public results of such evaluations often show a pattern — the mid-tier can approach the flagship tier at high reasoning effort, but at a per-task cost that may be an order of magnitude lower; meanwhile, the flagship tier still holds a clear advantage on research-type, more open-ended tasks.
The takeaway is that model selection should not be based on leaderboard rank alone; instead, build your own “task–cost matrix.” A recommended approach is to first pick 30–50 real defect samples internally, measure the average number of iterations, average number of tool calls, and pass rate for each task category, and then decide the default tier and escalation strategy accordingly. The escalation strategy can be designed so that when a loop fails to converge within budget, it automatically switches to a higher-capability tier and retries, saving the failed sample as a regression test case.
5. Reliability Engineering: Making Autonomous Repair Trustworthy
The biggest risk of an autonomous agent is not that it cannot make changes, but that it “makes the wrong change confidently.” So engineering guardrails must be layered on top:
- Sandboxing and least privilege: grant only repository read/write and test execution permissions; prohibit access to production environments and external networks.
- Minimal changes: limit the size of a single diff, and force task splitting when a threshold is exceeded.
- Evidence trail retention: save each round’s commands, output summaries, and test reports for later auditing.
- Human fallback: high-risk directories, database migrations, and permission-related changes must be reviewed by a human.
- Idempotence and rollback: all changes are based on independent branches, discarded on failure, and never pollute the main branch.
For observability, it is recommended to map each agent action to a structured event, connect it to logging services and monitoring/alerting systems, and build a dashboard of “task duration, iteration count, and failure reason distribution.” Only then can you continuously optimize prompts, context construction, and budget parameters.
6. How to Integrate with the Development Workflow
The step that truly produces compounding returns is embedding the agent into the existing pipeline rather than building it as an isolated demo tool. Three integration patterns are recommended:
- Defect triage assistant: automatically reads tickets and produces root-cause candidates and impact scope, shortening manual localization time.
- Change preparer: after developer confirmation, generates the branch, changes, and tests, with the pipeline judging quality.
- Regression guardian: continuously consumes failing test cases, automatically attempts fixes and validation, forming a self-healing regression loop.
Paired with a container platform and object storage, you can archive each task’s context package, logs, and artifacts for retrospectives and training-data accumulation; paired with a message queue, you can make long tasks asynchronous to avoid blocking the main workflow.
7. Adoption Recommendations and Conclusion
If you want to replicate the capability of “autonomously diagnosing issues and submitting changes that pass tests” in your team, you can proceed in four steps: first, establish task card and budget conventions; second, set up a sandbox and least-privilege execution environment; third, build an internal task–cost matrix to determine the default tier and escalation thresholds; fourth, connect the agent to the pipeline and observability system, and iterate in a data-driven way.
The conclusion is clear: the competitiveness of agentic coding has shifted from “single-point generation quality” to “convergence ability and cost efficiency in long loops.” Only by making task tiering, budget constraints, evidence trails, and human fallback solid can autonomous repair turn from an occasional surprise into a stable source of output.
