AI Agent Engineering: A Three-Layer Design Guide (Prompt, Context, and Harness)
This article breaks down a three-layer engineering approach to building reliable AI agents: prompt engineering, context engineering, and harness engineering. It explains why prompt tuning alone tends to plateau, how to assemble static and dynamic prompt layers, how to move from stuffing the context window to precise information supply through selection, summarization, retrieval, and isolation, and how external mechanisms such as tool contracts, validation loops, state persistence, sandboxing, and observability push success rates higher. It also covers a practical rollout order, layered evaluation metrics, and common anti-patterns to avoid.
1. Why Prompt Writing Alone Cannot Produce a Good Agent
When many teams start building an AI coding agent, their first instinct is to refine the prompt: make the role, rules, and output format more detailed. Prompt optimization does help, but it has a clear ceiling. For a task of moderate complexity, prompt engineering alone usually gets you to a usable level of around 70 out of 100. Beyond that, returns drop off quickly, because failures are often not about “how you say it” but about “what the model sees” and “what environment the model runs in.”
For this reason, the industry has increasingly split capability building for modern AI systems into three progressive layers:
- Prompt Engineering: solves “how to say it,” constraining the role, goals, and output contract.
- Context Engineering: solves “what to let the model see,” managing the selection, compression, and retrieval of information.
- Harness Engineering: solves “what runtime environment to build,” using tools, state, validation, and rollback to keep model behavior within a controllable range.
The relationship among the three is not parallel but cumulative. For an agent targeting 95 out of 100, prompts get you to just over 70, context management raises that to 80–85, and finally the hard constraints and automated validation of the harness push it to 90–95. The sections below present reusable design methods for each layer.
2. Layer One: Prompt Engineering — Assembling Static and Dynamic Information
The prompt of a high-quality agent is not a long block of text, but a structure assembled from a static layer and a dynamic layer.
The static layer contains the role definition, behavioral guidelines, coding conventions, and output contract (for example, field conventions for structured results). This content changes infrequently and is suitable for long-term caching. The dynamic layer contains the current task description, confirmed facts, environment differences, and failure history. It changes frequently and needs to be injected per turn.
An example structure:
[System / Static Layer]- Role: senior engineer responsible for completing a specified change in an existing codebase- Principles: read before writing; do not invent interfaces; keep changes minimal; make every step verifiable- Output contract: { "files_changed": [], "reason": "...", "verification": "..." }[Dynamic / Dynamic Layer]- Task: add idempotency checks to the order module- Known fact: retries are triggered by the message queue consumer- Constraint: do not modify public library signatures
Three easily overlooked design points:
- Instruction layering and priority. State “hard rules that must never be violated” separately from “soft preferences that are recommended,” so the model does not make random trade-offs when they conflict.
- Define the output contract first. Defining a parseable result structure before letting the model fill in content significantly reduces downstream parsing failures.
- Version your prompts. Manage prompts like code, recording changes and effect comparisons; otherwise you cannot tell which change produced the gain.
3. Layer Two: Context Engineering — From “Stuffing” to “Precise Supply”
As context windows have grown larger, the new problem is information overload: stuffing in too much irrelevant content dilutes attention and actually lowers accuracy. The core of context engineering is four actions.
Selection. Inject only information strongly relevant to the current subtask, such as the files, interface definitions, and callers directly related to the change, rather than the entire repository.
Summarization. Produce layered summaries of long histories: represent completed actions with a one-sentence conclusion, and keep details for unfinished ones. Example:
{"done": ["located where the idempotency check is missing"],"open": ["need to confirm the maximum number of message retries"],"next": "add the deduplication table write logic"}
Retrieval. Combine keyword and vector retrieval for hybrid recall, and attach the source path and fragment location to retrieval results so the model can cite them instead of fabricating.
Isolation. Open a separate context for different subtasks to avoid cross-contamination; the main context keeps only conclusions and decision records.
From an engineering standpoint, it is advisable to maintain a “fact ledger” that records verified facts and items to be confirmed. Each turn, the model reads the ledger before acting. This is more stable than repeatedly re-reading raw material and makes it easier to locate the source of errors.
4. Layer Three: Harness Engineering — Turning Free Generation into Controlled Execution
The harness layer is the key to scoring above 90. It does not rely on the model’s self-discipline for correctness, but uses external mechanisms as a safety net. It includes five capabilities.
- Tool contracts. Every tool has a clear input schema, output schema, and error codes, and the model can only call within the contract.
{"tool": "run_tests","input": { "scope": "module", "pattern": "order_*" },"output": { "passed": 0, "failed": 0, "cases": [] }}
Plan–execute–validate loop. Produce a plan first, then execute step by step, with automatic validation after each step; on failure, roll back to the previous step instead of continuing to stack changes.
State persistence. Persist task state, changed files, and validation results to disk so the process can recover after an interruption and long-running tasks do not “lose their memory.”
Permissions and sandboxing. Restrict write operations to specified directories, and require explicit confirmation for high-risk operations; run builds and tests in an isolated environment.
Observability. Record the input summary, tool calls, elapsed time, and result of each step, and use logging services and monitoring alerts to locate anomalies, forming a traceable evaluation set.
5. How the Three Layers Work Together and the Rollout Order
For implementation, it is recommended to proceed in the order “contracts first, then context, then automation”:
- Step one: solidify the output contract and hard rules to first suppress parsing failures and unauthorized changes.
- Step two: build retrieval and summarization pipelines to control the signal-to-noise ratio of injected information.
- Step three: complete validation, rollback, state, and observability capabilities to raise the success rate of long-running tasks.
For evaluation, do not look only at whether the final answer is correct; measure by layer instead: for the prompt layer, look at format compliance rate; for the context layer, look at citation accuracy and the proportion of irrelevant information; for the harness layer, look at first-pass rate, rollback rate, and average number of repair rounds. Layered measurement is what tells you which layer to invest in next.
6. Common Anti-Patterns
- Using an overly long prompt to replace context management, causing attention dilution.
- Pursuing full automation while omitting human confirmation points, leaving high-risk operations without a gate.
- Lacking state persistence, so a long task restarts from scratch once interrupted.
- Lacking an evaluation set, so optimization relies entirely on subjective feeling.
- Tools without contracts, so errors are amplified after multiple layers of calls and become hard to locate.
7. Conclusion
The reliability of an agent system is not the product of a single trick, but the result of three layers of engineering stacked together: prompts handle expression and contracts, context handles the signal-to-noise ratio of information supply, and the harness constrains generation behavior onto a track that is verifiable, rollback-able, and observable. Building by layer and measuring by layer is the realistic path to moving an agent from “usable in a demo” to “usable in production.”
