fix(memory): fall back to the default directory instead of exiting

d615de5 made an unusable memory directory fatal. That was the wrong
call and contradicts the forge and container paths: memory is one
capability among many, and refusing to start over a path denies the
operator chat, the dashboard and everything else -- then crash-loops
under Restart=on-failure with the real error scrolling past unread.

builtin.New now reports an unusable directory through IsAvailable and
Err rather than failing, so the caller decides. The daemon warns and
falls back to the location an unset work_dir would have produced, which
is where someone who copied a config from another host will look. If
that is unusable too it says what the operator loses -- no recollection
between conversations, and failing writes -- and carries on.

The provider stays readable while degraded, so a bad path reads as an
empty memory rather than breaking mid-conversation, and the dashboard's
memory page already renders IsAvailable so this is visible there.

Also fixes a defect the fallback test caught: an empty work_dir made
filepath.Join produce the relative path "memory", which MkdirAll
creates wherever the daemon was started from -- succeeding, and putting
memory somewhere nobody would look.

Refs archie-core-rml
This commit is contained in:
sam committed 2026-08-04 02:13:05 +10:00
1 parent 1ec5b507b3
commit 0d4d045050
6 files changed
+324 -39

No files matched your search

+68 -4
View File
@@ -571,10 +571,9 @@ func run() int {
// daemon work directory. External providers from config are added
// via RegisterExternal when cfg.Memory.Provider is set.
var memManager *memory.Manager
memDir := filepath.Join(cfg.WorkDir, "memory")
memProvider, err := builtin.New(builtin.Config{Dir: memDir})
if err != nil {
log.Error("memory provider init failed", "err", err)
memProvider, memDir := memoryProvider(cfg.WorkDir, log)
if memProvider == nil {
log.Error("memory provider init failed", "dir", memDir)
return 1
}
memManager, err = memory.NewManager(memProvider, nil)
@@ -938,6 +937,71 @@ func webTokenFor(listen, dbPath string, log *slog.Logger) string {
return tok
}
// memoryProvider builds the built-in memory provider, falling back to the
// default work directory when the configured one cannot be established.
//
// A bad path warns and degrades rather than stopping the daemon, in line with
// the forge and container paths: memory is one capability among many. The
// fallback is the location an unset work_dir would have produced, so an
// operator who copied a config from another host (a container path such as
// /var/lib/archie/work onto a laptop, say) lands somewhere predictable
// instead of somewhere only this function knows about.
//
// Returns the provider and the directory actually in use. A nil provider
// means the configuration is unusable in a way no fallback can fix.
func memoryProvider(workDir string, log *slog.Logger) (*builtin.Provider, string) {
// An empty workDir would make filepath.Join produce the relative path
// "memory", which MkdirAll creates in whatever directory the daemon
// happens to be started from -- succeeding, and putting memory somewhere
// nobody will look. Defaulting should have prevented an empty workDir;
// treat it as unset rather than trusting it.
var dir string
var p *builtin.Provider
if workDir == "" {
log.Warn("no work directory configured, using the default for memory")
} else {
dir = filepath.Join(workDir, "memory")
var err error
p, err = builtin.New(builtin.Config{Dir: dir})
if err != nil {
log.Warn("memory directory rejected, falling back to the default", "dir", dir, "err", err)
p = nil
}
if p != nil && p.IsAvailable() {
return p, dir
}
if p != nil {
log.Warn("memory directory unusable, falling back to the default",
"dir", dir, "err", p.Err())
}
}
fallback := filepath.Join(configuration.DefaultWorkDir(), "memory")
if fallback == dir {
// Already the default: there is nowhere else to try, so run degraded
// and say what that costs rather than pretending memory works.
log.Error("memory unavailable: the agent will start every conversation "+
"with no recollection of earlier ones, and memory writes will fail",
"dir", dir)
return p, dir
}
fb, err := builtin.New(builtin.Config{Dir: fallback})
if err != nil {
log.Error("memory provider init failed at the default directory", "dir", fallback, "err", err)
return p, dir
}
if !fb.IsAvailable() {
log.Error("memory unavailable: neither the configured nor the default "+
"directory is usable, so the agent will start every conversation "+
"with no recollection of earlier ones",
"configured", dir, "default", fallback, "err", fb.Err())
return fb, fallback
}
log.Warn("using the default memory directory", "dir", fallback)
return fb, fallback
}
// startContainers brings up the container pool and storage backend, returning
// nils when containers are disabled or unavailable.
//
+127
View File
@@ -0,0 +1,127 @@
package main
import (
"log/slog"
"os"
"path/filepath"
"strings"
"testing"
)
// TestMemoryProviderFallsBackInsteadOfFailing guards the same startup rule as
// TestResolveForgeDegradesInsteadOfFailing: a bad path must not take the
// daemon down. A config copied from another host (a container path such as
// /var/lib/archie/work onto a laptop) has to warn and land on the default,
// not exit 1 and crash-loop under Restart=on-failure.
func TestMemoryProviderFallsBackInsteadOfFailing(t *testing.T) {
tests := []struct {
name string
// workDir builds the configured work directory; the returned string
// is passed to memoryProvider.
workDir func(t *testing.T) string
// wantDefault says the result must be the default location rather
// than the configured one.
wantDefault bool
// wantAvailable says memory must end up actually usable.
wantAvailable bool
}{
{
name: "usable configured directory is kept",
workDir: func(t *testing.T) string { return t.TempDir() },
wantAvailable: true,
},
{
name: "missing configured directory is created",
workDir: func(t *testing.T) string {
return filepath.Join(t.TempDir(), "does", "not", "exist")
},
wantAvailable: true,
},
{
name: "unwritable configured directory falls back to the default",
workDir: func(t *testing.T) string {
ro := filepath.Join(t.TempDir(), "ro")
if err := os.Mkdir(ro, 0o500); err != nil {
t.Fatalf("mkdir: %v", err)
}
return filepath.Join(ro, "work")
},
wantDefault: true,
wantAvailable: true,
},
{
name: "empty work dir falls back to the default",
workDir: func(t *testing.T) string { return "" },
wantDefault: true,
wantAvailable: true,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
if tc.wantDefault && os.Geteuid() == 0 {
t.Skip("running as root: permission cases are not meaningful")
}
// Keep the default location inside the test's own tree so the
// fallback cannot write to the developer's real ~/.local/share.
dataHome := t.TempDir()
t.Setenv("XDG_DATA_HOME", dataHome)
wantDefaultDir := filepath.Join(dataHome, "archie", "work", "memory")
workDir := tc.workDir(t)
provider, dir := memoryProvider(workDir, slog.New(slog.DiscardHandler))
if provider == nil {
t.Fatal("memoryProvider returned nil: startup would exit 1 over a path problem")
}
if got := provider.IsAvailable(); got != tc.wantAvailable {
t.Fatalf("IsAvailable() = %v, want %v (dir %q, err %v)",
got, tc.wantAvailable, dir, provider.Err())
}
if tc.wantDefault {
if dir != wantDefaultDir {
t.Fatalf("dir = %q, want the default %q", dir, wantDefaultDir)
}
} else {
if want := filepath.Join(workDir, "memory"); dir != want {
t.Fatalf("dir = %q, want the configured %q", dir, want)
}
}
if tc.wantAvailable {
if info, err := os.Stat(dir); err != nil || !info.IsDir() {
t.Fatalf("reported available but %q is not a usable directory (err %v)", dir, err)
}
}
})
}
}
// The fallback is only worth anything if the operator can tell it happened
// and why -- a silent switch to a different directory looks like memory loss.
func TestMemoryProviderExplainsTheFallback(t *testing.T) {
if os.Geteuid() == 0 {
t.Skip("running as root: permission cases are not meaningful")
}
t.Setenv("XDG_DATA_HOME", t.TempDir())
ro := filepath.Join(t.TempDir(), "ro")
if err := os.Mkdir(ro, 0o500); err != nil {
t.Fatalf("mkdir: %v", err)
}
configured := filepath.Join(ro, "work")
var sb strings.Builder
log := slog.New(slog.NewTextHandler(&sb, &slog.HandlerOptions{Level: slog.LevelWarn}))
memoryProvider(configured, log)
out := sb.String()
if !strings.Contains(out, configured) {
t.Fatalf("log does not name the rejected directory %q: %s", configured, out)
}
if !strings.Contains(out, "default") {
t.Fatalf("log does not say a default was used: %s", out)
}
}
@@ -45,6 +45,15 @@ func (l *Loader) applyDefaults(cfg *config.Config) {
applyContainerDefaults(cfg)
}
// DefaultWorkDir returns the work directory an unset work_dir would have been
// given. Callers that must fall back when a configured path turns out to be
// unusable use this so the fallback is the same location the operator would
// have got by saying nothing, rather than a second guess that only this
// caller knows about.
func DefaultWorkDir() string {
return filepath.Join(xdgDataHome(), "archie", "work")
}
// applyGeneralDefaults derives the paths and limits that have no owning
// section.
func (l *Loader) applyGeneralDefaults(cfg *config.Config) {
+72 -24
View File
@@ -3,31 +3,38 @@ 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, long
// after startup reported success. New must settle the question up front.
// 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
wantErr bool
name string
dir func(t *testing.T) string
wantUsabl bool
}{
{
name: "existing directory",
dir: func(t *testing.T) string { return t.TempDir() },
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",
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 {
@@ -35,10 +42,9 @@ func TestNewEstablishesDir(t *testing.T) {
}
return filepath.Join(parent, "memory")
},
wantErr: true,
},
{
name: "path occupied by a file is reported",
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 {
@@ -46,36 +52,78 @@ func TestNewEstablishesDir(t *testing.T) {
}
return p
},
wantErr: true,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
// Running as root defeats permission-based cases.
if tc.wantErr && os.Geteuid() == 0 {
if !tc.wantUsabl && os.Geteuid() == 0 {
t.Skip("running as root: permission cases are not meaningful")
}
dir := tc.dir(t)
_, err := New(Config{Dir: dir})
if tc.wantErr {
if err == nil {
t.Fatalf("New(%q) = nil error, want a failure the operator can act on", dir)
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
}
if err != nil {
t.Fatalf("New(%q): %v", dir, err)
}
info, statErr := os.Stat(dir)
if statErr != nil {
t.Fatalf("New returned success but %q does not exist: %v", dir, statErr)
// 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 !info.IsDir() {
t.Fatalf("%q is not a directory", dir)
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")
}
}
+38 -11
View File
@@ -65,12 +65,28 @@ type Provider struct {
// 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.
@@ -79,22 +95,26 @@ func New(cfg Config) (*Provider, error) {
return nil, fmt.Errorf("builtin: Config.Dir must not be empty")
}
// Establish the directory up front. Both stores treat a missing file as
// an empty document, so without this a Dir that does not exist -- or one
// this process cannot write to -- is indistinguishable from a memory that
// simply has nothing in it yet: startup reports success and the failure
// surfaces at the agent's first memory write, mid-conversation.
var dirErr error
if err := os.MkdirAll(cfg.Dir, 0o755); err != nil {
return nil, fmt.Errorf("builtin: memory directory %s unusable: %w", cfg.Dir, err)
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 {
return nil, err
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 {
return nil, err
if dirErr == nil {
dirErr = err
}
userStore = emptyStore(filepath.Join(cfg.Dir, "USER.md"), cfg.MaxFileBytes)
}
// Frozen snapshot is enabled by default (DisableFrozenSnapshot defaults
@@ -105,15 +125,22 @@ func New(cfg Config) (*Provider, error) {
memory: memStore,
user: userStore,
frozenSnapshotEnabled: frozen,
dirErr: dirErr,
}, 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 }
// 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
+10
View File
@@ -77,6 +77,16 @@ 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 {