Skip to content
Why AI Agents Write Bad Code: The 4-Layer Harness Engineering Framework
R&D Management 24 min read

Why AI Agents Write Bad Code: The 4-Layer Harness Engineering Framework

This article dissects the Harness Engineering framework's four implementation layers (L0 Model, L1 Agent Runtime, L2 User Harness, L3 Project Harness) plus an L4 evolution layer, showing how to move beyond prompt engineering to build engineering systems that constrain AI agents with context, tooling, verification, and continuous improvement — illustrated with a real bug case and industry examples like DeepSeek Harness and DiDi's HelixHarness.

Ubiquitous Tech
Ubiquitous Tech
Ubiquitous Tech

The article opens with a core consensus: AI agents fail to produce good code not because they lack intelligence, but because they lack proper engineering environment — tools, architectural awareness, and accurate context. Harness Engineering addresses this by constructing a system where AI works in a stable, controllable, and verifiable manner.

The Four Implementation Layers (L0–L3)

The author presents a bottom-up architecture diagram illustrating that Harness is not a single tool but a decoupled, collaborative engineering system. Each layer answers a distinct engineering question:

L0: Model Layer — Capability Without Project Context

The base model provides general reasoning, generation, and decision-making. However, it does not automatically know project-specific facts: business module boundaries, authoritative data fields, or team architectural constraints. Even with long context windows, the model will not retrieve the right information unless it is explicitly supplied. Stronger models improve task handling but cannot guarantee adherence to rules they were never told or verified against.

L0 Model layer illustration
L0 Model layer illustration

L1: Agent Runtime Layer — From Answering to Executing

This layer organizes model capabilities into an execution loop (Agent Loop): receive task, assemble context, request model action, execute tool call, feed result back, repeat. It also handles tool integration, model adaptation, session state, permissions, and sandboxing. A key boundary: prompts express constraints, but runtime and infrastructure enforce executable constraints (e.g., restricting write directories, requiring approval for dangerous ops). Sandboxes are not absolute guarantees; their effectiveness depends on actual configuration.

L1 Agent Runtime loop
L1 Agent Runtime loop

L2: User Harness Layer — Personalizing the Agent

Developers configure the generic agent via instruction files ( CLAUDE.md, AGENTS.md), Skills (task-specific methods), Hooks (lifecycle checks), Subagents (delegated tasks), and MCP (standardized external tool access). Effective configuration is not stuffing all knowledge into prompts; it is delivering the right information at the right moment with mechanisms to verify results. The author emphasizes: documents navigate, tools gather evidence, checks provide feedback — these three outweigh merely lengthening prompts.

L2 User Harness configuration options
L2 User Harness configuration options

L3: Project Harness Layer — Team-Grade Governance

This layer moves from personal configuration to project-wide stability. It defines explicit workflows (requirements, design, coding, test, review, delivery), mandatory fact-checks, stop conditions, required tests, and ownership. Knowledge assets (specs, architecture decisions, contracts, coding standards, resolved issues) become maintainable, searchable resources with clear scope, source, and update status. L3 is not just dropping an AGENTS.md in the repo; it requires maintained rules, authoritative fact sources, executable process entry points, and evidenced quality gates.

L3 Project Harness governance
L3 Project Harness governance

Industry Components Mapped to Layers

DeepSeek Harness (dsh) — L1 Runtime with Open L2 Extension

DeepSeek Harness provides composable runtime infrastructure: model calls, tool execution, session state, and the execution loop. Using it to configure models, assemble tools, adjust approval policies is L2 work. Developing plugins that replace the loop or persistence goes deeper into L1 extension. The project demonstrates that the L1/L2 boundary is open: runtime offers extension points, developers compose them into task-fit environments. However, composable runtime does not auto-create project governance; L3 still needs continuous investment.

DeepSeek Harness architecture
DeepSeek Harness architecture

DiDi HelixHarness — L3 Practice Extended to L4 Evolution

The open-source repository https://github.com/didi/helixharness/tree/main contains two modules:

Base R&D plugins (L3): Focus on project-level Harness construction — injecting business knowledge, engineering norms, and R&D flow into the agent workflow via Propose, Apply, Archive phases with human confirmation to distill verified experience into long-term team memory.

Optional evolution platform helixharness-platform (L4): Addresses how to prove Harness changes are effective. It freezes a Base version and a Candidate version, runs controlled comparison on the same real-case set, uses regression gates and execution evidence to decide adoption. This is the meta-system (Meta-Harness) evolution layer.

The key distinction: L3 optimizes business delivery; L4 optimizes the Harness system itself through observation, evaluation, and controlled iteration.

HelixHarness repository structure
HelixHarness repository structure

Layers in Action: A Real Bug Case

Scenario: Agent returns a 64-bit snowflake ID as a JSON number, exceeding JavaScript's Number.MAX_SAFE_INTEGER, causing front-end precision loss. Fixing the single field takes seconds, but Harness thinking asks why the engineering system allowed the error to reach delivery. Multi-layer remediation:

L0: Does the model understand JS double-precision safe range?

L1: Can the runtime read contracts and run tests after code changes? Ensure toolchain connects local compile and unit test execution so errors surface inside the Agent Loop.

L2: Does personal config guide self-check of serialization rules? Add navigation in CLAUDE.md; create a Skill (interface spec) or Post-tool Hook to scan DTO/VO files for unserialized Long fields after modification.

L3: Does the team enforce specs and automated gates? Document rule: all external IDs must serialize as String (e.g., @JsonSerialize(using = ToStringSerializer.class) or global Jackson config). Add ArchUnit architecture test or CI contract script to block merges exposing raw Long IDs.

L4: Did the new rule actually catch subsequent regressions? Add this case to a regression eval set; observe whether agent first-pass compliance rate improves and token consumption stays reasonable.

Bug fix across layers diagram
Bug fix across layers diagram

The article stresses: fixing code solves the immediate bug; fixing Harness builds guardrails for all future similar tasks. Avoid mechanically adding global prompts for every sporadic error — prefer deterministic static checks (Hooks, ArchUnit, CI) over hoping the model "self-disciplines."

Starting Your Own Harness Construction

Begin with a recurring error class in your project: locate the authoritative rule, give the agent a clear information entry point, provide an executable check, and make the check result a task completion condition. Examples:

Repeated interface field guesses → complete contract and query entry.

Frequent wrong module edits → define code boundaries and navigation.

Claims of completion without verification → require test results and CI gates.

Starting Harness construction flowchart
Starting Harness construction flowchart

Each construction step should map to a real problem, not to fill diagram boxes. The four layers jointly aim: model supplies capability, runtime organizes execution, user configures work style, project system safeguards continuous delivery. Harness Engineering does not make the model never err; it makes errors detectable earlier, limits blast radius, and turns every verified lesson into the next task's foundation.

Learning Harness Engineering: Improving the Agent's Environment

Harness Engineering is a mindset and habit, not just prompt tricks or coding skill. When AI output disappoints, pause and ask three questions:

Feedforward sufficient? Before work starts, were goal, facts, constraints, and acceptance criteria clearly given to the agent?

Feedback effective? During execution, are there correct checks? Are results concrete, unambiguous, and guiding the next correction?

State persistent? Are prior conclusions, completed work, and open issues saved and correctly reused in the next round?

Then prioritize improving the corresponding Harness piece: missing facts → add info entry; missing verification → add check mechanism; lost state → build reliable recording and recovery. Prompts remain part of Harness but should not shoulder all problem-solving.

The learning path: start from one real problem, locate the missing link, make a small improvement, validate with subsequent tasks. This "self-strengthening" is not automatic; it is continuously converting failures into verifiable improvements and distilling effective practices into reusable engineering assets. Over time, not only the agent changes: project rules clarify, knowledge becomes accessible, quality becomes checkable, and human engineers shift from correcting execution details to designing boundaries, building environments, and establishing feedback loops.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

AI-assisted developmentProject GovernanceContinuous ImprovementAI Coding AgentsAgent RuntimeHarness Engineering
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.