Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

fix(memory): paginate matching candidates and evaluations (#961)

Divyam Talwarae2fe5682830
diff --git a/cli/beacon/internal/learning/store.go b/cli/beacon/internal/learning/store.go
index 9faf1a9a..f8c634a4 100644
--- a/cli/beacon/internal/learning/store.go
+++ b/cli/beacon/internal/learning/store.go
@@ -448,32 +448,10 @@ func (s *Store) ListEvaluations(query Query) ([]asymptoteobserve.LearningEvaluat
if err != nil {
return nil, err
}
- db, err := s.db()
- if err != nil {
- return nil, err
- }
- defer db.Close()
where, args := queryWhere(query, "project_id", "status", "")
- rows, err := db.Query(`SELECT evaluation_json FROM evaluations`+where+` ORDER BY updated_at DESC LIMIT ? OFFSET ?`, append(args, normalizeLimit(query.Limit), offset(query))...)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
- var out []asymptoteobserve.LearningEvaluationV1
- for rows.Next() {
- var raw string
- if err := rows.Scan(&raw); err != nil {
- return nil, err
- }
- var value asymptoteobserve.LearningEvaluationV1
- if err := json.Unmarshal([]byte(raw), &value); err != nil {
- return nil, err
- }
- if query.Q == "" || matchesText(query.Q, value.ID, value.Trace.ID, value.Trace.Title, value.Evaluator, value.Status) {
- out = append(out, value)
- }
- }
- return out, rows.Err()
+ return listJSON(s, query, `SELECT evaluation_json FROM evaluations`+where, args, func(e asymptoteobserve.LearningEvaluationV1) []string {
+ return []string{e.ID, e.Trace.ID, e.Trace.Title, e.Evaluator, e.Status}
+ })
}
func (s *Store) GetEvaluation(id string) (asymptoteobserve.LearningEvaluationV1, bool, error) {
@@ -522,32 +500,10 @@ func (s *Store) ListCandidates(query Query) ([]asymptoteobserve.LearningCandidat
if err != nil {
return nil, err
}
- db, err := s.db()
- if err != nil {
- return nil, err
- }
- defer db.Close()
where, args := queryWhere(query, "project_id", "state", "kind")
- rows, err := db.Query(`SELECT candidate_json FROM candidates`+where+` ORDER BY updated_at DESC LIMIT ? OFFSET ?`, append(args, normalizeLimit(query.Limit), offset(query))...)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
- var out []asymptoteobserve.LearningCandidateV1
- for rows.Next() {
- var raw string
- if err := rows.Scan(&raw); err != nil {
- return nil, err
- }
- var value asymptoteobserve.LearningCandidateV1
- if err := json.Unmarshal([]byte(raw), &value); err != nil {
- return nil, err
- }
- if query.Q == "" || matchesText(query.Q, value.ID, value.Title, value.Body, value.Kind, value.State) {
- out = append(out, value)
- }
- }
- return out, rows.Err()
+ return listJSON(s, query, `SELECT candidate_json FROM candidates`+where, args, func(c asymptoteobserve.LearningCandidateV1) []string {
+ return []string{c.ID, c.Title, c.Body, c.Kind, c.State}
+ })
}
func (s *Store) GetCandidate(id string) (asymptoteobserve.LearningCandidateV1, bool, error) {
@@ -593,55 +549,61 @@ func (s *Store) ListMemories(query Query) ([]asymptoteobserve.LearningMemoryV1,
if err != nil {
return nil, err
}
- db, err := s.db()
- if err != nil {
- return nil, err
- }
- defer db.Close()
where, args := queryWhere(query, "project_id", "", "kind")
if where == "" {
where = ` WHERE (superseded_by IS NULL OR superseded_by = '')`
} else {
where += ` AND (superseded_by IS NULL OR superseded_by = '')`
}
- hasTextFilter := strings.TrimSpace(query.Q) != ""
- sqlQuery := `SELECT memory_json FROM memories` + where + ` ORDER BY updated_at DESC`
- if !hasTextFilter {
- args = append(args, normalizeLimit(query.Limit), offset(query))
- sqlQuery += ` LIMIT ? OFFSET ?`
+ return listJSON(s, query, `SELECT memory_json FROM memories`+where, args, func(m asymptoteobserve.LearningMemoryV1) []string {
+ return []string{m.ID, m.Title, m.Body, m.Kind}
+ })
+}
+
+// listJSON runs selectSQL, a SELECT of one JSON column, newest first, and returns the requested
+// page of decoded records. A text query is matched against text(record) after decoding, so the page
+// counts matching records: paging in SQL would count rows the query then drops, returning empty or
+// shifted pages whenever newer non-matching records fill the SQL page.
+func listJSON[T any](s *Store, query Query, selectSQL string, args []interface{}, text func(T) []string) ([]T, error) {
+ db, err := s.db()
+ if err != nil {
+ return nil, err
}
- rows, err := db.Query(sqlQuery, args...)
+ defer db.Close()
+ limit, skip := normalizeLimit(query.Limit), offset(query)
+ filter := strings.TrimSpace(query.Q) != ""
+ selectSQL += ` ORDER BY updated_at DESC`
+ if !filter {
+ selectSQL += ` LIMIT ? OFFSET ?`
+ args = append(args, limit, skip)
+ }
+ rows, err := db.Query(selectSQL, args...)
if err != nil {
return nil, err
}
defer rows.Close()
- limit := normalizeLimit(query.Limit)
- skip := offset(query)
- matches := 0
- var out []asymptoteobserve.LearningMemoryV1
+ var out []T
+ matched := 0
for rows.Next() {
var raw string
if err := rows.Scan(&raw); err != nil {
return nil, err
}
- var value asymptoteobserve.LearningMemoryV1
+ var value T
if err := json.Unmarshal([]byte(raw), &value); err != nil {
return nil, err
}
- if hasTextFilter {
- if !matchesText(query.Q, value.ID, value.Title, value.Body, value.Kind) {
+ if filter {
+ if !matchesText(query.Q, text(value)...) {
continue
}
- matches++
- if matches <= skip {
+ if matched++; matched <= skip {
continue
}
- out = append(out, value)
- if len(out) >= limit {
- break
- }
- } else {
- out = append(out, value)
+ }
+ out = append(out, value)
+ if filter && len(out) >= limit {
+ break
}
}
if err := rows.Err(); err != nil {
diff --git a/cli/beacon/internal/learning/store_search_test.go b/cli/beacon/internal/learning/store_search_test.go
new file mode 100644
index 00000000..bbc3a4b4
--- /dev/null
+++ b/cli/beacon/internal/learning/store_search_test.go
@@ -0,0 +1,138 @@
+package learning
+
+import (
+ "fmt"
+ "path/filepath"
+ "slices"
+ "testing"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+)
+
+func TestLearningSearchPaginatesMatchingRows(t *testing.T) {
+ store := Open(filepath.Join(t.TempDir(), "memory.db"))
+ rows := []struct {
+ id, title, project, candidateState, evaluationState, kind string
+ }{
+ {"foreign", "Needle recovery", "other-project", "candidate", "completed", "workflow"},
+ {"wrong-state", "Needle recovery", "project", "rejected", "failed", "workflow"},
+ {"wrong-kind", "Needle recovery", "project", "candidate", "failed", "convention"},
+ {"nonmatch-a", "Ordinary task", "project", "candidate", "completed", "workflow"},
+ {"match-a", "Needle recovery", "project", "candidate", "completed", "workflow"},
+ {"nonmatch-b", "Needle without the other term", "project", "candidate", "completed", "workflow"},
+ {"match-b", "Older needle recovery", "project", "candidate", "completed", "workflow"},
+ }
+ for i, row := range rows {
+ putLearningSearchRow(t, store, row.id, row.title, row.project, row.candidateState, row.evaluationState, row.kind, len(rows)-i)
+ }
+
+ for _, collection := range learningSearchCollections(store) {
+ t.Run(collection.name, func(t *testing.T) {
+ for _, tc := range []struct {
+ name, query string
+ limit, page int
+ want []string
+ }{
+ {"first match page", "NEEDLE recovery", 1, 1, []string{"match-a"}},
+ {"second match page", "NEEDLE recovery", 1, 2, []string{"match-b"}},
+ {"beyond last match page", "needle recovery", 1, 3, nil},
+ {"both matches", "needle recovery", 2, 1, []string{"match-a", "match-b"}},
+ {"default limit", "needle recovery", 0, 1, []string{"match-a", "match-b"}},
+ {"negative page", "needle recovery", 1, -1, []string{"match-a"}},
+ {"zero page", "needle recovery", 1, 0, []string{"match-a"}},
+ {"no matches", "absent", 1, 1, nil},
+ {"empty query", "", 1, 2, []string{"match-a"}},
+ {"whitespace query", " \t\n ", 1, 2, []string{"match-a"}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ query := collection.query
+ query.Q, query.Limit, query.Page = tc.query, tc.limit, tc.page
+ got, err := collection.list(query)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(got, tc.want) {
+ t.Fatalf("IDs = %v, want %v", got, tc.want)
+ }
+ })
+ }
+ })
+ }
+}
+
+func TestLearningSearchFindsMatchesBeyondDefaultPage(t *testing.T) {
+ store := Open(filepath.Join(t.TempDir(), "memory.db"))
+ putLearningSearchRow(t, store, "match", "Needle recovery", "project", "candidate", "completed", "workflow", 0)
+ for i := 1; i <= 51; i++ {
+ putLearningSearchRow(t, store, fmt.Sprintf("unrelated-%d", i), "Ordinary task", "project", "candidate", "completed", "workflow", i)
+ }
+ for _, collection := range learningSearchCollections(store) {
+ t.Run(collection.name, func(t *testing.T) {
+ query := collection.query
+ query.Q = "needle"
+ got, err := collection.list(query)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(got, []string{"match"}) {
+ t.Fatalf("IDs = %v, want the match beyond the default raw page", got)
+ }
+ })
+ }
+}
+
+func putLearningSearchRow(t *testing.T, store *Store, id, title, project, candidateState, evaluationState, kind string, order int) {
+ t.Helper()
+ if err := store.PutCandidate(asymptoteobserve.LearningCandidateV1{
+ ID: id, Title: title, Project: asymptoteobserve.LearningProjectV1{ID: project}, State: candidateState, Kind: kind,
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if err := store.PutEvaluation(asymptoteobserve.LearningEvaluationV1{
+ ID: id, Project: asymptoteobserve.LearningProjectV1{ID: project}, Status: evaluationState,
+ Trace: asymptoteobserve.LearningTraceRefV1{ID: id, Title: title}, RubricHash: "rubric",
+ }); err != nil {
+ t.Fatal(err)
+ }
+ db, err := store.db()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ at := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC).Add(time.Duration(order) * time.Second).Format(time.RFC3339)
+ for _, stmt := range []string{`UPDATE candidates SET updated_at = ? WHERE id = ?`, `UPDATE evaluations SET updated_at = ? WHERE id = ?`} {
+ if _, err := db.Exec(stmt, at, id); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+func learningSearchCollections(store *Store) []struct {
+ name string
+ query Query
+ list func(Query) ([]string, error)
+} {
+ return []struct {
+ name string
+ query Query
+ list func(Query) ([]string, error)
+ }{
+ {"candidates", Query{ProjectID: "project", State: "candidate", Kind: "workflow"}, func(query Query) ([]string, error) {
+ values, err := store.ListCandidates(query)
+ var ids []string
+ for _, value := range values {
+ ids = append(ids, value.ID)
+ }
+ return ids, err
+ }},
+ {"evaluations", Query{ProjectID: "project", State: "completed"}, func(query Query) ([]string, error) {
+ values, err := store.ListEvaluations(query)
+ var ids []string
+ for _, value := range values {
+ ids = append(ids, value.ID)
+ }
+ return ids, err
+ }},
+ }
+}
diff --git a/docs/changelog/cli.mdx b/docs/changelog/cli.mdx
index 116b2911..cc0baed4 100644
--- a/docs/changelog/cli.mdx
+++ b/docs/changelog/cli.mdx
@@ -21,6 +21,7 @@ Stay up to date with the latest changes to the Agent Beacon CLI.
- **Hermes sync keeps profiles apart** · Every Hermes home shared one sync cursor, so syncing a second profile or a custom `HERMES_HOME` on the same host could skip sessions the first sync had already passed. Each home now has its own cursor, and synced events record the home in `harness.config_path` and the profile in the new `harness.profile` field. The native `~/.hermes` root keeps its existing cursor, and the home a default sync resolves to (through `HERMES_HOME` or a sticky profile) starts its keyed cursor from the one it had been advancing, so neither re-emits history; any other home collects its retained history once more on its first sync.
- **Failed Grok writes are recorded as failures** · When a Grok `write_file` or edit failed, the hook recorded it as a completed `file.modified` with a diff built from content that was never written, and the threat scan read that content as a change. The failed attempt is now a high-severity `tool.failed` with its tool, path and call ID and no diff. Successful writes are unchanged.
- **Vector forwarding configs work with Windows log paths** · Beacon wrote log paths into the Vector configs for Beacon Cloud and the SIEM packs without escaping them, so on Windows a path's backslashes made `vector.toml` fail to parse, or quietly point Vector at a different file. Paths are now escaped and Vector reads exactly the configured runtime, inventory and backfill logs.
+- **Memory candidate and evaluation search finds older matches** · `beacon memory candidates list` and `beacon memory evaluations list` with `--query` paged before matching, so a page could come back empty or skip matches whenever newer records that didn't match filled it. Searches now page over matching records, as `beacon memory list` already did.
- **Dashboard output tokens count reasoning once** · The local dashboard's token view added reasoning tokens to output, but `gen_ai.usage.output_tokens` already includes them, so models that report reasoning had their output and total tokens overstated. Output and the total now count reasoning once, the split bar no longer shows reasoning as a separate segment, and a note below it gives the reasoning count included in output. `beacon token-usage` already counted it this way.
---