A Three-Layer Approach to Agent Engineering: Prompts, Context, and Harness

    This article outlines a three-layer methodology for building reliable AI agents in production: prompt engineering, context engineering, and harness engineering. It explains the responsibilities of each layer, provides design patterns with code examples, and offers practical debugging and testing strategies for common failure modes such as instruction conflicts, context overflow, and uncontrolled tool usage.

    Introduction

    When a large language model (LLM) answers a single question, the engineering focus is on articulating the question clearly. An agent, however, operates differently: it calls tools, reads and writes state, runs over long horizons, and is accountable for its results across multiple turns of interaction. The factors that determine success are no longer just the wording of a single prompt—they involve the entire system.

    The industry typically decomposes this work into three progressive layers: Prompt Engineering, Context Engineering, and Harness Engineering. Each answers a distinct question:

    • What instructions should the model receive?
    • What information should the model see at this moment?
    • What execution environment does the model operate within?

    This article walks through each layer, covering design steps, code boundaries, debugging methods, and pre-release checklists. All code examples are illustrative and should be adapted to your specific model SDK and storage interfaces.

    Why Layering Matters

    Cramming all logic into one ultra-long prompt is common in early prototypes. In production, however, this approach typically encounters four recurring categories of failure.

    Problem Owning Layer Typical Failure Example
    Instruction conflicts Prompt layer Business rules say “answer first”; system rules say “confirm first”; model picks one randomly per call
    Context loss Context layer A single retrieval returns 20 long documents; key clauses get pushed out of the window
    Uncontrollable behavior Harness layer A read-only agent invokes a deletion tool
    Difficulty debugging Harness layer Logs store only the final reply; no record of which inputs the model actually received

    The value of layering is clear ownership. When something breaks, you know which layer to modify; when regression testing, you know which layer to exercise. Without clear ownership, teams end up patching the prompt repeatedly, making it increasingly difficult to maintain.

    Layer 1: Prompt Layer — Decompose by Responsibility, Assemble Dynamically

    The core work of the prompt layer is to split instructions into structurally stable parts and assemble them at runtime as needed.

    Decompose Instructions by Responsibility

    A maintainable system prompt typically contains four categories of content:

    • Identity and goal: The agent’s role and the final task it must complete.
    • Behavioral norms: Tone, output format, decision-making order.
    • Constraints: What is prohibited, and which actions require confirmation first.
    • Tool usage instructions: When and how to use each tool, and how to interpret return values.

    Once decomposed, each category can be versioned and tested independently. Modifying a tool description no longer risks accidentally altering security constraints.

    Dynamic Assembly at Runtime

    The same agent may require different instructions in different scenarios. A customer-facing Q&A session differs from internal operations in both permissions and output format. A recommended practice is to keep a base rule set and append session-specific fragments based on the conversation attributes.

    1. import logging
    2. from pathlib import Path
    3. logger = logging.getLogger(__name__)
    4. PROMPT_DIR = Path("prompts")
    5. def load_text(name: str) -> str:
    6. """Read a prompt file. Raises FileNotFoundError if missing; caller decides how to handle."""
    7. return (PROMPT_DIR / name).read_text(encoding="utf-8")
    8. def render_tool_guide(tools: list[str], registry: dict[str, str]) -> str:
    9. """Pull descriptions from the tool registry. Skip unregistered tools with a log entry; never fail the request."""
    10. lines = []
    11. for name in tools:
    12. desc = registry.get(name)
    13. if desc is None:
    14. logger.warning("tool guide missing: %s", name)
    15. continue
    16. lines.append(f"- {name}: {desc}")
    17. return ("Tool guide:\n" + "\n".join(lines)) if lines else ""
    18. ROLE_FILES = {"customer": "customer.md", "ops": "ops.md"}
    19. FALLBACK_ROLE = "customer" # Fall back to a lower-privilege role; never fall back to ops
    20. def build_system_prompt(session: dict, registry: dict[str, str]) -> str:
    21. # Base rules are the security baseline. Fail if missing—never continue with incomplete rules.
    22. base = load_text("base_rules.md")
    23. role = session.get("role", FALLBACK_ROLE)
    24. if role not in ROLE_FILES:
    25. logger.warning("unknown role %s, fallback to %s", role, FALLBACK_ROLE)
    26. role = FALLBACK_ROLE
    27. parts = [base, load_text(ROLE_FILES[role])]
    28. if session.get("locale"):
    29. parts.append(f"Response language: {session['locale']}")
    30. if session.get("tools_enabled"):
    31. guide = render_tool_guide(session["tools_enabled"], registry)
    32. if guide:
    33. parts.append(guide)
    34. return "\n\n".join(parts)

    There are three deliberate fallback strategies in this code, each requiring conscious design:

    1. Missing base rules: Fail fast. Safety rules must never be optional.
    2. Unknown role: Fall back to the role with the least privilege. A fallback in the wrong direction expands permissions—this is the most dangerous failure point.
    3. Missing tool description: Skip the tool and log the event. If the model cannot see a description, it usually will not call the tool, and the risk remains controlled.

    For testing, generate snapshots for each role and tool combination, and assert that critical constraints are present:

    1. def test_ops_prompt_contains_confirm_rule():
    2. prompt = build_system_prompt({"role": "ops", "tools_enabled": ["delete_record"]}, REGISTRY)
    3. assert "Before any delete operation, list the affected scope and wait for confirmation" in prompt
    4. def test_unknown_role_falls_back_to_customer():
    5. prompt = build_system_prompt({"role": "admin"}, REGISTRY)
    6. assert "ops" not in prompt

    The first test verifies that a constraint is not lost. The second verifies that an unknown role does not acquire elevated permissions.

    Turn Vague Descriptions into Decidable Rules

    A common problem in prompts is ambiguous phrasing, such as “be concise” or “handle with caution.” Model interpretation of such phrases fluctuates with context. Whenever a rule can be expressed as a testable condition, write it as a condition rather than a preference.

    Vague formulation Testable formulation Assertion method
    Be as concise as possible Body text no more than three paragraphs Count output paragraphs; assert ≤ 3
    Handle deletion carefully Before deletion, output a list of affected items and wait for user reply “confirmed” Check whether a confirmation record exists before the deletion tool is invoked
    Mind privacy Phone numbers and ID numbers: display only the last four digits Scan output with regex; assert no full number appears

    The second assertion does not rely on whether the model “obeys”—it checks system state. The test passes when the model follows the rule, and fails detectably when the model violates it.

    Layer 2: Context Layer — Budgets, Memory, and Degradation

    The context layer addresses information selection. Models have finite context windows; the longer the input, the higher the probability that key information is neglected. Context engineering is fundamentally budget management.

    Allocating the Budget

    The following ratios are illustrative—adjust them to your model’s window size and the results of your own experiments.

    Block Example share Overflow handling order
    System instructions 15% No trimming. If over budget, the prompt itself needs slimming—a developer task
    Tool descriptions 10% 3. Keep only the tools likely used this turn
    Message history 30% 1. Replace early messages with a rolling summary
    Retrieved snippets 35% 2. Truncate by relevance; retain source identifiers
    Output reservation 10%