Building Controllable and Reliable AI Agents for Software Engineering

    This article explains how to design software engineering AI agents as bounded task-execution systems rather than chat interfaces. It covers task scoping, layered architecture, orchestration and execution budgets, tool and permission boundaries, local and cloud execution models, context engineering, evidence-based code review, security governance, a minimal closed-loop implementation, evaluation methods, and a staged adoption path for controlled automation.

    1. Define the Goal: An Agent Is a Task Execution System, Not a Chat Window

    For developers, a useful AI agent should be able to understand a task, locate code, form a plan, invoke tools, and adjust subsequent actions based on execution results. The core difference between such an agent and a general question-answering system is whether it can form a closed loop of goal, action, feedback, and verification.

    For example, a user might ask to fix an endpoint that returns incorrect results under edge conditions. A question-answering system usually provides a suggested change. A software engineering agent needs to go further: find the relevant implementation, read the tests, propose a modification, run checks, and finally deliver a reviewable change with verification results.

    However, being able to modify files does not mean being able to complete engineering tasks reliably. A model may misunderstand requirements, a tool may fail, a test environment may lack dependencies, and repository documentation may be out of date. When building an agent, the focus should therefore be on task boundaries, context quality, execution constraints, and result verification, not simply on longer prompts or more tools.

    Start with a scenario that has a clear scope and easily checkable results, such as:

    • Adding edge-case tests for an existing function.
    • Performing a read-only review of a code change.
    • Fixing a small defect that can be reproduced reliably.
    • Checking whether documentation and interface implementation are consistent.
    • Executing repository maintenance tasks with explicit rules.

    At an early stage, do not grant permission to arbitrarily modify an entire codebase and automatically release changes. The clearer the task scope, the easier the system is to evaluate and the easier it is to identify the cause of failures.

    2. Overall Architecture: Separate Models, Tools, and Governance

    A maintainable software engineering agent can be divided into six layers:

    Task ingress → Task orchestration → Context construction → Model reasoning and tool invocation → Isolated execution → Verification and delivery

    These layers do not necessarily correspond to six independent services, but they should have clear responsibility boundaries.

    2.1 Task Ingress: Convert Natural-Language Requests into Structured Tasks

    Tasks may come from a terminal, a team messaging system, an issue tracking system, a code hosting system, or a web interface. Different entry points should be converted into a unified internal task object so that adding a new entry point does not require reimplementing the entire execution logic.

    A task object should include at least the target repository, baseline version, problem description, acceptance criteria, and permission scope. If information is insufficient, the agent should request clarification rather than modifying code directly based on a vague description.

    For example, “optimize performance” lacks clear boundaries. “Reduce duplicate computation in a specific processing flow while keeping output consistent, and add regression tests” is more suitable for execution.

    2.2 Task Orchestration: Use State Management Instead of an Unbounded Loop

    Agent execution usually includes reading, planning, modifying, checking, and delivery. The orchestration layer needs to record the current state and define stopping conditions.

    A state flow could be:

    Pending → Context preparation → Plan generation → Tool execution → Result verification → Awaiting approval or completed

    The system should also support failure, cancellation, and human-takeover states. When tools fail repeatedly, dependencies are unavailable, or requirements conflict, the system should stop explicitly instead of retrying indefinitely.

    Execution budgets should also be controlled by the orchestration layer, including maximum execution time, number of model calls, number of tool calls, and cost limits. Specific thresholds should be based on task risk and team budget; example values should not be treated as universal standards.

    2.3 Tool Layer: Provide Limited, Clear, and Auditable Capabilities

    The tool layer can provide capabilities such as file reading, code search, patch application, test execution, and change submission. Each tool should have clear inputs, outputs, error messages, and permission requirements.

    Semantically explicit operations are easier to govern than unrestricted command execution. For example, “read a specified file within the workspace” is generally safer than “execute arbitrary system commands.”

    If command execution is genuinely required, restrict the working directory, network access, available credentials, and execution time, and log the actual commands and outputs. A command proposed by a model should not be trusted by default simply because it looks reasonable.

    3. Two Execution Modes: Local Interaction and Cloud Background Execution Have Different Boundaries

    3.1 Local Interactive Agents

    Local mode is suitable for tasks in which developers remain involved, such as exploring code, discussing implementation options, adjusting tests, or locating problems step by step.

    A typical structure places the agent runtime and tool execution on the developer’s computer, while model inference may run locally or through a remote model service.

    This approach makes it easy to use the existing development environment, but it is important to distinguish “local execution” from “data never leaves the local environment.” Sending code snippets, logs, or prompts to a remote model may cause data to leave the boundary. Teams should define which data types are allowed to be sent and handle credentials, personal information, and sensitive business content accordingly.

    Local mode also needs to protect developers’ uncommitted changes. The workspace state should be checked before execution, and an isolated copy or separate workspace should be preferred so that the agent does not overwrite existing work.

    3.2 Cloud Background Agents

    Background mode is suitable for asynchronous tasks such as scheduled maintenance, defect handling, automatic test generation, or responding to code change events.

    Each task should receive an independent execution environment, pull the specified version of the code, complete analysis and modification in an isolated environment, and then submit a change for review. Developers can handle longer-running work without keeping a local terminal online.

    However, an isolated environment is not absolutely secure. It is still necessary to restrict network egress, resource usage, file mounts, and credential access, and to clean up temporary data after the task ends.

    When multiple tasks run in parallel, they should use separate workspaces and record a common baseline version. Before submission, the system should also check whether the target branch has changed, avoiding duplicate fixes, overwriting updates, or hard-to-understand conflicts.

    The two modes are not mutually exclusive: local mode emphasizes interactive feedback, while background mode emphasizes asynchronous execution and resource isolation. Both can share context rules, tool protocols, and review standards.

    4. Context Engineering: Make Sure the Agent Reads Correct and Useful Information

    Repository documentation should not exist as standalone explanatory material; it should become engineering knowledge tied to code versions.

    Context commonly used by an agent includes:

    • Directory structure and module responsibilities.
    • Interface contracts and data constraints.
    • Build, test, and run instructions.
    • Coding standards and review criteria.
    • Architecture decisions and historical reasons.
    • Known defects and maintenance notes.

    This information needs to be traceable. Conclusions in documentation should preferably be linked to relevant files, versions, and update times. When key implementation is involved, it should still be verified against the current code; historical documentation should not be treated directly as fact.

    4.1 Retrieve by Task Instead of Loading the Entire Repository at Once

    Sending all code and documentation to a model increases cost and makes it easy for irrelevant content to interfere with judgment.

    A more reasonable process is to first locate modules based on the task description, then read relevant implementations, call relationships, tests, and specifications. When necessary, combine keyword search, structural analysis, and semantic retrieval, expanding context gradually.

    Retrieval results should preserve file paths and version information. If the model cites a specification, reviewers should be able to find the corresponding source rather than seeing only an unverifiable summary.

    4.2 Separate Task Memory from Long-Term Knowledge

    Task memory records the current execution process, such as files already checked, failed commands, and open questions. Long-term knowledge stores confirmed, reusable engineering conclusions.

    Not all model outputs should be automatically written into long-term knowledge. Once an incorrect inference is continuously retrieved, it may create repeated misleading results.

    Long-term knowledge should be reviewed or reliably verified and should have mechanisms for updating, invalidation, and deletion. When code changes significantly, related knowledge needs to be rechecked. When sensitive information is involved, retention periods and access scope should also be defined.

    5. Code Review: Base Findings on Evidence, Not Just Opinions

    An effective review agent should ask verifiable questions about the impact of a change, rather than generating large numbers of generic comments such as “consider optimizing” or “watch out for exception handling.”

    Review can cover the following areas:

    • Whether logic and edge conditions meet requirements.
    • Whether interface behavior has changed incompatibly.
    • Whether permissions, input validation, and sensitive data handling are reasonable.
    • Whether concurrency access and resource release present risks.
    • Whether tests cover new or modified behavior.
    • Whether documentation needs to be updated together with code.

    Each review comment should ideally include the problem location, trigger conditions, potential impact, and verification method. For issues that cannot be confirmed, the agent should state uncertainty instead of presenting speculation as a confirmed defect.

    The review process should integrate with code change management: analyze based on an explicit change scope, link comments to specific locations, and recheck related issues after a new version is submitted. Automated review should not be treated as a complete replacement for human review, especially for changes involving permissions, security, data migration, and release strategy.

    6. Security Governance: Let the Agent Do Only What It Is Authorized to Do

    Code, documentation, task descriptions, and tool outputs may all contain misleading instructions. For example, a file might ask the agent to read credentials and send them to an external address. Such content should be treated as data to be analyzed, not as system instructions.

    Therefore, permission control cannot rely only on prompts such as “do not disclose information.” It must be enforced at the execution layer.

    6.1 Least Privilege

    A read-only review task should not have write and commit permissions. A test supplementation task usually does not need access to production environments. A routine maintenance task should not receive release credentials.

    Permissions should be granted dynamically based on task type, and short-lived, narrowly scoped credentials should be used where possible.

    6.2 Approval for High-Risk Operations

    Operations such as deleting large numbers of files, modifying permission rules, updating critical dependencies, executing data migrations, and triggering releases should have human approval gates.

    The approval basis should include the proposed operation, impact scope, and verification results, not merely a prompt asking whether to continue.

    6.3 Logging and Data Protection

    Model calls, tool executions, state changes, and final artifacts should be recorded, but logs may also contain code or sensitive information. Redaction, access control, and retention periods need to be designed at the same time.

    Observability does not mean retaining all data indefinitely. It means supporting troubleshooting, accountability, and quality analysis with appropriate information.

    7. Minimal Implementation: Start with a Verifiable Closed Loop

    The pseudocode below is only intended to illustrate the control flow and does not correspond to any actual product interface:

    1. task = receive_and_validate_task()
    2. permissions = derive_permission_scope(task.type)
    3. environment = create_isolated_workspace(task.base_version)
    4. context = retrieve_relevant_code_and_standards(task, environment)
    5. plan = generate_execution_plan(task, context)
    6. if plan.contains_high_risk_operation():
    7. wait_for_human_approval()
    8. while not task.is_complete() and not budget.is_exhausted():
    9. action = select_next_action()
    10. validate_action_permissions(action, permissions)
    11. result = execute_and_record(action, environment)
    12. if unrecoverable_error_occurred():
    13. stop_and_request_human_takeover()
    14. verification_result = run_required_checks(environment)
    15. deliver_change_and_report(verification_result)
    16. clean_up_temporary_environment()

    The most important part here is not the loop itself, but the constraints at each step: check permissions before executing an action, record results after execution, verify before submission, and stop when an exception occurs.

    An initial version can implement only code reading, relevant file retrieval, and read-only review. After evaluation results are stable, patch generation and test execution can be enabled. Only after that should automatic creation of changes for review be considered.

    8. Evaluation: Distinguish “Completed an Operation” from “Solved the Problem”

    An agent producing a patch does not mean the task succeeded. Passing tests does not mean all requirements have been met.

    It is advisable to establish a fixed evaluation set covering normal tasks, tasks with insufficient information, tasks with environment anomalies, and high-risk tasks. Evaluation should consider:

    • Whether requirements are truly satisfied.
    • Whether the change introduces regressions.
    • Whether review comments are accurate and actionable.
    • Whether permission and approval rules are followed.
    • Whether the agent stops correctly when facing uncertainty.
    • How much human effort is needed for correction and re-review.
    • Whether execution time and resource cost are acceptable.

    When comparing different models or strategies, keep the code version, execution environment, and budget as consistent as possible. Do not compare only output length or task completion rate; also check false positives, unauthorized operations, and changes reverted by humans.

    Failed tasks are especially valuable for analysis. Causes can be classified as unclear requirements, missing context, reasoning errors, tool failures, environment differences, and insufficient verification. Improvements should target specific stages rather than always being reduced to changing the model.

    9. Adoption Path: From Assistant Tool to Controlled Automation

    Building your own AI agent essentially means adding a participant to the existing engineering system that can execute tasks but must be constrained and verified.

    A safer path is to define task boundaries first, then establish code and documentation context; enable read-only capabilities first, then gradually introduce writing and execution; require human confirmation for each delivery first, then expand automation based on real evaluation results.

    If an open and modifiable implementation is used, teams can more easily adjust model selection, review rules, tool integrations, and observability mechanisms. However, openness alone does not guarantee reliability. It still requires dependency maintenance, auditing of execution logic, and continuous evaluation.

    Ultimately, a trustworthy agent system is not the one that can act autonomously the most. It is the one that can clearly explain what it did, what evidence it relied on, how far verification went, and when human intervention is required.