Agent Harness Engineering: Common Problems and an Optimization Framework

    This article explains why AI coding agents often feel unstable in real development workflows and breaks down six frequent issues, including token overuse, context overflow, missing cross-session memory, and inconsistent behavior. It presents a six-layer optimization framework covering context governance, memory persistence, skill reuse, cost optimization, security, and observability, along with sample code, configuration, and a four-week rollout plan.

    1. Why “Working” and “Working Well” Are Not the Same

    Over the past year, AI coding agents (Agent Harnesses) have moved from demos into real development workflows. However, many teams find that the first experience after adoption is not a jump in productivity but instability: a task that passes on the first attempt today may fail repeatedly tomorrow; long sessions gradually lose the original goal; and when development resumes across days, the background has to be explained again. These issues share a common trait: none is fatal on its own, but together they steadily erode engineering trust.

    From an engineering perspective, these symptoms point to three technical tracks advancing at the same time: improving the tool layer, accumulating methodology, and making progress in memory. The tool layer answers “whether the capability exists,” the methodology layer answers “how to use it reliably,” and the memory layer answers “whether work can continue across sessions.” In addition, agent security protocols and permission boundaries are becoming a fourth track that cannot be ignored.

    2. Six High-Frequency Problems and Their Root Causes

    1. Token consumption is too fast. System prompts, tool descriptions, and conversation history compete for the context window, reducing the density of useful information.
    2. Context explosion and goal drift. In long tasks, early constraints are pushed out of the window, and the model starts to deviate from the original intent.
    3. Cross-session experience cannot be retained. Every new session starts from zero, repeating explanations of project structure and conventions.
    4. Security scanning is missing. Generated code enters branches without policy checks, pushing risk to the review stage.
    5. Inconsistent behavior. Different tools and models respond very differently to the same instruction, making stable expectations hard to form.
    6. The execution process is invisible. When failures occur, intermediate state information is missing, so troubleshooting relies on guesswork.

    3. Capability Framework: A Six-Layer Structure

    It is better to split optimization into six layers and fill them one by one than to introduce a single “all-in-one solution” at once.

    • Context governance layer: layered loading (long-term conventions / task context / temporary observations), combined with compression and summarization.
    • Memory persistence layer: explicitly persist session state so a new session can resume.
    • Skill reuse layer: turn recurring handling patterns into callable units.
    • Cost optimization layer: model routing, prompt compression, background processes, and concurrency control.
    • Security and compliance layer: policy as code, with scanning moved forward to the generation stage.
    • Observability layer: auditing, metrics, and quality gates.

    Illustrative logic for layered context loading:

    1. def build_context(long_term, task, observation, budget=8000):
    2. # Priority: constraints > task > observation; trim from the tail when over budget
    3. parts = [long_term, task, observation]
    4. kept, used = [], 0
    5. for p in parts:
    6. if used + len(p) > budget:
    7. break
    8. kept.append(p); used += len(p)
    9. return "\n".join(kept)

    4. Memory Layer: From In-Session to Cross-Session

    The key to memory persistence is not saving all history but saving a “reusable state summary”: the current goal, confirmed constraints, completed steps, and open questions. In engineering practice, hooks usually trigger reads and writes at the start and end of a session, storing state in external storage (such as object storage or local files). When a new session starts, it loads the state before execution. It is important to note that memory should be searchable, expirable, and rollback-capable; otherwise it degrades into a source of noise.

    5. Skill Layer: Turning Repeated Patterns into Assets

    The value of a skill system is converting “one-off successful experience” into “repeatable capability.” The criterion can be simple: if the same type of handling pattern appears more than three times within a cycle and has clear input and output boundaries, it is worth solidifying. A solidified skill should contain four elements: trigger conditions, input contract, execution steps, and acceptance criteria, avoiding becoming a hard-to-maintain prompt fragment.

    1. skill:
    2. name: refactor-legacy-module
    3. trigger: "duplicate code + missing tests"
    4. input: { module_path: string, test_gap: list }
    5. steps: [scan, propose, patch, verify]
    6. acceptance: "100% test pass rate, no new warnings"

    6. Cost Optimization: Model Routing and Prompt Compression

    The core idea of cost optimization is “allocating compute by task difficulty.” Simple, formatted subtasks go to lightweight models, while complex reasoning and cross-file refactoring go to more capable models. At the same time, removing redundancy in system prompts, summarizing history, and limiting background tasks reduce wasted consumption. Routing policies should remain configurable and observable, with a manual override entry point.

    7. Security: From Post-Hoc Scanning to Generate-and-Verify

    Progress in the agent security protocol direction essentially moves permissions and policies forward. Feasible practices include: read/write boundaries with least privilege, a whitelist of dangerous commands, policy checks on generated content, and manual confirmation for critical operations. Security capabilities should be embedded into the workflow as commands or gates rather than relying on developer discipline.

    8. Observability and Quality Gates

    Without measurement there is no optimization. It is recommended to collect at least four metrics: token usage, task success rate, rework count, and average interaction rounds; and to set quality gates that block merges when targets are not met. Audit logs need to record key decision points to support retrospectives.

    9. Rollout Plan (Four Weeks)

    • Week 1: Introduce layered context and compression, and establish a metrics baseline.
    • Week 2: Add memory persistence and skill solidification, and verify cross-session resumption.
    • Week 3: Introduce model routing and security gates to reduce cost and move risk forward.
    • Week 4: Improve auditing and alerting to form a sustainable iteration mechanism.

    10. Conclusion

    The maturity of AI coding tools does not depend on how strong any single capability is, but on whether the six layers—context, memory, skills, cost, security, and observability—work together. If an organization needs foundational capabilities such as state storage, logging, and monitoring and alerting, it can consider combining general-purpose cloud service categories (such as object storage, log services, monitoring and alerting, and container platforms). Baidu AI Cloud can be one of the optional hosting options for such general-purpose capabilities.