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 UserPath(root string) string
- func ValidateName(name string) error
- type Candidate
- type Daily
- type DreamDiary
- type Dreamer
- type Hermes
- type Injector
- type MemFile
- type Projects
- 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).
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).
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.
Functions ¶
func MemoryPath ¶
MemoryPath is the MEMORY.md location for a memory root.
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/. Files that do not match the YYYY-MM-DD.md naming are left untouched, as is the archive directory itself. 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 {
// 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 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 (1375 chars) MEMORY.md what the agent knows — environment facts, conventions, corrections (2200 chars)
The remaining layers are the warm daily logs (daily/) and the cold Dreaming state (.dreams/, OpenClaw layout, Sprint 3.2).
func (*Hermes) ColdDir ¶
ColdDir is the .dreams/ directory holding Dreaming engine state (OpenClaw's machine-state location, Sprint 3.2).
func (*Hermes) LoadMemory ¶
LoadMemory reads MEMORY.md with the hot-layer limit applied.
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.
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) plus the world notes (MEMORY.md) most relevant to query. An empty query returns the full MEMORY.md (no relevance signal, so nothing is filtered); a non-empty query returns at most conversationMemoryK matching entries, so a growing hot layer no longer forces the whole file into every prompt. It returns "" when there is no memory. The result is a frozen snapshot — a later write does not change it.
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.
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.
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 entry (reusing the package's existing tokenize) and score by token overlap, a cheap TF-style relevance measure.
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.
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).