memory

package
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 18, 2026 License: MIT Imports: 13 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
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).

View Source
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.

View Source
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

View Source
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".

View Source
var ErrNoStore = errors.New("memory: no store configured for target")

ErrNoStore reports a tool targeting a layer whose store was not configured.

View Source
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

func MemoryPath(root string) string

MemoryPath is the MEMORY.md location for a memory root.

func UserPath

func UserPath(root string) string

UserPath is the USER.md location for a memory root.

func ValidateName

func ValidateName(name string) error

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 NewDaily

func NewDaily(dir string) *Daily

NewDaily wraps a daily/ directory.

func (*Daily) Append

func (d *Daily) Append(now time.Time, entry string) error

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

func (d *Daily) AppendExternal(now time.Time, entry string) error

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) PathFor

func (d *Daily) PathFor(date time.Time) string

PathFor returns the daily log path for a date.

func (*Daily) Prune

func (d *Daily) Prune(now time.Time) error

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.

func (*DreamDiary) Append

func (d *DreamDiary) Append(report Report, now time.Time) error

Append records one sweep as a dated section. It is append-only and creates the file on first use.

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

func NewDreamer(hermes *Hermes) *Dreamer

NewDreamer builds a dreamer with OpenClaw's default thresholds.

func (*Dreamer) Dream

func (d *Dreamer) Dream() (Report, error)

Dream runs one full Light→REM→Deep sweep over the warm layer and returns a report. Promotion writes MEMORY.md only.

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 NewHermes

func NewHermes(root string) *Hermes

NewHermes wraps a memory/ root directory.

func (*Hermes) ColdDir

func (h *Hermes) ColdDir() string

ColdDir is the .dreams/ directory holding Dreaming engine state (OpenClaw's machine-state location, Sprint 3.2).

func (*Hermes) LoadMemory

func (h *Hermes) LoadMemory() (MemFile, error)

LoadMemory reads MEMORY.md with the hot-layer limit applied.

func (*Hermes) LoadUser

func (h *Hermes) LoadUser() (MemFile, error)

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

func (h *Hermes) SaveMemory(m MemFile) error

SaveMemory writes MEMORY.md, enforcing the hot-layer cap.

func (*Hermes) SaveUser

func (h *Hermes) SaveUser(m MemFile) error

SaveUser writes USER.md, enforcing the user-profile cap (defaulting to UserCharLimit when unset).

func (*Hermes) WarmDir

func (h *Hermes) WarmDir() string

WarmDir is the daily/ directory.

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

func NewInjector(hermes *Hermes, projects *Projects) *Injector

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

func (i *Injector) ContextPack(project string) (string, error)

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

func (i *Injector) Conversation(query string) (string, error)

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

type MemFile struct {
	Entries []string
	Limit   int
}

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

func ParseMem(data []byte) MemFile

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

func (m *MemFile) Add(entry string) error

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) Bytes

func (m MemFile) Bytes() []byte

Bytes serializes the entries back to the on-disk format ("§"-separated).

func (MemFile) Chars

func (m MemFile) Chars() int

Chars returns the rune count of the serialized file (entries plus separators), the measure the character limit applies to.

func (*MemFile) Remove

func (m *MemFile) Remove(old string) error

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

func (m *MemFile) Replace(old, new string) error

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

func NewProjects(root string) *Projects

NewProjects wraps a projects/ root directory.

func (*Projects) List

func (p *Projects) List() ([]string, error)

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

func (p *Projects) Load(name string) (MemFile, error)

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) Path

func (p *Projects) Path(name string) (string, error)

Path returns the MEMORY.md path for a project, validating the name first.

func (*Projects) Save

func (p *Projects) Save(name string, m MemFile) error

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 entry (reusing the package's existing tokenize) and score by token overlap, a cheap TF-style relevance measure.

func (Retriever) Rank

func (Retriever) Rank(query string, entries []string, k int) []string

Rank returns up to k entries most relevant to query, highest first. Entries with no token overlap are dropped. An empty query returns the first k entries unchanged (no relevance signal).

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.

func (*Scheduler) Run

func (s *Scheduler) Run(ctx context.Context) error

Run ticks until ctx is done. A failed sweep is reported to OnError (if set) and retried on the next tick rather than aborting the loop.

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

func (s Sources) Trusted() bool

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).

func NewTool

func NewTool(hermes *Hermes, projects *Projects) *Tool

NewTool builds a tool executor. Either store may be nil to disable its layer.

func (*Tool) Execute

func (t *Tool) Execute(name string, args map[string]any) (string, error)

Execute runs one tool call and returns a short, user-facing result. name must be a Tool* constant; args is the model-supplied argument map, validated here rather than trusted verbatim.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL