From 4877db85aea33b05261347c240c4053e4d5f9a37 Mon Sep 17 00:00:00 2001 From: sausheong Date: Sat, 9 May 2026 06:54:16 +0800 Subject: [PATCH] memory: add end-to-end integration tests + polish --- tool/memory/integration_test.go | 129 ++++++++++++++++++++++++++++++++ tool/memory/jsonl/store.go | 10 +++ tool/memory/tool.go | 9 ++- tool/memory/tool_test.go | 21 +++--- 4 files changed, 158 insertions(+), 11 deletions(-) create mode 100644 tool/memory/integration_test.go diff --git a/tool/memory/integration_test.go b/tool/memory/integration_test.go new file mode 100644 index 0000000..e0bfd55 --- /dev/null +++ b/tool/memory/integration_test.go @@ -0,0 +1,129 @@ +package memory_test + +// Separate _test package to verify the public surface wires together +// without internal fakes. + +import ( + "context" + "encoding/json" + "path/filepath" + "testing" + + "github.com/sausheong/harness/tool/memory" + "github.com/sausheong/harness/tool/memory/jsonl" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestEndToEnd_SaveListUpdateRemoveRoundTrip(t *testing.T) { + dir := t.TempDir() + store := jsonl.NewStore(filepath.Join(dir, "memory.jsonl")) + tool := &memory.MemoryTool{Store: store} + + // Save two entries. + for _, content := range []string{"first preference", "second preference"} { + in, _ := json.Marshal(map[string]any{ + "action": "save", + "content": content, + "tags": []string{"pref"}, + }) + res, err := tool.Execute(context.Background(), in) + require.NoError(t, err) + assert.Empty(t, res.Error) + } + + // List both back. + in, _ := json.Marshal(map[string]any{"action": "list"}) + res, err := tool.Execute(context.Background(), in) + require.NoError(t, err) + var entries []memory.Entry + require.NoError(t, json.Unmarshal([]byte(res.Output), &entries)) + require.Len(t, entries, 2) + + // Update the first. + firstID := entries[0].ID + in, _ = json.Marshal(map[string]any{ + "action": "update", + "id": firstID, + "content": "first preference (revised)", + }) + res, err = tool.Execute(context.Background(), in) + require.NoError(t, err) + var ar struct { + Success bool `json:"success"` + ID string `json:"id"` + } + require.NoError(t, json.Unmarshal([]byte(res.Output), &ar)) + assert.True(t, ar.Success) + newID := ar.ID + assert.NotEqual(t, firstID, newID) + + // Old id is gone via the provider adapter (the system-prompt path). + provider := store.AsMemoryProvider() + _, ok := provider.Get(firstID) + assert.False(t, ok, "old id must be unreachable through MemoryProvider") + body, ok := provider.Get(newID) + assert.True(t, ok) + assert.Equal(t, "first preference (revised)", body) + + // FormatIndex includes both live entries. + idx := provider.FormatIndex() + assert.Contains(t, idx, "first preference (revised)") + assert.Contains(t, idx, "second preference") + assert.NotContains(t, idx, "first preference\n", "old version must not appear") + + // Remove the second. + secondID := entries[1].ID + in, _ = json.Marshal(map[string]any{"action": "remove", "id": secondID}) + _, err = tool.Execute(context.Background(), in) + require.NoError(t, err) + + in, _ = json.Marshal(map[string]any{"action": "list"}) + res, err = tool.Execute(context.Background(), in) + require.NoError(t, err) + require.NoError(t, json.Unmarshal([]byte(res.Output), &entries)) + require.Len(t, entries, 1) + assert.Equal(t, "first preference (revised)", entries[0].Content) +} + +func TestEndToEnd_ProviderRoundTripAfterCompact(t *testing.T) { + // Save 5, remove 2, update 1, compact, verify state preserved. + dir := t.TempDir() + store := jsonl.NewStore(filepath.Join(dir, "memory.jsonl")) + memTool := &memory.MemoryTool{Store: store} + + ids := []string{} + for range 5 { + in, _ := json.Marshal(map[string]any{ + "action": "save", + "content": "entry", + }) + res, _ := memTool.Execute(context.Background(), in) + var ar struct { + ID string `json:"id"` + } + _ = json.Unmarshal([]byte(res.Output), &ar) + ids = append(ids, ar.ID) + } + + // Remove 2. + for _, id := range ids[:2] { + in, _ := json.Marshal(map[string]any{"action": "remove", "id": id}) + _, _ = memTool.Execute(context.Background(), in) + } + + // Update 1. + in, _ := json.Marshal(map[string]any{ + "action": "update", + "id": ids[2], + "content": "updated", + }) + _, _ = memTool.Execute(context.Background(), in) + + require.NoError(t, store.Compact(context.Background())) + + // State preserved post-compact. + all, err := store.List(context.Background(), "") + require.NoError(t, err) + require.Len(t, all, 3) +} diff --git a/tool/memory/jsonl/store.go b/tool/memory/jsonl/store.go index c866868..c62269d 100644 --- a/tool/memory/jsonl/store.go +++ b/tool/memory/jsonl/store.go @@ -34,6 +34,7 @@ import ( "encoding/json" "fmt" "os" + "path/filepath" "slices" "sort" "strings" @@ -337,6 +338,15 @@ func (s *Store) Compact(_ context.Context) error { os.Remove(tmp) return fmt.Errorf("rename: %w", err) } + // Fsync the parent directory so the rename is durable across crashes. + // On Linux, an unfsync'd directory metadata change can be rolled back + // after a power loss even though the rename(2) syscall succeeded. + // On Windows, opening a directory like this isn't supported; ignore + // the error there since flock is also a no-op. + if dir, err := os.Open(filepath.Dir(s.path)); err == nil { + _ = dir.Sync() + _ = dir.Close() + } return nil } diff --git a/tool/memory/tool.go b/tool/memory/tool.go index 0a2a551..1e76228 100644 --- a/tool/memory/tool.go +++ b/tool/memory/tool.go @@ -13,6 +13,13 @@ import ( // or write memory entries. Wraps any MemoryStore; the default JSONL // implementation is in tool/memory/jsonl/. // +// Five actions are dispatched on the "action" field: +// - save: create a new entry (id auto-generated when omitted) +// - update: replace an existing entry's content (assigns a fresh id) +// - remove: tombstone an entry (idempotent for unknown ids) +// - list: return all entries as a JSON array, optionally tag-filtered +// - get: return one entry as a JSON object by id +// // Schema is one tool with an "action" enum rather than five separate // tools, to keep the request prefix small (less schema bloat -> better // prompt-cache hits). @@ -25,7 +32,7 @@ func (t *MemoryTool) Name() string { return "memory" } // Description is shown to the model in the tool list. func (t *MemoryTool) Description() string { - return "Save, update, remove, or list memory entries — durable facts " + + return "Save, update, remove, list, or get memory entries — durable facts " + "and preferences that survive across sessions. Use to capture user " + "preferences, project context, or workflow conventions worth " + "remembering." diff --git a/tool/memory/tool_test.go b/tool/memory/tool_test.go index cacf1bf..b117105 100644 --- a/tool/memory/tool_test.go +++ b/tool/memory/tool_test.go @@ -3,6 +3,8 @@ package memory import ( "context" "encoding/json" + "fmt" + "slices" "testing" "time" @@ -17,9 +19,9 @@ func TestMemoryTool_NameDescriptionSchema(t *testing.T) { assert.NotEmpty(t, tool.Description()) var schema struct { - Type string `json:"type"` - Properties map[string]interface{} `json:"properties"` - Required []string `json:"required"` + Type string `json:"type"` + Properties map[string]any `json:"properties"` + Required []string `json:"required"` } require.NoError(t, json.Unmarshal(tool.Parameters(), &schema)) assert.Equal(t, "object", schema.Type) @@ -39,6 +41,7 @@ func TestMemoryTool_IsConcurrencySafeFalse(t *testing.T) { type fakeStore struct { entries []Entry failOn string // method name to fail on, e.g. "Save" + nextID int // auto-incremented for empty-id Save calls } func (f *fakeStore) Save(_ context.Context, e Entry) (Entry, error) { @@ -46,7 +49,8 @@ func (f *fakeStore) Save(_ context.Context, e Entry) (Entry, error) { return Entry{}, assertErr("save failed") } if e.ID == "" { - e.ID = "fake_id" + f.nextID++ + e.ID = fmt.Sprintf("fake_id_%d", f.nextID) } e.CreatedAt = time.Now() e.UpdatedAt = e.CreatedAt @@ -83,11 +87,8 @@ func (f *fakeStore) List(_ context.Context, tag string) ([]Entry, error) { } out := []Entry{} for _, e := range f.entries { - for _, t := range e.Tags { - if t == tag { - out = append(out, e) - break - } + if slices.Contains(e.Tags, tag) { + out = append(out, e) } } return out, nil @@ -118,7 +119,7 @@ func TestMemoryTool_SaveHappyPath(t *testing.T) { require.NoError(t, json.Unmarshal([]byte(res.Output), &ar)) assert.True(t, ar.Success) assert.Equal(t, "memory", ar.Target) - assert.Equal(t, "fake_id", ar.ID) + assert.Equal(t, "fake_id_1", ar.ID) assert.Contains(t, ar.Message, "user likes terse output") require.Len(t, store.entries, 1)