Three-Layer Engineering Design for AI Agent Systems
This article breaks down a three-layer engineering approach to building AI agent systems: prompt engineering, context engineering, and runtime environment (harness) engineering. It explains why prompt tuning alone plateaus at a usable but unreliable level, how each layer maps to a concrete limitation of large language models, and what each layer should contain in practice—static and dynamic prompts, layered context supply, compression and isolation, least-privilege tool access, verification loops, termination conditions, and observability. A recommended implementation order and a comparison table are included to help teams move long-horizon agent tasks from occasional impressive results to dependable delivery.
Three-Layer Engineering Design for AI Agent Systems
1. Why “Writing Good Prompts” Is Not the Same as “Delivering a Task”
When many teams start building agent systems, their first instinct is to polish the prompt: make the role description more detailed, tighten the output format constraints, and lengthen the list of prohibited actions. This works well for short conversations and single-turn question answering, but the effectiveness drops noticeably once the task becomes a long-horizon one that requires multi-step reasoning, cross-file modification, and long-running execution.
A repeatedly validated rule of thumb: if a perfect score is 100, prompt engineering alone typically brings a system to around 70 points—the “usable” range. Adding context engineering raises it to roughly 80–85 points. Only when runtime environment engineering (harness engineering) adds constraints, validation, and feedback does the system have a chance of entering the 90+ “trustworthy” range.
This layering is not mysticism; it follows from three objective limitations of large language models:
- Attention is a finite resource: the longer the context, the higher the chance that key information gets diluted.
- State does not persist automatically: the model itself keeps no memory across turns, so everything depends on external injection.
- Output is probabilistic sampling: the same input does not guarantee the same output, so external validation is required as a safety net.
A mature agent system is therefore the product of three factors—model capability + information supply + runtime constraints—not the sum of prompt tweaks. The three dimensions are covered below.
2. Prompt Engineering: From Static Roles to Dynamic Assembly
2.1 The Static Layer: Writing “Who I Am and What I Follow” as a Stable Contract
Static prompts address identity and boundaries, and should remain highly stable rather than change frequently. They usually contain four blocks:
- Role and goal: clarify whether the task is code comprehension and modification, document generation, or data analysis;
- Behavioral rules: for example, read before writing, keep changes minimal, never invent interfaces that do not exist;
- Output contract: structure, language, comment style, and whether verification steps must be provided;
- Safety boundaries: dangerous operations require confirmation, sensitive information must not be leaked, out-of-scope requests must not be executed.
A schematic structure looks like this:
[Role] You are a senior code collaborator[Goal] Fulfill the request without breaking existing behavior[Rules] Locate before modifying; keep the change scope minimal; ask when uncertain[Output] Change summary + key code snippets + verification approach[Boundaries] Request confirmation first for high-risk actions such as deletion, renaming, and bulk replacement
2.2 The Dynamic Layer: Injecting “What the Current Task Is” Turn by Turn
The dynamic prompt is where the real difference is made. Instead of stuffing all information in at once, it should be injected incrementally according to “current progress.” Typical fields include the user’s original request, confirmed facts, current assumptions, pending steps, and the result of the previous step.
The key design principle is making the model explicitly distinguish “known facts” from “inferences.” For example, maintain a lightweight state block during a long task:
{"goal": "Add failure retry to the login module","confirmed": ["entry function is in auth/login.ts", "existing test framework is ready"],"assumptions": ["retry limit reuses the existing config item"],"next": ["read login.ts", "add unit tests"]}
The benefit: when a task spans dozens of turns, the model does not forget the original goal, nor does it keep reasoning from assumptions as if they were facts.
2.3 Common Anti-Patterns at the Prompt Layer
- Piling up dozens of rules at once, which conflict with each other and dilute one another;
- Writing volatile information (file names, line numbers, temporary paths) into the static prompt, which pollutes the context;
- Listing only “what not to do,” with no positive path for “what should be done.”
3. Context Engineering: Deciding What the Model Sees
3.1 Layered Supply: Global Overview + Local Detail + On-Demand Retrieval
The core of context engineering is not “stuff in more,” but “provide exactly enough.” A widely used approach in the industry is a three-tier structure:
- Global layer: project structure, module responsibilities, and a dependency overview that helps the model build a map;
- Local layer: file fragments, interface definitions, and data structures directly relevant to the current subtask;
- Retrieval layer: pulled on demand via keyword or semantic retrieval, avoiding full injection.
3.2 Compression and Summarization: Fighting Context Bloat
Long-horizon tasks inevitably produce large amounts of intermediate output. Viable strategies include producing structured summaries of completed steps, keeping only conclusions and key diffs, and converting lengthy logs into statistical results. A summary should preserve the “basis for decisions” and discard “process noise.”
3.3 Isolation and Reclamation: Separate Contexts for Different Subtasks
When a task can be split into multiple subgoals, opening an independent context window for each subgoal and reclaiming the conclusions after completion significantly reduces mutual interference. This is similar to the idea of process isolation in operating systems: the context is the address space, and the conclusion is the message passed in inter-process communication.
3.4 A Context Governance Checklist
- Classify information into three types: “must be visible,” “optionally visible,” and “must not be visible”;
- Mask or replace sensitive configuration and credential information with placeholders;
- Record the source of each injection to make issue tracing easier.
4. Runtime Environment Engineering: Caging Uncertainty
4.1 Tools and Permissions: The Greater the Capability, the More Constraints Must Come First
Agents complete real tasks through tool calls: reading and writing files, executing commands, launching retrieval, and calling APIs. But tools are also entry points for risk. Mature designs follow the least-privilege principle: read-only by default, write operations require explicit authorization, high-risk actions require a second confirmation, and all calls are logged and auditable.
4.2 The Verification Loop: Generate—Execute—Verify—Correct
A single generation is untrustworthy; only a closed loop is deliverable. A general loop looks like this:
Plan → Execute → Automated validation (compile/test/static checks) → Retry with error information on failure → Output on success
The key point is feeding error information back to the model in a structured way rather than simply retrying. Error feedback should include the failure location, the error type, and the difference between expected and actual results.
4.3 Termination Conditions and Budget Control
You must explicitly define when to stop: acceptance criteria met, maximum number of steps reached, time or call budget exhausted, or consecutive failures exceeding a threshold. An agent without termination conditions often falls into unproductive loops during long tasks.
4.4 Observability
Logs, metrics, and tracing are all indispensable. At minimum, the system must be able to answer: why was this step triggered, which context was injected, which tools were called, and what were the elapsed time and failure reason. Observability is not an add-on for operations; it is a prerequisite for the iteration methodology.
5. How the Three Layers Work Together and in What Order to Implement Them
The three layers are not parallel; each one amplifies the previous:
| Layer | Problem it solves | Typical gain range | Failure symptom |
|---|---|---|---|
| Prompt engineering | How to express | Basic usability | Format drift, goal drift |
| Context engineering | What the model sees | Clear improvement | Missing key files, duplicated work |
| Runtime environment engineering | Which environment it runs in | Approaching stability | Cannot verify, loops never terminate |
The recommended implementation order: first stabilize the output contract, then govern context supply, and finally complete tool constraints and the verification loop. Reversing the order easily leads to spinning in place—“the constraints are all written out, but the model never actually saw the key code.”
6. Conclusion
The ceiling of an agent system is determined by the model; the floor is determined by engineering design. Treating the prompt as a contract, the context as a scarce resource that needs governance, and the runtime environment as a controllable and verifiable sandbox is what turns long-horizon complex tasks from “occasionally impressive” into “consistently delivered.” When implementing on the cloud, you can combine container platforms for environment isolation, log services for call traceability, and monitoring and alerting as a fallback for anomalies, turning the methodology above into sustainable engineering capability that keeps iterating.
