Software Agent Engineering: Architecture Principles and Evaluation Practices

    Software agents move beyond code completion toward task-level automation: reading issue descriptions, understanding repository structure, planning changes, invoking tools, and validating results through tests. This article examines the engineering implications, including layered architecture, isolated execution, observability and replay, and model-agnostic interfaces. It then covers the core observe-plan-act-verify loop, tool permissions and security boundaries, and an evaluation framework with task types, metrics, and common pitfalls. Finally, it outlines feedback-driven improvement, fair comparison methodology, and phased adoption recommendations. Readers will gain a practical framework for building, evaluating, and operating software agents under real-world constraints.

    1. Background: From Code Completion to Task-Level Automation

    Over the past few years, code assistance tools have largely remained at the level of completing functions, explaining errors, and generating boilerplate code. Developers still need to break down requirements, locate files, run tests, and verify results themselves. The goal of a software agent is to let a model drive this chain autonomously: read the problem description, understand the repository structure, plan modification steps, invoke tools to execute changes, and validate results through tests.

    This shift introduces new engineering problems. Models can lose context during multi-step operations, tool calls may fail, execution environments can create security risks if they lack constraints, and final results need reproducible, measurable verification. Therefore, whether an agent is usable depends less on whether a single generation is impressive and more on whether it can complete tasks reliably under real constraints.

    1.1 Core Needs of Developers and Enterprises

    Different roles focus on different aspects of agents:

    • Individual developers care about task completion rate and response speed, and want to reduce repetitive work such as batch-fixing similar defects, completing unit tests, and migrating API call patterns.
    • Team leads care about consistency and auditability. They need to know which files the agent changed, what evidence supported those changes, and whether tests were run.
    • Enterprise security and compliance staff care about permission boundaries, data flows, and secret management. They require that agents cannot access production environments beyond their authority or leak source code.
    • Platform engineers care about resource cost, concurrency capacity, and fault isolation. They need to provide scalable runtime infrastructure for agents.

    These requirements are interconnected. For example, relaxing permissions to improve completion rate increases security risk; recording every intermediate step for auditability increases storage and cost pressure. Design requires explicit trade-offs among these goals.

    1.2 Differences Between Agents and Traditional Assistance Tools

    Dimension Traditional assistance tools Software agent
    Unit of interaction Single request and response Multi-step task loop
    Context source Current file or selected snippet Entire repository, runtime logs, test results
    Action capability Generate text suggestions Read and write files, execute commands, call external interfaces
    Result verification Relies on human reading Can be verified through automated tests and check scripts
    Main risk Unstable suggestion quality Unauthorized operations, unintended code changes, resource abuse

    2. Basic Principles of Architecture Design

    In engineering practice, agent system architecture usually follows several basic principles. These are not proprietary specifications of a particular product, but common approaches for building maintainable intelligent systems.

    2.1 Layered Decoupling

    An agent system can be divided into four layers: model interface layer, reasoning and planning layer, tool execution layer, and state and record layer. The layers communicate through clearly defined interfaces. The model interface layer interacts with different model services, the reasoning and planning layer decides the next action, the tool execution layer actually operates on files and commands, and the state and record layer stores the input, output, and results of each step.

    The benefit of layering is local replaceability. When a model service changes, only the interface layer needs adjustment; when a new tool is needed, it only needs to be registered in the tool execution layer without changing planning logic.

    2.2 Execution Environment Isolation

    Commands executed by an agent may delete files, modify configurations, or access networks, so they must run in an isolated environment. Common practices include using containers or lightweight virtualized environments to host execution, restricting file system mount ranges, disabling unnecessary network egress, and assigning an independent working directory to each task. After a task ends, the environment should be destroyed or reset to prevent residual state from affecting later tasks.

    2.3 Observability and Replay

    Every action should leave a structured record, including a summary of model input, the selected tool, parameters, returned results, and elapsed time. Records are valuable in two ways: first, when a problem occurs, it is possible to locate the specific step; second, a task can be replayed with the same input for regression testing and evaluation.

    2.4 Model-Agnostic Interface Design

    The same agent framework should support multiple underlying models so that cost, speed, and capability can be traded off. The implementation approach is to abstract model calls into a unified interface and decouple prompt templates, output parsing, and retry strategies from specific models. This also facilitates fair multi-model comparisons, because all models run with the same tool set and workflow.

    The following simplified interface sketch illustrates the structural idea:

    1. from typing import Protocol, Any
    2. class ModelClient(Protocol):
    3. def complete(self, messages: list[dict[str, Any]], tools: list[dict]) -> dict:
    4. """Return a structured result containing text or a tool-call request."""
    5. ...
    6. class ToolRegistry:
    7. def __init__(self) -> None:
    8. self._tools: dict[str, callable] = {}
    9. def register(self, name: str, fn: callable) -> None:
    10. if name in self._tools:
    11. raise ValueError(f"Tool already exists: {name}")
    12. self._tools[name] = fn
    13. def invoke(self, name: str, arguments: dict[str, Any]) -> Any:
    14. if name not in self._tools:
    15. raise KeyError(f"Unregistered tool: {name}")
    16. return self._tools[name](**arguments)

    In the example, the model client and tool registry are independent of each other, and replacing the implementation of either does not affect the other.

    3. The Core Working Loop of an Agent

    Most software agents operate around a loop of four stages: observe, plan, act, and verify.

    1. Observe: Read the task description, relevant source files, recent error logs, and test output.
    2. Plan: Determine the next goal based on observations, such as locating the function containing a defect or first adding a reproduction script.
    3. Act: Invoke tools to perform concrete operations, such as searching code, editing files, and running tests.
    4. Verify: Check whether the action result meets expectations, and decide whether to continue, roll back, or finish.

    Loop termination conditions need to be clearly defined. Common conditions include all tests passing, reaching the maximum number of steps, detecting repeated ineffective operations, or exceeding the budget limit. Without termination conditions, an agent can easily fall into meaningless repeated attempts, wasting resources and potentially continuously changing code, making the problem harder to diagnose.

    1. def run_task(task: str, model: ModelClient, tools: ToolRegistry,
    2. max_steps: int = 50, budget_tokens: int = 200_000) -> dict:
    3. history = [{"role": "user", "content": task}]
    4. used_tokens = 0
    5. for step in range(max_steps):
    6. response = model.complete(history, tools=list_tool_schemas(tools))
    7. used_tokens += response.get("usage_tokens", 0)
    8. if used_tokens > budget_tokens:
    9. return {"status": "budget_exceeded", "steps": step}
    10. if response.get("finished"):
    11. return {"status": "completed", "steps": step, "result": response["text"]}
    12. call = response["tool_call"]
    13. result = tools.invoke(call["name"], call["arguments"])
    14. history.append({"role": "tool", "name": call["name"], "content": str(result)})
    15. return {"status": "max_steps_reached", "steps": max_steps}

    The list_tool_schemas function in the example describes available tools to the model, which is a common function-calling implementation pattern.

    4. Tool Invocation and Security Boundaries

    Tools are the only way for an agent to affect the external world, so tool design directly determines system security. In practice, the following rules should be followed.

    4.1 Least Privilege

    Each tool should expose only the capabilities necessary to complete the task. For example, code modification tasks usually only need read and write access to the repository directory, not access to system configuration or other projects. Command execution tools should use an allowlist mechanism, permitting only pre-approved commands and argument combinations.

    4.2 Input Validation and Escaping

    Parameters generated by the model are untrusted input. When concatenated into command lines, query statements, or file paths, they must be strictly validated and escaped. Path parameters should be resolved to absolute paths and then checked to ensure they are within allowed directories, preventing path traversal.

    4.3 Secret Management

    Credentials that an agent needs during runtime should be injected through environment variables or a dedicated secret service, and must not be written into prompts, code files, or logs. Fields suspected of containing secrets should be redacted before log output.

    4.4 Human Confirmation for High-Risk Operations

    Operations such as deleting files, pushing code, modifying permissions, and calling external interfaces are irreversible or have a large impact scope, so confirmation steps should be set up. Confirmation policies can be graded by risk level: low-risk operations execute automatically, medium-risk operations are recorded and flagged, and high-risk operations require human approval.

    5. Evaluation System Design

    Evaluation is the basis for determining an agent’s capability boundaries. A reliable evaluation system needs to address four questions: task selection, metric definition, execution method, and result interpretation.

    5.1 Task Types

    Evaluation tasks usually fall into two categories:

    • Code repair tasks: Given a real code repository and a problem description, the agent needs to generate a patch that makes preset tests in the project pass. These tasks can be judged automatically and are suitable for large-scale evaluation.
    • General tasks: The agent is required to complete multi-step operations, such as retrieving information, performing calculations, reading and writing files, and summarizing results. These tasks are closer to daily office and operations scenarios, and judgment criteria often require a combination of rule checks and human sampling.

    5.2 Core Metrics

    • Solve rate: The proportion of tasks completed successfully, the most intuitive metric.
    • Average steps and elapsed time: Reflect efficiency. Too many steps usually indicate insufficient planning capability or unclear tool feedback.
    • Cost: Includes model call billing units and resource consumption of tool execution, determining whether a solution can scale.
    • Failure type distribution: Classify failures as localization errors, modification errors, tool invocation errors, budget overruns, and so on, to support targeted improvement.
    • Stability: Consistency of results across multiple runs of the same task.

    5.3 Common Pitfalls

    Evaluation results can be distorted by poor experimental design. Main risks include:

    1. Data contamination: If evaluation questions or their reference answers have appeared in model training data, scores will be overestimated.
    2. Single-run variance: Model output is stochastic, and a single result is insufficient to demonstrate capability. Multiple samples should be taken and the mean and variance range reported.
    3. Environment differences: Timeout thresholds, dependency versions, and concurrency levels all affect results. These parameters should be fixed and disclosed.
    4. Overfitting to the evaluation set: If a team repeatedly adjusts prompts and workflows for the same evaluation set, score improvements may not represent real capability improvements.

    The following is a simplified evaluation loop sketch:

    1. def evaluate(tasks: list[dict], run_fn, repeats: int = 3) -> dict:
    2. records = []
    3. for task in tasks:
    4. for trial in range(repeats):
    5. outcome = run_fn(task["prompt"], task["repo_snapshot"])
    6. records.append({
    7. "task_id": task["id"],
    8. "trial": trial,
    9. "passed": outcome["status"] == "completed" and task["check"](outcome),
    10. "steps": outcome["steps"],
    11. })
    12. solved = sum(r["passed"] for r in records)
    13. return {"solve_rate": solved / len(records), "records": records}

    The check function in the example should run independently of the agent, executing tests directly in an isolated environment so that the agent does not modify the evaluation logic itself.

    6. Continuous Improvement Based on User Feedback

    Data generated in real usage is an important source for improving agents. Signals that can be collected include whether a task is accepted by the user, the extent to which the user modifies the generated patch, where a task is interrupted or rolled back, and explicit user ratings and textual feedback.

    6.1 Data Collection Principles

    • Explicit consent: Before collection, inform users of the data purpose and provide an opt-out option.
    • Data minimization: Retain only fields needed for improvement, and avoid storing irrelevant personal information and complete sensitive code.
    • De-identification: Replace or delete information such as paths, accounts, and secrets.
    • Access control: Access to datasets should have audit records and be limited to necessary personnel.

    6.2 How Data Is Used

    Feedback data can support improvement at multiple levels:

    • Adjust prompt templates so common failure scenarios receive clearer instructions.
    • Fix tool return formats to reduce model parsing errors.
    • Build targeted training or fine-tuning data to improve performance on specific languages or frameworks.
    • Update the failure case library and add cases to the evaluation set to prevent similar issues from regressing.

    After optimization, re-evaluation is mandatory. Looking only at positive user feedback metrics can easily lead to local optima and ignore degradation in other scenarios.

    7. Comparison Methodology Across Options

    When selecting an underlying model or comparing different solutions, the reliability of conclusions depends on whether the comparison method is fair.

    1. Uniform conditions: Tool sets, prompt templates, step limits, budgets, and timeout settings must be the same.
    2. Multiple runs: Each option should run multiple times on the same task set, and the mean and confidence intervals should be reported.
    3. Independent reproduction: Prefer results run independently by third parties or internal teams, and record the runtime environment.
    4. Dimension-based presentation: Overall capability, cost, speed, and security performance should be listed separately, avoiding the use of a single score to replace all judgment.
    5. Treat conclusions as time-sensitive: Model versions update frequently, so comparison conclusions have a shelf life and should be retested periodically.

    When an individual or team states that a model has “stronger overall capability,” they should explain the task scope and test conditions behind that judgment. Conclusions lacking this information can only serve as reference and cannot directly guide procurement or architecture decisions.

    8. Practical Adoption Recommendations

    Agent adoption should proceed step by step rather than replacing existing workflows all at once.

    8.1 Phased Rollout

    • Pilot stage: Select tasks with clear boundaries and automatic verification, such as adding unit tests or fixing known defect types, and run them in isolated branches.
    • Expansion stage: Based on pilot data, determine the applicable task scope and gradually increase task types and team size.
    • Steady-state stage: Incorporate agents into daily development workflows while retaining monitoring, auditing, and rollback mechanisms.

    8.2 Key Metrics and Acceptance Criteria

    Acceptance criteria should be defined before launch, such as a solve rate reaching a preset threshold, human review pass rate, per-task cost ceiling, and zero security incidents. Metrics should align with business goals, avoiding lowering review standards just to improve numbers.

    8.3 Main Risks and Mitigations

    • Code quality risk: Agent-generated code may pass tests but have design flaws. Code review should be retained, and stricter review rules should be set for critical modules.
    • Security risk: Reduce impact scope through execution isolation, permission control, and secret management, and conduct regular security audits.
    • Cost risk: Set budget caps and alert thresholds, and monitor resource consumption per task.
    • Dependency risk: Avoid binding the entire workflow to a single model service, and retain switching options.

    9. Conclusion

    The value of software agents lies in handing repetitive and verifiable development tasks to the system while allowing people to focus on requirement judgment and design decisions. Adoption effectiveness depends on three foundations: clear architecture layering and security boundaries, reproducible evaluation methods, and continuous improvement based on real feedback. Before adoption, teams should first define target tasks and acceptance criteria, then choose an appropriate scope and pace for gradual rollout.