From Prompt to Loop: The Evolution and Practice of Agent Engineering Paradigms

    This article explains how modern AI agent engineering evolves from prompt writing to loop design, and why context engineering, harness engineering, and loop engineering are layered rather than interchangeable. It covers practical techniques for managing context budgets, enforcing hard constraints, building controllable state-machine loops, handling common long-task failures, and establishing observability and evaluation for reliable agent operations.

    1. Where the Problem Starts: Three Layers That Stack, Not Replace

    Several concepts are often used interchangeably in agent engineering discussions, but they actually sit at different abstraction levels. Context engineering determines what the model can see at each step. Harness engineering determines what the model must not do and what it must do. Loop engineering determines who decides the next step and when to stop. These layers are nested and additive; missing any one of them tends to amplify into systemic failure during long-running tasks.

    A simple layered model:

    1. Loop Engineering (orchestration: state, scheduling, termination)
    2. └── Harness Engineering (constraints: permissions, validation, rollback)
    3. └── Context Engineering (information: retrieval, compression, ordering)

    2. Context Engineering: Treat the Window as a Scarce Resource

    The context window is both a cost item and a quality item. Engineering it requires three explicit decisions: what to include (relevance filtering), what to exclude (denoising and summarization), and in what order to include it (recency effects and instruction priority).

    Key practices:

    • Layered memory: keep short-term working memory for the current subgoal, and store long-term memory in a database for retrieval instead of reloading everything.
    • Structured compression: convert verbose tool output into structured summaries (conclusions, evidence, todos) rather than truncating strings.
    • Positional strategy: place critical constraints in stable positions, and put volatile data at the end with timestamps.
    • Budgeting: set quotas for system instructions, retrieved snippets, and tool results, and evict by priority when limits are exceeded.

    Illustrative pseudocode:

    1. def build_context(task, mem, budget=8000):
    2. parts = [system_rules(), task_spec(task)] # high priority, stable position
    3. parts += retrieve(mem, task.query, limit=3) # relevant long-term memory
    4. parts += summarize(tool_logs(), keep="conclusion") # compressed evidence
    5. return fit_by_priority(parts, budget) # trim by quota

    3. Harness Engineering: Hard Boundaries Beyond Soft Constraints

    As tasks get longer, “please do not” instructions in prompts start to fail. A reliable approach is to layer constraints: the prompt layer handles preferences, the validation layer handles correctness, and the execution layer handles safety.

    • Hard constraints: deny dangerous operations by default, use allowlists rather than blocklists; require confirmation or idempotency tokens for write operations.
    • Validation loops: outputs must pass schema validation, unit tests, or static checks; on failure, retry with error information.
    • Sandboxing and least privilege: minimize file and network access scope, and keep credentials short-lived and revocable.
    • Rollback capability: commit all changes as patches or transactions, and retain snapshots for recovery.
    1. policy:
    2. tools_allow: [read_file, run_tests, write_patch]
    3. deny: [delete_bucket, send_email]
    4. require_confirmation: [write_patch]
    5. max_retries: 3
    6. sandbox: {network: false, fs_scope: workspace}

    4. Loop Engineering: From “I Prompt the Model” to “I Design the Loop”

    Instead of directly prompting an agent, you design a system in which the loop prompts the agent. In engineering terms, this rewrites the interaction from a one-shot question-and-answer into a controlled state machine: each round, a scheduler assembles the context, selects tools, evaluates results, and decides whether to continue or terminate. This is fundamentally different from scheduled jobs: scheduled jobs are time-driven with fixed actions, while loops are state-driven with actions determined by evaluation results.

    A minimal viable loop:

    1. for step in range(max_steps):
    2. ctx = build_context(task, memory)
    3. action = policy(llm.decide(ctx)) # decisions constrained by the policy layer
    4. result = sandbox.run(action) # execution protected by hard constraints
    5. memory.write(result)
    6. if verifier.passed(result, task.goal):
    7. return result
    8. task = replanner.revise(task, result) # revise the plan on failure
    9. raise BudgetExceeded(max_steps)

    Design points: termination conditions must be decidable (tests pass, metrics meet targets, human confirmation); every round must have a verifiable progress measure to avoid “looking busy”; budgets (steps, time, cost) must be explicit, with graceful exit when exceeded.

    5. Four Typical Failures in Long Tasks and Their Countermeasures

    • Repeater loops: repeatedly using the same strategy. Countermeasure: introduce strategy diversity and “failure fingerprint” deduplication; force a different path or escalate to a stronger model after two consecutive rounds without progress.
    • Unauthorized or dangerous operations: soft constraints fail. Countermeasure: execution-layer allowlists, sandboxes, and human gates.
    • Diluted key memory: all information is present but the key points are lost. Countermeasure: structured summaries, explicit goal anchors, and retrieval reranking.
    • Plan drift: subgoals deviate from the overall goal. Countermeasure: check goal consistency every round, and keep the original acceptance criteria from being rewritten.

    6. Observability and Evaluation: Making Loops Debuggable

    Loop systems must be replayable: log each round’s input summary, decision, tool calls, validation results, and time and cost; use offline evaluation sets to regress prompt and policy changes; classify failure samples by attribution (insufficient information, missing constraints, wrong termination). For cloud deployment, container platforms can host sandbox execution, object storage can hold snapshots and artifacts, message queues can decouple tasks, and logging services with monitoring and alerting can track step and cost curves. Baidu AI Cloud typically composes these general capabilities on demand; refer to the official documentation for specifics.

    1. First make context budgeting and structured memory solid; 2. add hard constraints and rollback; 3. replace one-shot prompting with a state machine, with explicit termination and budgets; 4. build a replay and evaluation loop, and gradually increase the level of automation. Stacking the three layers and hardening them one by one is what moves long-task agents from “demoable” to “operable.”