Skip to content

fix(memory): scope every trace query to its brain - #530

Merged
jddunn merged 3 commits into
masterfrom
fix/memory-brain-scope
Oct 16, 2026
Merged

jddunn merged 3 commits into
masterfrom
fix/memory-brain-scope

Conversation

@jddunn

@jddunn jddunn commented Oct 16, 2026 •

Copy link
Copy Markdown
Member

Summary

Several brains can share one database: every row carries its brain's id, and Memory.createPostgres() documents brainId as the multi-tenant scope of every query. The Memory facade wrote and deleted by brain, but these reads did not filter brain_id:

  • _findExistingTraceByHash, the dedup on remember(), matched content_hash or import_hash across every brain.
  • recall(): the conditions of both full-text paths and of the LIKE fallback (no FTS5), and the fetch of the hybrid path's top candidates by id.
  • The HNSW sidecar: the count behind the 1,000-trace threshold, both rebuilds (in remember() and after an import), and the index file itself, brain.hnsw in the database's directory: one file for every brain in the file and every database in the directory, loaded by any brain that opened after another brain wrote it.
  • health(): every count (traces, active traces, strength, per type, per scope, documents, graph nodes and edges, last consolidation).
  • MarkdownExporter (the markdown and obsidian formats of export()): the trace query.
  • MemoryAddTool: its full-text sync finds the row it just wrote by id alone, and its ids, mt_<ms>_<counter>, are unique only within one process.

Effect: with a shared database, a brain's remember() could return another brain's trace (its content and id) and never write its own; its recall() could return another brain's memories; its vector index could hold and serve other brains' vectors; health() counted every brain; a Markdown or Obsidian export wrote every brain's traces; and two processes serving two brains could give two memory_add traces one id, indexing one brain's text under the other brain's row.

What changed, per query:

  • _findExistingTraceByHash: brain_id = ? first.
  • recall(): t.brain_id = ? leads the conditions of both full-text queries and of the LIKE fallback, and the top-candidate fetch reads t.brain_id = ? AND t.deleted = 0 AND t.id IN (...). The match clause now comes first in the full-text queries: Postgres's rank expression reads the query text as $1, the statement's first parameter, so a condition before the match would have ranked against the brain id (with a type or scope filter it already ranked against the filter's value). The LIKE fallback binds its parameters in the order their placeholders appear (its select-list score comes before the conditions); before, any filter value was bound to a LIKE.
  • HNSW: one helper reads the brain's own embedded traces for both rebuilds; the threshold counts the brain's live traces; the embedding read after a store is by brain_id and id. HnswSidecar takes an optional brainId; with it the index file is <database file name>.<digest>.hnsw beside the database, the digest a SHA-256 of the file name and the brain id, so brains and databases in one directory never share an index. Without it the file stays brain.hnsw.
  • health(): every count is of the brain's rows, read through Number() (Postgres returns COUNT(*) as a bigint string, and ran_at too).
  • MarkdownExporter: brain_id = ? AND deleted = 0; ObsidianExporter inherits it.
  • MemoryAddTool: ids are mt_ and a v4 UUID, as the facade, CognitiveMemoryManager and every importer already name traces, so the sync's lookup by id reaches only the row the same transaction wrote.

Stays as it was, with the reason:

  • The full-text sync after an insert (syncInsert with (SELECT rowid FROM memory_traces WHERE id = ?)), in remember(), ingest() and memory_add: the id is a v4 UUID made in the same call and written by the brain-scoped insert just before, and on Postgres the adapter's syncInsert binds $1 as the id, so a brain-scoped row expression cannot pass through it (MemoryStore skips Postgres for the same reason).
  • Brain._repairFullTextIndex counts every row of the file: it checks the file-wide FTS5 index against its content table.

Seen, not changed here:

  • The sqlite export runs VACUUM INTO, a copy of the whole file with every brain in it, as docs/memory/MEMORY_STORAGE.md documents; Brain.exportToSqlite() is the per-brain copy.
  • ObsidianExporter._prefetchRelatedNodes joins knowledge_edges and knowledge_nodes without brain_id (knowledge tables, used for wikilinks).
  • On Postgres, the full-text rebuild that follows an import (and memory_update, memory_merge, consolidation) runs the adapter's rebuild, an UPDATE of every brain's _tsv; each row's vector comes from its own content, so nothing crosses brains, but the cost is the whole table's.
  • The hybrid path applies the type, scope, scopeId, minStrength, after and before filters to the full-text candidates only; the vector candidates are fetched by brain and deleted only.
  • SqliteImporter copies every brain of the source file into the importing brain.

Linked issues

None.

Type of change

  • Bug fix
  • Feature
  • Performance
  • Documentation
  • Refactor
  • Tests
  • Build or CI

How this was verified

CI only. src/cognition/memory/io/facade/__tests__/Memory.brain-scope.test.ts opens two Memory instances with different brain ids on one SQLite file through @framers/sql-storage-adapter and, with AGENTOS_TEST_POSTGRES_URL (set by the Test & Lint job), on one Postgres database:

  • the same text stored in both brains is two traces, one in each, and still one trace inside a brain;
  • recall by text in one brain never returns the other's trace (Postgres and SQLite, with and without the FTS5 table, with a type filter);
  • health() counts the brain's own rows;
  • with the HNSW index active, recall by meaning never returns the other brain's trace, an import builds the index from the brain's own vectors, the threshold counts the brain's own traces, and the store that brings a brain to 1,000 traces indexes that brain's 1,000 vectors;
  • a brain opened after another brain wrote its index does not load it;
  • a Markdown export writes the brain's own traces.

hnswlib-node's native build does not run in CI, so the test replaces its index with an exact nearest-neighbour index with the same methods, written to the index file as JSON; Memory, HnswSidecar, HnswIndexSidecar and the database are the real code. tools.test.ts pins the memory_add id to mt_ and a v4 UUID.

The test went in first as its own commit: run 38904519073, Test & Lint red on its 11 tests (8 SQLite, 3 Postgres), every other test file green. The fix (f8bf790): run 38962692936, every check green, the 11 tests and tools.test.ts among 960 passing test files.

Migration notes

None required. An index file written before this change (brain.hnsw) is not read, since it can hold other brains' vectors; each brain's index is built again from its own traces at its next store with an embedding once it holds 1,000 traces, or at its next import. The old brain.hnsw and brain.hnsw.map.json can be deleted. Traces stored through memory_add from now on have ids of the form mt_<uuid>; ids stored earlier keep theirs.

Checklist

  • Tests cover the changed behavior.
  • Docs are updated.
  • The title follows Conventional Commits, with ! before the colon for a change that breaks users (feat!: or feat(api)!:).
  • No secrets or private data are included.
  • Every automated review thread is settled (how).
  • I have read this change and can explain every line.

🤖 Generated with Claude Code

Summary by Sourcery

Enforce brain isolation across memory queries, vector indexes, exports, metrics, and tool-generated trace identifiers.

Bug Fixes:

  • Scope memory deduplication, recall, health metrics, and Markdown/Obsidian exports to the active brain in shared SQLite and Postgres databases.
  • Prevent HNSW indexes from mixing brains by rebuilding from brain-local embeddings, counting brain-local traces, and using per-database, per-brain index files.
  • Generate process-independent UUID-based memory tool trace IDs to avoid cross-brain collisions.

Enhancements:

  • Correct full-text and LIKE fallback parameter ordering so searches and ranking use the intended query values across supported backends.

Documentation:

  • Document brain-scoped health and Markdown exports, whole-database SQLite exports, and the new per-brain HNSW index naming and behavior.

Tests:

  • Add SQLite and Postgres coverage for brain isolation across deduplication, text and vector recall, health reporting, HNSW behavior, and Markdown exports.
  • Update memory tool tests for UUID-based trace identifiers.

…ort only their own traces

Opens two Memory instances with different brain ids on one SQLite file and,
when AGENTOS_TEST_POSTGRES_URL is set, on one Postgres database: the same
text stored in both brains, recall by text with and without the full-text
index, recall by meaning with the HNSW index active, the index rebuild and
its 1,000-trace threshold, a brain opened after another brain wrote its
index, health() and a Markdown export.
@coderabbitai

coderabbitai Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

  • Run on-demand review

This review includes 11 billable files and costs up to $2.75.

  • Ask an admin to make reviews automatic

Open in CodeRabbit

Reviews can continue after your included limit without a manual trigger. An admin must approve usage-based billing.

Or wait 41 minutes for your next included review.

Check out review usage here.

View limit details

Limit details: You’ve used all 4 included reviews currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration
  • Configuration used: Repository: framerslab/agentos/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Team
  • Run ID: 5eb392ef-7346-4cb5-a234-52d835c676f3
📥 Commits

Reviewing files that changed from the base of the PR and between cf74121 and 8842e33.

📒 Files selected for processing: 11
  • docs/MEMORY_OPERATIONS.md
  • docs/getting-started/SQL_STORAGE_QUICKSTART.md
  • docs/memory/MEMORY_STORAGE.md
  • src/cognition/memory/io/MarkdownExporter.ts
  • src/cognition/memory/io/facade/Memory.ts
  • src/cognition/memory/io/facade/__tests__/Memory.brain-scope.test.ts
  • src/cognition/memory/io/tools/MemoryAddTool.ts
  • src/cognition/memory/io/tools/MemoryDeleteTool.ts
  • src/cognition/memory/io/tools/MemoryUpdateTool.ts
  • src/cognition/memory/io/tools/__tests__/tools.test.ts
  • src/cognition/memory/retrieval/store/HnswSidecar.ts
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

@sourcery-ai

sourcery-ai Bot commented Oct 16, 2026

Copy link
Copy Markdown

Reviewer's Guide

This fix enforces brain-level tenancy across Memory's read paths and exports, and isolates HNSW sidecar files and rebuild inputs per brain and database. Comprehensive SQLite and Postgres regression tests verify that deduplication, lexical/vector recall, health reporting, indexing, and Markdown export never cross brain boundaries.

File-Level Changes

Change Details Files
Scopes all trace reads, deduplication, search paths, health metrics, and Markdown exports to the active brain.
  • Adds brain_id predicates to hash deduplication and full-text, LIKE, and hybrid candidate queries.
  • Corrects SQLite/Postgres parameter ordering for ranking and LIKE fallback placeholders.
  • Scopes health counts across traces, documents, graph data, and consolidation metadata, including bigint conversion.
  • Restricts Markdown and Obsidian trace exports to non-deleted rows belonging to the brain.
src/cognition/memory/io/facade/Memory.ts
src/cognition/memory/io/export/MarkdownExporter.ts
Makes HNSW vector indexes tenant-isolated and rebuilds them from only the owning brain's live traces.
  • Scopes threshold counts, post-store index reads, and rebuild inputs by brain_id.
  • Adds an optional brain identifier to sidecar naming, using a SHA-256-derived filename beside the database to prevent cross-database and cross-brain collisions.
  • Preserves the legacy brain.hnsw path only when no brain identifier is supplied.
src/cognition/memory/io/facade/Memory.ts
src/cognition/memory/io/hnsw/HnswSidecar.ts
src/cognition/memory/io/hnsw/HnswIndexSidecar.ts
Adds cross-backend regression coverage for multi-brain storage isolation.
  • Tests deduplication, lexical recall with FTS and LIKE fallback, filtered recall, health metrics, vector recall, import and 1,000-trace index thresholds, index-file isolation, and Markdown export.
  • Runs the suite against shared SQLite and optionally shared Postgres databases.
  • Mocks hnswlib-node with a file-backed exact nearest-neighbor implementation so sidecar behavior is tested without the native addon.
src/cognition/memory/io/facade/__tests__/Memory.brain-scope.test.ts

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Several brains can share one database, and every row carries its brain's id,
but these reads of the Memory facade did not filter brain_id:

- the content-hash dedup in remember(), so a store in one brain could return
  another brain's trace and never write its own;
- recall(): both full-text queries, the LIKE fallback and the fetch of the
  hybrid path's top candidates by id;
- the HNSW sidecar: the 1,000-trace threshold count, both rebuilds and the
  index file, brain.hnsw, shared by every brain and database in a directory;
- health(), and the Markdown and Obsidian exports.

Each now reads the brain's rows only. The sidecar keeps one index file per
database file and brain. The full-text queries put the match first, since
Postgres's rank reads the query text as $1, and the LIKE fallback binds its
parameters in the order of its placeholders. health() returns numbers on
Postgres, where COUNT(*) comes back as a string.

The memory_add tool names its traces with v4 UUIDs, as the facade and the
importers do: its full-text sync finds the new row by id, and an id unique
only within one process could name another brain's row.
@jddunn
jddunn marked this pull request as ready for review October 16, 2026 20:36
@jddunn
jddunn requested a review from Victor-Evogor as a code owner October 16, 2026 20:36
@sourcery-ai

sourcery-ai Bot commented Oct 16, 2026

Copy link
Copy Markdown

Sorry @jddunn, you've used your own review budget of 250,000 diff characters for the last 7 days.

You can request another review in 1 day and 6 hours by commenting @sourcery-ai review. Upgrade to get a review now.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-16T20:39:03.992024Z f8bf790 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Summary by Qodo

Scope memory reads and vector indexes to each brain

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Scope deduplication, recall, health reports, and Markdown exports to the current brain.
• Isolate HNSW indexes by database and brain; use cross-process-unique memory-add IDs.
• Add shared-database regression tests and document the changed behavior.
Diagram

graph TD
  B["Brain ID"] --> M["Memory facade"] --> D[("Shared database")]
  M --> S["HNSW sidecar"] --> I["Scoped index file"]
  M --> E["Markdown exporter"] --> D
  T["Memory add tool"] --> D
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Enforce brain scope in the storage layer
  • ➕ Could prevent future unscoped queries across all callers.
  • ➖ Requires a broader storage API change and careful handling of file-wide operations such as FTS repair and SQLite export.

Recommendation: The targeted query fixes and per-brain index files are the safer choice for this bug fix. A scoped storage API is worth considering separately to reduce the risk of future omissions.

Files changed (11) +573 / -139

Bug fix (4) +180 / -124
MarkdownExporter.tsRestrict Markdown exports to the current brain +8/-4

Restrict Markdown exports to the current brain

• Filters the live-trace export query by brain ID, also protecting the inheriting Obsidian exporter.

src/cognition/memory/io/MarkdownExporter.ts

Memory.tsScope memory queries and HNSW rebuilds by brain +130/-104

Scope memory queries and HNSW rebuilds by brain

• Adds brain filters to deduplication, all recall paths, embedding reads, index thresholds and rebuilds, and health aggregates. Corrects full-text and LIKE parameter ordering and passes the brain ID to the HNSW sidecar.

src/cognition/memory/io/facade/Memory.ts

MemoryAddTool.tsGenerate cross-process-unique memory-add IDs +7/-11

Generate cross-process-unique memory-add IDs

• Replaces timestamp-and-counter IDs with 'mt_'-prefixed v4 UUIDs so an ID-only full-text sync cannot collide with another process's trace.

src/cognition/memory/io/tools/MemoryAddTool.ts

HnswSidecar.tsPersist HNSW indexes per database and brain +35/-5

Persist HNSW indexes per database and brain

• Adds an optional brain ID and derives a distinct index filename from the database filename and a SHA-256 digest. Callers without a brain ID retain the legacy 'brain.hnsw' path.

src/cognition/memory/retrieval/store/HnswSidecar.ts

Tests (2) +377 / -1
Memory.brain-scope.test.tsExercise two brains sharing a database +375/-0

Exercise two brains sharing a database

• Adds SQLite and conditional Postgres coverage for deduplication, recall, and health isolation, plus SQLite coverage for the LIKE fallback, HNSW builds and loading, and Markdown export. Uses an exact-neighbor mock in place of the native HNSW addon.

src/cognition/memory/io/facade/tests/Memory.brain-scope.test.ts

tools.test.tsAssert memory-add IDs contain v4 UUIDs +2/-1

Assert memory-add IDs contain v4 UUIDs

• Updates the trace ID assertion to verify the new 'mt_'-prefixed v4 UUID format.

src/cognition/memory/io/tools/tests/tools.test.ts

Documentation (5) +16 / -14
MEMORY_OPERATIONS.mdClarify export scope and UUID trace IDs +11/-11

Clarify export scope and UUID trace IDs

• Replaces timestamp-based trace ID examples with UUID-based IDs. Clarifies that Markdown exports contain the brain's traces, JSON exports are brain-scoped, and SQLite exports copy the whole database file.

docs/MEMORY_OPERATIONS.md

SQL_STORAGE_QUICKSTART.mdDocument per-brain HNSW index files +1/-1

Document per-brain HNSW index files

• Explains index naming, the brain-scoped build threshold, and why legacy shared index files are not loaded.

docs/getting-started/SQL_STORAGE_QUICKSTART.md

MEMORY_STORAGE.mdDocument brain-scoped health counts +2/-0

Document brain-scoped health counts

• States that health counts exclude other brains sharing the database and are numeric on SQLite and Postgres.

docs/memory/MEMORY_STORAGE.md

MemoryDeleteTool.tsRefresh memory-delete ID example +1/-1

Refresh memory-delete ID example

• Changes the API example to show the UUID-based trace ID format.

src/cognition/memory/io/tools/MemoryDeleteTool.ts

MemoryUpdateTool.tsRefresh memory-update ID example +1/-1

Refresh memory-update ID example

• Changes the API example to show the UUID-based trace ID format.

src/cognition/memory/io/tools/MemoryUpdateTool.ts

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f8bf7905f4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

.update(`${databaseFile}\u0000${config.brainId}`, 'utf8')
.digest('hex')
.slice(0, 32);
return join(directory, `${databaseFile.replace(/[^A-Za-z0-9._-]/g, '_')}.${digest}.hnsw`);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep sidecar filenames within filesystem limits

When the SQLite database has an ASCII basename longer than roughly 208 bytes, the added digest and .hnsw.map.json suffix push the sidecar map beyond the common 255-byte component limit. The database itself can still open, but saving the HNSW index fails; after restart the incomplete sidecar cannot load, so semantic-only recall silently falls back to FTS until another rebuild. Truncate or hash the database-name portion so both generated filenames always fit.

Useful? React with 👍 / 👎.

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0)

Grey Divider

Great, no issues found!

Qodo reviewed your code and found no material issues that require review

Grey Divider

Tip of the day
💡 Did you know, you can pick a display mode instead of tweaking every Display option by hand

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@jddunn
jddunn merged commit bdc7bab into master Oct 16, 2026
11 checks passed
@jddunn
jddunn deleted the fix/memory-brain-scope branch October 16, 2026 20:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant