chore(memory): delete internal/memory (unification slice 5) (#889)

Deletes internal/memory (Manager, builtin.Provider, memory_edit tool) now
that slices 2-4 built the CRUD engine family and its per-turn read/write
seams. Also deletes internal/infrastructure/memory/builtin/provider.go (the
memory_edit adapter over the old package -- its markdown store already
relocated in slice 2), internal/tools/provider/memory (the old tool
registration, redundant with slice 4's memory_create/update/delete/list),
config.Memory.{Provider,ProviderConfig} and the validateMemory rejection
that existed only to complain about Provider, and webui.MemoryStatus/
MemoryProviderHandle plus its dashboard page -- never wired in production
(s.Memory was always nil), confirmed by /api/capabilities always reporting
"memory": false.

Rewrites ARCHITECTURE.md's "Memory engine family" section to describe the
current engine (internal/domain/memory contract, internal/infrastructure/
memory builtin engine + its builtin/ markdown store, the per-turn read seam
in gateway/turn_memory.go, the per-turn write tools in
gateway/turn_memory_tool.go) instead of the deleted Manager. Fixes two
docs/architecture/configuration.md rows that described the deleted
manager's literals and SaveConfig mechanism.
This commit is contained in:
sam authored and GitHub committed 2026-09-19 13:43:16 +10:00
1 parent a18067d85d
commit 04d4d8f1d8
43 files changed
+92 -5619

No files matched your search

@@ -1,129 +0,0 @@
package builtin
import (
"os"
"path/filepath"
"strings"
"testing"
)
// A missing memory directory is indistinguishable from an empty memory: both
// stores treat ENOENT as "no content yet". That makes a misconfigured Dir
// invisible until the agent's first memory write fails mid-conversation.
//
// New settles the question at construction, but an unusable directory is not
// grounds for refusing to start -- the daemon falls back to the default
// location and carries on. So New reports the problem through IsAvailable and
// Err rather than by failing.
func TestNewEstablishesDir(t *testing.T) {
tests := []struct {
name string
dir func(t *testing.T) string
wantUsabl bool
}{
{
name: "existing directory",
dir: func(t *testing.T) string { return t.TempDir() },
wantUsabl: true,
},
{
name: "missing directory is created",
dir: func(t *testing.T) string {
return filepath.Join(t.TempDir(), "nested", "memory")
},
wantUsabl: true,
},
{
name: "unwritable parent is reported, not fatal",
dir: func(t *testing.T) string {
parent := filepath.Join(t.TempDir(), "ro")
if err := os.Mkdir(parent, 0o500); err != nil {
t.Fatalf("mkdir: %v", err)
}
return filepath.Join(parent, "memory")
},
},
{
name: "path occupied by a file is reported, not fatal",
dir: func(t *testing.T) string {
p := filepath.Join(t.TempDir(), "memory")
if err := os.WriteFile(p, []byte("not a dir"), 0o600); err != nil {
t.Fatalf("write: %v", err)
}
return p
},
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
// Running as root defeats permission-based cases.
if !tc.wantUsabl && os.Geteuid() == 0 {
t.Skip("running as root: permission cases are not meaningful")
}
dir := tc.dir(t)
p, err := New(Config{Dir: dir})
if err != nil {
t.Fatalf("New(%q) = %v, want a usable provider: an unusable "+
"directory must not stop the daemon starting", dir, err)
}
if p == nil {
t.Fatal("New returned a nil provider without an error")
}
if got := p.IsAvailable(); got != tc.wantUsabl {
t.Fatalf("IsAvailable() = %v, want %v", got, tc.wantUsabl)
}
if tc.wantUsabl {
if p.Err() != nil {
t.Fatalf("Err() = %v, want nil", p.Err())
}
info, statErr := os.Stat(dir)
if statErr != nil {
t.Fatalf("provider reports available but %q does not exist: %v", dir, statErr)
}
if !info.IsDir() {
t.Fatalf("%q is not a directory", dir)
}
return
}
// An unavailable provider must say why: the operator's only clue
// is what gets logged, and "memory unavailable" alone is not
// actionable.
if p.Err() == nil {
t.Fatal("IsAvailable() is false but Err() is nil, leaving the operator nothing to act on")
}
if !strings.Contains(p.Err().Error(), dir) {
t.Fatalf("Err() = %q, want it to name the offending directory %q", p.Err(), dir)
}
})
}
}
// A provider on an unusable directory must still answer every read, so a
// degraded memory reads as empty rather than panicking mid-conversation.
func TestUnusableDirStillReadable(t *testing.T) {
if os.Geteuid() == 0 {
t.Skip("running as root: permission cases are not meaningful")
}
parent := filepath.Join(t.TempDir(), "ro")
if err := os.Mkdir(parent, 0o500); err != nil {
t.Fatalf("mkdir: %v", err)
}
p, err := New(Config{Dir: filepath.Join(parent, "memory")})
if err != nil {
t.Fatalf("New: %v", err)
}
if err := p.Initialize("session-1"); err != nil {
t.Fatalf("Initialize on an unusable dir: %v", err)
}
if block := p.SystemPromptBlock(); block != "" {
t.Fatalf("SystemPromptBlock() = %q, want empty", block)
}
if len(p.GetToolSchemas()) == 0 {
t.Fatal("GetToolSchemas() is empty: the tool must still be offered")
}
}
@@ -1,403 +0,0 @@
package builtin
import (
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"github.com/samcharles93/archie-core/internal/memory"
"github.com/samcharles93/archie-core/internal/tools"
)
// providerName is the value returned by Provider.Name() and used to route
// tool calls to this provider.
const providerName = "builtin"
// toolName is the single tool this provider exposes to the agent.
const toolName = "memory_edit"
// Config configures a Provider.
type Config struct {
// Dir is the directory MEMORY.md and USER.md are read from and written
// to (e.g. ~/.config/archie/profiles/{profile}/memory/). It is created
// if it does not exist.
Dir string
// MaxFileBytes bounds the size of each file. Zero or negative uses
// defaultMaxFileBytes (100KB).
MaxFileBytes int
// DisableFrozenSnapshot, when true, causes SystemPromptBlock() to read
// live content from the stores on every call instead of using the
// snapshot captured at Initialize() time. Defaults to false (frozen
// snapshot enabled).
DisableFrozenSnapshot bool
}
// Provider is the built-in, file-backed MemoryProvider. It persists agent
// memory to MEMORY.md and user-provided context to USER.md under Config.Dir,
// and exposes a single "memory_edit" tool with add/replace/remove actions.
//
// By default, the provider captures a frozen snapshot of both files at
// Initialize() time and uses that snapshot for the system prompt block
// (SystemPromptProvider). Writes go to disk immediately but the snapshot is
// not updated mid-session -- only the next session (or next Initialize call)
// picks up the changes. Set Config.FrozenSnapshot to false to read live
// content on every SystemPromptBlock() call.
type Provider struct {
memory *Store
user *Store
// frozenSnapshotEnabled mirrors Config.FrozenSnapshot. When unset
// (default), Initialize() captures a snapshot that SystemPromptBlock()
// returns for the lifetime of the session.
frozenSnapshotEnabled bool
// frozenMu guards frozenMemory and frozenUser, since Initialize() can
// race with SystemPromptBlock() if a caller re-initializes a session on
// a Provider shared across goroutines.
frozenMu sync.RWMutex
// frozen memory and frozen user hold the Render() output captured at
// Initialize() time. They are only valid after Initialize() has been
// called and only used when frozenSnapshotEnabled is true.
frozenMemory string
frozenUser string
// dirErr records a Config.Dir that could not be established. The
// provider stays usable for reads -- a memory that cannot be written is
// still better than a daemon that will not start -- and reports itself
// unavailable so the failure is visible rather than looking like a
// memory that simply has nothing in it yet.
dirErr error
}
// New creates a Provider backed by the two markdown files under cfg.Dir.
// Both files are read immediately so the provider is ready for use as soon
// as New returns.
//
// An unusable cfg.Dir is reported through IsAvailable and Err, not by
// failing: memory is one capability among many, and a bad path is not worth
// refusing to start over. The caller decides whether to fall back elsewhere.
// Establishing the directory here is still what makes the problem visible at
// all -- both stores treat a missing file as an empty document, so otherwise
// a directory that does not exist is indistinguishable from a memory that
// simply has nothing in it yet, and the failure surfaces at the agent's
// first write, mid-conversation.
//
// FrozenSnapshot defaults to true (frozen snapshot enabled). Set it
// explicitly to false to have SystemPromptBlock() read live content from
// the stores.
func New(cfg Config) (*Provider, error) {
if cfg.Dir == "" {
return nil, fmt.Errorf("builtin: Config.Dir must not be empty")
}
var dirErr error
if err := os.MkdirAll(cfg.Dir, 0o755); err != nil {
dirErr = fmt.Errorf("builtin: memory directory %s unusable: %w", cfg.Dir, err)
}
// A store that cannot read its file starts empty rather than failing,
// for the same reason: reads must keep working on a degraded provider.
memStore, err := NewStore(filepath.Join(cfg.Dir, "MEMORY.md"), cfg.MaxFileBytes)
if err != nil {
if dirErr == nil {
dirErr = err
}
memStore = emptyStore(filepath.Join(cfg.Dir, "MEMORY.md"), cfg.MaxFileBytes)
}
userStore, err := NewStore(filepath.Join(cfg.Dir, "USER.md"), cfg.MaxFileBytes)
if err != nil {
if dirErr == nil {
dirErr = err
}
userStore = emptyStore(filepath.Join(cfg.Dir, "USER.md"), cfg.MaxFileBytes)
}
// Frozen snapshot is enabled by default (DisableFrozenSnapshot defaults
// to false).
frozen := !cfg.DisableFrozenSnapshot
return &Provider{
memory: memStore,
user: userStore,
frozenSnapshotEnabled: frozen,
dirErr: dirErr,
}, nil
}
// Name returns the provider's identifier.
func (p *Provider) Name() string { return providerName }
// IsAvailable reports whether the backing directory could be established.
// The built-in provider has one external dependency after all -- the
// filesystem -- and a directory it cannot write to means memory reads as
// empty and every write will fail.
func (p *Provider) IsAvailable() bool { return p.dirErr == nil }
// Err returns why the provider is unavailable, or nil. Callers log this: an
// operator told only that memory is unavailable has nothing to act on.
func (p *Provider) Err() error { return p.dirErr }
// SystemPromptBlock implements memory.SystemPromptProvider. It returns a
// markdown-formatted block containing the frozen snapshot of MEMORY.md and
// USER.md content, wrapped in <memory>…</memory> fences.
//
// When the frozen snapshot is enabled (the default), the block is built from
// the snapshot captured at Initialize() time and does not change for the
// duration of the session. When disabled (Config.DisableFrozenSnapshot =
// true), the block is built from the live store content on every call.
//
// Returns an empty string when both stores are empty.
func (p *Provider) SystemPromptBlock() string {
mem, user := p.snapshotContent()
if mem == "" && user == "" {
return ""
}
var sb strings.Builder
sb.WriteString("<memory>\n")
if mem != "" {
sb.WriteString(mem)
}
if user != "" {
if mem != "" {
sb.WriteString("\n")
}
sb.WriteString(user)
}
sb.WriteString("\n</memory>\n")
return sb.String()
}
// snapshotContent returns the memory and user content, either from the frozen
// snapshot or live from the stores, depending on the FrozenSnapshot config.
func (p *Provider) snapshotContent() (memory, user string) {
if p.frozenSnapshotEnabled {
p.frozenMu.RLock()
defer p.frozenMu.RUnlock()
return p.frozenMemory, p.frozenUser
}
return p.memory.Render(), p.user.Render()
}
// Initialize reloads MEMORY.md and USER.md from disk so that any changes
// made outside this process (or by a previous provider instance) since
// New was called are picked up before the session begins.
//
// When frozen snapshot is enabled (the default), Initialize captures the
// rendered content of both files for use by SystemPromptBlock(). The snapshot
// is not updated on subsequent writes -- only the next Initialize() call (or
// the next session) picks up the fresh content.
func (p *Provider) Initialize(sessionID string) error {
if err := p.memory.Reload(); err != nil {
return err
}
if err := p.user.Reload(); err != nil {
return err
}
if p.frozenSnapshotEnabled {
mem := p.memory.Render()
user := p.user.Render()
p.frozenMu.Lock()
p.frozenMemory = mem
p.frozenUser = user
p.frozenMu.Unlock()
}
return nil
}
// GetToolSchemas returns the memory_edit tool definition. Handler is left
// nil so the MemoryManager injects a delegating handler via
// ToolCallProvider (see Manager.GetToolSchemas); callers that bypass the
// Manager should invoke HandleToolCall directly.
func (p *Provider) GetToolSchemas() []tools.ToolEntry {
return []tools.ToolEntry{
{
Name: toolName,
Toolset: "memory",
Description: "Persist or edit agent memory. Add, replace, or remove content in a named section of MEMORY.md (agent memory) or USER.md (user-provided context).",
Schema: toolSchema,
},
}
}
// toolSchema is the JSON Schema for the memory_edit tool's input.
var toolSchema = tools.JSONSchema{
"type": "object",
"properties": map[string]any{
"file": map[string]any{
"type": "string",
"enum": []string{"memory", "user"},
"description": "Which file to edit: \"memory\" for MEMORY.md (agent memory) or \"user\" for USER.md (user-provided context). Defaults to \"memory\".",
},
"action": map[string]any{
"type": "string",
"enum": []string{"add", "replace", "remove"},
"description": "The action to perform: add a new entry, replace a substring, or remove a matching entry.",
},
"section": map[string]any{
"type": "string",
"description": "Name of the section (markdown header) to operate on. Alphanumeric and spaces only, max 64 characters. Created automatically by \"add\" if it does not exist.",
},
"content": map[string]any{
"type": "string",
"description": "Content to append as a new entry. Required for the \"add\" action.",
},
"substring": map[string]any{
"type": "string",
"description": "Exact substring to locate within the section. Required for \"replace\" and \"remove\".",
},
"replacement": map[string]any{
"type": "string",
"description": "Text to substitute in place of substring. Required for the \"replace\" action.",
},
"case_sensitive": map[string]any{
"type": "boolean",
"description": "Whether substring matching is case-sensitive. Defaults to true.",
},
},
"required": []string{"action", "section"},
}
// HandleToolCall implements memory.ToolCallProvider. It dispatches the
// memory_edit tool's add/replace/remove actions to the selected store.
func (p *Provider) HandleToolCall(name string, args map[string]any) (any, error) {
if name != toolName {
return nil, fmt.Errorf("builtin: unknown tool %q", name)
}
store, fileLabel, err := p.selectStore(args)
if err != nil {
return nil, err
}
action, _ := args["action"].(string)
caseSensitive := true
if v, ok := args["case_sensitive"].(bool); ok {
caseSensitive = v
}
switch action {
case "add":
return p.handleAdd(store, fileLabel, args)
case "replace":
return p.handleReplace(store, fileLabel, args, caseSensitive)
case "remove":
return p.handleRemove(store, fileLabel, args, caseSensitive)
default:
return nil, fmt.Errorf("builtin: unknown action %q (want add, replace, or remove)", action)
}
}
func (p *Provider) handleAdd(store *Store, fileLabel string, args map[string]any) (any, error) {
content, _ := args["content"].(string)
if content == "" {
return nil, fmt.Errorf("builtin: add requires non-empty \"content\"")
}
section, _ := args["section"].(string)
res, err := store.Add(section, content)
if err != nil {
return nil, err
}
verb := "appended to"
if res.Created {
verb = "created"
}
return map[string]any{
"success": true,
"file": fileLabel,
"action": "add",
"section": res.Section,
"chars_added": res.CharsAdded,
"section_chars": res.SectionChars,
"file_bytes": res.FileBytes,
"message": fmt.Sprintf("%s section %q (%d chars added, %d bytes in file)", capitalize(verb), res.Section, res.CharsAdded, res.FileBytes),
}, nil
}
func (p *Provider) handleReplace(store *Store, fileLabel string, args map[string]any, caseSensitive bool) (any, error) {
substring, _ := args["substring"].(string)
replacement, _ := args["replacement"].(string)
if substring == "" {
return nil, fmt.Errorf("builtin: replace requires non-empty \"substring\"")
}
section, _ := args["section"].(string)
res, err := store.Replace(section, substring, replacement, caseSensitive)
if err != nil {
return nil, err
}
return map[string]any{
"success": true,
"file": fileLabel,
"action": "replace",
"section": res.Section,
"chars_removed": res.CharsRemoved,
"chars_added": res.CharsAdded,
"section_chars": res.SectionChars,
"file_bytes": res.FileBytes,
"message": fmt.Sprintf("Replaced %d chars with %d chars in section %q (%d bytes in file)", res.CharsRemoved, res.CharsAdded, res.Section, res.FileBytes),
}, nil
}
func (p *Provider) handleRemove(store *Store, fileLabel string, args map[string]any, caseSensitive bool) (any, error) {
substring, _ := args["substring"].(string)
if substring == "" {
return nil, fmt.Errorf("builtin: remove requires non-empty \"substring\"")
}
section, _ := args["section"].(string)
res, err := store.Remove(section, substring, caseSensitive)
if err != nil {
return nil, err
}
return map[string]any{
"success": true,
"file": fileLabel,
"action": "remove",
"section": res.Section,
"chars_removed": res.CharsRemoved,
"section_chars": res.SectionChars,
"file_bytes": res.FileBytes,
"message": fmt.Sprintf("Removed %d chars from section %q (%d bytes in file)", res.CharsRemoved, res.Section, res.FileBytes),
}, nil
}
// selectStore resolves the "file" argument to the corresponding store,
// defaulting to the memory (MEMORY.md) store.
func (p *Provider) selectStore(args map[string]any) (*Store, string, error) {
file, _ := args["file"].(string)
switch file {
case "", "memory":
return p.memory, "memory", nil
case "user":
return p.user, "user", nil
default:
return nil, "", fmt.Errorf("builtin: unknown file %q (want \"memory\" or \"user\")", file)
}
}
// capitalize upper-cases the first byte of s. It is only used for
// short, ASCII, English status verbs, so byte-level capitalization is
// sufficient.
func capitalize(s string) string {
if s == "" {
return s
}
b := []byte(s)
if b[0] >= 'a' && b[0] <= 'z' {
b[0] -= 'a' - 'A'
}
return string(b)
}
// Compile-time interface checks.
var (
_ memory.MemoryProvider = (*Provider)(nil)
_ memory.ToolCallProvider = (*Provider)(nil)
_ memory.SystemPromptProvider = (*Provider)(nil)
)
@@ -1,507 +0,0 @@
package builtin
import (
"context"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"testing"
)
func newTestProvider(t *testing.T) *Provider {
t.Helper()
p, err := New(Config{Dir: t.TempDir()})
if err != nil {
t.Fatalf("New: %v", err)
}
return p
}
func TestProvider_Identity(t *testing.T) {
p := newTestProvider(t)
if p.Name() != "builtin" {
t.Fatalf("expected name builtin, got %q", p.Name())
}
if !p.IsAvailable() {
t.Fatalf("expected builtin provider to always be available")
}
if err := p.Initialize("session-1"); err != nil {
t.Fatalf("Initialize: %v", err)
}
}
func TestProvider_Initialize_ReloadsFromDisk(t *testing.T) {
dir := t.TempDir()
p, err := New(Config{Dir: dir})
if err != nil {
t.Fatalf("New: %v", err)
}
if err := os.WriteFile(filepath.Join(dir, "MEMORY.md"), []byte("## Facts\n\nexternal entry\n"), 0o644); err != nil {
t.Fatalf("writing external content: %v", err)
}
if err := p.Initialize("session-1"); err != nil {
t.Fatalf("Initialize: %v", err)
}
if !strings.Contains(p.memory.Render(), "external entry") {
t.Fatalf("expected Initialize to reload MEMORY.md, got %q", p.memory.Render())
}
}
func TestProvider_New_RequiresDir(t *testing.T) {
if _, err := New(Config{}); err == nil {
t.Fatalf("expected error for empty Dir")
}
}
func TestProvider_New_CreatesDirAndFiles(t *testing.T) {
dir := filepath.Join(t.TempDir(), "nested", "memory")
p, err := New(Config{Dir: dir})
if err != nil {
t.Fatalf("New: %v", err)
}
if _, err := p.HandleToolCall(toolName, map[string]any{
"action": "add",
"section": "Facts",
"content": "hello",
}); err != nil {
t.Fatalf("HandleToolCall add: %v", err)
}
if _, statErr := os.Stat(filepath.Join(dir, "MEMORY.md")); statErr != nil {
t.Fatalf("expected MEMORY.md to exist: %v", statErr)
}
}
// TestProvider_GetToolSchemas checks the exported schema shape, and that
// Handler is left nil for the Manager to inject via ToolCallProvider (per
// Manager.GetToolSchemas' documented behavior).
func TestProvider_GetToolSchemas(t *testing.T) {
p := newTestProvider(t)
entries := p.GetToolSchemas()
if len(entries) != 1 {
t.Fatalf("expected exactly one tool entry, got %d", len(entries))
}
e := entries[0]
if e.Name != toolName {
t.Fatalf("expected tool name %q, got %q", toolName, e.Name)
}
if e.Handler != nil {
t.Fatalf("expected nil Handler so Manager injects the ToolCallProvider delegate")
}
// Simulate the Manager's injection and confirm the resulting entry
// passes Validate().
e = e.Clone()
e.Handler = func(ctx context.Context, input map[string]any) (any, error) {
return p.HandleToolCall(e.Name, input)
}
if err := e.Validate(); err != nil {
t.Fatalf("ToolEntry.Validate() after injection: %v", err)
}
}
func TestProvider_HandleToolCall_UnknownTool(t *testing.T) {
p := newTestProvider(t)
if _, err := p.HandleToolCall("not_memory_edit", map[string]any{}); err == nil {
t.Fatalf("expected error for unknown tool name")
}
}
func TestProvider_HandleToolCall_Add_DefaultsToMemoryFile(t *testing.T) {
p := newTestProvider(t)
out, err := p.HandleToolCall(toolName, map[string]any{
"action": "add",
"section": "Facts",
"content": "the sky is blue",
})
if err != nil {
t.Fatalf("HandleToolCall: %v", err)
}
result, ok := out.(map[string]any)
if !ok {
t.Fatalf("expected map[string]any result, got %T", out)
}
if result["file"] != "memory" {
t.Fatalf("expected default file \"memory\", got %v", result["file"])
}
if !strings.Contains(p.memory.Render(), "the sky is blue") {
t.Fatalf("expected content written to MEMORY.md, got %q", p.memory.Render())
}
if strings.Contains(p.user.Render(), "the sky is blue") {
t.Fatalf("did not expect content in USER.md")
}
}
func TestProvider_HandleToolCall_Add_UserFile(t *testing.T) {
p := newTestProvider(t)
_, err := p.HandleToolCall(toolName, map[string]any{
"file": "user",
"action": "add",
"section": "Preferences",
"content": "likes dark mode",
})
if err != nil {
t.Fatalf("HandleToolCall: %v", err)
}
if !strings.Contains(p.user.Render(), "likes dark mode") {
t.Fatalf("expected content written to USER.md, got %q", p.user.Render())
}
}
func TestProvider_HandleToolCall_UnknownFile(t *testing.T) {
p := newTestProvider(t)
_, err := p.HandleToolCall(toolName, map[string]any{
"file": "bogus",
"action": "add",
"section": "Facts",
"content": "x",
})
if err == nil {
t.Fatalf("expected error for unknown file selector")
}
}
func TestProvider_HandleToolCall_UnknownAction(t *testing.T) {
p := newTestProvider(t)
_, err := p.HandleToolCall(toolName, map[string]any{
"action": "delete",
"section": "Facts",
})
if err == nil {
t.Fatalf("expected error for unknown action")
}
}
func TestProvider_HandleToolCall_Replace(t *testing.T) {
p := newTestProvider(t)
if _, err := p.HandleToolCall(toolName, map[string]any{
"action": "add", "section": "Facts", "content": "the sky is blue",
}); err != nil {
t.Fatalf("add: %v", err)
}
out, err := p.HandleToolCall(toolName, map[string]any{
"action": "replace", "section": "Facts", "substring": "blue", "replacement": "green",
})
if err != nil {
t.Fatalf("replace: %v", err)
}
result, ok := out.(map[string]any)
if !ok {
t.Fatalf("out is %T, want map[string]any", out)
}
if result["action"] != "replace" {
t.Fatalf("expected action replace, got %v", result["action"])
}
if !strings.Contains(p.memory.Render(), "the sky is green") {
t.Fatalf("expected replacement applied, got %q", p.memory.Render())
}
}
func TestProvider_HandleToolCall_Remove(t *testing.T) {
p := newTestProvider(t)
if _, err := p.HandleToolCall(toolName, map[string]any{
"action": "add", "section": "Facts", "content": "entry one",
}); err != nil {
t.Fatalf("add: %v", err)
}
out, err := p.HandleToolCall(toolName, map[string]any{
"action": "remove", "section": "Facts", "substring": "entry one",
})
if err != nil {
t.Fatalf("remove: %v", err)
}
result, ok := out.(map[string]any)
if !ok {
t.Fatalf("out is %T, want map[string]any", out)
}
if result["action"] != "remove" {
t.Fatalf("expected action remove, got %v", result["action"])
}
if strings.Contains(p.memory.Render(), "entry one") {
t.Fatalf("expected entry removed, got %q", p.memory.Render())
}
}
func TestProvider_HandleToolCall_Add_RequiresContent(t *testing.T) {
p := newTestProvider(t)
if _, err := p.HandleToolCall(toolName, map[string]any{
"action": "add", "section": "Facts",
}); err == nil {
t.Fatalf("expected error when content is missing")
}
}
func TestProvider_HandleToolCall_Replace_RequiresSubstring(t *testing.T) {
p := newTestProvider(t)
if _, err := p.HandleToolCall(toolName, map[string]any{
"action": "replace", "section": "Facts", "replacement": "x",
}); err == nil {
t.Fatalf("expected error when substring is missing")
}
}
func TestProvider_HandleToolCall_InvalidSectionName(t *testing.T) {
p := newTestProvider(t)
if _, err := p.HandleToolCall(toolName, map[string]any{
"action": "add", "section": "bad-section!", "content": "x",
}); err == nil {
t.Fatalf("expected error for invalid section name")
}
}
// TestProvider_ConcurrentToolCalls exercises the store's mutex under
// concurrent add calls from multiple goroutines, simulating concurrent
// tool invocations against the same provider.
func TestProvider_ConcurrentToolCalls(t *testing.T) {
p := newTestProvider(t)
const n = 50
var wg sync.WaitGroup
for i := range n {
wg.Add(1)
go func(i int) {
defer wg.Done()
_, err := p.HandleToolCall(toolName, map[string]any{
"action": "add",
"section": "Facts",
"content": "entry " + strconv.Itoa(i),
})
if err != nil {
t.Errorf("concurrent add %d: %v", i, err)
}
}(i)
}
wg.Wait()
rendered := p.memory.Render()
if strings.Count(rendered, "## Facts") != 1 {
t.Fatalf("expected exactly one Facts header after concurrent writes, got: %q", rendered)
}
}
// ── Frozen snapshot tests ─────────────────────────────────────────────
func TestProvider_FrozenSnapshot_NotUpdatedOnWrite(t *testing.T) {
p := newTestProvider(t)
// Add content before Initialize so the snapshot captures it.
if _, err := p.HandleToolCall(toolName, map[string]any{
"action": "add", "section": "Facts", "content": "initial fact",
}); err != nil {
t.Fatalf("add before init: %v", err)
}
if err := p.Initialize("session-1"); err != nil {
t.Fatalf("Initialize: %v", err)
}
firstBlock := p.SystemPromptBlock()
if !strings.Contains(firstBlock, "initial fact") {
t.Fatalf("snapshot should contain initial fact, got: %s", firstBlock)
}
if !strings.Contains(firstBlock, "<memory>") {
t.Fatalf("snapshot should be wrapped in <memory> fences, got: %s", firstBlock)
}
// Write after initialization -- the snapshot must not change.
if _, err := p.HandleToolCall(toolName, map[string]any{
"action": "add", "section": "Facts", "content": "new fact after init",
}); err != nil {
t.Fatalf("add after init: %v", err)
}
secondBlock := p.SystemPromptBlock()
if secondBlock != firstBlock {
t.Fatalf("snapshot changed after write!\nbefore: %s\nafter: %s", firstBlock, secondBlock)
}
// The file on disk should have the new content.
if !strings.Contains(p.memory.Render(), "new fact after init") {
t.Fatal("file on disk should contain the new fact")
}
}
func TestProvider_FrozenSnapshot_Disabled_ReadsLive(t *testing.T) {
dir := t.TempDir()
p, err := New(Config{Dir: dir, DisableFrozenSnapshot: true})
if err != nil {
t.Fatalf("New: %v", err)
}
if _, err := p.HandleToolCall(toolName, map[string]any{
"action": "add", "section": "Facts", "content": "first",
}); err != nil {
t.Fatalf("add: %v", err)
}
if err := p.Initialize("session-1"); err != nil {
t.Fatalf("Initialize: %v", err)
}
block1 := p.SystemPromptBlock()
if !strings.Contains(block1, "first") {
t.Fatalf("expected 'first' in block, got: %s", block1)
}
// With frozen disabled, writes are immediately visible.
if _, err := p.HandleToolCall(toolName, map[string]any{
"action": "add", "section": "Facts", "content": "second",
}); err != nil {
t.Fatalf("add: %v", err)
}
block2 := p.SystemPromptBlock()
if !strings.Contains(block2, "second") {
t.Fatalf("expected 'second' in live block, got: %s", block2)
}
if block1 == block2 {
t.Fatal("live mode should reflect writes immediately, but blocks are identical")
}
}
func TestProvider_FrozenSnapshot_EmptyStores(t *testing.T) {
p := newTestProvider(t)
if err := p.Initialize("session-1"); err != nil {
t.Fatalf("Initialize: %v", err)
}
block := p.SystemPromptBlock()
if block != "" {
t.Fatalf("expected empty block for empty stores, got: %s", block)
}
}
func TestProvider_FrozenSnapshot_OnlyMemory(t *testing.T) {
p := newTestProvider(t)
if _, err := p.HandleToolCall(toolName, map[string]any{
"action": "add", "section": "Facts", "content": "mem only",
}); err != nil {
t.Fatalf("add: %v", err)
}
if err := p.Initialize("session-1"); err != nil {
t.Fatalf("Initialize: %v", err)
}
block := p.SystemPromptBlock()
if !strings.Contains(block, "mem only") {
t.Fatalf("expected memory content, got: %s", block)
}
if !strings.Contains(block, "<memory>") {
t.Fatal("missing <memory> fence")
}
}
func TestProvider_FrozenSnapshot_OnlyUser(t *testing.T) {
p := newTestProvider(t)
if _, err := p.HandleToolCall(toolName, map[string]any{
"file": "user", "action": "add", "section": "Preferences", "content": "user only",
}); err != nil {
t.Fatalf("add: %v", err)
}
if err := p.Initialize("session-1"); err != nil {
t.Fatalf("Initialize: %v", err)
}
block := p.SystemPromptBlock()
if !strings.Contains(block, "user only") {
t.Fatalf("expected user content, got: %s", block)
}
}
func TestProvider_FrozenSnapshot_ReInitialize(t *testing.T) {
p := newTestProvider(t)
if _, err := p.HandleToolCall(toolName, map[string]any{
"action": "add", "section": "Facts", "content": "before",
}); err != nil {
t.Fatalf("add: %v", err)
}
if err := p.Initialize("session-1"); err != nil {
t.Fatalf("Initialize: %v", err)
}
block1 := p.SystemPromptBlock()
if !strings.Contains(block1, "before") {
t.Fatalf("expected 'before', got: %s", block1)
}
// Add more content and re-initialize -- snapshot should refresh.
if _, err := p.HandleToolCall(toolName, map[string]any{
"action": "add", "section": "Facts", "content": "after",
}); err != nil {
t.Fatalf("add: %v", err)
}
if err := p.Initialize("session-2"); err != nil {
t.Fatalf("Initialize: %v", err)
}
block2 := p.SystemPromptBlock()
if !strings.Contains(block2, "after") {
t.Fatalf("re-init should capture new content, got: %s", block2)
}
if block1 == block2 {
t.Fatal("re-init should produce a fresh snapshot")
}
}
func TestProvider_FrozenSnapshot_DefaultEnabled(t *testing.T) {
// When FrozenSnapshot is not explicitly set, it defaults to true.
dir := t.TempDir()
p, err := New(Config{Dir: dir})
if err != nil {
t.Fatalf("New: %v", err)
}
if _, err := p.HandleToolCall(toolName, map[string]any{
"action": "add", "section": "Facts", "content": "pre-init",
}); err != nil {
t.Fatalf("add: %v", err)
}
if err := p.Initialize("session-1"); err != nil {
t.Fatalf("Initialize: %v", err)
}
block1 := p.SystemPromptBlock()
// Write after init -- snapshot should be frozen.
if _, err := p.HandleToolCall(toolName, map[string]any{
"action": "add", "section": "Facts", "content": "post-init",
}); err != nil {
t.Fatalf("add: %v", err)
}
block2 := p.SystemPromptBlock()
if block1 != block2 {
t.Fatal("default frozen snapshot should not change after writes")
}
}
func TestProvider_FrozenSnapshot_BothFiles(t *testing.T) {
p := newTestProvider(t)
if _, err := p.HandleToolCall(toolName, map[string]any{
"action": "add", "section": "Facts", "content": "mem content",
}); err != nil {
t.Fatalf("add memory: %v", err)
}
if _, err := p.HandleToolCall(toolName, map[string]any{
"file": "user", "action": "add", "section": "Preferences", "content": "user content",
}); err != nil {
t.Fatalf("add user: %v", err)
}
if err := p.Initialize("session-1"); err != nil {
t.Fatalf("Initialize: %v", err)
}
block := p.SystemPromptBlock()
if !strings.Contains(block, "mem content") {
t.Fatal("missing memory content")
}
if !strings.Contains(block, "user content") {
t.Fatal("missing user content")
}
if !strings.Contains(block, "<memory>") && !strings.Contains(block, "</memory>") {
t.Fatal("missing <memory> fences")
}
}
@@ -77,16 +77,6 @@ func NewStore(path string, maxBytes int) (*Store, error) {
return s, nil
}
// emptyStore returns a Store bound to path with no content, for a file that
// could not be read. Reads answer as empty and a later write still attempts
// the file, so a directory that becomes usable repairs itself.
func emptyStore(path string, maxBytes int) *Store {
if maxBytes <= 0 {
maxBytes = defaultMaxFileBytes
}
return &Store{path: path, maxBytes: maxBytes}
}
// Reload re-reads the backing file from disk, replacing all in-memory
// state. A missing file resets the store to empty rather than erroring.
func (s *Store) Reload() error {