Growing AI Agent Architecture: Practices in Closed-Loop Learning and Persistent Memory

    This article explores the architectural design of growing AI agents capable of accumulating operational experience across sessions. It details how to implement closed-loop learning to transform validated task results into reusable skills, design a three-tier memory system for persistent state, and decouple architecture to enforce execution boundaries. Additionally, it outlines evaluation metrics and a phased approach for building a trustworthy, continuously improving agent system.

    1. From “Answering” to “Accumulating”: The Core Problem

    In a complex task, an AI agent may successfully understand the project directory, deployment constraints, user preferences, and troubleshooting procedures. However, if this information is not saved and properly loaded in a subsequent session, the system must collect the background context all over again, potentially repeating past mistakes.

    This phenomenon should not simply be attributed to the model lacking memory. More accurately, model inference typically relies only on the context provided in the current request. Whether cross-session state can be sustained depends on whether the application layer has designed mechanisms for persistence, retrieval, and updating. While some conversational systems already feature history logging or preference saving, “having saved information” is not equivalent to “reliably utilizing experience.”

    Therefore, a growing AI agent must answer three questions:

    1. After a task is completed, what experience is worth retaining?
    2. During the next execution, how can the system find applicable information and discard outdated content?
    3. How can the system continuously accumulate capabilities while maintaining controllable behavior, clear permissions, and verifiable results?

    The corresponding engineering approach involves: accumulating operational experience through closed-loop learning, saving long-term state through hierarchical memory, and controlling execution boundaries through architectural decoupling. The “growth” here primarily refers to the continuous improvement of application-layer knowledge and workflows, and should not be directly interpreted as an update to the underlying model’s parameters.

    2. Closed-Loop Learning: Turning Tasks into Reusable Capabilities

    2.1 Task Completion Does Not Equal Valid Experience

    A common agent workflow can be summarized as: “understand goal—plan steps—invoke tools—check results—output conclusion.” Without subsequent processing, effective experience gained during execution remains only in the session record and is difficult to reuse reliably.

    However, directly saving every successful process as a skill carries risks. An operation might succeed by chance or depend on the specific environmental state at the time. For example, a deployment process passing in a test environment does not mean it can be directly applied to a production environment.

    Therefore, the entry point for closed-loop learning should be “verified task results,” not the model’s self-proclaimed completion. Verification criteria can include test results, service health checks, output validation, and user confirmation. For tasks involving data modification, production changes, or external communications, audit evidence of key operations should be retained.

    2.2 Distilling Processes, Not Copying Logs

    Execution logs answer “what happened,” whereas skill documentation answers “under what conditions, what should be done.”

    A reusable skill typically needs to include:

    • Scope: What types of problems it solves, and which scenarios it is not applicable to.
    • Preconditions: Required permissions, input information, and environmental constraints.
    • Parameter Definitions: Which values are provided by task input, and which are determined after inspection.
    • Execution Steps: Operation sequence, checkpoint nodes, and branch handling.
    • Success Criteria: What evidence proves the objective has been achieved.
    • Failure Handling: When to stop, how to roll back, and when to request human intervention.
    • Maintenance Information: Version, verification time, applicable environment, and responsible person.

    Taking containerized deployment as an example, a skill should abstract the process of “check artifacts—verify configuration—execute release—confirm health status—rollback if necessary,” rather than hardcoding a specific server address or temporary credentials used in a previous release.

    Parameterization also cannot rely solely on text replacement. Target environments, artifact versions, and release scopes should undergo format checking and permission validation to avoid directly converting unverified inputs into execution commands.

    2.3 Establishing a Lifecycle for Candidate, Evaluation, and Release

    Automatically generated experience is better suited as a candidate skill rather than immediately becoming an official capability. The following lifecycle is recommended:

    Task verification passed → Extract candidate experience → Sanitize sensitive information → Offline evaluation → Manual review or policy approval → Versioned release → Runtime monitoring.

    Candidate skills need to be verified across multiple representative scenarios to check whether they over-rely on a single environment, omit exception branches, or introduce additional risks. Modifications to existing skills should also undergo regression testing against the baseline version.

    If a new version introduces a higher failure rate, more invalid tool calls, or privilege escalation, the release should be halted, and the old version restored. The value of a closed loop is not “continuously producing more documents,” but “continuously filtering out more reliable execution methods.”

    2.4 Prompt Optimization vs. Model Training

    The system can use evaluation feedback to improve skill descriptions, tool instructions, and task prompts, such as supplementing missing verification steps, clarifying prohibited conditions, or adjusting easily misunderstood phrasing. These improvements can be completed via model calls without involving model parameter training.

    However, this does not imply “no computational cost” or “inevitable order-of-magnitude improvements.” Candidate generation, repeated evaluation, and regression testing all consume resources, and the effectiveness depends on task distribution and evaluation quality.

    Engineering efforts should clarify optimization goals: whether to increase success rate, reduce cost, shorten execution time, or lower the incidence of high-risk operations. Conflicts may arise among multiple goals, requiring prioritization based on business risk.

    3. Three-Tier Memory: Storing, Retrieving, and Revoking Information

    3.1 Long-Term Memory: Stable and Explicit Information

    Long-term memory is suitable for storing relatively stable user preferences and project constraints, such as output language, documentation style, change approval requirements, and project runtime environments.

    This type of information should be kept concise, recording its source, update time, and scope of application. Preferences explicitly confirmed by the user have a different level of credibility than those inferred by the system from a single conversation and should not be conflated.

    Long-term memory should also not store all chat content. Temporary discussions, unverified guesses, and one-off environmental states, if retained long-term, may adversely affect subsequent judgment. Sensitive information like passwords and access tokens should be handled by dedicated credential management mechanisms rather than being fed to the model as ordinary memory.

    3.2 Session Retrieval: Restoring Processes and Historical Context

    Historical sessions are better suited for saving decision processes, troubleshooting paths, and task context. When a user requests to “continue handling the previous failure,” the system needs to retrieve relevant session fragments rather than loading the entire history.

    The retrieval process can combine keyword matching, semantic similarity, and structured filtering. Project, time, task type, user identity, and permission scope should serve as important filter criteria.

    After a retrieval hit, timeliness must still be checked. For instance, past configuration instructions might have been replaced by a new solution. The system should prioritize currently valid materials and prompt the user for confirmation in case of conflicts, rather than assuming historical content is always correct.

    Session summaries can reduce context costs, but summaries might omit constraints. Therefore, for critical operations, the system should allow tracing back to original records, avoiding execution based solely on compressed conclusions.

    3.3 External Knowledge Integration: Fetching Latest Business Facts

    Long-term memory and historical sessions cannot replace business systems. Information such as inventory, work orders, configuration states, and latest approval results should be read from authorized external data sources.

    Standardized connection layers can be used to integrate document repositories, databases, object storage, or other business systems. However, it is necessary to distinguish between two uses: one is retrieving static knowledge, and the other is querying or modifying real-time state. The latter typically requires stricter permissions and approval controls.

    External content also cannot directly become system instructions. Text in documents, prompts in logs, and operational suggestions in search results should all be treated as data to be analyzed and must not gain the ability to modify permission policies or bypass approvals.

    3.4 Memory Governance Over Storage Scale

    A persistent system should possess at least the following governance capabilities:

    • Isolation: Divide access scopes by user, organization, and project.
    • Update: Allow new facts to correct old records while retaining necessary change evidence.
    • Expiration: Set validity periods or review conditions for volatile information.
    • Deletion: Support users revoking memory and handle associated indexes and caches.
    • Traceability: Be able to explain where a specific memory came from and why it was used.

    When memory conflicts occur, the result should not be determined solely by generation time. Source credibility, explicit confirmation status, and scope of application are equally important. When judgment is impossible, the system should ask the user rather than silently selecting one version.

    4. Architectural Decoupling: Preventing Uncontrollable Monoliths

    A growing AI agent can be divided by responsibility into modules: model access, task orchestration, tool execution, memory and skills, and evaluation/audit.

    The model access layer handles unified inference requests and output processing; the task orchestration layer manages task states, step dependencies, timeouts, and retries; the tool execution layer handles real-world operations; the memory and skills layer manages knowledge versioning and retrieval; and the evaluation/audit layer records evidence and judges whether results meet standards.

    The primary value of this division is not merely the ease of replacing components, but the clarification of responsibility boundaries. The model can propose operational plans but cannot autonomously expand execution permissions; memory can provide background but cannot automatically change approval rules; skills can guide workflows but cannot exempt the tool side from input validation.

    4.1 Enforcing Tool Permissions Programmatically

    Simply writing “do not modify the production environment” in the prompt is insufficient. Actual tools should validate based on identity, resource scope, and operation type.

    For operations such as deleting data, changing production configurations, or sending external notifications, explicit confirmation can be required, displaying the target, impact scope, and rollback method. The execution environment should employ the principle of least privilege, restricting network access and writable directories to mitigate the impact of operational errors.

    4.2 Recoverable State Management for Long-Running Tasks

    If a task spans multiple steps, the system should save stage states and key outputs. After a process restart, it should recover from the confirmed state rather than blindly executing from the beginning.

    For operations that produce side effects, idempotent mechanisms should be designed. For example, checking whether the target change has already been completed before retrying, to avoid duplicate resource creation, duplicate message sending, or duplicate modifications.

    A timeout also does not equate to operation failure. The system needs to distinguish between “execution failed,” “result unknown,” and “execution succeeded but response lost,” adopting different recovery strategies accordingly.

    Observability needs to cover task steps, tool calls, error classifications, memory reads, and skill versions, but logs should not indiscriminately save sensitive content.

    It is recommended to desensitize credentials and personal information, and set retention periods based on data types. When an error occurs, the system should be able to pinpoint whether it was due to retrieval inaccuracy, skill inapplicability, tool failure, or missing validation rules, rather than just logging “task incomplete.”

    5. Evaluating Agent Effectiveness

    Whether a growing AI agent is worth the investment cannot be judged solely by demo effects or the number of generated skills. It should be evaluated through fixed task sets and real usage feedback using the following metrics:

    • Task Success Rate: Whether predefined goals are met, rather than just providing plausible-sounding answers.
    • Experience Reusability Quality: Whether loading old skills improves the success rate or reduces repetitive work.
    • Memory Accuracy: Whether saved information is correct and outdated information is identified promptly.
    • Risk Control Capability: Whether privilege escalation, mis-execution, data leakage, or approval bypass occurs.
    • Resource Cost: The total investment including inference, retrieval, evaluation, storage, and manual review.
    • Recovery Capability: Whether tasks can resume after interruption and erroneous changes can be rolled back.

    During evaluation, a baseline “without long-term memory or skill reuse” should be established for comparison under identical tasks and environments. For low-frequency, high-risk tasks, lack of experience is often more dangerous than a lengthy process. In such cases, prioritizing manual confirmation over pursuing full automation is advisable.

    6. Starting with a Minimum Viable Closed Loop

    In practice, there is no need to build a complete self-evolving system all at once. A more prudent route is to first select scenarios with high repetition rates, verifiable results, and limited impact, such as internal document organization, test environment checks, or standardized failure information collection.

    • Phase 1: Save structured task records and clarify success and failure criteria.
    • Phase 2: Manually distill a small number of skills and establish versioning and regression testing.
    • Phase 3: Introduce long-term preferences and historical retrieval, and refine deletion, expiration, and isolation mechanisms.
    • Phase 4: Allow the system to generate candidate improvements while retaining approval and gray release processes.

    The scope of automation should only be gradually expanded when evaluations prove that experience reuse is indeed effective and risk control covers the real execution path.

    The core of a growing AI agent is not granting the system infinite memory or allowing it to modify everything autonomously, but establishing a trustworthy experience management mechanism: summarizing with evidence, storing within boundaries, reusing under conditions, and improving under supervision. By achieving these, an agent can evolve from a one-off Q&A interface into a collaborative system capable of continuously reducing repetitive labor and accumulating working methodologies.