feat: built-in file-backed memory tool (18.12, 18.13)

internal/memory/builtin/provider.go — MemoryProvider backed by
MEMORY.md + USER.md files. LLM-callable memory tool with
add/replace/remove actions using section-sign delimited entries
and substring matching.

internal/memory/builtin/store.go — file read/write with atomic
replace and chmod 0600.
This commit is contained in:
sam committed 2026-07-26 08:58:27 +10:00
1 parent e8fe1b12a7
commit 942deb9336
4 files changed
+1462

No files matched your search

+251
View File
@@ -0,0 +1,251 @@
package builtin
import (
"fmt"
"path/filepath"
"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
}
// 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.
type Provider struct {
memory *Store
user *Store
}
// 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.
func New(cfg Config) (*Provider, error) {
if cfg.Dir == "" {
return nil, fmt.Errorf("builtin: Config.Dir must not be empty")
}
memStore, err := NewStore(filepath.Join(cfg.Dir, "MEMORY.md"), cfg.MaxFileBytes)
if err != nil {
return nil, err
}
userStore, err := NewStore(filepath.Join(cfg.Dir, "USER.md"), cfg.MaxFileBytes)
if err != nil {
return nil, err
}
return &Provider{memory: memStore, user: userStore}, nil
}
// Name returns the provider's identifier.
func (p *Provider) Name() string { return providerName }
// IsAvailable always returns true: the built-in provider has no external
// dependency that can be unavailable.
func (p *Provider) IsAvailable() bool { return true }
// 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.
func (p *Provider) Initialize(sessionID string) error {
if err := p.memory.Reload(); err != nil {
return err
}
return p.user.Reload()
}
// 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)
section, _ := args["section"].(string)
caseSensitive := true
if v, ok := args["case_sensitive"].(bool); ok {
caseSensitive = v
}
switch action {
case "add":
content, _ := args["content"].(string)
if content == "" {
return nil, fmt.Errorf("builtin: add requires non-empty \"content\"")
}
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
case "replace":
substring, _ := args["substring"].(string)
replacement, _ := args["replacement"].(string)
if substring == "" {
return nil, fmt.Errorf("builtin: replace requires non-empty \"substring\"")
}
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
case "remove":
substring, _ := args["substring"].(string)
if substring == "" {
return nil, fmt.Errorf("builtin: remove requires non-empty \"substring\"")
}
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
default:
return nil, fmt.Errorf("builtin: unknown action %q (want add, replace, or remove)", action)
}
}
// 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)
)
+277
View File
@@ -0,0 +1,277 @@
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 := out.(map[string]any)
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 := out.(map[string]any)
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)
}
}
+490
View File
@@ -0,0 +1,490 @@
// Package builtin implements the built-in, file-backed MemoryProvider. It
// persists agent memory to MEMORY.md and USER.md as plain markdown, using
// "## " headers to delimit named sections. Content within a section is
// organized into blank-line-separated blocks; add/replace/remove act on
// those blocks and on substrings within them.
package builtin
import (
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
)
// defaultMaxFileBytes is the default per-file size bound (100KB).
const defaultMaxFileBytes = 100 * 1024
// sectionNamePattern restricts section names to alphanumerics and spaces,
// matching the tool's input-validation contract.
var sectionNamePattern = regexp.MustCompile(`^[A-Za-z0-9 ]{1,64}$`)
// ValidateSectionName reports an error if name is empty, too long, or
// contains characters outside [A-Za-z0-9 ].
func ValidateSectionName(name string) error {
if !sectionNamePattern.MatchString(name) {
return fmt.Errorf("builtin: invalid section name %q: must be 1-64 alphanumeric/space characters", name)
}
return nil
}
// section is a named markdown block within a store file. blocks holds the
// section's content split into blank-line-separated paragraphs.
type section struct {
name string
blocks []string
}
// clone returns a deep copy of the section so callers can mutate a
// candidate version without touching the committed state.
func (s *section) clone() *section {
blocks := make([]string, len(s.blocks))
copy(blocks, s.blocks)
return &section{name: s.name, blocks: blocks}
}
// Store is a thread-safe, size-bounded, file-backed markdown document. It
// reads its full content at construction and rewrites the whole file on
// every mutation.
type Store struct {
mu sync.RWMutex
path string
maxBytes int
preamble string
sections []*section
}
// NewStore loads path if it exists (creating an empty in-memory document
// otherwise) and returns a Store bounded to maxBytes. maxBytes <= 0 uses
// defaultMaxFileBytes.
func NewStore(path string, maxBytes int) (*Store, error) {
if maxBytes <= 0 {
maxBytes = defaultMaxFileBytes
}
s := &Store{path: path, maxBytes: maxBytes}
data, err := os.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
return s, nil
}
return nil, fmt.Errorf("builtin: reading %s: %w", path, err)
}
s.preamble, s.sections = parseSections(string(data))
return s, nil
}
// 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 {
data, err := os.ReadFile(s.path)
if err != nil {
if os.IsNotExist(err) {
s.mu.Lock()
s.preamble, s.sections = "", nil
s.mu.Unlock()
return nil
}
return fmt.Errorf("builtin: reading %s: %w", s.path, err)
}
preamble, sections := parseSections(string(data))
s.mu.Lock()
s.preamble, s.sections = preamble, sections
s.mu.Unlock()
return nil
}
// Path returns the file path backing this store.
func (s *Store) Path() string {
return s.path
}
// MaxBytes returns the configured size bound for this store.
func (s *Store) MaxBytes() int {
return s.maxBytes
}
// Render returns the current serialized document. Safe for concurrent use.
func (s *Store) Render() string {
s.mu.RLock()
defer s.mu.RUnlock()
return renderSections(s.preamble, s.sections)
}
// Size returns the current serialized document length in bytes.
func (s *Store) Size() int {
s.mu.RLock()
defer s.mu.RUnlock()
return len(renderSections(s.preamble, s.sections))
}
// AddResult describes the outcome of a successful Add.
type AddResult struct {
Section string
CharsAdded int
SectionChars int
FileBytes int
Created bool // true if the section did not exist before this call
}
// Add appends content as a new block in the named section, creating the
// section if it does not already exist. The write is rejected — with no
// change to in-memory state or disk — if the resulting file would exceed
// the store's size bound.
func (s *Store) Add(sectionName, content string) (AddResult, error) {
if err := ValidateSectionName(sectionName); err != nil {
return AddResult{}, err
}
content = strings.TrimSpace(content)
if content == "" {
return AddResult{}, fmt.Errorf("builtin: content must not be empty")
}
s.mu.Lock()
defer s.mu.Unlock()
candidate := cloneSections(s.sections)
sec, created := findOrCreateSection(&candidate, sectionName)
sec.blocks = append(sec.blocks, content)
rendered := renderSections(s.preamble, candidate)
if len(rendered) > s.maxBytes {
return AddResult{}, fmt.Errorf("builtin: add to section %q would exceed max file size (%d > %d bytes)", sectionName, len(rendered), s.maxBytes)
}
if err := writeFileAtomic(s.path, rendered); err != nil {
return AddResult{}, err
}
s.sections = candidate
return AddResult{
Section: sectionName,
CharsAdded: len(content),
SectionChars: sectionChars(sec),
FileBytes: len(rendered),
Created: created,
}, nil
}
// ReplaceResult describes the outcome of a successful Replace.
type ReplaceResult struct {
Section string
CharsRemoved int
CharsAdded int
SectionChars int
FileBytes int
}
// Replace finds the first occurrence of substring within the named
// section's content and replaces it with replacement. It returns an error
// if the section does not exist, if substring is not found, or if the
// result would exceed the store's size bound.
func (s *Store) Replace(sectionName, substring, replacement string, caseSensitive bool) (ReplaceResult, error) {
if err := ValidateSectionName(sectionName); err != nil {
return ReplaceResult{}, err
}
if substring == "" {
return ReplaceResult{}, fmt.Errorf("builtin: substring must not be empty")
}
s.mu.Lock()
defer s.mu.Unlock()
candidate := cloneSections(s.sections)
sec := findSection(candidate, sectionName)
if sec == nil {
return ReplaceResult{}, fmt.Errorf("builtin: section %q not found", sectionName)
}
blockIdx, pos, matchLen := findInBlocks(sec.blocks, substring, caseSensitive)
if blockIdx < 0 {
return ReplaceResult{}, fmt.Errorf("builtin: substring %q not found in section %q", substring, sectionName)
}
block := sec.blocks[blockIdx]
sec.blocks[blockIdx] = block[:pos] + replacement + block[pos+matchLen:]
rendered := renderSections(s.preamble, candidate)
if len(rendered) > s.maxBytes {
return ReplaceResult{}, fmt.Errorf("builtin: replace in section %q would exceed max file size (%d > %d bytes)", sectionName, len(rendered), s.maxBytes)
}
if err := writeFileAtomic(s.path, rendered); err != nil {
return ReplaceResult{}, err
}
s.sections = candidate
return ReplaceResult{
Section: sectionName,
CharsRemoved: matchLen,
CharsAdded: len(replacement),
SectionChars: sectionChars(sec),
FileBytes: len(rendered),
}, nil
}
// RemoveResult describes the outcome of a successful Remove.
type RemoveResult struct {
Section string
CharsRemoved int
SectionChars int
FileBytes int
}
// Remove deletes the first block within the named section whose text
// contains substring. It returns an error if the section does not exist
// or if no block matches.
func (s *Store) Remove(sectionName, substring string, caseSensitive bool) (RemoveResult, error) {
if err := ValidateSectionName(sectionName); err != nil {
return RemoveResult{}, err
}
if substring == "" {
return RemoveResult{}, fmt.Errorf("builtin: substring must not be empty")
}
s.mu.Lock()
defer s.mu.Unlock()
candidate := cloneSections(s.sections)
sec := findSection(candidate, sectionName)
if sec == nil {
return RemoveResult{}, fmt.Errorf("builtin: section %q not found", sectionName)
}
blockIdx, _, _ := findInBlocks(sec.blocks, substring, caseSensitive)
if blockIdx < 0 {
return RemoveResult{}, fmt.Errorf("builtin: substring %q not found in section %q", substring, sectionName)
}
removed := sec.blocks[blockIdx]
sec.blocks = append(sec.blocks[:blockIdx], sec.blocks[blockIdx+1:]...)
rendered := renderSections(s.preamble, candidate)
// Removal only ever shrinks the file, but a bound check is kept for
// consistency with Add/Replace and to guard against pathological
// preamble/header growth from re-serialization.
if len(rendered) > s.maxBytes {
return RemoveResult{}, fmt.Errorf("builtin: remove from section %q would exceed max file size (%d > %d bytes)", sectionName, len(rendered), s.maxBytes)
}
if err := writeFileAtomic(s.path, rendered); err != nil {
return RemoveResult{}, err
}
s.sections = candidate
return RemoveResult{
Section: sectionName,
CharsRemoved: len(removed),
SectionChars: sectionChars(sec),
FileBytes: len(rendered),
}, nil
}
// ── Parsing & rendering ────────────────────────────────────────────────
// sectionHeaderPrefix is the markdown header marker that delimits sections.
const sectionHeaderPrefix = "## "
// parseSections splits document content into a preamble (any content before
// the first section header) and an ordered list of sections. Each section's
// body is split into blocks on blank lines.
func parseSections(content string) (preamble string, sections []*section) {
lines := strings.Split(content, "\n")
var preambleLines []string
var cur *section
var bodyLines []string
flush := func() {
if cur != nil {
cur.blocks = splitBlocks(bodyLines)
sections = append(sections, cur)
}
bodyLines = nil
}
for _, line := range lines {
if strings.HasPrefix(line, sectionHeaderPrefix) {
flush()
name := strings.TrimSpace(strings.TrimPrefix(line, sectionHeaderPrefix))
cur = &section{name: name}
continue
}
if cur == nil {
preambleLines = append(preambleLines, line)
} else {
bodyLines = append(bodyLines, line)
}
}
flush()
preamble = strings.TrimRight(strings.Join(preambleLines, "\n"), "\n \t")
return preamble, sections
}
// splitBlocks groups lines into blank-line-separated blocks, trimming
// leading/trailing blank lines and skipping empty blocks.
func splitBlocks(lines []string) []string {
var blocks []string
var cur []string
flush := func() {
if len(cur) > 0 {
blocks = append(blocks, strings.TrimRight(strings.Join(cur, "\n"), "\n"))
cur = nil
}
}
for _, line := range lines {
if strings.TrimSpace(line) == "" {
flush()
continue
}
cur = append(cur, line)
}
flush()
return blocks
}
// renderSections serializes a preamble and ordered sections back into the
// on-disk markdown format.
func renderSections(preamble string, sections []*section) string {
var sb strings.Builder
if preamble != "" {
sb.WriteString(preamble)
if len(sections) > 0 {
sb.WriteString("\n\n")
} else {
sb.WriteString("\n")
}
}
for i, sec := range sections {
if i > 0 {
sb.WriteString("\n")
}
sb.WriteString(sectionHeaderPrefix)
sb.WriteString(sec.name)
sb.WriteString("\n")
if len(sec.blocks) > 0 {
sb.WriteString("\n")
for j, block := range sec.blocks {
if j > 0 {
sb.WriteString("\n\n")
}
sb.WriteString(block)
}
sb.WriteString("\n")
}
}
return sb.String()
}
// sectionChars returns the serialized character count of a single section's
// body (blocks only, joined as they would appear on disk).
func sectionChars(sec *section) int {
return len(strings.Join(sec.blocks, "\n\n"))
}
// cloneSections returns a deep copy of a section slice.
func cloneSections(sections []*section) []*section {
out := make([]*section, len(sections))
for i, sec := range sections {
out[i] = sec.clone()
}
return out
}
// findSection returns the section with the given name, or nil.
func findSection(sections []*section, name string) *section {
for _, sec := range sections {
if sec.name == name {
return sec
}
}
return nil
}
// findOrCreateSection returns the named section from *sections, appending a
// new empty section (and reporting created=true) if none exists.
func findOrCreateSection(sections *[]*section, name string) (sec *section, created bool) {
if sec := findSection(*sections, name); sec != nil {
return sec, false
}
sec = &section{name: name}
*sections = append(*sections, sec)
return sec, true
}
// findInBlocks searches blocks in order for the first occurrence of
// substring, returning the block index, the byte offset within that block,
// and the byte length of the match. Returns (-1, -1, 0) if not found.
func findInBlocks(blocks []string, substring string, caseSensitive bool) (blockIdx, pos, matchLen int) {
for i, block := range blocks {
if caseSensitive {
if idx := strings.Index(block, substring); idx >= 0 {
return i, idx, len(substring)
}
continue
}
if idx, l := indexFold(block, substring); idx >= 0 {
return i, idx, l
}
}
return -1, -1, 0
}
// indexFold finds the first byte index in haystack where a substring of the
// same rune length as needle case-insensitively equals needle, using
// strings.EqualFold for comparison. Returns (-1, 0) if not found.
func indexFold(haystack, needle string) (int, int) {
needleRunes := len([]rune(needle))
runes := []rune(haystack)
for i := range runes {
if i+needleRunes > len(runes) {
break
}
candidate := string(runes[i : i+needleRunes])
if strings.EqualFold(candidate, needle) {
// Translate the rune index back to a byte offset.
byteOffset := len(string(runes[:i]))
return byteOffset, len(candidate)
}
}
return -1, 0
}
// writeFileAtomic writes content to path by writing to a temp file in the
// same directory and renaming it into place, so a crash mid-write cannot
// leave a truncated file behind.
func writeFileAtomic(path, content string) error {
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0o755); err != nil {
return fmt.Errorf("builtin: creating directory %s: %w", dir, err)
}
tmp, err := os.CreateTemp(dir, ".tmp-*")
if err != nil {
return fmt.Errorf("builtin: creating temp file in %s: %w", dir, err)
}
tmpPath := tmp.Name()
if _, err := tmp.WriteString(content); err != nil {
_ = tmp.Close()
_ = os.Remove(tmpPath)
return fmt.Errorf("builtin: writing %s: %w", path, err)
}
if err := tmp.Close(); err != nil {
_ = os.Remove(tmpPath)
return fmt.Errorf("builtin: closing %s: %w", path, err)
}
if err := os.Chmod(tmpPath, 0o644); err != nil {
_ = os.Remove(tmpPath)
return fmt.Errorf("builtin: setting permissions on %s: %w", path, err)
}
if err := os.Rename(tmpPath, path); err != nil {
_ = os.Remove(tmpPath)
return fmt.Errorf("builtin: renaming into %s: %w", path, err)
}
return nil
}
+444
View File
@@ -0,0 +1,444 @@
package builtin
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestValidateSectionName(t *testing.T) {
tests := []struct {
name string
input string
wantErr bool
}{
{"valid simple", "Facts", false},
{"valid with spaces", "User Preferences", false},
{"valid alphanumeric", "Section 123", false},
{"empty", "", true},
{"too long", strings.Repeat("a", 65), true},
{"exactly max length", strings.Repeat("a", 64), false},
{"invalid punctuation", "Facts!", true},
{"invalid hyphen", "my-section", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := ValidateSectionName(tt.input)
if (err != nil) != tt.wantErr {
t.Fatalf("ValidateSectionName(%q) error = %v, wantErr %v", tt.input, err, tt.wantErr)
}
})
}
}
func newTestStore(t *testing.T, maxBytes int) *Store {
t.Helper()
dir := t.TempDir()
s, err := NewStore(filepath.Join(dir, "MEMORY.md"), maxBytes)
if err != nil {
t.Fatalf("NewStore: %v", err)
}
return s
}
func TestStore_NewStore_MissingFile(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "MEMORY.md")
s, err := NewStore(path, 0)
if err != nil {
t.Fatalf("NewStore: %v", err)
}
if s.Render() != "" {
t.Fatalf("expected empty render for missing file, got %q", s.Render())
}
if s.MaxBytes() != defaultMaxFileBytes {
t.Fatalf("expected default max bytes, got %d", s.MaxBytes())
}
}
func TestStore_Add_CreatesSection(t *testing.T) {
s := newTestStore(t, 0)
res, err := s.Add("Facts", "the sky is blue")
if err != nil {
t.Fatalf("Add: %v", err)
}
if !res.Created {
t.Fatalf("expected Created=true for new section")
}
if res.Section != "Facts" {
t.Fatalf("expected section Facts, got %q", res.Section)
}
rendered := s.Render()
if !strings.Contains(rendered, "## Facts") {
t.Fatalf("expected rendered content to contain header, got %q", rendered)
}
if !strings.Contains(rendered, "the sky is blue") {
t.Fatalf("expected rendered content to contain the entry, got %q", rendered)
}
// Verify the write actually landed on disk.
data, err := os.ReadFile(s.Path())
if err != nil {
t.Fatalf("reading file: %v", err)
}
if string(data) != rendered {
t.Fatalf("disk content does not match in-memory render:\ndisk: %q\nmem: %q", data, rendered)
}
}
func TestStore_Add_AppendsToExistingSection(t *testing.T) {
s := newTestStore(t, 0)
if _, err := s.Add("Facts", "first entry"); err != nil {
t.Fatalf("first Add: %v", err)
}
res, err := s.Add("Facts", "second entry")
if err != nil {
t.Fatalf("second Add: %v", err)
}
if res.Created {
t.Fatalf("expected Created=false when appending to existing section")
}
rendered := s.Render()
if strings.Count(rendered, "## Facts") != 1 {
t.Fatalf("expected exactly one Facts header, got: %q", rendered)
}
if !strings.Contains(rendered, "first entry") || !strings.Contains(rendered, "second entry") {
t.Fatalf("expected both entries present, got %q", rendered)
}
}
func TestStore_Add_InvalidSectionName(t *testing.T) {
s := newTestStore(t, 0)
if _, err := s.Add("bad-name!", "content"); err == nil {
t.Fatalf("expected error for invalid section name")
}
}
func TestStore_Add_EmptyContent(t *testing.T) {
s := newTestStore(t, 0)
if _, err := s.Add("Facts", " "); err == nil {
t.Fatalf("expected error for empty content")
}
}
func TestStore_Add_RejectsOversizedWrite(t *testing.T) {
s := newTestStore(t, 32) // tiny bound
_, err := s.Add("Facts", strings.Repeat("x", 100))
if err == nil {
t.Fatalf("expected error when write would exceed max bytes")
}
if s.Render() != "" {
t.Fatalf("expected no mutation on rejected write, got %q", s.Render())
}
if _, statErr := os.Stat(s.Path()); statErr == nil {
t.Fatalf("expected no file to be written on rejected write")
}
}
func TestStore_Replace_FindsAndReplaces(t *testing.T) {
s := newTestStore(t, 0)
if _, err := s.Add("Facts", "the sky is blue"); err != nil {
t.Fatalf("Add: %v", err)
}
res, err := s.Replace("Facts", "blue", "green", true)
if err != nil {
t.Fatalf("Replace: %v", err)
}
if res.CharsRemoved != len("blue") || res.CharsAdded != len("green") {
t.Fatalf("unexpected char counts: %+v", res)
}
rendered := s.Render()
if !strings.Contains(rendered, "the sky is green") {
t.Fatalf("expected replacement applied, got %q", rendered)
}
if strings.Contains(rendered, "blue") {
t.Fatalf("expected original substring gone, got %q", rendered)
}
}
func TestStore_Replace_CaseInsensitive(t *testing.T) {
s := newTestStore(t, 0)
if _, err := s.Add("Facts", "The Sky Is Blue"); err != nil {
t.Fatalf("Add: %v", err)
}
if _, err := s.Replace("Facts", "sky", "ocean", false); err != nil {
t.Fatalf("Replace: %v", err)
}
rendered := s.Render()
if !strings.Contains(rendered, "The ocean Is Blue") {
t.Fatalf("expected case-insensitive replacement, got %q", rendered)
}
}
func TestStore_Replace_CaseSensitiveMismatchFails(t *testing.T) {
s := newTestStore(t, 0)
if _, err := s.Add("Facts", "The Sky Is Blue"); err != nil {
t.Fatalf("Add: %v", err)
}
if _, err := s.Replace("Facts", "sky", "ocean", true); err == nil {
t.Fatalf("expected case-sensitive mismatch to fail")
}
}
func TestStore_Replace_MissingSection(t *testing.T) {
s := newTestStore(t, 0)
if _, err := s.Replace("Nope", "a", "b", true); err == nil {
t.Fatalf("expected error for missing section")
}
}
func TestStore_Replace_SubstringNotFound(t *testing.T) {
s := newTestStore(t, 0)
if _, err := s.Add("Facts", "the sky is blue"); err != nil {
t.Fatalf("Add: %v", err)
}
if _, err := s.Replace("Facts", "purple", "green", true); err == nil {
t.Fatalf("expected error when substring not found")
}
}
func TestStore_Replace_FirstOccurrenceOnly(t *testing.T) {
s := newTestStore(t, 0)
if _, err := s.Add("Facts", "cat cat cat"); err != nil {
t.Fatalf("Add: %v", err)
}
if _, err := s.Replace("Facts", "cat", "dog", true); err != nil {
t.Fatalf("Replace: %v", err)
}
rendered := s.Render()
if !strings.Contains(rendered, "dog cat cat") {
t.Fatalf("expected only first occurrence replaced, got %q", rendered)
}
}
func TestStore_Remove_RemovesMatchingBlock(t *testing.T) {
s := newTestStore(t, 0)
if _, err := s.Add("Facts", "entry one"); err != nil {
t.Fatalf("Add: %v", err)
}
if _, err := s.Add("Facts", "entry two"); err != nil {
t.Fatalf("Add: %v", err)
}
res, err := s.Remove("Facts", "entry one", true)
if err != nil {
t.Fatalf("Remove: %v", err)
}
if res.CharsRemoved != len("entry one") {
t.Fatalf("unexpected chars removed: %d", res.CharsRemoved)
}
rendered := s.Render()
if strings.Contains(rendered, "entry one") {
t.Fatalf("expected entry one removed, got %q", rendered)
}
if !strings.Contains(rendered, "entry two") {
t.Fatalf("expected entry two to remain, got %q", rendered)
}
// The section header should remain even though a block was removed.
if !strings.Contains(rendered, "## Facts") {
t.Fatalf("expected section header to remain, got %q", rendered)
}
}
func TestStore_Remove_MissingSection(t *testing.T) {
s := newTestStore(t, 0)
if _, err := s.Remove("Nope", "a", true); err == nil {
t.Fatalf("expected error for missing section")
}
}
func TestStore_Remove_SubstringNotFound(t *testing.T) {
s := newTestStore(t, 0)
if _, err := s.Add("Facts", "entry one"); err != nil {
t.Fatalf("Add: %v", err)
}
if _, err := s.Remove("Facts", "nonexistent", true); err == nil {
t.Fatalf("expected error when substring not found")
}
}
func TestStore_PersistsAcrossReload(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "MEMORY.md")
s1, err := NewStore(path, 0)
if err != nil {
t.Fatalf("NewStore: %v", err)
}
if _, err := s1.Add("Facts", "persisted entry"); err != nil {
t.Fatalf("Add: %v", err)
}
s2, err := NewStore(path, 0)
if err != nil {
t.Fatalf("NewStore reload: %v", err)
}
if !strings.Contains(s2.Render(), "persisted entry") {
t.Fatalf("expected reloaded store to contain persisted entry, got %q", s2.Render())
}
}
func TestStore_Reload_PicksUpExternalChanges(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "MEMORY.md")
s, err := NewStore(path, 0)
if err != nil {
t.Fatalf("NewStore: %v", err)
}
if s.Render() != "" {
t.Fatalf("expected empty store initially")
}
// Simulate an external write (e.g. a prior process, or manual edit)
// happening after construction but before Reload.
if err := os.WriteFile(path, []byte("## Facts\n\nexternal entry\n"), 0o644); err != nil {
t.Fatalf("writing external content: %v", err)
}
if err := s.Reload(); err != nil {
t.Fatalf("Reload: %v", err)
}
if !strings.Contains(s.Render(), "external entry") {
t.Fatalf("expected reload to pick up external entry, got %q", s.Render())
}
}
func TestStore_Reload_MissingFileResetsToEmpty(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "MEMORY.md")
s, err := NewStore(path, 0)
if err != nil {
t.Fatalf("NewStore: %v", err)
}
if _, err := s.Add("Facts", "entry"); err != nil {
t.Fatalf("Add: %v", err)
}
if err := os.Remove(path); err != nil {
t.Fatalf("removing file: %v", err)
}
if err := s.Reload(); err != nil {
t.Fatalf("Reload: %v", err)
}
if s.Render() != "" {
t.Fatalf("expected empty store after reload of missing file, got %q", s.Render())
}
}
func TestStore_EmptySectionRoundTrip(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "MEMORY.md")
const original = "## Empty\n\n## Next\n\nContent\n"
if err := os.WriteFile(path, []byte(original), 0o644); err != nil {
t.Fatalf("writing seed file: %v", err)
}
s, err := NewStore(path, 0)
if err != nil {
t.Fatalf("NewStore: %v", err)
}
got := s.Render()
if got != original {
t.Fatalf("expected stable round-trip for empty section:\nwant %q\ngot %q", original, got)
}
// Re-rendering after a fresh reload must be idempotent (no growth from
// repeated parse/render cycles).
if err := s.Reload(); err != nil {
t.Fatalf("Reload: %v", err)
}
if got := s.Render(); got != original {
t.Fatalf("expected reload to preserve round-trip:\nwant %q\ngot %q", original, got)
}
}
func TestStore_ConsecutiveEmptySectionsRoundTrip(t *testing.T) {
// Extends TestStore_EmptySectionRoundTrip to two consecutive empty
// sections followed by a populated one, since the fix must generalize
// past a single degenerate case.
dir := t.TempDir()
path := filepath.Join(dir, "MEMORY.md")
multi := "## E1\n\n## E2\n\n## Facts\n\nfact one\n"
if err := os.WriteFile(path, []byte(multi), 0o644); err != nil {
t.Fatalf("writing fixture: %v", err)
}
s2, err := NewStore(path, 0)
if err != nil {
t.Fatalf("NewStore: %v", err)
}
if got := s2.Render(); got != multi {
t.Fatalf("round-trip mismatch for consecutive empty sections:\norig: %q\nrender: %q", multi, got)
}
}
func TestStore_PreambleOnlyRoundTrip(t *testing.T) {
// Regression test: a file with no section headers at all (just
// preamble content) must not gain a spurious trailing blank line.
dir := t.TempDir()
path := filepath.Join(dir, "MEMORY.md")
content := "Hello\nWorld\n"
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatalf("writing fixture: %v", err)
}
s, err := NewStore(path, 0)
if err != nil {
t.Fatalf("NewStore: %v", err)
}
if got := s.Render(); got != content {
t.Fatalf("round-trip mismatch for preamble-only file:\norig: %q\nrender: %q", content, got)
}
}
func TestStore_MultipleSectionsRoundTrip(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "MEMORY.md")
s1, err := NewStore(path, 0)
if err != nil {
t.Fatalf("NewStore: %v", err)
}
if _, err := s1.Add("Facts", "fact one"); err != nil {
t.Fatalf("Add: %v", err)
}
if _, err := s1.Add("Preferences", "pref one"); err != nil {
t.Fatalf("Add: %v", err)
}
if _, err := s1.Add("Facts", "fact two"); err != nil {
t.Fatalf("Add: %v", err)
}
s2, err := NewStore(path, 0)
if err != nil {
t.Fatalf("NewStore reload: %v", err)
}
rendered := s2.Render()
for _, want := range []string{"## Facts", "## Preferences", "fact one", "fact two", "pref one"} {
if !strings.Contains(rendered, want) {
t.Fatalf("expected rendered content to contain %q, got %q", want, rendered)
}
}
// Now mutate the reloaded store and ensure both sections survive.
if _, err := s2.Remove("Facts", "fact one", true); err != nil {
t.Fatalf("Remove: %v", err)
}
rendered = s2.Render()
if strings.Contains(rendered, "fact one") {
t.Fatalf("expected fact one removed, got %q", rendered)
}
if !strings.Contains(rendered, "fact two") || !strings.Contains(rendered, "pref one") {
t.Fatalf("expected other entries to survive, got %q", rendered)
}
}