Documentation
¶
Overview ¶
Package memory implements the two-layer memory system (design doc §17): Hermes personal-assistant memory and per-project memory, kept physically isolated by an isolation wall. The on-disk format and hot-layer model follow Hermes Agent (Nous Research); the cold-layer layout follows OpenClaw.
Layout (design doc §17.2, aligned to upstream):
memory/ Hermes personal memory
MEMORY.md hot layer — §-separated entries, 2200-char cap
daily/YYYY-MM-DD.md warm layer — operational logs (30d archive → 90d delete)
.dreams/ cold layer — Dreaming engine state (OpenClaw, Sprint 3.2)
DREAMS.md human-readable dream diary (Sprint 3.2)
projects/{name}/MEMORY.md project memory — one §-separated file per project
The isolation wall is structural: Hermes memory is injected only into conversation/short-task system prompts, and project memory is injected only into that project's agent execution context. The two never cross.
Index ¶
- Constants
- Variables
- func MemoryPath(root string) string
- func RenderManifest(files []FileSummary) string
- func UserPath(root string) string
- func ValidateName(name string) error
- type Candidate
- type Daily
- type DreamDiary
- type Dreamer
- type FileSummary
- type Hermes
- func (h *Hermes) ColdDir() string
- func (h *Hermes) DeleteTopic(name string) error
- func (h *Hermes) Files() ([]FileSummary, error)
- func (h *Hermes) ListTopics() ([]string, error)
- func (h *Hermes) LoadMemory() (MemFile, error)
- func (h *Hermes) LoadTopic(name string) (MemFile, error)
- func (h *Hermes) LoadUser() (MemFile, error)
- func (h *Hermes) SaveMemory(m MemFile) error
- func (h *Hermes) SaveTopic(name string, m MemFile) error
- func (h *Hermes) SaveUser(m MemFile) error
- func (h *Hermes) TopicPath(name string) (string, error)
- func (h *Hermes) TopicsDir() string
- func (h *Hermes) UpdateMemory(fn func(*MemFile) error) error
- func (h *Hermes) UpdateTopic(name string, fn func(*MemFile) error) error
- func (h *Hermes) UpdateUser(fn func(*MemFile) error) error
- func (h *Hermes) WarmDir() string
- type Injector
- type Limits
- type MemFile
- type Projects
- func (p *Projects) Delete(name string) error
- func (p *Projects) Limit() int
- func (p *Projects) List() ([]string, error)
- func (p *Projects) Load(name string) (MemFile, error)
- func (p *Projects) Path(name string) (string, error)
- func (p *Projects) Rename(oldName, newName string) error
- func (p *Projects) Save(name string, m MemFile) error
- func (p *Projects) Update(name string, fn func(*MemFile) error) error
- type Report
- type Retriever
- type Scheduler
- type Source
- type Sources
- type Tool
Constants ¶
const ( UserCharLimit = 1375 // Hermes USER.md (~500 tokens) MemoryCharLimit = 2200 // Hermes MEMORY.md (~800 tokens) ProjectCharLimit = 8000 // per-project MEMORY.md (PANDA-specific) )
Character caps follow Hermes Agent: limits are measured in characters, not tokens, so they stay model-agnostic. Hermes splits memory into two files — USER.md (who the user is, ~500 tokens) and MEMORY.md (what the agent knows about the world, ~800 tokens) — and PANDA gives project memory more room because it is injected into a full agent context (design §17.2).
These constants are the compile-time fallbacks; deployments configure real caps via config memory.limits.{user,memory,project}, injected at store construction (NewHermesWithLimits / NewProjectsWithLimits).
const ( ToolRead = "memory_read" ToolAdd = "memory_add" ToolReplace = "memory_replace" ToolRemove = "memory_remove" )
Tool names — the whitelist of memory tools the entry model may invoke via tool_call. These are protocol strings shared with the entry-layer prompt; Tool.Execute enforces them, so the model never touches memory files directly.
const ExternalMarker = "[ext]"
ExternalMarker prefixes a daily-log line whose content derives from external input (task titles, user text, wire payloads) rather than the agent's own observations. The Dreaming engine's provenance gate (design §17.3, OpenClaw taint model) treats such lines as untrusted and never promotes them into MEMORY.md (P1-22).
const ( // PromotionSourceTag marks entries promoted through the repeated-emphasis // whitelist channel, so the user can tell log-derived memory in MEMORY.md // and correct or delete it via the memory API. PromotionSourceTag = "[from:日志]" )
Variables ¶
var ErrDuplicate = errors.New("memory: duplicate entry")
ErrDuplicate reports an add of an entry that already exists verbatim. Callers that consolidate a stream of candidates treat it as "skip", not "abort".
var ErrNoStore = errors.New("memory: no store configured for target")
ErrNoStore reports a tool targeting a layer whose store was not configured.
var ErrOverLimit = errors.New("memory: character limit exceeded")
ErrOverLimit reports that an add/replace would exceed the file's character limit. The caller (or the agent) should consolidate entries and retry, which is the Hermes workflow: merge proactively above ~80% capacity.
var ErrSeparator = errors.New("memory: entry must not contain the § separator")
ErrSeparator rejects entry text containing "§" — the on-disk delimiter. Writing it would silently split one entry into two on the next load.
Functions ¶
func MemoryPath ¶
MemoryPath is the MEMORY.md location for a memory root.
func RenderManifest ¶ added in v0.0.2
func RenderManifest(files []FileSummary) string
RenderManifest renders a file index as the prompt section handed to external agents (A3 selective loading): a per-file line with entry count, absolute path and a summary hint, plus the "read on demand" instruction. The block is fenced as data (P1-23) — summaries derive from memory content, which may embed user-originated text and must never be read as instructions. An empty index renders to "" (no manifest noise when there is no memory).
func ValidateName ¶
ValidateName rejects project names that are empty or could escape the projects root via a path separator. A valid name is a single path segment.
Types ¶
type Candidate ¶
type Candidate struct {
Text string
Days []time.Time // distinct days the text appeared
Count int // total occurrences
Sources []Source
Score float64 // filled during Deep
}
Candidate is one short-term signal consolidated out of the daily logs.
type Daily ¶
type Daily struct {
// contains filtered or unexported fields
}
Daily appends to and prunes the warm-layer daily logs under memory/daily/.
func (*Daily) Append ¶
Append writes one timestamped line to the day's log, creating the file and directory as needed. Append is safe for concurrent callers — the core's task goroutines complete tasks in parallel, so appends are serialized here.
The entry is sanitized to a single line: an embedded newline would inject phantom log lines and corrupt the Dreaming statistics built on top (P2-16). Use AppendExternal instead when the entry carries user- or wire-controlled text, so the provenance gate can taint it.
func (*Daily) AppendExternal ¶
AppendExternal is Append for content derived from external input (task titles, user instructions, wire payloads). The line is tagged with ExternalMarker so light() marks its provenance untrusted and the Deep phase can never consolidate it into long-term memory — closing the stored prompt-injection channel where task text was "consolidated" into MEMORY.md and from there into every future system prompt (P1-22).
func (*Daily) Prune ¶
Prune enforces the retention windows at now: files older than deleteDays are deleted, files older than archiveDays (but not yet deleteDays) are moved to daily/archive/. The delete window sweeps the archive too — archiving moves a log out of the warm scan path, it does not exempt it from deletion, or archive/ would grow without bound. Files that do not match the YYYY-MM-DD.md naming are left untouched. It shares the Daily mutex with Append so a prune cannot race an in-flight append.
type DreamDiary ¶
type DreamDiary struct {
// contains filtered or unexported fields
}
DreamDiary appends human-readable consolidation entries to DREAMS.md (OpenClaw Dream Diary, design §17.3). The diary is for a human to read — it is not a promotion source; only the Dreamer's Deep phase writes MEMORY.md.
func NewDreamDiary ¶
func NewDreamDiary(path string) *DreamDiary
NewDreamDiary wraps a DREAMS.md path.
type Dreamer ¶
type Dreamer struct {
// OnPromotion, when set, is invoked for every entry promoted into
// MEMORY.md (A4 visibility): the daemon records an audit/event
// (core.EvMemoryPromotion) so the console can show what the Dreaming
// engine memorized and let the user correct or delete it. viaWhitelist
// reports whether the entry came through the repeated-emphasis channel.
OnPromotion func(entry string, viaWhitelist bool)
// contains filtered or unexported fields
}
Dreamer runs the three-phase memory consolidation (design §17.3), aligned with OpenClaw: Light dedupes daily-log lines into candidates, REM groups them into themes, and Deep scores them on six signals and promotes the ones that clear the threshold + provenance gates into MEMORY.md. It never touches the personal USER.md.
func NewDreamer ¶
NewDreamer builds a dreamer with OpenClaw's default thresholds.
type FileSummary ¶ added in v0.0.2
type FileSummary struct {
Name string // "USER.md", "MEMORY.md", "topics/<name>.md"
Path string // absolute on-disk path
Entries int
Chars int
Summary string // first entry, truncated to summaryRunes
}
FileSummary indexes one memory file for selective loading (A3) and the console: where it lives, how big it is, and a one-line hint of its content.
type Hermes ¶
type Hermes struct {
// contains filtered or unexported fields
}
Hermes manages the Hermes personal-assistant memory store rooted at a memory/ directory (design §17.2). Following Hermes Agent, personal memory is split into two files with distinct roles and caps:
USER.md who the user is — role, preferences, communication style MEMORY.md what the agent knows — environment facts, conventions, corrections
On top of the two core files, optional topic files under memory/topics/ extend the hot layer into multiple files (A3 multi-file memory); agents load them selectively instead of receiving everything in every prompt.
The remaining layers are the warm daily logs (daily/) and the cold Dreaming state (.dreams/, OpenClaw layout, Sprint 3.2).
func NewHermes ¶
NewHermes wraps a memory/ root directory with the historical compile-time caps. Configured deployments use NewHermesWithLimits instead.
func NewHermesWithLimits ¶ added in v0.0.2
NewHermesWithLimits wraps a memory/ root directory with configurable character caps (config memory.limits); non-positive fields fall back to the package constants.
func (*Hermes) ColdDir ¶
ColdDir is the .dreams/ directory holding Dreaming engine state (OpenClaw's machine-state location, Sprint 3.2).
func (*Hermes) DeleteTopic ¶ added in v0.0.2
DeleteTopic removes one topic file. Deleting a missing topic is an error so callers can tell a typo from a removal.
func (*Hermes) Files ¶ added in v0.0.2
func (h *Hermes) Files() ([]FileSummary, error)
Files indexes the non-empty personal memory files: USER.md, MEMORY.md and every topic file. Empty or missing files are omitted — a file with nothing in it is not worth an agent's read.
func (*Hermes) ListTopics ¶ added in v0.0.2
ListTopics returns the names (file stem, sorted) of the topic files that exist under topics/. A missing directory yields an empty list.
func (*Hermes) LoadMemory ¶
LoadMemory reads MEMORY.md with the hot-layer limit applied.
func (*Hermes) LoadTopic ¶ added in v0.0.2
LoadTopic reads one topic file with the hot-layer (memory) limit applied. A missing file yields an empty MemFile, like the core files.
func (*Hermes) LoadUser ¶
LoadUser reads USER.md with the user-profile limit applied, so subsequent Add/Replace enforce the cap. A missing file yields an empty MemFile.
func (*Hermes) SaveMemory ¶
SaveMemory writes MEMORY.md, enforcing the hot-layer cap.
func (*Hermes) SaveTopic ¶ added in v0.0.2
SaveTopic writes one topic file (creating the topics/ directory as needed), enforcing the hot-layer cap and writing atomically, same as the core files.
func (*Hermes) TopicPath ¶ added in v0.0.2
TopicPath returns the on-disk path of a topic file, validating the name first so it cannot escape the topics directory (directory traversal).
func (*Hermes) TopicsDir ¶ added in v0.0.2
TopicsDir is the memory/topics/ directory holding optional topic files.
func (*Hermes) UpdateMemory ¶ added in v0.1.1
UpdateMemory runs fn against the current MEMORY.md and writes the result back as one critical section.
func (*Hermes) UpdateTopic ¶ added in v0.1.1
UpdateTopic runs fn against one topic file's current contents and writes the result back as one critical section.
func (*Hermes) UpdateUser ¶ added in v0.1.1
UpdateUser runs fn against the current USER.md and writes the result back as one critical section. fn's error aborts the write.
type Injector ¶
type Injector struct {
// contains filtered or unexported fields
}
Injector assembles the memory text injected into a given context (design §17.2). It is the only sanctioned way to pull memory into a prompt; its two methods are deliberately separate so Hermes and project memory can never mix.
func NewInjector ¶
NewInjector builds an injector over a Hermes store and a project store. Either may be nil to disable that layer (e.g. a minimal node with no personal memory); the corresponding methods then return empty.
func (*Injector) ContextPack ¶
ContextPack builds the agent execution context for a project: the project's own MEMORY.md only. Hermes memory is never packed here.
The pack is fenced as data (P1-23), same as Conversation: project memory is consolidated from task history and must carry an explicit data-not-instructions boundary into the agent prompt.
func (*Injector) Conversation ¶
Conversation returns the Hermes personal memory for the entry model's system prompt: the full user profile (USER.md, always relevant — it is small) plus the world notes (MEMORY.md and the topics/*.md extension files) most relevant to query. The hot-layer files are scored together as one pool (A3 multi-file retrieval): a non-empty query returns at most conversationMemoryK matching entries across all files, so a growing hot layer no longer forces the whole file set into every prompt; an empty query returns the full pool (no relevance signal, so nothing is filtered). It returns "" when there is no memory. The result is a frozen snapshot — a later write does not change it.
func (*Injector) Manifest ¶ added in v0.0.2
func (i *Injector) Manifest() ([]FileSummary, error)
Manifest returns the personal memory file index (absolute paths + one-line summaries) for selective loading by external agents (A3): instead of packing the whole memory content into the agent prompt, the agent receives the list and reads the files it needs with its own file tools. Nil hermes yields nil.
func (*Injector) ProjectManifest ¶ added in v0.0.8
ProjectManifest is the project-context counterpart to RenderManifest: a pointer to the project's own memory file, with its size, so the agent can read it with its own file tools if the task needs the background.
It exists because a project task used to receive *less* context than a non-project one. Outside a project the agent gets the personal-memory manifest (A3); inside a project it got nothing at all — the isolation wall (D3) correctly keeps Hermes memory out, and nothing was put in its place, so the agent had no way to know the project even had memory. That inversion is what made a delegated project task arrive not knowing what it was working on.
A pointer rather than the content, deliberately: injecting project memory wholesale is what the A1 decision removed for burning tokens on every task. The wall still holds — this reads only the named project, never Hermes.
workDir, when non-empty, is named too. The tree is the other half of what a project *is*, and an agent that is told where the files are does not have to guess which directory it landed in. loc is the prompt language the caller already resolved (see PromptLanguagePolicy) — the manifest rides the agent prompt, so it follows the same language as the hints around it instead of a hard-coded one.
type Limits ¶ added in v0.0.2
type Limits struct {
User int // USER.md cap
Memory int // MEMORY.md and topics/*.md cap
Project int // per-project MEMORY.md cap
}
Limits carries the configurable character caps (config memory.limits). A non-positive field falls back to the matching compile-time constant, so a zero Limits keeps the historical behavior.
type MemFile ¶
MemFile is an in-memory MEMORY.md: an ordered list of entries separated on disk by "§". The zero value is an empty file. Limit is the character cap; a non-positive value means unlimited.
func ParseMem ¶
ParseMem decodes MEMORY.md bytes into a MemFile. Entries are split on "§" and surrounding whitespace is trimmed. The Limit is not read from the file — the caller sets it from the store that owns the file.
func (*MemFile) Add ¶
Add appends an entry, rejecting empty and exact-duplicate entries and enforcing the character limit when set. An over-limit add is rolled back and reported with current usage so the agent can consolidate before retrying.
func (MemFile) Chars ¶
Chars returns the rune count of the serialized file (entries plus separators), the measure the character limit applies to.
func (*MemFile) Remove ¶
Remove deletes the entry containing old, again requiring a unique substring match. An empty replacement is not used here — callers drop entries outright.
func (*MemFile) Replace ¶
Replace swaps the entry containing old with new. Matching is substring-based (Hermes semantics): old must match exactly one entry, else the change is rejected so the caller can supply a more specific substring. An over-limit replacement is rolled back so the MemFile stays consistent.
type Projects ¶
type Projects struct {
// contains filtered or unexported fields
}
Projects manages per-project memory files (design §17.2). Each project's memory lives at projects/{name}/MEMORY.md in the same §-separated format as Hermes, and is injected only into that project's agent context — never into Hermes.
func NewProjects ¶
NewProjects wraps a projects/ root directory with the historical compile-time cap. Configured deployments use NewProjectsWithLimits instead.
func NewProjectsWithLimits ¶ added in v0.0.2
NewProjectsWithLimits wraps a projects/ root directory with a configurable character cap (config memory.limits.project); a non-positive value falls back to ProjectCharLimit.
func (*Projects) Delete ¶ added in v0.0.8
Delete removes a project's directory — its MEMORY.md and any project-scoped skills alongside it. This is the only destructive call in the package, so the containment argument is worth stating: ValidateName has already rejected path separators, "." and "..", so the join can only name a direct child of the root, and nothing outside p.root is reachable from any input.
A project that has no directory is already deleted, so that is not an error.
func (*Projects) List ¶
List returns the names of the projects that exist under the root (i.e. have a directory), sorted. A missing root yields an empty list — no projects yet.
func (*Projects) Load ¶
Load reads a project's memory as a MemFile with the project limit applied. A missing file yields an empty MemFile, so a project with no memory simply contributes nothing.
func (*Projects) Rename ¶ added in v0.1.1
Rename carries a project's memory over to a new name: copy, then drop the old directory. It is copy-then-drop rather than a directory move so a failure part-way leaves the old file intact — losing the memory is the one outcome worth paying an extra write to avoid.
The whole sequence holds the store's lock, because the alternative is a read-write-delete triple with two windows in it: an entry added between the read and the copy would be copied stale, and one added between the copy and the drop would be erased by the drop.
func (*Projects) Save ¶
Save writes a project's memory, creating the project directory as needed. It enforces the project character cap and refuses an over-limit file rather than silently truncating, mirroring Hermes.save.
type Report ¶
type Report struct {
Candidates int
Promoted []string
Themes map[string]int // REM theme -> candidate count
}
Report summarizes one sweep for the scheduler and the DREAMS.md diary.
type Retriever ¶
type Retriever struct{}
Retriever ranks memory entries against a query in memory. Memory is tiny (a few KB), so no external index or vector store is needed: tokenize query and entries (reusing the package's existing tokenize) and score with a BM25-lite measure — shared tokens are weighted by inverse document frequency across the pool (a token present in every entry carries almost no signal) and normalized by entry length (a long entry is not automatically the best one).
type Scheduler ¶
type Scheduler struct {
// OnError, when set, receives sweep failures so the daemon can log them
// rather than have them swallowed silently.
OnError func(error)
// contains filtered or unexported fields
}
Scheduler runs the Dreamer when the node is idle, at most once per day. It is the Go-side trigger (design P3-11); the "idle" predicate is supplied by the caller (the core checks its running-task count) so this package stays free of a scheduler dependency. When a Daily store is attached (WithDaily), each tick additionally enforces the daily-log retention windows at most once per day — the production wiring of daily.Prune (A4).
func NewScheduler ¶
func NewScheduler(dreamer *Dreamer, diary *DreamDiary, idle func() bool, every time.Duration) *Scheduler
NewScheduler builds a scheduler. idle may be nil (treat as always idle); every is the tick interval.
type Source ¶
type Source struct {
Path string // daily log filename, e.g. "2026-08-13.md"
Line int // 1-based line number
Trusted bool // whether this origin may be promoted into MEMORY.md
}
Source records where a memory candidate came from (OpenClaw provenance, design §17.3). A Trusted source is the agent's own daily log; untrusted or system sources are excluded from promotion by the provenance gate.
type Sources ¶
type Sources []Source
Sources is a candidate's provenance list.
func (Sources) Trusted ¶
Trusted reports whether the candidate has at least one source and every source is trusted. OpenClaw removes untrusted/system provenance before consolidation — a structural taint gate, not a score penalty — so a candidate with any untrusted origin is dropped wholesale rather than partially trusted.
type Tool ¶
type Tool struct {
// contains filtered or unexported fields
}
Tool executes whitelisted memory tools against the Hermes and project stores. It is the Go-side executor the entry model's tool_call output lands in; the model never touches the files directly (design §7.3: Go core validates and executes, the model emits only the request).