How to Build a Self-Contained AI Agent Factory
This article explains why software teams should move from a single AI coding assistant to an AI agent factory: a set of composable, replaceable, and traceable agents backed by shared infrastructure. It walks through five layers—local agents, cloud agents, review agents, codebase memory, and observability with governance—along with task description and rule file examples, and ends with a practical adoption roadmap and core metrics.
1. Why You Need an Agent Factory, Not a Single Agent
Most teams start with “an assistant that can write code” when introducing AI coding capabilities, but they quickly hit three walls: capability boundaries are dictated by external services, behavior is not observable, and the tool cannot integrate with existing development workflows. Overcoming these obstacles requires shifting the perspective from a single-point tool to an agent factory: a group of agents with clear responsibilities that are composable, replaceable, and traceable, plus the shared infrastructure that lets them run, remember, and be governed.
A mature agent factory typically has five layers:
- Execution layer: local agents and cloud agents, covering interactive and background work respectively.
- Quality layer: automated review agents that independently validate outputs.
- Context layer: codebase documentation and a memory system that give agents a stable, retrievable knowledge base.
- Model layer: model choice stays with the team, combining open-source self-hosted and cloud-hosted options.
- Observability layer: cross-system call chain tracing, logs, and metrics for behavior auditing and effectiveness evaluation.
None of these five layers is optional. With only the execution layer, output quality is uncontrollable; with only the quality layer, efficiency cannot improve; without the context layer, agents repeat the same mistakes; without the observability layer, the team cannot answer “why did it make this change.”
2. Layer One: Local Agents, the Entry Point for Interactive Development
The core design principle of local agents is: the runtime stays local, the model lives in the cloud. The CLI and the agent runtime are deployed on the developer’s machine, with direct access to the local codebase, local dependencies, and the local test environment; model inference calls remote compute through an API. This split yields two direct benefits: developers can explore and modify the real working copy without uploading code, and they can use large-parameter models far beyond what a laptop can host locally.
Typical scenarios for local agents include: quickly tracing the implementation path of a feature in the terminal, completing cross-file refactoring from natural language instructions, and running closed-loop tasks of “implement—run tests—fix.” To keep such loops reliable, it is recommended to build a minimal toolset into the runtime: file read/write, regex search, dependency lookup, test execution, and diff preview. A sample task description structure could be:
Goal: Add idempotency checks to the order moduleConstraints: Do not change public interface signatures; new logic must have unit test coverageContext: Search docs/ and existing test cases firstAcceptance: All module tests pass, and output a change summary
The key is to write “constraints” and “acceptance” explicitly into the task description instead of relying on the model to infer them, which significantly reduces ineffective changes.
3. Layer Two: Cloud Agents, Freeing Engineering Tasks from the Terminal
Real development work does not always start in a terminal. Bugs may appear in discussions on a collaboration platform, requirements may be recorded in a project tracking system, and some maintenance tasks (dependency upgrades, bulk refactoring, configuration inspections) need to run automatically on a schedule. The value of cloud agents is taking on these “non-interactive” entry points.
There are three design points:
- Multiple trigger entry points. Connect collaboration platforms, project tracking systems, code hosting platforms, and a self-built web interface to the same scheduling layer, normalizing messages from different sources into standard task objects (containing repository identifier, task type, constraints, priority).
- Sandboxed execution. Each task pulls code, installs dependencies, applies changes, and verifies them in an isolated environment, which is destroyed when the task ends. Isolation brings two benefits: many tasks can run in parallel without disturbing anyone’s local environment, and a single task failure does not pollute shared resources.
- Deliverables as change proposals. Completed tasks are not written directly to the main branch; instead they submit a merge request containing a change description, verification records, and impact scope, returning the final decision to humans.
Standardizing the task object can be simplified as:
{"repo": "service/order","type": "bugfix","trigger": "chat","constraints": ["keep interface compatibility", "add regression tests"],"acceptance": ["module tests pass", "no new static check warnings"],"priority": "normal"}
Once trigger entry points are unified and task structures are unified, cloud agents go from “demo” to high-frequency infrastructure—which is also the core indicator of whether an agent factory is truly in place: daily task volume, not the number of demos.
4. Layer Three: Review Agents, Independent, Strict, and Coupled with the Code Hosting Workflow
Letting the same agent both write and review code amounts to removing the quality gate. A review agent should be an independent instance with its own context and its own judgment criteria, tightly integrated with the merge request workflow of the code hosting platform: automatically leaving structured comments on proposals, marking the file and line range where the problem is, distinguishing three levels of “must fix,” “suggested improvement,” and “note only,” and re-verifying after fix pushes.
A good way to improve review quality is to migrate the standards from prompts to versionable rule files, for example:
rules:- id: securityseverity: blockerchecks: ["missing input validation", "hardcoded sensitive information", "privilege escalation paths"]- id: styleseverity: suggestionchecks: ["naming consistency", "comments in sync with implementation"]- id: testseverity: blockerchecks: ["new branches without test coverage"]
Rule files are reviewed and evolve together with the code, so review behavior becomes explainable and regression-testable rather than dependent on some invisible default tendency.
5. Layer Four: Codebase Memory, Turning Documentation into Usable Context for Agents
The ceiling of an agent is often determined by context quality. Codebase documentation should not just be explanations for humans, but organized as a knowledge layer that agents can retrieve and cite: architecture overview, module boundaries, build and test methods, coding conventions, and historical decision records. Three engineering recommendations:
- Evolve from the same source as the code. Documentation changes and code changes are reviewed in the same proposal, avoiding documentation rot.
- Organize in layers. Global conventions, module descriptions, and task-level prompts are stored in layers, and retrieval is scoped by range to reduce irrelevant context interference.
- Updatable and traceable. Memory entries retain their source and update time; when conflicts occur, the newer, reviewed entry prevails.
This way, agents retrieve memory first and then modify code when taking on a task, so recurring problems are solved once rather than appearing repeatedly.
6. Layer Five: Observability and Governance, Making Behavior Controllable
Across local, cloud, and review agents, a unified tracing system is needed: recording task inputs, retrieved context, model calls, tool call sequences, elapsed time, and result status. Based on this data, teams can locate the failing step (missing context, insufficient tool permissions, or ambiguous constraint wording) and run comparative evaluations of different models and prompt strategies.
The governance checklist can include: clear model sources and data flows, access whitelists for sensitive repositories, least-privilege tool permissions, mandatory human merging of change proposals, and a retention period for full-chain logs. Open-sourcing is the prerequisite for governance—only with an auditable, modifiable implementation can teams swap models, adjust review standards, and integrate internal tools without being locked into the capability boundaries of a single service.
7. Recommended Adoption Path
- Build the context layer and tracing layer first, then the execution layer, avoiding “get it running first and add governance later.”
- Have local agents cover high-frequency interactive scenarios first, and cloud agents cover batch tasks that can be standardized and verified first.
- Launch review agents together with the code hosting workflow to form a “generate—review—merge” loop.
- Use task volume, first-pass rate, and manual rework rate as core metrics, and continuously iterate rules and memory.
Following this path, a team gets not just a better code-writing assistant, but a software engineering agent system that is auditable, modifiable, and measurable. When elastic compute and parallel tasks are needed, it can be carried by general cloud capabilities such as container platforms, task queues, object storage, and monitoring and alerting; Baidu AI Cloud’s related infrastructure can also serve as a general foundation for this type of architecture.
