Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Hermes Agent Memory System

Hermes Agent Memory System

Hermes' core differentiating capability is not tool calling, but that it truly remembers you.

Most AI tools start from scratch with every conversation--you spend an hour today teaching it your project structure, naming conventions, and deployment workflow, and tomorrow with a new session, it all starts over.

This chapter deeply analyzes how Hermes solves this problem with a three-layer memory structure, and how the Agent autonomously manages memory to achieve cross-session search and recall.


Three-layer memory architecture

Hermes uses three mutually independent, complementary memory structures to store and recall information.

The core idea of the three-layer design: high-frequency important information stays in context, low-frequency historical information is recalled on demand, and deep patterns are automatically inferred by AI--striking a balance between memory capability and Token cost.



┌─────────────────────────────────────────────────┐

│       第一层:持久记忆(Persistent Memory)        │

│  MEMORY.md(环境事实)+ USER.md(用户画像)          │

│  → 每次会话启动时自动注入系统提示词,始终可见          │

├─────────────────────────────────────────────────┤

│       第二层:情节日志(Session History)            │

│  SQLite + FTS5 全文检索,存储所有历史对话             │

│  → Agent 主动搜索时按需加载,不占用固定 Token         │

├─────────────────────────────────────────────────┤

│       第三层:用户建模(Honcho,可选)               │

│  辩证推理引擎,提取跨会话模式、偏好与目标              │

│  → 比你亲口说出来的更深层地理解你                     │

└─────────────────────────────────────────────────┘

Memory layer Storage location Capacity Loading method Purpose
Persistent memory Markdown files under ~/.hermes/memories/ ~1,300 tokens total Automatically injected into the system prompt at session start Key facts, always visible
Episodic log SQLite database + JSONL transcript files Unlimited (all historical conversations) Agent searches on demand, FTS5 full-text search Find specific historical discussions
Honcho user modeling Honcho server-side API Isolated per Agent Background inference injected every round / every N rounds Automatically infer deep preferences and goals

The three layers are not substitutes but complements. Persistent memory answers "I always need to know these", the episodic log answers "Did we discuss this last week?", and Honcho answers "What do you really want?".


Persistent memory files

Persistent memory is the first and most fundamental layer of the Hermes memory system.

It consists of two Markdown files stored under ~/.hermes/memories/ that directory, automatically injected into the system prompt at each session start.

Two core files

The two files each have their own role and do not overlap.

file Purpose Character limit Approximately equal to
MEMORY.md The Agent's personal notes--environment facts, project conventions, things learned at work 2,200 characters ~800 tokens
USER.md User profile--your preferences, communication style, work habits, skill level 1,375 characters ~500 tokens

The character limit is intentional--it keeps memory content concise and focused. If a new entry exceeds the limit, the memory tool returns an error so the Agent organizes the space before writing, instead of silently discarding old entries.

How memory is injected into the system prompt

At each session start, the contents of the two files are injected into the system prompt in a fixed format, as follows:



══════════════════════════════════════════════

MEMORY(Agent 个人笔记)[67% — 1,474/2,200 字符]

══════════════════════════════════════════════

用户的项目是位于 ~/code/myapi 的 Rust Web 服务,使用 Axum + SQLx

§

本机运行 Ubuntu 22.04,已安装 Docker 和 Podman

§

用户偏好简洁回复,不喜欢冗长解释

Here are several key design details:

Frozen snapshot mode: memory content in the system prompt is captured once at session start and is not updated mid-session.

This is intentional--to keep the LLM's prefix cache (Prompt Cache) valid and reduce Token cost.

When the Agent modifies memory during a session, changes are written to disk immediately but only appear in the context at the next session start.

Usage percentage visible:[67% — 1,474/2,200] Lets the Agent always know the remaining capacity and proactively organize as it approaches the limit.

§ as entry separator: each memory is separated by §, and an entry itself can be multi-line text.

How the Agent operates memory

The Agent manages memory through the built-in memory tool, supporting three operations.

Operation Description Parameters
add Add a memory entry target (memory/user), content
replace Replace an existing entry (located by substring match) target, old_text, content
remove Delete an existing entry (located by substring match) target, old_text

Note: there is no read operation--memory content is already injected into the system prompt at session start, and the Agent sees it directly in the context without needing an extra read.

replace and remove Locate entries using substring matching; you do not need to provide the full entry text:

Example

Scenario: current memory contains "User prefers a dark theme in all editors"

Now it needs to be updated to a more precise version

Locate using substring matching--just provide a fragment that uniquely identifies it

memory

(

    action

=

"replace"

,

    target

=

"memory"

,

    old_text

=

"dark theme"

,

 

A unique substring is enough to locate the original entry

    content

=

"User uses a light theme in VS Code and a dark theme in the terminal"

 

The new content after replacement

)

If the substring matches multiple entries, the tool returns an error requesting a more precise match string.


What to remember and what not to

The Agent automatically judges and saves valuable information--you usually do not need to ask explicitly.

But understanding the criteria helps you understand the Agent's behavior and manually guide it when needed.

Should proactively save to memory (environment and work)

The following types of information trigger the Agent to write to MEMORY.md:

Type Example
Environment facts This machine runs Debian 12, PostgreSQL 16, with Docker replaced by Podman
Project conventions ~/code/api uses Go 1.22, sqlc queries, chi routing; tests use make test
Tool experience The staging server SSH port is 2222, not 22, with the key at ~/.ssh/staging_ed25519
Correction records Do not run Docker commands with sudo, the user is already in the docker group
Completed work 2026-01-15 Completed the database migration from MySQL to PostgreSQL

Should proactively save to user (about you)

The following types of information trigger the Agent to write to USER.md:

Type Example
Identity information Name, job title, time zone
Communication preferences Prefers concise replies, no need to explain obvious steps
Dislikes Do not add too many comments in code
Work habits Does not check messages before 3 PM every day
Skill level Familiar with Rust and Python, Go is newly learned

Content that should not be saved

The following content is not worth taking up precious memory space:

Type Example Reason
Too vague The user has a project No information content, cannot be reused
Can be looked up anytime Python 3.12 supports f-string nesting A search is enough, not worth the space
Raw data Large logs, code blocks, data tables Exceeds the character limit, structured memory is more useful
Temporary content The temporary file path for this debugging session Won't be needed next time
Content already in the context Information already in the project's SOUL.md and AGENTS.md Repeated injection wastes Token

Good memory vs bad memory

The same information, written well, one entry can be worth ten; written poorly, it is worthless.

Rating Example Comment
Good The user's macOS 14 Sonoma, Homebrew, Docker Desktop, Shell is zsh with oh-my-zsh, editor is VS Code + Vim keybindings High information density, related facts packaged together
Good Project ~/code/api uses Go 1.22, sqlc for DB queries, chi routing. Tests: make test. CI: GitHub Actions Specific, executable conventions
Good Staging server (10.0.1.50) SSH port 2222 is not 22, key ~/.ssh/staging_ed25519 Lessons learned with context, avoiding pitfalls
Poor The user has a project Too vague to guide any action
Poor On January 5, 2026, the user asked me to look at his project located at ~/code/api, and I found it uses Go 1.22... Too verbose, the core information is drowned in the narration

Memory capacity management

Memory files have strict character limits, and the Agent needs to proactively organize as it approaches the limit.

What happens when approaching the limit

When a new entry would exceed the character limit, the tool returns an error instead of silently truncating:



{

  "success": false,

  "error": "Memory 已用 2,100/2,200 字符。新条目(250 字符)会超出上限。

            请先整理:用 replace 合并重叠条目,或 remove 过时条目,

            再重试——在同一轮对话中完成。",

  "current_entries": [

    "用户的 macOS 14 Sonoma,Homebrew,Docker Desktop",

    "项目 ~/code/api 使用 Go 1.22,sqlc 做 DB 查询"

  ],

  "usage": "2,100/2,200"

}

After receiving this error, the correct action for the Agent is:

  1. Read all current entries (already included in the error response)
  2. Find entries that can be deleted or merged
  3. Using replace Merge several related entries into a more concise version
  4. Then retry adding the new entry

Best practice: when the system prompt shows memory usage above 80%, organize proactively, do not wait for an error. Prevention is always cheaper in Token than remediation.

Capacity reference

Storage Limit Typical number of entries
MEMORY.md 2,200 characters 8-15 entries
USER.md 1,375 characters 5-10 entries

Control memory write permissions

By default, the Agent can freely write to memory--including the background-triggered self-improvement review (running in the background after a conversation round, distilling memory and skills).

If you want to review anything before it is written to memory, you can enable write approval.

Enable write approval

Just set it in the configuration file:

Example

File path: ~/.hermes/config.yaml

Enable memory write approval--all write operations require manual approval

memory

:

  write_approval

:

true  

Default false (free write)

Behavior changes after enabling:

Scenario Behavior
In CLI interaction, the Agent wants to write memory Prompts you inline in the terminal for approval
Messaging platform / background automatic review Writes are staged, waiting for your manual approval

Approval management commands

Use the following slash commands to manage pending memory writes:

Example

View pending memory writes (auto-triggered ones marked [auto])

/

memory pending

Approve a write by specified ID, or approve all

/

memory approve

<

id

/

memory approve all

Reject a write by specified ID, or reject all

/

memory reject

<

id

/

memory reject all

Enable or disable approval at runtime (setting is persisted)

/

memory approval on

/

memory approval off

Use cases: if the Agent saved a wrong assumption about you, or you want full control over memory content, enabling write_approval is the most direct approach.

About background self-improvement review

After each conversation round, Hermes runs a self-improvement review (background review) in the background, analyzing the round and distilling memory or skills worth keeping.

By default, a one-line prompt is shown in the chat Memory updated.

You can adjust the verbosity of the notification:

Example

File path: ~/.hermes/config.yaml

Control the notification verbosity of the background review

display

:

  memory_notifications

:

on      

off | on (default) | verbose

Value effect
off No notification shown, but the review still runs and still writes
on (default) Short prompt, e.g. Memory updated
verbose Include a change preview, e.g. Memory + user prefers concise replies

If your main model is expensive, you can run the background review on a cheaper model:

Example

File path: ~/.hermes/config.yaml

Background review uses a separate model to reduce cost

auxiliary

:

  background_review

:

    provider

:

openrouter

    model

:

google/gemini-

3

-flash-preview  

Default auto = main model


Episodic log and cross-session search

The second layer of memory--the episodic log (Session History)--stores complete records of all historical conversations, supporting full-text search and on-demand recall.

All conversations are saved automatically

Every session--whether from CLI, Telegram, Discord, or any other platform--is automatically saved to two locations:

Storage location Format Content
~/.hermes/state.db SQLite database + FTS5 full-text index Structured metadata, complete message history (including tool calls and results), Token usage, timestamps
~/.hermes/sessions/ JSONL transcript files Raw conversation transcripts, including tool call records

session_search tool

The Agent has a built-in session_search tool that can perform full-text search across all historical conversations.

The whole process requires no LLM involvement in the search phase, and is completed directly by the SQLite FTS5 engine:

Workflow:

  1. FTS5 retrieves matching messages sorted by relevance
  2. Group by session, take the most relevant sessions (3 by default)
  3. Load each session's conversation, extract about 100,000 characters around the match point
  4. Generate a focused summary with a lightweight summarization model
  5. Return the summary and context of each session to the Agent

Supported search syntax (FTS5 standard):

Syntax Example Description
Keyword search docker deployment Match messages containing any of the keywords
Phrase match "exact phrase" Exactly match the entire phrase
Boolean OR docker OR kubernetes Match any keyword
Boolean NOT python NOT java Exclude specific keywords
Prefix wildcard deploy* Match words starting with deploy

Trigger: the Agent automatically calls session_search when you mention "the thing we discussed last time..." or "that earlier plan...", instead of making you explain again.

session_search vs persistent memory

The two are complementary, not substitutes:

Comparison Dimensions Persistent memory (MEMORY.md / USER.md) Episodic log (Session Search)
Capacity ~1,300 tokens total Unlimited (all historical conversations)
Speed Instant (already in the system prompt) ~20ms (FTS5 query)
Token cost Fixed cost per session On demand, no cost if not queried
Purpose Key facts, always visible Find specific historical discussions
Management method Agent proactively organizes Fully automatic, no intervention needed

Memory is for "things I always need to know"--environment facts, user preferences, project conventions.

The episodic log is for "Did we discuss this last week?"--finding specific historical discussions.


Session management

Each session in the episodic log can be named, restored, exported, and cleaned up.

Naming and restoration

Hermes automatically generates a short session title (3-7 words) after the first round of conversation, running asynchronously in the background without affecting response speed.

You can also name it manually:

Example

Manually set the title within the session

/

title Refactor authentication module

After naming, you can use the title directly when restoring a session:

Example

Restore a session by title

hermes

-c

"Refactor the auth module"

Restore the most recent session

hermes

--continue

Restore by session ID

hermes

-r

<

session_id

Auto-Lineage: when a session undergoes context compression, Hermes automatically creates a continuation session and numbers it:



"我的项目" → "我的项目 #2" → "我的项目 #3"

When restoring by title, the latest continuation session is automatically selected.

Common session management commands

Example

List the most recent 20 sessions

hermes sessions list

Filter by source platform

hermes sessions list

--source

telegram

Show more entries

hermes sessions list

--limit

50

Rename a specified session

hermes sessions rename

<

id

"New Title"

Export all sessions to a file

hermes sessions

export

backup.jsonl

Delete a specified session

hermes sessions delete

<

id

Clean up old sessions from 30 days ago

hermes sessions

prune

--older-than

30

View statistics

hermes sessions stats

hermes sessions list Example output:



标题                 预览                               最近活跃    ID

────────────────────────────────────────────────────────────────────

重构认证模块          帮我重构认证模块的代码                2 小时前   20260305_09...

我的项目 #3          检查一下测试失败的原因                昨天        20260304_14...

—                   Python 装饰器怎么用                  3 天前      20260303_10...

Automatic session cleanup (optional)

By default, session history is kept permanently (because it provides data for session_search).

If automatic cleanup is needed, enable it in the configuration:

Example

File path: ~/.hermes/config.yaml

Enable automatic session cleanup (off by default)

sessions

:

  auto_prune

:

true        

Default false

  retention_days

:

90

     

Keep the most recent 90 days

  vacuum_after_prune

:

true

  min_interval_hours

:

24


Honcho user modeling

Honcho is an AI-native memory backend developed by Plastic Labs, integrated into Hermes as a plugin.

It does not replace MEMORY.md and USER.md, but adds a dialectical reasoning layer on top of them--by analyzing your conversation patterns, it automatically infers preferences, goals, and habits you have not explicitly expressed.

Unlike the manual curation of MEMORY.md, Honcho is fully automatic: it reasons in the background after each conversation round (configurable frequency), accumulating an increasingly deep understanding of you.

Honcho vs built-in memory

Capability Built-in memory Honcho
Cross-session persistence Local files Server-side API
User profile Manual curation (USER.md) Automatic dialectical reasoning
Session summary — Session-level context injection
Multi-Agent isolation — Modeled separately per Agent
Semantic search FTS5 full-text Based on reasoning conclusions

Two-layer context injection

For each conversation turn, Honcho assembles a two-layer context injection system prompt:

Base layer (Base Context): session summary + user representation + user Peer Card + AI self-representation. Refreshed once per contextCadence (every N turns). This is the 'who this user is' layer.

Dialectic layer (Dialectic Supplement): generated in real time by Honcho's LLM engine, focusing on 'what is most relevant right now'. Refreshed by dialecticCadence.

Two startup modes for dialectical reasoning:

Mode Conditional Query mode
Cold start No historical data Generic query - 'Who is this user? What are their preferences, goals, and working style?'
Warm start Historical data available Session-focused query - 'Based on what has been discussed in this session, what is the most relevant context about this user?'

Three independent tuning knobs

Parameters What it controls Default value
contextCadence Base layer refresh interval (call the API every N turns) 1
dialecticCadence Dialectic layer refresh interval (call the LLM every N turns) 2 (recommended 1-5)
dialecticDepth Reasoning depth per dialectic (1-3 passes) 1

The three knobs are fully independent - you can refresh the base layer frequently and run dialectical reasoning infrequently, or the other way around:

Example

{

  "contextCadence": 1,

  "dialecticCadence": 5,

  "dialecticDepth": 2

}

The above configuration means: refresh the base layer every turn, and run a 2-pass deep dialectical reasoning every 5 turns.

Multi-pass dialectical reasoning

When dialecticDepth is set greater than 1, each dialectical reasoning runs multiple LLM calls:

Pass Task Description
Pass 0 Cold/warm start reasoning Build an initial assessment
Pass 1 Self-audit Identify blind spots in the initial assessment and synthesize recent session evidence
Pass 2 Reconciliation Check contradictions from the first two rounds and produce a final synthesized conclusion

Depth 3 does not necessarily mean 3 LLM calls - if the previous round already produced high-quality output, the next round exits early, saving tokens.

Quick start with Honcho

Example

Interactive setup, select the honcho provider

hermes memory setup

Or configure manually:

Example

File path: ~/.hermes/config.yaml

Enable Honcho as the memory provider

memory

:

  provider

:

honcho

Example

Write the API Key to the environment variable file

echo

'HONCHO_API_KEY=your_key'

~

/

.hermes

/

.env

Get an API Key at honcho.dev.

Tools provided by Honcho

After enabling Honcho, the Agent can use five dedicated tools:

Tool Purpose
honcho_profile Read or update the user Peer Card
honcho_search Semantic search based on reasoning conclusions (raw snippets, no LLM synthesis)
honcho_context Get the full session context (summary, user representation, recent messages)
honcho_reasoning Call Honcho LLM reasoning (reasoning_level can be specified)
honcho_conclude Create or delete reasoning conclusions

Honcho CLI commands

Example

View Honcho connection status, configuration, and key settings

hermes honcho status

View or set the session policy

hermes honcho strategy

View or set the recall mode (hybrid/context/tools)

hermes honcho mode

View or set the Token budget

hermes honcho tokens

List known Honcho session mappings

hermes honcho sessions


Memory system configuration reference

Below is the complete reference for all memory-related configurations, which you can copy directly into your config file.

Example

============================================

File path: ~/.hermes/config.yaml

Hermes memory system complete configuration reference

============================================

--- Persistent memory configuration ---

memory

:

  memory_enabled

:

true          

Whether to enable persistent memory (MEMORY.md)

  user_profile_enabled

:

true    

Whether to enable the user profile (USER.md)

  memory_char_limit

:

2200

     

MEMORY.md character limit (about 800 tokens)

  user_char_limit

:

1375

       

USER.md character limit (about 500 tokens)

  write_approval

:

false        

true = all memory writes require manual approval

  provider

:

honcho              

Optional: enable the Honcho memory provider

--- Automatic session cleanup (optional, off by default) ---

sessions

:

  auto_prune

:

false            

Whether to automatically clean up old sessions

  retention_days

:

90

           

Keep sessions from the last N days

  vacuum_after_prune

:

true      

Whether to reclaim disk space after cleanup

  min_interval_hours

:

24

       

Minimum interval between two cleanups

--- Background review notifications ---

display

:

  memory_notifications

:

on      

off | on | verbose

--- Use a cheaper model for background reviews (optional) ---

auxiliary

:

  background_review

:

    provider

:

openrouter        

Model provider

    model

:

google/gemini-

3

-flash-preview  

Model name


Quick reference for common memory operations

Control memory directly in conversation

You can instruct Hermes to operate on memory using natural language, without memorizing any commands:

Example

Add a memory

Remember: this project uses Poetry to manage dependencies, not pip

Delete or overwrite a memory

Forget the previous notes about MySQL; we have migrated to PostgreSQL

Update information in memory

Update the staging server IP to 10.0.2.100

Query memory

Tell me what information about me you currently remember

Slash commands

Example

View current memory content

/

memory

View pending writes

/

memory pending

Approve all pending

/

memory approve all

Reject all pending

/

memory reject all

Enable write approval

/

memory approval on

Disable write approval

/

memory approval off

Edit memory files directly

Memory files are plain Markdown and can be opened and edited directly with an editor:

Example

View current memory content

cat

~

/

.hermes

/

memories

/

MEMORY.md

cat

~

/

.hermes

/

memories

/

USER.md

Open and edit with an editor

nano

~

/

.hermes

/

memories

/

MEMORY.md

Note: after editing the file directly, changes take effect at the next session start and are not immediately reflected in the current session's context.


Memory security and privacy

Security scanning

Memory content is security-scanned before writing to detect injection attacks and data exfiltration patterns.

The system detects the following threat patterns:

Threat type What is detected
Prompt injection Injection patterns that attempt to override the Agent's system instructions
Credential theft Instructions that induce the Agent to leak API Keys or Tokens
Backdoor installation Instructions to install SSH backdoors or remote access
Hidden characters Invisible Unicode characters (zero-width spaces, direction overrides, etc.)

Content matching a threat pattern is refused for writing.

Redaction of sensitive information in logs

Sensitive information such as API Keys and Tokens is automatically redacted in all log files - even if it appears in tool output, it is never recorded in plaintext:

Example

File path: ~/.hermes/config.yaml

Enabled by default, sensitive information is automatically redacted

security

:

  redact_secrets

:

true

Local data storage

All memory data (MEMORY.md, USER.md, state.db) is stored locally by default ~/.hermes/ directory and is not uploaded to the cloud.

When you choose to use Honcho, conversation data is sent to Honcho's servers for processing - this is a deliberate trade-off: uploading data in exchange for deeper reasoning capabilities.