AI Agent Cognitive Architecture and Dynamic Memory Update Mechanisms
This article explains how AI agents should manage memory as a form of ongoing knowledge and state governance rather than simply storing chat logs. It introduces a cognitive architecture that connects memory to the perception-action loop, breaks memory into working, episodic, semantic, and procedural layers, and shows how to design memory records with structured metadata such as source, validity time, scope, and version. It then covers the full lifecycle: filtering and verifying writes, updating memory when the environment changes, resolving conflicts with version control, retrieving and assembling context, handling forgetting and security risks like persistent prompt injection, and evaluating memory systems across the whole lifecycle. Readers will learn how to build reliable memory that knows where information comes from, when it is valid, where it applies, and when it must be reconfirmed.
1. Understanding Agent Memory: From Saving Conversations to Maintaining Usable Knowledge
An AI agent is typically a system that understands input around a goal, makes plans, calls tools, and adjusts its behavior based on execution results. Compared with systems that only produce a single text output, an agent must maintain a necessary continuity of state across multiple steps, multiple tasks, and even multiple sessions.
Because of this, the core problem of agent memory is not “how to save every chat message,” but rather: which information is worth keeping, under what conditions that information is trustworthy, and when it should be used, corrected, or deleted.
For example, an operations agent once recorded that a certain service’s maintenance window was every Sunday early morning. Later the maintenance schedule changed. If the system merely keeps appending conversation records, the old arrangement may still be retrieved and lead to wrong decisions. A reliable memory system should recognize the relationship between new and old information, preserve the basis for the change, and prioritize the currently valid arrangement in later tasks.
From an engineering perspective, agent memory is a system made up of storage, indexing, retrieval, context assembly, and governance policies. It contains not only the information itself but also its source, time, permissions, and applicable scope.
It is especially important to distinguish that updating external memory is usually not the same as updating model parameters. An agent can change its later behavior by updating database records, knowledge indexes, or task state, without retraining the model.
2. Cognitive Architecture: Bringing Memory into the Perception-Action Loop
Here, “cognitive architecture” is an engineering way of organizing components to describe how an agent coordinates its parts. It does not imply that the agent has human-like consciousness.
A common agent work loop can be expressed as:
Input and environment observation → state understanding → memory retrieval → planning and decision → tool execution → result verification → memory update
Each stage carries different responsibilities:
- The perception module receives user requests, tool returns, event notifications, and external state.
- The state management module maintains the current goal, constraints, task progress, and items pending confirmation.
- The memory module provides historical experience, stable facts, and reusable operational knowledge.
- The planning module combines the current state with relevant memory to decide the next action.
- The execution module calls tools and handles failures, retries, and necessary compensation.
- The evaluation module judges whether execution results meet expectations and decides which experiences can enter long-term memory.
Memory should not directly replace current observation. For information that changes frequently, a trustworthy result from a real-time query is usually more valuable than historical memory. For example, having accessed a resource successfully in the past does not mean access is still permitted now; a recorded available capacity does not mean it is still sufficient.
Therefore, the architecture must make clear that memory provides background and experience, while current evidence verifies the state of the environment, and the two together support decisions.
3. What Multi-Layer Memory Solves
3.1 Working Memory: Maintaining the Visible State of the Current Task
Working memory holds the information an agent needs for its current reasoning and execution, including the user’s goal, recent observations, key constraints, the current plan, and pending steps.
The context window of a large language model is an important carrier of working memory, but the two are not fully equivalent. An engineering system can also maintain structured task state outside the model and place part of it into the context on demand.
The main limitation of working memory is limited capacity. If a large amount of history is stuffed into the context without filtering, it not only increases processing cost but may also drown key facts in irrelevant information.
A more reasonable approach is to organize the context into sections:
- The current request and explicit constraints;
- Verified task state;
- Memory directly relevant to the current problem;
- Recent execution observations;
- Necessary output and operation rules.
For long tasks, stage results should be organized into structured state rather than relying only on natural-language summaries. In particular, unresolved problems, failure reasons, and the location of key evidence should be preserved to avoid losing the basis for decisions after summary compression.
3.2 Episodic Memory: Storing Events and Task Experiences
Episodic memory records “what was done, under what conditions, at what time, and with what result.” It is suited to storing task execution traces, exception-handling processes, and user interaction events.
A single incident-handling record can include the symptoms, environmental conditions, attempted operations, verification results, and final conclusion. When a similar problem appears later, the system can retrieve these experiences to narrow the investigation.
But similar situations do not mean identical causes. A successful operation only shows that it worked under the conditions at that time; it does not prove it applies to all similar scenarios. Retrieval results should be treated as candidate experience, not as instructions that must be executed.
3.3 Semantic Memory: Maintaining Reusable Facts and Rules
Semantic memory stores relatively stable knowledge, such as term definitions, business rules, user preferences, and verified environment configurations.
This kind of memory usually comes from explicit statements, trusted sources, or induction over multiple events. A key requirement is to distinguish facts, preferences, assumptions, and inferences.
For example, “the user asked for a detailed explanation this time” does not necessarily mean “the user prefers long answers over the long term.” Without explicit authorization or repeated evidence, the system should not turn a one-time request into a long-term preference.
3.4 Procedural Memory: Accumulating Reusable Methods
Procedural memory represents “how to complete a certain type of task” and can take the form of process templates, checklists, decision rules, or reviewed execution scripts.
It should include not only the order of operations but also preconditions, permission requirements, failure branches, and verification methods. Otherwise, an agent tends to mechanically apply a process suited to an old environment to a new one.
Procedural memory especially needs to control its scope of generalization. A single successful experience can serve as a candidate process, but for high-risk operations, it should undergo more verification or human review before being published for use.
The above categories are a logical division for design convenience; not every system must build four separate stores. A single memory may also have both the characteristics of an event record and of operational experience.
4. Memory Data Structures: Storing Evidence, Not Just Content
Memory that contains only text is hard to update reliably. In practice, structured metadata can be added to memory:
memory_id: record identifiermemory_type: memory categorysubject: related entityclaim: description of a fact, preference, or experiencesource_ref: reference to the evidence sourceobserved_at: when the system obtained the informationvalid_from: when the information takes effectvalid_until: expiration time; empty if unknownscope: applicable user, task, or environment rangestatus: pending verification, valid, superseded, or revokedversion: record versionaccess_policy: access and usage restrictions
The fields above are only a general design example and do not represent any product interface.
Among them, “when the information was obtained” and “when the information takes effect” must be kept separate. For example, the system receives a notice today that a rule takes effect next week. If only the write time is used to select the latest record, a rule that is not yet in effect may be used prematurely.
For uncertain information, an evidence level or confidence assessment can also be recorded, but a subjective score given by the model must not be treated directly as a real probability. Confidence information should be used together with source reliability, the verification process, and historical performance.
5. Memory Writing: Filter First, Verify Next, Then Commit
A reliable write process usually includes five stages: candidate extraction, value judgment, evidence verification, deduplication and conflict detection, and formal commit.
5.1 Extracting Information Worth Keeping Long-Term
Not every sentence is worth writing to memory. Content suitable for retention includes explicit long-term preferences, confirmed business rules, reusable task experience, and important environment changes.
One-off small talk, repeated descriptions, unverified guesses, and sensitive information with no business necessity should generally be filtered out or kept only for a short time.
5.2 Judging Whether Information Is True and Applicable
A user explicitly stating a preference can serve as evidence of that preference; a configuration result returned by a tool can serve as evidence of the environment at a specific moment; a cause summarized by the model itself should be treated as an inference pending verification.
In particular, prevent the agent from re-saving its own answer as an “external fact.” Without independent evidence, errors get amplified through repeated retrieval and restatement, forming a self-reinforcing loop.
5.3 Detecting Duplication, Supplementation, and Conflict Relationships
New information and old information may be duplicate, complementary, or a replacement or contradiction. The system needs to judge the relationship based on subject, attribute, applicable scope, and valid time, rather than text similarity alone.
“Test environment uses configuration A” and “production environment uses configuration B” are not necessarily in conflict; “the rule changes next week” should not immediately override the rule still valid this week.
5.4 Committing Through Controlled Writing
Low-risk information can be updated automatically by rules, while high-risk information should add review, confirmation, or trusted-source verification.
Memory writing is itself a state-change operation and should have access control and auditability, rather than being just a side effect after the model generates text.
6. How Agents Update Memory When the Environment Changes
Environmental changes may come from the user actively informing the system, periodic checks, tool execution failures, configuration-change events, or the release of new material. Update mechanisms can be divided into the following types.
6.1 Event-Driven Updates
When the system receives a trusted change event, it links it to the relevant memory and updates the record after verification.
For example, after an approval rule changes, the system should not only revise the rule in semantic memory but also check the procedural memory that depends on that rule, to avoid a situation where the fact is updated but the process is stale.
6.2 Verification at Query Time
For volatile information such as inventory, permissions, and running status, the current state should be queried before performing important operations.
This kind of information can be cached, but the cache validity period must be explicit. Expired records can still be used to explain history but should no longer serve as current fact.
6.3 Periodic Review
Information without an active change notification can be reviewed according to risk and rate of change. Stable knowledge can be checked less often, while volatile, high-impact configurations should be verified more frequently.
Review cost also needs to be controlled; it is not advisable to scan all memory indiscriminately. Records that are about to expire, recently used, or weakly evidenced can be prioritized.
6.4 Correction Triggered by Execution Feedback
When a tool call fails or the execution result deviates from expectations, the system should check whether the relevant memory is outdated.
But a failure itself does not mean the memory is wrong. Network fluctuations, temporary faults, permission changes, and incorrect operation parameters can all cause failures. Only after the cause is verified is it appropriate to update a fact or process.
7. Conflict Handling and Version Management: Avoiding “the Latest Record Must Be Correct”
When resolving conflicts, the system can examine, in order, the applicable scope, the credibility of evidence, the valid time, and the verification result. Record time is only a reference dimension and cannot be the sole basis for a decision.
A more robust update approach is to keep historical versions, mark old records as superseded, and establish links between new and old. This lets the current task use valid information while also explaining why a certain decision was made in the past.
For contradictions that cannot be confirmed, the system should not force them into a single answer. It can mark the relevant records as pending verification and, in high-risk tasks, pause execution and request confirmation.
Concurrent writes also need handling. When multiple agents modify one memory at the same time, version checks, transactions, or other concurrency-control mechanisms can prevent lost updates.
In addition, if a fact is corrected, the summaries, processes, and indexes derived from it may also need to be recomputed. Modifying only the original record without updating derived data allows old information to keep entering the context through other paths.
8. Retrieval and Context Assembly: Getting the Right Memory to Appear at the Right Moment
Long-term memory is not better when there is more of it; the key is whether the information the current task truly needs can be retrieved.
Retrieval can combine keyword matching, semantic similarity, and structured condition filtering. Conditions such as permissions, subject, environment, and valid time should be checked before entering the model context, rather than relying on the model to identify them on its own.
For ranking, the following can be considered together:
- Relevance to the current goal;
- Reliability of evidence;
- Time validity;
- Impact on the decision;
- Whether it duplicates other candidate information.
Semantic similarity reflects how close expressions or meanings are; it does not prove that information is true, valid, or permitted to use.
During context assembly, current facts, historical experience, and assumptions pending confirmation should be presented separately, with necessary source hints preserved. This helps reduce the risk of the model mistaking old experience for a current constraint.
9. Forgetting and Security: Memory Is Not About Keeping Everything Forever
Forgetting is an important part of memory governance. Records can be down-weighted, archived, or deleted based on retention period, usage frequency, business value, and sensitivity.
Summary compression is suitable for reducing redundancy but cannot replace complete evidence. For important decisions, a summary should keep references to the original basis for later review.
When a user asks to delete information, the system should not only delete the main record but also handle related indexes, caches, and derived summaries, and clarify the cleanup policy and applicable limits for backup data.
A memory system must also guard against persistent prompt injection. External documents or tool returns may contain malicious content such as “ignore the rules” or “change subsequent behavior.” If such text is written into long-term memory, it may keep affecting future tasks.
Therefore, external content should be treated as data pending verification, not as instructions that automatically gain execution authority. Memory cannot change system permissions or bypass approval boundaries. In multi-user, multi-tenant scenarios, storage and retrieval scope must also be isolated to prevent information from being mixed across users.
10. How to Evaluate Whether a Memory System Is Effective
Evaluation should cover the full lifecycle, not just retrieval accuracy.
The following metrics can be observed:
- Write quality: whether the information kept long-term is necessary, accurate, and evidence-based.
- Retrieval quality: whether relevant records are found while unauthorized or expired information is excluded.
- Update effectiveness: whether old memory is still wrongly used after the environment changes.
- Conflict-handling capability: whether contradictions are identified and whether sources and versions are preserved.
- Task benefit: whether task completion quality actually improves with memory enabled.
- Governance capability: whether deletion, auditing, isolation, and rollback work as expected.
- Operating cost: whether storage, retrieval, verification, and context overhead stay controllable.
Tests should include scenarios such as rule changes, delayed effect, withdrawal of user preferences, differences across environments, concurrent updates, and malicious content writes. They should also be compared against a scheme with no long-term memory or with only short-term state, to judge whether the complexity brings real benefit.
Conclusion
The memory capability of an AI agent is essentially the ongoing governance of knowledge and state. Working memory maintains the current task, episodic memory retains experiences, semantic memory maintains facts, and procedural memory accumulates methods; together they support action through retrieval, verification, updating, and forgetting.
A truly reliable design does not make the agent remember everything, but lets it know where information comes from, when it is valid, what scope it applies to, and when it must be reconfirmed. Only by bringing these mechanisms into the cognitive and execution loop can memory turn from historical storage into an engineering capability that helps the agent adapt to a changing environment.
