AI Agent System Design: A Three-Layer Engineering Approach (Prompts, Context, and Scaffolding)

    This article explains why a strong foundation model does not automatically produce a strong AI agent system, and breaks down the three progressive engineering layers that determine real-world performance: prompt engineering, context engineering, and scaffolding engineering. It covers practical techniques for each layer, including output contracts, retrieval-based context loading, layered summarization, externalized memory, sandboxed execution, verification loops, checkpoints, observability, and cost control, along with a suggested implementation order for engineering teams.

    1. Background: Why a Strong Model Does Not Equal a Strong System

    In real development work, teams often run into a counterintuitive pattern: the same foundation model performs only moderately when called through a standardized API, yet completes long-horizon tasks noticeably better once it is wrapped in a mature coding tool. This shows that model capability is only the upper bound of system capability. What actually determines the experience is the engineering system built around the model.

    The industry usually divides modern agent systems into three progressive layers:

    • Prompt engineering focuses on “how to instruct.”
    • Context engineering focuses on “what the model gets to see.”
    • Scaffolding engineering (also called harness engineering) focuses on “what runtime environment to build.”

    These are not parallel layers. Each one amplifies the one below it.

    A reference scoring model looks like this:

    • Prompt optimization only: roughly 70 points, able to handle single-turn tasks with clear boundaries.
    • Adding context engineering: roughly 80–85 points, able to handle medium-complexity tasks that span files and turns.
    • Adding scaffolding engineering on top: roughly 90–95 points, able to reliably complete long-horizon, multi-constraint, verifiable tasks.

    These numbers are engineering experience ranges. They illustrate where marginal gains come from, not a performance promise for any specific product.

    2. Prompt Engineering: Making Implicit Rules Explicit

    The goal of the prompt layer is not to write fancier prompts. It is to turn a team’s implicit conventions into explicit constraints the model can execute. Four reusable practices stand out.

    First, anchor the role and objective. Use a stable block of text to define the system’s identity, who it serves, and its capability boundaries, so the model does not drift during long conversations.

    Second, define an output contract. Make hard rules for format, fields, naming, and error handling so downstream programs can parse results reliably:

    1. Output requirements:
    2. 1. Return JSON only, with no explanatory text;
    3. 2. Fields are fixed as status / summary / files_changed / risks;
    4. 3. The risks field must not be omitted even when it is an empty array.

    Third, state behavioral rules and prohibitions. Rules such as “read before writing,” “do not invent APIs,” and “ask first when something is ambiguous” work better than repeatedly appending adjectives.

    Fourth, structure prompts in layers. Separate the invariant system constraints, reusable domain conventions, and task-specific instructions into distinct blocks. This makes version management and canary validation easier.

    Compared with common open-source agents, mature commercial tools tend to keep the prompt layer “short and hard”: fewer rules, testable phrasing, and clear priority when rules conflict. This significantly reduces instruction interference during long tasks.

    3. Context Engineering: From Stuffing to Governance

    The most common mistake at the context layer is treating the context window as a warehouse. In practice, irrelevant information dilutes attention and raises the error rate. The governance approach comes down to four points.

    First, retrieval-based loading. Build a task view first, then pull files and snippets by relevance instead of injecting the entire codebase at once.

    Second, layered summarization. Compress long histories with rolling summaries that keep three kinds of information—decisions, conclusions, and to-dos—and drop process chatter and repeated output.

    Third, externalized memory. Write stable facts into documentation files or structured storage inside the project, and let the context read them on demand instead of permanently occupying the window.

    Fourth, rollback-able context snapshots. Save state at key points so that when a task goes off track, the agent can return to the last trusted view and avoid accumulating errors.

    A schematic context assembly flow:

    1. def build_context(task, repo_index, memory):
    2. plan = summarize_task(task) # task view
    3. hits = repo_index.search(plan.keywords) # relevant snippets
    4. facts = memory.load(plan.scope) # long-term facts
    5. history = compress(history, keep=["decision", "todo"])
    6. return assemble(system_rules, facts, hits, history)

    The gains from this layer show up mainly in scenarios that require global consistency, such as cross-file refactoring and API migration.

    4. Scaffolding Engineering: Making Reliability an Environment Property

    The scaffolding layer is where scores jump. It turns “hoping the model does the right thing” into “making it hard for the model to do the wrong thing.” Mechanisms that can be put in place include:

    • Tool-scoped capability boundaries: reads, writes, search, execution, and testing all go through controlled tools with whitelisted parameters, avoiding arbitrary operations;
    • Sandboxing and least privilege: network and system-level calls are restricted by default, and high-risk actions require explicit confirmation;
    • Verification loops: after a change, automatically run builds, static checks, and tests, and retry with the error information attached on failure, forming an “execute–feedback–correct” loop;
    • Long-task decomposition and checkpoints: split the objective into verifiable subtasks and commit them segment by segment to reduce the cost of a single failure;
    • Full-chain observability: log decision rationale, tool calls, and elapsed time, and use logging services and monitoring alerts to locate degradation points;
    • Cost control: set thresholds for context length, retry counts, and concurrency, and use message queues and container platforms for task isolation and elastic scaling when needed.

    A simplified execution loop:

    1. while not done:
    2. action = plan_next(state)
    3. result = sandbox.run(action) # restricted execution
    4. if verify(result) fails:
    5. state = attach_error(result) # feedback loop
    6. continue
    7. checkpoint(state) # persist a rollback point

    5. How the Three Layers Work Together and How to Start

    The three layers have clear division of labor: the prompt layer reduces ambiguity, the context layer keeps information sufficient and clean, and the scaffolding layer provides hard constraints and feedback. Missing any layer discounts the effort above it—no matter how clear the rules are, without a verification loop the system still “looks right and runs wrong.”

    A suggested implementation order for teams: first fill in output contracts and prohibitions, then build the retrieval and summarization pipeline, and finally invest in the sandbox, verification, and observability systems. To get started quickly, you can build an isolated execution and observability foundation on general-purpose capabilities such as the container platform, object storage, logging service, and monitoring alerts offered by Baidu AI Cloud, keeping engineering effort focused on prompt and context strategies.

    Overall, the competitiveness of agent systems is shifting from “tuning the model” to “designing the environment.” Writing conventions as testable rules, governing context as a limited budget, and handing correctness to a verification loop is the practical path to reliable delivery of complex tasks.