> ## Documentation Index
> Fetch the complete documentation index at: https://docs.zeus.agentspro.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# Memory

> Zeus Memory System — Architecture, Implementation & Personalization

## Overview

Zeus's memory system provides the Agent with cross-session user awareness capabilities. By extracting, storing, and retrieving key information from conversations, the Agent continuously accumulates understanding of users and projects, delivering personalized, contextually coherent interactions.

The memory system addresses three core problems:

* **Personalization**: Remember user preferences (coding style, language, toolchain) without requiring repeated explanation
* **Context Continuity**: Maintain awareness of project background and technical decisions across sessions
* **Intelligent Reasoning**: Make more accurate judgments and suggestions based on historical memory

***

## Architecture

### Four-Layer Memory Model

Zeus's memory system consists of four layers with different lifecycles, forming a complete cognitive hierarchy from ephemeral runtime state to permanent user profiles.

```mermaid theme={null}
graph TB
    subgraph WM["Working Memory"]
        direction LR
        wm_desc["todo_list · tool_calls · intermediate reasoning state"]
    end

    subgraph STM["Short-term Memory"]
        direction LR
        stm_desc["Current session message list · conversation context"]
    end

    subgraph LTM["Long-term Memory"]
        direction LR
        ltm_desc["User preferences · project context · skills · decision records"]
    end

    subgraph EM["Episodic Memory"]
        direction LR
        em_desc["Session snapshots · Agent state · pending approval operations"]
    end

    WM -->|"Destroyed after task completion"| STM
    STM -->|"Important info extraction"| LTM
    STM -->|"State persistence"| EM
    EM -->|"Interrupt recovery"| STM

    WM -.- mem["Memory"]
    STM -.- pg1["PostgreSQL · message"]
    LTM -.- pg2["PostgreSQL + pgvector"]
    EM -.- pg3["PostgreSQL · checkpoint"]
```

| Layer             | Lifecycle                | Storage                       | Responsibility                                                                             |
| ----------------- | ------------------------ | ----------------------------- | ------------------------------------------------------------------------------------------ |
| Working Memory    | Single Agent invocation  | In-memory                     | Temporary context for task execution: todo\_list, tool\_calls, reasoning state             |
| Short-term Memory | Single session           | PostgreSQL (message table)    | Current session conversation history, automatically compressed via SummarizationMiddleware |
| Long-term Memory  | Permanent (user-managed) | PostgreSQL + pgvector         | Cross-session user/project information, supports semantic retrieval                        |
| Episodic Memory   | Recoverable              | PostgreSQL (checkpoint table) | Session state snapshots, supports page refresh, interrupt recovery, error retry            |

### Three-Layer Data Architecture (memU)

Long-term Memory adopts a memU-inspired three-layer structure, progressively abstracting raw resources into structured profiles:

| Layer   | Name              | Content                                                                                                          | Description                                                                                                       |
| ------- | ----------------- | ---------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| Layer 1 | Resource Layer    | Chat conversations, Knowledge Base documents, Project Resources                                                  | Raw data sources — the original material from which memories are extracted                                        |
| Layer 2 | Memory Item Layer | preference, fact, skill, habit, event, context, constraint, decision                                             | Structured memory entries extracted from raw data, categorized by type                                            |
| Layer 3 | Profile Layer     | User Profile (global preferences, professional background), Project Profile (tech stack, constraints, decisions) | Aggregated profiles injected directly into the [System Prompt](/en/documentation/core-capabilities/system-prompt) |

Data flows upward: Layer 1 raw resources are **extracted** into Layer 2 memory items, which are then **aggregated** into Layer 3 profiles.

***

## Data Model

### Memory Item

Memory items are the core data unit of the system. Each memory entry contains content, classification, scope, and metadata. Key fields include:

* **content**: Memory content text
* **memory\_type**: Memory type classification
* **scope** / **scope\_id**: Scope (user / project / session) and corresponding ID
* **source** / **source\_id**: Source (user / ai / knowledge\_base / project\_resource) and associated ID
* **confidence**: Confidence score (0.0 \~ 1.0)
* **visibility**: Visibility range (public / members / owner\_only), only effective for project scope
* **status**: Status (active / archived / superseded)
* **last\_used\_at**: Last retrieval timestamp

### Memory Type

Each type corresponds to different kinds of information. The Agent must select the correct type when extracting memories:

| Type         | Semantics           | Example                                   |
| ------------ | ------------------- | ----------------------------------------- |
| `preference` | User preferences    | Likes concise code, prefers dark theme    |
| `fact`       | Factual information | User is a frontend engineer, named John   |
| `skill`      | Skill level         | Proficient in React, expert in TypeScript |
| `habit`      | Usage habits        | Frequently uses VS Code, prefers Git Flow |
| `event`      | Important events    | Completed Project A launch                |
| `context`    | Project context     | Currently developing the payment module   |
| `constraint` | Constraints         | Project must support PostgreSQL 16        |
| `decision`   | Decision records    | Chose Next.js over Remix                  |

### Memory Scope

Scope determines the visibility and lifecycle of memories:

```mermaid theme={null}
graph LR
    subgraph UserScope["user scope"]
        direction TB
        us_desc["Cross-project, cross-session<br/>Personal information<br/>e.g.: profession, preferences, skills"]
    end
    subgraph ProjectScope["project scope"]
        direction TB
        ps_desc["Shared among project members<br/>Project-specific context<br/>e.g.: tech stack, conventions, constraints"]
    end
    subgraph SessionScope["session scope"]
        direction TB
        ss_desc["Current session only<br/>Temporary information<br/>e.g.: intermediate results, temporary decisions"]
    end

    SessionScope -->|"Highest priority"| ProjectScope -->|"Second priority"| UserScope
```

### User Profile

The user profile aggregates global user characteristics and is injected into the System Prompt for every conversation. Key fields include:

* **username**: Username
* **background**: User background description
* **profession**: Profession
* **communication\_style**: Communication style (concise / detailed / technical)
* **response\_format**: Response format preference (markdown / plain / code)
* **language\_preference**: Language preference (zh-CN / en / ja, etc.)
* **characteristics**: Personality traits
* **content**: Custom Instructions
* **expertise\_areas**: Areas of expertise
* **programming\_languages**: Programming languages
* **frequently\_used\_tools**: Frequently used tools

### Project Profile

The project profile records team-shared project context. Key fields include:

* **project\_goal**: Project goal
* **tech\_stack**: Technology stack
* **constraints**: Constraints
* **key\_decisions**: Key decisions (including decision content, rationale, and timestamp)
* **team\_conventions**: Team conventions
* **current\_phase**: Current phase

***

## Core Components

### MemoryService

`MemoryService` is the core service of the memory system, managing memory read/write and retrieval. It interacts with both PostgreSQL (metadata) and pgvector (vector index).

```mermaid theme={null}
graph TD
    subgraph MemoryService["MemoryService"]
        gate["Gate<br/>validate_memory()<br/>check_duplicate()<br/>check_rate_limit()"]
        write["Write<br/>add_explicit_memory()"]
        search["Retrieve<br/>search_memories()"]
        profile["Profile<br/>get_profile_for_agent()"]
        format["Format<br/>format_memories_for_prompt()"]
    end

    gate -->|"Validation passed"| write
    write -->|"1. Vector write"| pgvector["pgvector<br/>collection: memory"]
    write -->|"2. Metadata write"| nextjs["Next.js API<br/>POST /api/memory"]
    search -->|"Semantic search"| pgvector
    profile -->|"Get profile"| nextjs2["Next.js API<br/>GET /api/memory/profile"]
```

#### Key Methods

| Method                         | Responsibility                                                          |
| ------------------------------ | ----------------------------------------------------------------------- |
| `add_explicit_memory()`        | Save memory — gate validation → pgvector write → PostgreSQL write       |
| `search_memories()`            | Semantic retrieval — multi-scope search → merge and sort → return Top K |
| `validate_memory()`            | Content validation — confidence, sensitive information, content length  |
| `check_duplicate()`            | Deduplication — pgvector similarity ≥ 0.85 is considered duplicate      |
| `check_rate_limit()`           | Rate limiting — max 3 extractions per session per 24h                   |
| `get_profile_for_agent()`      | Get user/project profile for System Prompt injection                    |
| `format_memories_for_prompt()` | Format memories into prompt-readable text                               |

### Memory Gate

The gate layer performs multi-dimensional validation before memory writes, preventing low-quality, sensitive, or duplicate information from entering the memory store:

```mermaid theme={null}
flowchart TD
    input["Memory write request"]
    conf{"Confidence ≥ 0.7?"}
    sensitive{"Contains sensitive info?<br/>password · api_key<br/>credit card · token"}
    length{"Content length<br/>5 ~ 2000 characters?"}
    dup{"Semantic duplicate?<br/>similarity ≥ 0.85"}
    rate{"Rate limited?<br/>≤ 3 times/session/24h"}
    pass["Validation passed → Write"]
    reject["Rejected"]

    input --> conf
    conf -->|"No"| reject
    conf -->|"Yes"| sensitive
    sensitive -->|"Yes"| reject
    sensitive -->|"No"| length
    length -->|"No"| reject
    length -->|"Yes"| dup
    dup -->|"Yes"| reject
    dup -->|"No"| rate
    rate -->|"Exceeded"| reject
    rate -->|"Passed"| pass
```

Gate configuration supports environment variable overrides:

| Parameter               | Default             | Environment Variable         |
| ----------------------- | ------------------- | ---------------------------- |
| Minimum confidence      | 0.7                 | `MEMORY_MIN_CONFIDENCE`      |
| Deduplication threshold | 0.85                | `MEMORY_DUPLICATE_THRESHOLD` |
| Rate limit              | 3 times/session/24h | `MEMORY_MAX_EXTRACTIONS`     |
| Minimum content length  | 5 characters        | `MEMORY_MIN_LENGTH`          |
| Maximum content length  | 2000 characters     | `MEMORY_MAX_LENGTH`          |

### Memory Tools

The Agent autonomously manages memories through two built-in tools:

```mermaid theme={null}
graph LR
    Agent["Agent"]
    add["memory_add<br/>Save memory"]
    search["memory_search<br/>Search memories"]

    Agent --> add
    Agent --> search

    add --> MS["MemoryService"]
    search --> MS
```

| Tool            | Trigger Scenario                                 | Parameters                           |
| --------------- | ------------------------------------------------ | ------------------------------------ |
| `memory_add`    | User says "remember", "remember this", "I am..." | `content`, `memory_type`, `scope`    |
| `memory_search` | Agent needs to recall user information           | `query`, `k`, `memory_type`, `scope` |

Tools receive `user_id`, `project_id`, `session_id` via `RunnableConfig`, enabled by default in Agent mode (`enable_memory=True`).

***

## Agent Integration

### Complete Data Flow

The following diagram shows how the memory system participates in a complete Agent invocation:

```mermaid theme={null}
sequenceDiagram
    participant User
    participant Frontend as Frontend (Next.js)
    participant Backend as Backend (FastAPI)
    participant MS as MemoryService
    participant PGV as pgvector
    participant PG as PostgreSQL

    User->>Frontend: Send message
    Frontend->>Backend: POST /api/agent/invoke<br/>(message + chat_history)

    rect rgb(240, 248, 255)
        Note over Backend,PG: Context Assembly Phase
        Backend->>MS: _fetch_profile(user_id, project_id)
        MS->>PG: GET /api/memory/profile
        PG-->>MS: UserProfile + ProjectProfile
        MS-->>Backend: formatted profile

        Backend->>MS: _fetch_relevant_memories(user_id, query)
        MS->>PGV: similarity_search(query, filter)
        PGV-->>MS: Top K memories
        MS-->>Backend: formatted memories
    end

    Backend->>Backend: _build_system_prompt()<br/>base_prompt + profile + memories

    rect rgb(255, 248, 240)
        Note over Backend,PGV: Agent Execution Phase
        Backend->>Backend: agent.invoke(messages)
        Backend->>MS: memory_add (Agent proactive extraction)
        MS->>MS: Gate validation
        MS->>PGV: Vector write
        MS->>PG: POST /api/memory (metadata write)
    end

    Backend-->>Frontend: Streaming response
    Frontend-->>User: Display result
```

### System Prompt Injection

During the [System Prompt](/en/documentation/core-capabilities/system-prompt) assembly (steps 12–13 of the 15-step pipeline), the system fetches profile and memory data and appends them as structured text at the end of the prompt. Specifically:

* **User Profile** — background, communication style, expertise areas, programming languages, and frequently used tools
* **Project Profile** — project goals, tech stack, constraints, key decisions, and current phase
* **Related Memories** — memory entries semantically related to the current conversation, each annotated with its scope identifier and type

This injection is handled by `_fetch_profile()` and `_fetch_relevant_memories()` within `_init_context()`. For the full System Prompt assembly pipeline, see [System Prompt](/en/documentation/core-capabilities/system-prompt). For how this fits into the broader Context, see [Context](/en/documentation/core-capabilities/context).

### Retrieval Ranking Algorithm

After multi-scope memory retrieval, results are merged and sorted by weighted scoring:

**final\_score = similarity × 0.5 + confidence × 0.3 + scope\_priority × 0.2**

Where scope priority:

| Scope   | Priority Weight | Description                      |
| ------- | --------------- | -------------------------------- |
| session | 1.0             | Most relevant to current session |
| project | 0.8             | Project context is secondary     |
| user    | 0.6             | Global information as baseline   |

After deduplication within the same type, the highest-scoring entries are retained, and the final Top K results are returned.

***

## Permission Model

Project-level memories have fine-grained permission control:

```mermaid theme={null}
graph TD
    subgraph Roles["Project Roles"]
        owner["Owner"]
        admin["Admin"]
        editor["Editor"]
        viewer["Viewer"]
    end

    subgraph Actions["Permissions"]
        read["Read"]
        create["Create"]
        edit["Edit"]
        del["Delete"]
    end

    owner --> read & create & edit & del
    admin --> read & create & edit & del
    editor --> read & create
    editor -->|"Own creations only"| edit & del
    viewer --> read
```

| Role   | Read | Create | Edit               | Delete             |
| ------ | ---- | ------ | ------------------ | ------------------ |
| Owner  | All  | All    | All                | All                |
| Admin  | All  | All    | All                | All                |
| Editor | All  | All    | Own creations only | Own creations only |
| Viewer | All  | No     | No                 | No                 |

The `visibility` field further controls the visible range:

* `public`: Visible to all project members
* `members`: Visible to project members (default)
* `owner_only`: Visible to the creator only

***

## Vector Storage

Memory vector storage uses the **PostgreSQL pgvector** extension, sharing underlying infrastructure with the RAG knowledge base:

```mermaid theme={null}
graph LR
    subgraph VectorStore["VectorStore (Singleton)"]
        direction TB
        cache["Collection cache pool"]
        embed["Embedding config<br/>Supports user customization"]
    end

    memory_col["collection: memory"]
    rag_col["collection: knowledge_base"]

    VectorStore --> memory_col
    VectorStore --> rag_col
    memory_col --> pgvector["PostgreSQL pgvector"]
    rag_col --> pgvector
```

| Configuration     | Default                  | Description                     |
| ----------------- | ------------------------ | ------------------------------- |
| Embedding Model   | `text-embedding-3-small` | Supports user-customized models |
| Vector Dimensions | 1536                     | Matches the model               |
| Similarity Metric | Cosine                   | Cosine similarity               |
| Collection Name   | `memory`                 | Dedicated memory collection     |

Each user can configure their own Embedding API (model, Base URL, API Key). The system automatically loads the corresponding configuration via `create_embeddings(user_id)`.

***

## Episodic Memory & Checkpoint

Episodic Memory is implemented through LangGraph's `PostgresSaver`, responsible for session state persistence and recovery:

```mermaid theme={null}
sequenceDiagram
    participant User
    participant Agent
    participant Checkpoint as PostgresSaver
    participant PG as PostgreSQL

    Note over Agent,PG: Normal execution
    Agent->>Checkpoint: Auto-save checkpoint
    Checkpoint->>PG: INSERT langgraph_checkpoint

    Note over User,Agent: Page refresh / interrupt
    User->>Agent: resume(session_id)
    Agent->>Checkpoint: aget_state(thread_id)
    Checkpoint->>PG: SELECT checkpoint
    PG-->>Checkpoint: messages + agent_state + pending_tool_calls
    Checkpoint-->>Agent: Restore state
    Agent->>Agent: Continue from breakpoint
```

Checkpoint stored content:

| Data                 | Description                                          |
| -------------------- | ---------------------------------------------------- |
| messages             | Complete message history                             |
| agent\_state         | Agent internal state (todo\_list, reasoning context) |
| tool\_states         | Tool execution states                                |
| pending\_tool\_calls | Operations pending user approval (HITL)              |

Additionally, the `session_state_snapshot` table and `checkpoint_archive` table are used for session state snapshots and expired checkpoint archival, respectively.
