agentmemory

package
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 13 Imported by: 0

README

Agent memory store

The daemon owns one Store and shares it across transports. Callers resolve the immutable profile ID, definition origin (user, extension-<id>, or workspace-<id>) and agent slug before calling the store. Always-on eligibility and caller authorization belong to the transport-independent service boundary, not the file format.

Read returns the editable file and its digest. Write requires that digest; Add, Replace, Remove, and Rollback serialize with it per key. Replacements enforce the 1,000-character limit on each resulting note, excluding its date, scope, and valid expiry metadata. Repeated matches cannot multiply a short replacement past the limit; rejection leaves the document unchanged. Writes redact secrets before persistence. Load returns a bounded startup snapshot, archiving dated overflow first. When undated content alone exceeds the budget, loading truncates without changing disk and entry mutations fail; an operator can repair the file with a digest-checked write.

The store writes archive.md before replacing MEMORY.md. A crash between these operations can duplicate archived notes but cannot lose the original notes. File revisions retain the latest 50 snapshots, including the content before an edit, and rollback uses the same redaction and budget path. Files use mode 0600 and directories use 0700. Retiring an agent renames its directory; removing an extension must not call retirement.

Search scans current and archived notes, ranks by the fraction of query terms matched, and preserves file/line order for ties. With include_sessions, the shared API service also pages the profile session catalog, authorizes each workspace before reading its transcript, and appends redacted matches with source: session and session_id. Denied workspaces are omitted without requesting broader access. Both HTTP and native tools use this service.

The owning contract is ADR-007 and the Memory sections of the always-on-agent spec. This package introduces no database or configuration changes and does not import legacy memory files. Its focused filesystem suite covers US-025/US-026 storage invariants; public transport, startup, and eligibility checks belong to their owning integration suites.

Verification ownership

Spec cases Canonical coverage
UT-050, UT-053, UT-085 agentmemory.TestStore/Should persist scoped entries and redact every write path; shared API memory routes also reject stale edits.
UT-051 agentmemory.TestStore/Should archive oldest dates while preserving undated notes
UT-052, UT-056 agentmemory.TestStore/Should rank lexical matches and support replacement and removal
UT-054 daemon.TestAgentMemoryNativeTools; core_test.TestAgentMemoryRoutes
UT-055, UT-102, UT-104 agentmemory.TestStore/Should preserve parallel adds and isolate definition origins; deletion retirement also runs through TestBaseHandlersAgentDefinitionMutations.
UT-101 agentmemory.TestStore/Should bound oversized undated snapshots without modifying notes
UT-103 agentmemory.TestMemoryBoundaries/Should archive oversized loaded files and tolerate interrupted archival
IT-022 daemon.TestPromptInputCompositeIntegrationAgentMemory and TestPromptInputCompositeIntegrationActiveAgentMemory: cross-workspace fenced snapshots and active/new session behavior.
IT-023 TestPromptInputCompositeIntegrationActiveAgentMemory: SQLite session transcripts and the default workspace policy; core.TestAgentMemorySessionSearch owns pagination and exclusion before transcript reads.
IT-024 Store rollback/reopen and retirement cases, shared definition deletion regression, and startup after a profile-name change with the same immutable profile ID.

Focused commands (from the repository root):

CGO_ENABLED=1 go test -race ./internal/agentmemory -count=1
CGO_ENABLED=1 go test -race ./internal/api/core -run 'TestAgentMemory|TestBaseHandlersAgentDefinitionMutations/Should_delete_only' -count=1
CGO_ENABLED=1 go test -race -tags integration ./internal/daemon -run 'TestAgentMemoryNativeTools|TestPromptInputCompositeIntegration.*AgentMemory' -count=1
go build ./...

Documentation

Overview

Package agentmemory owns bounded, explicit agent notes.

Index

Constants

View Source
const (
	MaxLines           = 200
	MaxBytes           = 24 * 1024
	MaxEntryCharacters = 1000
	TruncationMarker   = "[Memory truncated: undated notes exceed the load budget.]"
	// RulePrefix marks an operator rule. Lines without it are notes, so files
	// written before rules existed load unchanged.
	RulePrefix = "- [rule] "

	KindNote = "note"
	KindRule = "rule"
)

Variables

View Source
var (
	ErrBudgetExceeded = errors.New("agent_memory_budget_exceeded")
	ErrEntryTooLarge  = errors.New("agent_memory_entry_too_large")
	ErrConflict       = errors.New("agent_memory_conflict")
	// ErrRuleProtected refuses an agent write that would create, change or delete an operator rule.
	ErrRuleProtected = errors.New("agent_memory_rule_protected")
)

Functions

func FormatEntry

func FormatEntry(now time.Time, scope, text, until string) (string, error)

func FormatRule

func FormatRule(text string) (string, error)

FormatRule builds an operator rule line. Rules carry no date: they stay in force until the operator removes them and are never archived by overflow.

func IsRule

func IsRule(line string) bool

IsRule reports whether a memory line is an operator rule.

func Overflow

func Overflow(content string) (string, string, error)

Overflow returns an archive plan; callers persist the archive before replacing memory.

func Snapshot

func Snapshot(content string) string

Snapshot bounds startup data without changing the operator's file.

func Split

func Split(content string) ([]string, string)

Split separates operator rules (text only, in file order) from the notes document, which keeps every other line byte for byte.

Types

type AgentWriter

type AgentWriter struct {
	// contains filtered or unexported fields
}

AgentWriter is the store as an agent may write it. Every method keeps the operator rules exactly as they are and fails with ErrRuleProtected otherwise.

func (AgentWriter) Add

func (w AgentWriter) Add(key Key, now time.Time, scope, text, until string) (Document, error)

func (AgentWriter) Remove

func (w AgentWriter) Remove(key Key, match string) (Document, int, error)

func (AgentWriter) Replace

func (w AgentWriter) Replace(key Key, match, text string) (Document, error)

func (AgentWriter) Rollback

func (w AgentWriter) Rollback(key Key, revision string) (Document, error)

func (AgentWriter) Write

func (w AgentWriter) Write(key Key, content, expectedDigest string) (Document, error)

type Budget

type Budget struct {
	Lines    int `json:"lines"`
	MaxLines int `json:"max_lines"`
	Bytes    int `json:"bytes"`
	MaxBytes int `json:"max_bytes"`
}

func Measure

func Measure(content string) Budget

type Document

type Document struct {
	Content string `json:"content"`
	Digest  string `json:"digest"`
	Budget  Budget `json:"budget"`
}

type Key

type Key struct{ ProfileID, Origin, Agent string }

type Revision

type Revision struct {
	ID     string `json:"id"`
	Digest string `json:"digest"`
}

type SearchResult

type SearchResult struct {
	SessionID string  `json:"session_id,omitempty"`
	Source    string  `json:"source"`
	File      string  `json:"file"`
	Line      int     `json:"line"`
	Text      string  `json:"text"`
	Score     float64 `json:"score"`
}

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store is owned by the daemon; all transports share this instance.

func NewStore

func NewStore(home string) *Store

func (*Store) Add

func (s *Store) Add(key Key, now time.Time, scope, text, until string) (Document, error)

func (*Store) AddRule

func (s *Store) AddRule(key Key, text string) (Document, error)

AddRule appends an operator rule. Only operator surfaces call it.

func (*Store) AsAgent

func (s *Store) AsAgent() AgentWriter

AsAgent returns the write surface for a caller that acts as the agent itself.

func (*Store) History

func (s *Store) History(key Key) ([]Revision, error)

func (*Store) Load

func (s *Store) Load(key Key) (string, error)

func (*Store) Read

func (s *Store) Read(key Key) (Document, error)

func (*Store) Remove

func (s *Store) Remove(key Key, match string) (Document, int, error)

Remove deletes every matching line.

func (*Store) Replace

func (s *Store) Replace(key Key, match, text string) (Document, error)

Replace rewrites every matching line.

func (*Store) Retire

func (s *Store) Retire(key Key, now time.Time) error

func (*Store) Rollback

func (s *Store) Rollback(key Key, revision string) (Document, error)

func (*Store) Rules

func (s *Store) Rules(key Key) ([]string, error)

Rules returns the operator rules currently in force, without the archiving side effect of Load.

func (*Store) Search

func (s *Store) Search(key Key, query string) ([]SearchResult, error)

func (*Store) Write

func (s *Store) Write(key Key, content, expectedDigest string) (Document, error)

Jump to

Keyboard shortcuts

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