AI Coding Agents Need a Closed Loop: Why the Model and the Harness Must Work Together
The ceiling on AI coding performance is often set not by model size but by whether the model can see what its code actually does at runtime. This article breaks down the structural gap between remote inference and local execution, explains the engineering meaning behind the formula "model + harness = agent" across three threads—data loops, interaction cost, and engineering capability—and closes with a layered architecture and sample code you can build on.
When people talk about “AI coding,” the real ceiling is usually not parameter count. It is whether the model can see what its own code does in a real environment. A long-standing structural break sits underneath: code executes on the developer’s machine or in a build cluster, while model inference happens remotely. With no return channel for execution results, the model is forever “writing blind.” This article abstracts that problem into a general technical proposition, unpacks the engineering meaning behind the formula “model + engineering harness = agent,” argues the case along three threads—data loops, interaction cost, and engineering capability—and ends with a layered architecture and sample code you can actually implement.
1. Where the Break Is: Missing Runtime Feedback Caps Capability
The interaction model of traditional coding assistants can be summarized as “one-shot generation”: the developer supplies a prompt, the model emits code, and then all verification happens outside the model’s field of view. Whether compilation succeeds, whether static analysis warns, whether unit tests cover the boundary cases—this information stays in the terminal as text and never returns in structured form to the next inference turn.
Three consequences follow directly:
- Humans do the error correction: the model does not know where it went wrong, so it depends on the developer manually pasting error messages—high interaction cost and lossy information.
- No reinforcement signal can form: without automatically decidable success/failure labels, you cannot construct high-quality preference data or reward signals.
- Long tasks become uncontrollable: multi-step refactors and cross-file migrations need dozens of “modify–verify” round trips; without a loop, you are gambling on a single long output.
So the engineering work the industry genuinely undervalues is not “generation” but “verification and feedback.” Whoever owns the verification stage owns the entrance to the data flywheel.
2. Solution One: Put the Harness and the Model in the Same Data Loop
Doing this layer yourself means merging two previously separate sides into one observable system. The harness executes code in a sandbox and collects structured signals; the model iterates on those signals. Both share the same data contract, which closes the loop.
A minimal signal structure looks like this (language-agnostic, showing field design only):
{"task_id": "refactor-auth-01","step": 7,"signals": [{"type": "compile_error", "file": "src/auth/session.ts", "line": 42,"code": "TS2345", "message": "Argument of type 'string' is not assignable..."},{"type": "lint", "rule": "no-unused-vars", "severity": "warning"},{"type": "test", "suite": "session", "passed": 12, "failed": 2,"failures": [{"name": "expires_at_boundary", "assert": "expected 0, got -1"}]}],"verdict": "fail"}
Key design points that make the loop run:
- Structured signals: parse unstructured terminal text into objects with type, location, and severity, so the model does not have to guess through noise.
- Automated verdicts: compile pass rate, test pass rate, and static-analysis warning counts are objective scalars, naturally suited as reward or filtering criteria.
- Replayable traces: store each step’s patch alongside its signals, useful both for human debugging and for accumulating training data.
- Sandboxing and isolation: all execution happens in controlled containers or temporary workspaces, with a general-purpose container platform and object storage holding artifacts, so the developer’s machine stays clean.
Pseudocode for one loop iteration:
def agent_loop(task, model, harness, max_steps=40):ctx = task.to_context()for step in range(max_steps):patch = model.propose(ctx) # generate or modify coderesult = harness.apply_and_verify(patch) # execute in sandbox and collect signalsctx = ctx.append(patch, result.signals)if result.verdict == "pass":return patch, ctx.trace()return None, ctx.trace() # failed traces are valuable too
One caveat: a closed loop does not mean letting the model retry until tests pass. Engineering requires budget caps, rollback policies, and a minimal-change principle; otherwise you get “special-case code” written purely to satisfy tests. Workable constraints include limiting lines changed per step, requiring new tests to pass alongside the change, and scoring any patch that deletes assertions as an automatic loss.
3. Solution Two: Interaction Cost Determines Loop Density
A loop’s value is proportional to the number of round trips you can afford. If the marginal cost of one “generate–verify” cycle is too high, teams compress verification frequency and the loop degrades into an occasional behavior. So the inference cost structure is not a finance question; it is an architecture question.
The main variables driving per-interaction cost are context length and repeated prefixes. Every turn the harness carries the task description, repo structure, relevant files, and prior signals—a highly repetitive prefix, which is exactly where prefix caching pays off: cached input portions are billed significantly lower than uncached ones. Caching policies and billing rules vary widely across vendors, so architecture should treat “cache hit rate” as a first-class metric to monitor, not something to optimize after the fact.
Practical cost reductions:
- Layered context: keep the system prompt and repo conventions fixed at the front, put volatile signals at the end, maximizing prefix reuse.
- Signal trimming: attach full stack traces only for failing cases; keep counts only for passing ones.
- Tiered model routing: hand mechanical fixes to a smaller model and complex refactors to a larger one.
- Observability: use a general-purpose logging service and monitoring/alerting to track tokens consumed per task, cache hit rate, and average round trips.
Illustrative routing logic:
def route(signals, task):if task.complexity == "low" and all(s.type in {"lint", "format"} for s in signals):return "small_model"if signals.count("test_fail") > 5:return "large_model"return "mid_model"
Only when input cost drops by one or two orders of magnitude can a team make “run full verification after every line changed” the default policy—and that is the real source of loop density.
4. Solution Three: The Underrated Engineering Capability Gap
A third kind of information is routinely ignored: the bottleneck in these systems is usually not algorithms but high-reliability systems engineering. A distributed system that must complete risk checks, order routing, and failure retries within tens of milliseconds is technically close kin to a coding harness that must keep state consistent, recover from failures, and hold latency in check across multi-step tasks:
- State machines and idempotency: every patch application must be replayable and reversible, avoiding workspace drift from repeated execution.
- Timeouts and graceful degradation: build and test durations have obvious long tails, requiring tiered timeouts and usable partial results.
- Determinism first: randomness belongs in model sampling, not in the execution environment; container images and dependency versions must be pinned.
- Observability and auditability: trace every tool call end to end, so you can tell whether a failure is a model problem or an environment problem.
Engineers with experience in low-latency, high-reliability decision systems fill exactly this gap. It also explains why “strong model” and “good product” so often diverge: the gap lives in the harness.
5. Recommended Architecture
A reusable layered design:
- Access layer: a unified task entry point handling authentication, quotas, and audit.
- Orchestration layer: task decomposition, step scheduling, budget control, failure retries.
- Harness layer: file reads/writes, dependency installation, builds, static analysis, and test execution, all inside isolated containers.
- Signal layer: parse and normalize execution results of every kind into one unified structure.
- Model layer: route models of different sizes by complexity, with prefix caching support.
- Data layer: traces and signals go to object storage, metrics go into the monitoring system, forming feedback samples.
The practical advice is to start with a “read-only verification loop” (collect signals, change no code), confirm signal quality, then open up automatic patching, and only then introduce automatic commits—risk stays controlled and every step is measurable.
6. Conclusion
“Model + engineering harness = agent” is not a marketing formula but an accurate description of capability boundaries: the model supplies generation and reasoning, the harness supplies execution and feedback, and the loop binds the two into an iterable system. The industry signal worth watching is not another benchmark product, but teams that begin investing in all three lines at once—model, harness, and engineering system. The practical takeaway for developers is clear: structure your verification signals, sandbox your execution environment, and make interaction cost observable before talking about how intelligent the system is. Baidu AI Cloud’s combination of general-purpose capabilities—container platform, object storage, logging service, and monitoring/alerting—can serve as one underlying choice for carrying such a loop, while the quality of the loop itself still depends on how deeply the team invests in the verification stage.
