AI Agent Coding: Consistency and Autonomy in Practice

    This article examines why strong single-turn code generation often fails on long, multi-file agent tasks, and how to address it through system design rather than relying on a more capable model. It covers layered thinking, externalizing task state and decisions to prevent drift, and building a verifiable delivery loop with structured tool feedback. It also outlines practical evaluation metrics, sandbox-first rollout practices, and common pitfalls for teams moving agentic coding from demos to production.

    1. The Problem: Why “Writing Code” Is Not the Same as “Delivering”

    Over the past two years, large language models have improved rapidly at code generation. Yet when these capabilities are put into real engineering workflows, the failures usually do not come from the quality of a single generation. They come from stability across long chains of tasks.

    A typical scenario: you ask an agent to take on a feature change that spans multiple files. In the first round, it proposes an architecture that looks reasonable. In the second round, it starts modifying interfaces. By the third round, it has forgotten the original constraints and produces a batch of patches that conflict with each other and do not compile.

    Abstracted from cases like this, three common bottlenecks emerge:

    1. Insufficient code logic consistency: generation, retrieval, and modification happen in separate steps with no unified source of constraints, so naming, error-handling style, and dependency versions drift across the change.
    2. Thinking drift and forgetting in multi-turn tasks: the context window is limited, early reasoning conclusions get pushed out by later content, and the model “forgets why it did something.”
    3. Fragmented tool use and context: file reads, retrieval, command execution, and test runs each return large blocks of unstructured text, key information gets buried in noise, and the model struggles to form a stable judgment.

    It is worth stressing that these are not defects unique to any one model. They are shared challenges of current agent architectures. The solution, therefore, should not depend on “switching to a stronger model.” It has to start at the system design level.

    2. Core Mechanism: Making “Thinking” a Manageable Engineering Object

    The traditional generation paradigm can be reduced to “input directly produces text.” It has no explicit reasoning stage, so the logic chain breaks easily. The emerging consensus in the industry is to introduce an explicit reasoning step before output and tool calls, and treat it as a first-class citizen in orchestration.

    2.1 Layered Thinking: Match Depth to Granularity

    A practical approach is to split thinking into three layers and select the depth dynamically based on task complexity:

    • Instant layer: for small single-file changes, short reasoning and fast output to control cost and latency.
    • Interleaved Thinking: generate a brief implicit reasoning block before each response or tool call, making explicit “what this step does, why, and what the expected result is.” This is the key to maintaining consistency across long chains.
    • Planning layer: for cross-module changes, produce a structured plan first (goal, impact surface, verification method), then execute step by step, with the option to fall back and replan when verification fails.

    A schematic data structure can be expressed like this (pseudocode, not the interface of any specific product):

    1. plan = {
    2. "goal": "Add idempotent writes to the order module",
    3. "constraints": ["Do not change public DTOs", "Keep the existing error code conventions"],
    4. "steps": [
    5. {"action": "read", "target": "order/service"},
    6. {"action": "patch", "target": "order/repo", "expect": "compiles"},
    7. {"action": "test", "target": "order/idempotency", "expect": "all pass"}
    8. ],
    9. "revision": 0
    10. }

    2.2 Thinking Consistency: Rely on External State, Not “Memory”

    Relying on the model to remember every premise across a very long context is unreliable. A more robust approach is externalizing state: write the goal, constraints, completed steps, and open questions into an explicit task state file or structured object, and re-inject the key fragments before each round of reasoning.

    1. state.json
    2. {
    3. "constraints": ["Pin dependency versions", "No new third-party libraries"],
    4. "decisions": [{"id": "D1", "text": "Use optimistic locking for idempotency"}],
    5. "open_questions": ["Do we need backward compatibility with old data"],
    6. "verified": ["unit:test_order_idem"]
    7. }

    Two disciplines go with this. First, leave a decision trail: record the reason and alternatives for each technical choice so it can be reviewed later. Second, constraints take priority: when conflicts arise, the constraint list has the highest priority, which prevents the model from “improvising freely.”

    3. Coding Autonomy: From Generating Code to a Closed Delivery Loop

    Autonomy does not mean letting the model execute freely. It means building a “verifiable closed loop.” A mature agentic coding flow usually has six stages:

    1. Requirement clarification: turn a vague description into verifiable items, and ask questions when information is missing instead of guessing.
    2. Context retrieval: retrieve relevant code by symbol, call relationships, and change history, control the injection size, and provide only the necessary fragments.
    3. Planning and decomposition: output an impact analysis and a sequence of steps, with risk points marked.
    4. Edit execution: modify with minimal diffs as the principle, keeping the project’s existing style and directory conventions.
    5. Verification feedback: run the build, static checks, and unit tests, then feed structured failure information back to the model.
    6. Retrospective capture: archive successful paths and lessons from pitfalls into reusable team knowledge.

    Step 5 is the dividing line for autonomy. Generation without a feedback signal is just “guessing.” Only with the hard constraints of compilation and tests does the model gain the ability to self-correct. In engineering terms, it is recommended to denoise and structure tool return values, for example returning only error codes, failing cases, and key stack traces:

    1. {"cmd":"build","status":"fail","errors":[{"file":"order/repo.ts","line":42,"msg":"type mismatch"}]}

    4. Evaluation and Rollout: Replace Leaderboard Thinking with Real-World Metrics

    Leaderboard scores often diverge from the real delivery experience. It is recommended that teams build layered evaluation close to their own codebase:

    • Consistency metrics: number of constraint violations after multiple rounds of modification, style drift rate.
    • Autonomy metrics: first-pass rate, average number of correction rounds, share of ineffective tool calls.
    • Efficiency and cost: end-to-end task latency, reasoning and execution overhead per task.
    • Security metrics: number of unauthorized file accesses, number of intercepted dangerous command triggers.

    For rollout, “sandbox first” is recommended: a containerized, isolated execution environment combined with least-privilege credentials, a command allowlist, full logging, and monitoring alerts; high-risk operations require mandatory human confirmation. Object storage can hold build artifacts, a message queue can decouple long-running tasks, and logging and monitoring services can provide traceability.

    5. Common Pitfalls

    • Treating long context as memory: the longer the context, the more noise, and key constraints are actually more likely to be lost.
    • Only optimizing prompts without changing the architecture: prompt gains have a ceiling; state management and the feedback loop are the real source of stability.
    • Injecting the entire codebase at once: too much irrelevant information significantly lowers the hit rate.
    • Missing rollback design: autonomous execution must assume failure, so keep branches and snapshots for fast recovery.

    6. Conclusion

    The competitiveness of agents in coding scenarios is shifting from “whether a single generation looks good” to “whether long chains are reliable.” Making thinking explicit and layered, externalizing state and decisions, and then forming a verification loop with builds and tests, together with business-relevant evaluation and a security sandbox, is what moves agentic coding from demos to production. For teams that want to build these capabilities in their own R&D systems, general capabilities such as the container platform, object storage, logging service, and monitoring alerts offered by Baidu AI Cloud can be used to build an isolated, observable execution foundation, so that engineering focus stays on process design and quality gates.