How Deep Agents Implements Memory: AGENTS.md Injection as Procedural Memory

This article maps cognitive psychology's semantic, episodic, and procedural memory to AI agent architecture, then details Deep Agents' MemoryMiddleware implementation that loads AGENTS.md files at initialization and injects their content into system prompts, functioning as procedural memory with semantic elements.

Code Archaeology
Code Archaeology
Code Archaeology
How Deep Agents Implements Memory: AGENTS.md Injection as Procedural Memory

1. Cognitive Psychology Concepts

In cognitive psychology, long-term memory is divided into three types:

Semantic memory — memory for facts, like an encyclopedia stored in the brain, without specific time, place, or emotion.

Episodic memory — memory for personal experiences at specific times and places, like a private diary with timestamps and emotional color.

Procedural memory — memory for how to do things, covering skills, habits, and operational steps; it runs largely unconsciously, like the brain's operating system.

These three often work together. For example, learning a piano piece: semantic memory decodes the sheet symbols; episodic memory recalls the teacher correcting your fingering last week; procedural memory lets your fingers press keys automatically without conscious step-by-step thought.

2. Mapping Concepts to AI Agents

The three concepts map to AI agent architecture as design patterns:

2.1 Semantic Memory → Knowledge Base / Vector Store

Semantic memory corresponds to the agent's static knowledge reserve . It acts as a long-term memory warehouse storing facts, concepts, and business documents. Typically implemented with a vector database plus an embedding model. The agent's LLM has general knowledge; private data is chunked, vectorized, and stored for retrieval.

2.2 Episodic Memory → Conversation History / Session Cache

Episodic memory corresponds to the current session context — what just happened between the agent and the user — essential for conversational coherence. It lets the agent remember what the user said earlier, avoiding a fresh-start response each turn.

2.3 Procedural Memory → Tools / Chains / Agent Execution Logic

Procedural memory corresponds to the agent's ability to act . It determines whether the agent is only a theorist that chats or an executor that can perform tasks.

2.4 Collaboration in an Agent: Medical Consultation Assistant Example

Semantic memory (knowledge base) : Vector database stores medical textbooks and drug inserts. When the user asks "What are aspirin's side effects?", the agent retrieves relevant passages.

Episodic memory (conversation history) : ChatMessageHistory holds the dialogue. When the user follows up "What about taking it with ibuprofen?", the agent knows "that" refers to aspirin and answers the interaction.

Procedural memory (tools and execution) : The agent has a Calculator tool and a MedicalDatabaseAPI. For "Based on my 80 kg weight, what aspirin dosage?", the agent triggers procedural memory, calls the calculator or API, and returns a natural-language answer.

3. Deep Agents' MemoryMiddleware

Deep Agents' MemoryMiddleware provides memory capability closest to procedural memory, but may also include partial semantic memory .

3.1 before_agent Loads State

MemoryMiddleware

runs only during main agent initialization; due to state isolation between main and sub-agents, its information does not leak to sub-agents.

def before_agent(self, state, runtime, config):
    """Load memory before agent execution"""
    # 1. Check if already loaded (avoid duplication)
    if "memory_contents" in state:
        return None
    # 2. Resolve backend
    backend = self._get_backend(state, runtime, config)
    contents = {}
    # 3. Batch download all source files
    results = backend.download_files(list(self.sources))
    # 4. Process each source
    for path, response in zip(self.sources, results, strict=True):
        if response.error is not None:
            if response.error == "file_not_found":
                continue  # file missing, skip
            raise ValueError(f"Failed to download {path}: {response.error}")
        if response.content is not None:
            contents[path] = response.content.decode("utf-8")
            logger.debug("Loaded memory from: %s", path)
    # 5. Return state update
    return MemoryStateUpdate(memory_contents=contents)
sources

are typically AGENTS.md files at various path levels. AGENTS.md has become a de facto standard (see agents.md at https://agents.md/). The memory_contents state stores file content keyed by file path.

3.2 wrap_model_call Assembles System Prompt

The wrap_model_call hook assembles memory_contents into the system prompt.

def modify_request(self, request: ModelRequest) -> ModelRequest:
    """Inject memory into system message"""
    # 1. Get loaded memory contents
    contents = request.state.get("memory_contents", {})
    # 2. Format as system prompt
    agent_memory = self._format_agent_memory(contents)
    # 3. Append to existing system message
    new_system_message = append_to_system_message(
        request.system_message,
        agent_memory
    )
    # 4. Return modified request
    return request.override(system_message=new_system_message)

Formatting logic in _format_agent_memory:

def _format_agent_memory(self, contents: dict<str, str>) -> str:
    """Format memory contents"""
    if not contents:
        return MEMORY_SYSTEM_PROMPT.format(agent_memory="(No memory loaded)")
    # Build sections in source order
    sections = [
        f"{path}
{contents[path]}"
        for path in self.sources
        if contents.get(path)
    ]
    if not sections:
        return MEMORY_SYSTEM_PROMPT.format(agent_memory="(No memory loaded)")
    memory_body = "

".join(sections)
    return MEMORY_SYSTEM_PROMPT.format(agent_memory=memory_body)

Sample assembled prompt:

<agent_memory>
~/.deepagents/AGENTS.md
# User Preferences
I prefer Python and concise code style.

./.deepagents/AGENTS.md
# Project Guidelines
This project uses TypeScript and follows ESLint rules.
</agent_memory>

<memory_guidelines>
[Detailed memory update guidelines...]
</memory_guidelines>

The update mechanism resides in the memory_guidelines section of the system prompt . When certain scenarios occur, the agent updates memory via the edit_file tool:

User explicitly asks to remember

User describes a role or behavior

User gives feedback on work quality

Information needed for tool use

Context useful for the future

Newly discovered patterns or preferences

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

AI agentsAGENTS.mdLLM Engineeringprocedural memoryDeep AgentsMemoryMiddleware
Code Archaeology
Written by

Code Archaeology

Learn from the past to understand the present

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.