feat: add built-in per-repo memory tools #22
No reviewers
Labels
No labels
code-review
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
sam/brainless!22
Loading…
Reference in a new issue
No description provided.
Delete branch "feat/memory-tools"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Implements the ADK
memory.Serviceover a per-repo SQLite store, so the nativeload_memory/preload_memorytools and four curation tools (create_memory,add_observations,delete_memory,read_graph) share one store, modeled after the reference MCP memory server (https://github.com/modelcontextprotocol/servers/tree/main/src/memory).Design
google.golang.org/adk/v2/memory.Service; the two read tools are ADK's nativeloadmemorytool/preloadmemorytool, wired throughrunner.Config.MemoryService.defaultmemory. Entries from different repos never mix.memory.dbunder the state dir, WAL +_txlock=immediate): no whole-file rewrites, and two agents working the same repo serialize writes through SQLite's file locks.-ephemeralkeeps the store in memory only.gorm.G[T]) for reads; writes via plain chained calls (need RowsAffected for idempotency reporting).entity:<name>,obs:<name>:<hash>,rel:<from>:<to>:<type>) make creates idempotent by primary key (OnConflict DoNothing), matching the MCP reference dedupe semantics.AddSessionToMemoryrefuses, so memory never ingests whole conversations — only the small facts the model writes with the curation tools.load_memory,preload_memory,create_memory(entities?, relations?),add_observations,delete_memory(entities?, observations?, relations?),read_graph(names?).Files
internal/tools/memory.go— thememory.Serviceimplementation (store + graph ops + search)internal/tools/memory_tools.go— the four curation tools plus native tool registrationinternal/tools/memory_test.go— 15 tests: roundtrip, idempotency, endpoint validation, cascade delete, repo isolation, search scoping, ephemeral mode, concurrent createsinternal/harness/harness.go— runnerMemoryService, tool registration, always-visible set, tool-kind mappingsNotes
from/toare SQLite reserved words and are backtick-quoted in raw WHERE clauses.session/databaseowns session storage and uses the classic gorm API internally; that code is upstream and out of scope here.AI-driven review: feat: add built-in per-repo memory tools
Reviewed against the samber/cc-skills-golang skill set (code-style/naming/docs, error-handling/safety/concurrency, security/dependencies, testing/perf/observability/modernize). One 🔴 blocking correctness bug, three suggestions — inline comments below.
Verification performed in this session on a fresh clone of the PR head
315bca9(all API/dependency claims proven, not recalled):go build ./...— clean;go vet ./internal/tools/ ./internal/harness/— cleango test ./...— all PR tests pass;racedetector test ./internal/tools/— no data races;golangci-lint run ./internal/tools/ ./internal/harness/— 0 issues on PR codego doc google.golang.org/adk/v2/memory.Service— interface is exactly {AddSessionToMemory, SearchMemory};runner.Config.MemoryServiceexists and is wired into the invocation context (adk runner.go:677-679);loadmemorytool/preloadmemorytoolcallctx.SearchMemory— the harness wiring is correctpragma BUSY_TIMEOUT(5000)per connection and validates_txlock=immediate+_pragma=journal_mode(WAL)— the cross-process write-serialization claim holdsgo list -m -versions gorm.io/gorm— v1.31.2 is the latest release; the indirect→direct promotion is correct (gorm.G, gorm.DB, clause used directly); ADK in-memory search scoring (memory/inmemory.go) matches the mirroring claimgovulncheck ./internal/tools/— 0 reachable vulnerabilities; the 2 module-level findings (grpc GO-2026-6443, x/crypto openpgp GO-2026-5932) are pre-existing indirect deps untouched by this PRStrengths (not re-commented inline): consistently wrapped
%werrors; all SQL parameterized (no injection surface); deterministic IDs +OnConflict DoNothingidempotency is sound; WAL +_txlock=immediate+ driver busy-timeout make the two-agent claim real; 15 parallel tests pass under the race detector; README is thorough and accurate except the one observation claim flagged inline.@ -729,3 +751,3 @@return acp.ToolKindFetchcase strings.Contains(lower, "read"), strings.Contains(lower, "get"), strings.Contains(lower, "list"),strings.Contains(lower, "inspect"), strings.Contains(lower, "capture"):strings.Contains(lower, "inspect"), strings.Contains(lower, "capture"), strings.Contains(lower, "load"):🟡 SUGGESTION — substring matching on "load" and "add" misclassifies unrelated MCP tools. Every connected tool whose name contains "load" (e.g.
upload_file,download_file,reload_config,payload_*) is now classifiedToolKindRead, and any containing "add" (e.g.address_lookup,addon_*) becomesToolKindEdit; before this PR those names fell through to the default"". The memory feature only needs two names. Fix: match the memory tools exactly (name == "load_memory" || name == "preload_memory", andname == "add_observations") before the substring cases, or use word-boundary matching.@ -0,0 +606,4 @@// the requested set stay discoverable.func (m *Memory) openNodes(ctx context.Context, repo string, names []string) (graphResult, error) {entries, err := gorm.G[memoryEntry](m.db).Where("repo = ? AND (kind = ? AND entity_name IN ? OR kind = ? AND (`from` IN ? OR `to` IN ?))",🔴 BLOCKING —
read_graph(names)silently drops every observation. The WHERE clause selects only entity rows (kind = 'entity') and relation rows (kind = 'relation'); observation rows (kind = 'observation') are never fetched, sogroupGraphreturns the named entities with emptyobservations. Reproduced with a scratch test in this session:go test ./internal/tools/ -run TestReviewOpenNodesObservationsfails withopenNodes observations for alice: [] (len=0)while alice has 2 stored observations. This contradicts the README and the tool description ("with names, those entities with their observations plus every relation touching either of them").TestMemoryOpenNodespasses only because it never asserts observations. Fix: add the observation rows to the predicate, e.g.Where("repo = ? AND ((kind = ? AND entity_name IN ?) OR (kind = ? AND entity_name IN ?) OR (kind = ? AND (fromIN ? ORtoIN ?)))", repo, kindEntity, names, kindObservation, names, kindRelation, names, names).@ -0,0 +704,4 @@// observationContent is the display text of one observation: the owning// entity's name followed by the observation, so load_memory results show which// entity each fact belongs to.func observationContent(entityName, observation string) string {🟡 SUGGESTION — searching an entity name never surfaces its observations.
observationContentstores"alice: likes coffee", so tokenizing (entryMatches) yieldsalice:(with colon) and the whole-token ASCII matchalice:!=alicenever hits. Reproduced:go test ./internal/tools/ -run TestReviewSearchFindsObservations— hits for query "alice" are only["Entity alice (type person)"]; the observation rows never match, soload_memory/preload_memoryunder-recall exactly the curated facts this feature exists to surface. NoteTestMemorySearch's "want 2" assertion codifies the gap (entity + relation match, observation skipped). Fix options: store observation content without the"<name>: "prefix (the owning entity is already in theentity_namecolumn and metadata), or strip the prefix before tokenizing, or treat the first token"<name>":as the name.@ -0,0 +309,4 @@return toolResult{Output: "Nothing deleted: nothing matched."}, nil}out := "Deleted " + strings.Join(parts, ", ") + "."🟡 SUGGESTION — malformed output when nothing is deleted. When every requested entity is missing,
partsis empty andstrings.Join(parts, ", ")yields "", so the tool answersDeleted . (entities not found: ghost)(space-dot). Reproduced:go test ./internal/tools/ -run TestReviewDeleteNothingOutput→output: "Deleted . (entities not found: ghost)". Fix: only emit the"Deleted ..."sentence whenlen(parts) > 0; otherwise return the notes alone.All four review findings resolved in
dc2ab6a. Verification: full suite + golangci-lint 0 issues; the fixes are covered by updated/extended tests.openNodesnow includes observation rows (kind = 'observation' AND entity_name IN ?) in the WHERE predicate, soread_graph(names)returns the named entities with their observations.TestMemoryOpenNodesnow asserts alice's observations come through.entryMatchesnow matches an observation row when the query word equals the owning entity's name, soload_memory/preload_memoryfind the curated facts by entity despite the<name>:display prefix.TestMemorySearchnow expects all 3 alice entries (entity, observation, relation).TestMemoryDeleteNothingOutputasserts(entities not found: ghost).toolKindmatchesload_memory/preload_memory/add_observationsexactly in the built-in switch; the"load"/"add"substrings were removed.TestToolKindnow pinsupload_file,download_file,reload_config,payload_status,address_lookup,addon_installto"".