Skip to content

feat(memory): memory_traces.scope_id at schema version 3, filled on upgrade and set by its writers, and importers that deduplicate inside one scope id - #451

Merged
jddunn merged 11 commits into
masterfrom
feat/learning-i2-ledger-store
Oct 16, 2026
Merged

jddunn merged 11 commits into
masterfrom
feat/learning-i2-ledger-store

Conversation

@jddunn

@jddunn jddunn commented Oct 14, 2026 •

Copy link
Copy Markdown
Member

Summary

memory_traces gains a scope_id column: each trace's scope id as a column of its own, with the index idx_memory_traces_brain_scope_id on (brain_id, scope, scope_id, created_at). Before it, the scope id lived only in the metadata JSON, so a read of one scope scanned every row of a brain.

  • Brain schema version 3. A database written at version 2 gains the column at its first open, filled from each row's metadata JSON for every brain the table holds, about one read and one write statement per 300 rows; a row whose JSON cannot be read, or names no scope id, keeps ''. Each brain's own migration then fills its rows that still hold '', which catches rows an older release wrote after another brain's migration added the column. On Postgres the migration runs in one transaction, so the table is locked for every brain until that fill commits. Brain also adds the column, on any open, to a table another path created without it.
  • The writers set it: MemoryStore.store(), Memory.remember(), the ingest, memory_add, the five importers, and Brain.importFromSqlite(), which copies the column from a source it opens at version 3. A release without the column writes its default, ''.
  • The importers file each record under its scope id (its metadata scopeId, else the scope_id an export of a version-3 brain carries, else '') and deduplicate, merge tags and remap trace ids inside one scope and scope id: a record whose text another tenant's trace holds is imported, where before it was dropped. Markdown, Obsidian and ChatGPT records file under ''.
  • The importers' duplicate check is the one reader of the column in this pull request.
  • docs/memory/MEMORY_STORAGE.md gives the column and schema version 3; docs/MEMORY_OPERATIONS.md gives the import rule.

Not in this pull request

The branch was opened for the whole learning increment: the learning store, the hash-chained ledger, the operator host calls on AgentOS.getLearningLayer() and agent.learning, namespaced scope ids for the GMI's memory, the memory tools, the standalone retriever and the rolling-summary sink, forgetUser and its tombstones, persistAccessState, the withdrawal of memory_reflect, and memory.store on gmi(). None of that is in this diff. The description the branch was opened with is kept below for the pull request that carries it.

The learning increment as first described (not in this diff)

Learning gets a durable record. With the learning flag on, a learning store keeps each learner's trait row, the run-time freezes and suspensions, a sessions index and the tombstones of forgotten users; an append-only ledger, one hash chain per learner whose heads advance by compare-and-swap, records every memory write the memory tools and the rolling-summary sink make and every operator call, so an edit made outside the layer shows at the next load. Operators freeze, suspend, set, revert, export, import and forget through host calls on AgentOS.getLearningLayer() and agent.learning. Memory a learner owns is filed and read under scope ids that keep tenants, users and sessions apart (the GMI's memory, the memory tools, the standalone retriever and the rolling-summary sink), and every write of a user's memory honours forgetUser's tombstone, writes in flight included. gmi() gets durable memory (memory.store). For every host: memory_traces.scope_id, per-scope import deduplication, and the stability fix behind persistAccessState.

For every host, flag on or off:

  • memory_traces gains a scope_id column (Brain schema version 3), backfilled from each row's metadata and set by every INSERT: the store's, Memory.remember()'s, the ingest's, memory_add's, the five importers' and Brain.importFromSqlite()'s. Nothing reads it with the learning flag off. An older release's writes leave it ''. The first open of a Brain after the upgrade adds the column and fills it for every brain in the table, about one read and one write statement per 300 rows; on Postgres the table is locked for every brain until that fill commits.
  • The importers deduplicate, merge tags and remap trace ids inside one scope and scope id: a record whose text another tenant's scope holds is imported, where before it was dropped.
  • A trace's stability, access count and reinforcement interval are written to its Brain row at every access and read back at load (persistAccessState, default true; false keeps the previous behaviour for one release).
  • A deleted trace takes its knowledge-graph copy with it.
  • The memory tools that write, and memory_reflect, refuse with frozen under AGENTOS_LEARNING_FREEZE=1, with a learning layer or without one.
  • New optional members on exported interfaces (IKnowledgeGraph.deleteMemories, ICognitiveMemoryManager.deleteScope and deleteTraces, the learning interfaces, IAgentOS.getLearningLayer), which no implementer has to add.
  • gmi()'s memory.store needs the learning option and learning.agentKey, and fails at construction naming them without either.

With the learning flag on:

  • A learning store keeps each learner's trait row, the run-time freezes and suspensions, the sessions index and the tombstones, and an append-only, hash-chained ledger records every memory write of the memory tools and the rolling-summary sink and every operator call; learning.ledgerKey keys the hashes.
  • Host calls: freeze, unfreeze, suspend, unsuspend, operatorSet, revert, exportLearnedState, importLearnedState, forgetUser (on AgentOS.getLearningLayer(), and on agent.learning with the agent's key and namespace filled in).
  • A learner whose namespace is set files and recalls its memory under namespaced scope ids: a host that passed organization ids before this release reads its earlier traces for those users after re-filing them with MemoryStore.refileScope, and runs it before it relies on forgetUser for them (until then forgetUser with a namespace leaves their plain-form traces and logs a WARNING).
  • Every plain id in a user or persona scope that holds a /, a % or a : is filed percent-encoded, and a Brain's earlier traces under such ids are re-filed when a layer first opens it.
  • A turn with no learner files under its session's own form, which no user id takes; a turn's own conversation and session thread ids are filed and read in that form, so a conversation's thread traces from before the layer are not read.
  • The GMI id and the memory owner id leave the user recall list; the bridge no longer adds the owner id to the organization list, where a turn's own organization ids stay; an owner id that begins with / or holds // leaves the thread list.
  • The memory tools, the standalone retriever and the rolling-summary sink file and read under the turn's scope ids; the tools reach no other scope's trace by id, search only the turn's own scopes and the unscoped traces, and refuse an organization write; their writes and the sink's are recorded, with no user on a turn with no learner; only a freeze stops them, and in mode off or under a suspension they write with no row.
  • memory_reflect is withdrawn; hosts consolidate with Memory.consolidate().
  • memory.store on gmi() gives durable memory, with the learning store on the same adapter.
  • Every process that serves one Brain turns the flag on together, on this release or a later one. In this release a host's Memory.consolidate() merges and derives across scope ids, and forgetUser does not reach the memory archive (its report names it), so products turn the flag on with the release that keeps consolidation inside each scope id and reaches the archive, or a later one.

Linked issues

None.

Type of change

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

How this was verified

CI on this pull request (ci.yml): Build, the exports check, Lint, the documentation word check, Type check and Test with coverage. Brain.scope-id.test.ts runs on real SQLite files through @framers/sql-storage-adapter: the migration of a version-2 file holding two brains (every metadata shape, a malformed row, and 650 rows a brain across pages), a fresh brain, a row an older writer adds after another brain migrated, MemoryStore.store(), remember(), the ingest and memory_add, and the JSON, SQLite, CSV and Markdown importers with two tenants holding one equal text. Brain.test.ts and Brain.postgres.test.ts read schema version 3.

Migration notes

No caller changes. A host's first open at version 3 adds and fills the column (see the Summary); on Postgres that fill holds the table's lock for every brain until it commits. An import that skipped a record because a trace of another scope id held its text imports it now.

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.

Summary by Sourcery

Introduce schema version 3 scope IDs for memory traces and apply scope-aware persistence and import deduplication.

New Features:

  • Add a dedicated scope_id column and supporting index to memory traces in schema version 3.
  • Make memory writers persist trace scope IDs and make importers deduplicate records within matching scope and scope ID, preserving same-content records across tenants or users.

Bug Fixes:

  • Prevent imports from incorrectly discarding same-content traces belonging to different scope IDs.

Enhancements:

  • Backfill scope IDs during upgrades, including legacy and malformed metadata handling, and ensure the column exists for externally created tables.

Documentation:

  • Document the schema version 3 scope_id column and scope-aware import deduplication behavior.

Tests:

  • Add coverage for migrations, backfills, indexes, writers, and scope-aware behavior across memory importers.

@coderabbitai

coderabbitai Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

  • Run on-demand review

This review includes 18 billable files and costs up to $4.50.

  • 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 4 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: ab355c13-f47c-438b-9ef4-856bb86d2100
📥 Commits

Reviewing files that changed from the base of the PR and between 1e430ca and dd9723a.

📒 Files selected for processing: 18
  • docs/MEMORY_OPERATIONS.md
  • docs/memory/MEMORY_STORAGE.md
  • src/cognition/memory/io/ChatGptImporter.ts
  • src/cognition/memory/io/CsvImporter.ts
  • src/cognition/memory/io/JsonImporter.ts
  • src/cognition/memory/io/MarkdownImporter.ts
  • src/cognition/memory/io/SqliteImporter.ts
  • src/cognition/memory/io/facade/Memory.ts
  • src/cognition/memory/io/facade/types.ts
  • src/cognition/memory/io/importScope.ts
  • src/cognition/memory/io/tools/MemoryAddTool.ts
  • src/cognition/memory/retrieval/store/Brain.ts
  • src/cognition/memory/retrieval/store/MemoryStore.ts
  • src/cognition/memory/retrieval/store/__tests__/Brain.postgres.test.ts
  • src/cognition/memory/retrieval/store/__tests__/Brain.scope-id.test.ts
  • src/cognition/memory/retrieval/store/__tests__/Brain.test.ts
  • src/cognition/memory/retrieval/store/migrations/index.ts
  • src/cognition/memory/retrieval/store/migrations/v2-to-v3.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 14, 2026

Copy link
Copy Markdown

Reviewer's Guide

This PR adds an opt-in durable learning layer with per-learner hash-chained audit records and host controls, then threads tenant/session scope IDs through Brain, memory writers, retrieval, imports, summaries, and gmi() durable memory. It also migrates existing Brain databases to schema version 3, persists access state, adds deletion/freeze safeguards, and validates enabled, disabled, migration, and multi-tenant paths with unit and integration tests.

File-Level Changes

Change Details Files
Introduces durable, tenant-isolated learning state and an append-only per-learner ledger, exposed through host and agent learning operations.
  • Persist learner traits, runtime freeze/suspension state, sessions, tombstones, and hash-chain ledger entries.
  • Add freeze, suspend, operator mutation, revert, import/export, and forget-user host calls.
  • Enforce ledger keys, tombstone-aware writes, and freeze behavior across memory tools and rolling summaries.
  • Expose optional learning and deletion APIs without requiring existing implementers to change.
Learning store and ledger implementation files (not shown in the supplied diff)
Host/agent learning API files (not shown in the supplied diff)
Memory tool and rolling-summary integration files (not shown in the supplied diff)
Adds scope-aware durable memory so traces remain isolated across tenants, users, sessions, and encoded identifiers.
  • Add and backfill the Brain schema version 3 scope_id column, including per-scope indexing and writes from memory insertion paths.
  • Refile namespaced and percent-encoded scopes, constrain retrieval and writes to turn scopes, and prevent organization writes.
  • Apply scope-aware import deduplication, tag merging, trace-id remapping, standalone retrieval, and rolling-summary persistence.
  • Remove memory_reflect in favor of Memory.consolidate and add deletion propagation to knowledge-graph copies.
src/cognition/memory/retrieval/store/Brain.ts
src/cognition/memory/retrieval/store/MemoryStore.ts
src/cognition/memory/retrieval/store/__tests__/Brain.scope-id.test.ts
Memory tools, retriever, importer, bridge, summary sink, and knowledge-graph files (not shown in the supplied diff)
Makes memory persistence and access-state behavior durable and configurable, including durable gmi() memory.
  • Persist stability, access count, and reinforcement interval on every access, controlled by persistAccessState.
  • Require learning configuration and agent identity when constructing gmi() with memory.store.
  • Use the learning store on the same adapter for gmi() durable memory and preserve prior behavior when learning is disabled.
gmi runtime and memory configuration files (not shown in the supplied diff)
Brain access-state persistence files (not shown in the supplied diff)
Adds migration and integration coverage for scope identifiers and the learning-enabled runtime paths.
  • Verify schema-2 migration fills scope_id for every brain, handles malformed or absent metadata, and processes rows across multiple pages.
  • Verify fresh schema version 3 setup, scope-aware MemoryStore writes, and the composite scope index.
  • Cover gmi(), AgentOS tenant isolation, ledger paths, and flag-off behavior through end-to-end tests and CI checks.
src/cognition/memory/retrieval/store/__tests__/Brain.scope-id.test.ts
gmi-runtime.learning-store.test.ts
agentos-learning-memory.e2e.test.ts
agentos-learning-tenants.e2e.test.ts
ledger.integration.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

…ne scope and scope id

A record's scope id is its metadata scopeId, else the scope_id an export of
a schema-3 brain carries, else ''; every importer's INSERT names scope_id.
The dedup check matches only a trace of the same scope and scope id, so a
record whose text another tenant's trace holds is imported, and the SQLite
importer's tag and time merge stays inside one scope id. Markdown, Obsidian
and ChatGPT records carry no scope id and file under ''.
@jddunn jddunn changed the title feat(learning): the ledger, the learning store and the host calls, scope ids that keep tenants apart, and durable memory on gmi() feat(memory): memory_traces.scope_id at schema version 3, filled on upgrade and set by its writers, and importers that deduplicate inside one scope id Oct 16, 2026
@jddunn
jddunn marked this pull request as ready for review October 16, 2026 12:20
@jddunn
jddunn requested a review from Victor-Evogor as a code owner October 16, 2026 12:20
@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 14 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-16T12:26:19.325830Z d54c426 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

feat(memory): persist trace scope IDs and scope import deduplication

✨ Enhancement 🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Add indexed memory_traces.scope_id and backfill existing traces during the schema-version-3
 upgrade.
• Set scope IDs on trace writes and deduplicate imports within each scope and scope ID.
• Test migration and tenant-separated imports; document the schema and import rules.
Diagram

graph TD
  Open["Brain open"] --> Migration["V3 migration"] --> Traces[("Memory traces")]
  Writers["Trace writers"] --> Traces
  Importers["Trace importers"] --> Resolver["Scope resolver"] --> Dedup["Scoped dedup"] --> Traces
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Derive scope IDs from metadata at query time
  • ➕ Avoids synchronizing a separate column with metadata.
  • ➖ Retains JSON-dependent scope reads and cannot provide the same portable indexed lookup.
  • ➖ Malformed metadata complicates database-side extraction.

Recommendation: Keep the dedicated, indexed column: it supports scope-filtered reads across adapters and preserves malformed rows during migration. The trade-off is maintaining consistency between the column and metadata across every writer; the migration and write-path tests are therefore central to review.

Files changed (18) +583 / -81

Enhancement (7) +179 / -13
Memory.tsPersist scope IDs in facade trace writes +5/-4

Persist scope IDs in facade trace writes

• Writes the requested scope ID for remember() traces and an empty ID for ingest-created semantic traces.

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

importScope.tsCentralize imported scope-ID resolution +26/-0

Centralize imported scope-ID resolution

• Adds a helper that prefers a string metadata.scopeId, falls back to an exported scope_id, and otherwise returns an empty ID. It also copies a fallback column value into metadata for trace loading.

src/cognition/memory/io/importScope.ts

MemoryAddTool.tsPersist memory_add's resolved scope ID +3/-3

Persist memory_add's resolved scope ID

• Includes the scope ID resolved from the tool context in each inserted trace row.

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

Brain.tsInitialize trace tables with indexed scope IDs +9/-2

Initialize trace tables with indexed scope IDs

• Adds scope_id to new memory_traces tables and ensures the column and index exist on open, including for tables created without the column. Existing SQLite import copying reads the source through an upgraded Brain.

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

MemoryStore.tsWrite trace scope IDs from MemoryStore +3/-2

Write trace scope IDs from MemoryStore

• Adds scope_id to the trace upsert, using the trace's scopeId or an empty ID.

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

index.tsRegister the version-3 migration +3/-2

Register the version-3 migration

• Adds the v2-to-v3 migration to the ordered registry, making version 3 the latest schema.

src/cognition/memory/retrieval/store/migrations/index.ts

v2-to-v3.tsAdd and backfill indexed trace scope IDs +130/-0

Add and backfill indexed trace scope IDs

• Adds scope_id and its compound index, then backfills values from metadata in 300-row pages across all brains when the column is first added. Each brain's migration also fills its remaining empty values; malformed or missing metadata leaves them empty.

src/cognition/memory/retrieval/store/migrations/v2-to-v3.ts

Bug fix (5) +97 / -52
ChatGptImporter.tsConfine ChatGPT duplicates to unscoped user traces +8/-4

Confine ChatGPT duplicates to unscoped user traces

• Checks import hashes only in the user scope with an empty scope ID and explicitly writes that ID on insert.

src/cognition/memory/io/ChatGptImporter.ts

CsvImporter.tsUse CSV metadata scope IDs during import +20/-14

Use CSV metadata scope IDs during import

• Parses metadata before duplicate checks, restricts those checks to the row's scope and scope ID, and persists the resolved ID.

src/cognition/memory/io/CsvImporter.ts

JsonImporter.tsScope JSON trace deduplication and ID remapping +34/-17

Scope JSON trace deduplication and ID remapping

• Accepts exported scope_id values, resolves each trace's scope ID before deduplication, and writes it with the trace. Duplicate trace IDs now remap only to a match in the same scope and scope ID.

src/cognition/memory/io/JsonImporter.ts

MarkdownImporter.tsImport Markdown within its scope and empty scope ID +12/-7

Import Markdown within its scope and empty scope ID

• Uses the file's scope when checking import hashes and explicitly inserts traces with an empty scope ID.

src/cognition/memory/io/MarkdownImporter.ts

SqliteImporter.tsKeep SQLite duplicate merges inside one scope ID +23/-10

Keep SQLite duplicate merges inside one scope ID

• Resolves scope IDs from metadata or the source column and limits hash or content matches to that scope pair. Tag and creation-time merges therefore do not affect another scope ID's trace.

src/cognition/memory/io/SqliteImporter.ts

Tests (3) +298 / -11
Brain.postgres.test.tsExpect schema version 3 on PostgreSQL +7/-7

Expect schema version 3 on PostgreSQL

• Updates first-open, reopen, and concurrent-open assertions for the new schema version.

src/cognition/memory/retrieval/store/tests/Brain.postgres.test.ts

Brain.scope-id.test.tsExercise scope-ID migration, writers, and imports +287/-0

Exercise scope-ID migration, writers, and imports

• Adds real-file SQLite tests for multi-brain backfills, pagination, late legacy writes, and fresh schema creation. Also checks facade and store writes and tenant-separated JSON, SQLite, CSV, and Markdown imports.

src/cognition/memory/retrieval/store/tests/Brain.scope-id.test.ts

Brain.test.tsExpect schema version 3 on SQLite +4/-4

Expect schema version 3 on SQLite

• Updates first-creation and reopen assertions to the latest schema version.

src/cognition/memory/retrieval/store/tests/Brain.test.ts

Documentation (3) +9 / -5
MEMORY_OPERATIONS.mdDocument scope-aware import deduplication +1/-1

Document scope-aware import deduplication

• Explains that importers check duplicates within the same scope and scope ID, including fallback rules for imported IDs and SQLite's duplicate merge behavior.

docs/MEMORY_OPERATIONS.md

MEMORY_STORAGE.mdDocument schema-version-3 trace storage +5/-2

Document schema-version-3 trace storage

• Adds the scope_id column, its index, and upgrade behavior to the storage reference. Updates schema-version examples to 3.

docs/memory/MEMORY_STORAGE.md

types.tsClarify the import deduplication contract +3/-2

Clarify the import deduplication contract

• Documents that ImportOptions.dedup compares hashes within the same scope and scope ID.

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

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

qodo-free-for-open-source-projects Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (2) 📘 Rule violations (1) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. The schema migration lacks TSDoc 📘 Rule violation ⚙ Maintainability
Description
The exported v2ToV3 migration object has no symbol-level TSDoc describing its contract. Because
the migration is registered and exported from migrations/index.ts, generated API documentation and
later maintainers have no direct explanation of the version-3 upgrade it performs.
Code

src/cognition/memory/retrieval/store/migrations/v2-to-v3.ts[R122-129]

+export const v2ToV3: Migration = {
+  version: 3,
+  async up(adapter: StorageAdapter, _features: StorageFeatures, brainId: string): Promise<void> {
+    // A file with no `memory_traces` gets the table, with the column, from the schema step that follows.
+    if (!(await tableExists(adapter, 'memory_traces'))) return;
+    await ensureScopeIdColumn(adapter);
+    await backfill(adapter, brainId);
+  },
Evidence
The checklist requires TSDoc for every exported symbol. The changed file exports v2ToV3 without a
symbol-level TSDoc comment, while the migration registry imports and exposes it as part of the
active migration set.

AGENTS.md: Document Exported Symbols and Nonobvious Code: AGENTS.md: Document Exported Symbols and Nonobvious Code: AGENTS.md: Document Exported Symbols and Nonobvious Code: AGENTS.md: Document Exported Symbols and Nonobvious Code
src/cognition/memory/retrieval/store/migrations/v2-to-v3.ts[122-129]
src/cognition/memory/retrieval/store/migrations/index.ts[14-19]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The exported `v2ToV3` migration object lacks symbol-level TSDoc, so the public migration symbol is not documented as required by the repository compliance checklist.
## Fix Focus Areas
- src/cognition/memory/retrieval/store/migrations/v2-to-v3.ts[122-129]
## Recommended Fix
Add a TSDoc comment immediately before `v2ToV3` explaining that it migrates schema version 2 to version 3, ensures the `scope_id` column and index exist, and backfills scope IDs for the current brain.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

2. Repeated imports duplicate legacy traces 🐞 Bug ≡ Correctness
Description
The importers' duplicate checks require a matching scope_id, but an older writer can add a row
with metadata.scopeId and the column's default '' after that brain has migrated. Reimporting the
same scoped record then misses its existing hash and inserts another trace, because subsequent opens
skip the per-brain backfill once its schema version is 3.
Code

src/cognition/memory/io/JsonImporter.ts[R331-332]

+       WHERE brain_id = ? AND scope = ? AND scope_id = ?
+         AND ${dialect.jsonExtract('metadata', '$.import_hash')} = ?
Evidence
The new column defaults to empty; the migration refills empty rows for a brain only when its
version-3 migration runs. The new JSON duplicate query requires the nonempty scope ID derived from
the imported metadata, so it cannot match a later legacy write with that same metadata and hash but
an empty column.

src/cognition/memory/retrieval/store/Brain.ts[408-413]
src/cognition/memory/retrieval/store/migrations/v2-to-v3.ts[109-129]
src/cognition/memory/retrieval/store/migrations/MigrationRunner.ts[88-100]
src/cognition/memory/io/JsonImporter.ts[330-356]
src/cognition/memory/retrieval/store/tests/Brain.scope-id.test.ts[100-113]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
An older writer can insert a trace with `metadata.scopeId` but leave `scope_id` at its default after the brain migrates. Scoped duplicate checks then miss that trace on a repeated import.
## Fix Focus Areas
- src/cognition/memory/io/JsonImporter.ts[330-356]
- src/cognition/memory/io/SqliteImporter.ts[157-183]
- src/cognition/memory/io/CsvImporter.ts[114-152]
- src/cognition/memory/retrieval/store/migrations/v2-to-v3.ts[109-129]
## Recommended Fix
Make scoped duplicate checks recognize and normalize legacy rows whose `scope_id` is empty but whose metadata names the requested scope ID. Cover writes made after the brain has already reached schema version 3, not only rows present during migration.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational

3. First brain in a migrating database scans its rows twice 🐞 Bug ➹ Performance
Description
v2ToV3.up calls ensureScopeIdColumn, which already runs backfillEveryBrain for the whole table
when it adds the column, and then unconditionally calls backfill(adapter, brainId) again for the
migrating brain's own rows. For the brain that triggers the column addition, every row of that brain
that is still '' (including rows with no scope id, which never leave '') is read and matched
against twice, doubling the read work for that brain's migration which runs inside the Postgres
transaction that holds memory_traces locked for every brain.
Code

src/cognition/memory/retrieval/store/migrations/v2-to-v3.ts[R124-129]

+  async up(adapter: StorageAdapter, _features: StorageFeatures, brainId: string): Promise<void> {
+    // A file with no `memory_traces` gets the table, with the column, from the schema step that follows.
+    if (!(await tableExists(adapter, 'memory_traces'))) return;
+    await ensureScopeIdColumn(adapter);
+    await backfill(adapter, brainId);
+  },
Evidence
ensureScopeIdColumn runs backfillEveryBrain(adapter) (which iterates every brain_id and calls
backfill on each) whenever it adds the column; v2ToV3.up then calls
ensureScopeIdColumn(adapter) followed unconditionally by await backfill(adapter, brainId) for
the same brainId, so the triggering brain's rows are paged and matched against the metadata JSON
twice in the same migration transaction.

src/cognition/memory/retrieval/store/migrations/v2-to-v3.ts[94-130]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`v2ToV3.up` calls `ensureScopeIdColumn(adapter)`, which itself runs `backfillEveryBrain` (filling every brain's rows, including the current one) when it adds the column, and then unconditionally calls `backfill(adapter, brainId)` again for the triggering brain, re-reading and re-matching rows that are already filled or already known to have no scope id.
## Fix Focus Areas
- src/cognition/memory/retrieval/store/migrations/v2-to-v3.ts[109-129]
## Recommended Fix
Have `ensureScopeIdColumn` report whether it added the column (return a boolean), and have `v2ToV3.up` skip its own `backfill(adapter, brainId)` call when the column was just added by this call (since `backfillEveryBrain` already covered it), only running the extra backfill when the column already existed.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


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

Comment thread src/cognition/memory/io/JsonImporter.ts Resolved

@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: d54c426d7b

ℹ️ 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".

@jddunn
jddunn merged commit 73c39bc into master Oct 16, 2026
11 checks passed
@jddunn
jddunn deleted the feat/learning-i2-ledger-store branch October 16, 2026 12:35
jddunn added a commit that referenced this pull request Oct 16, 2026
…Lite import, Obsidian links and the Postgres full-text rebuild stay within the brain

- recall: the candidates of both halves of the hybrid recall pass the
  recall's filters (brain, deleted, type, scope, scope id, strength, after,
  before) before reciprocal rank fusion, and each half's ranks count the
  candidates that passed; with none left the full-text path answers.
- export({ format: 'sqlite' }): Brain.exportToSqlite writes this brain's
  rows of every portable table to a new SQLite file from either backend.
  It replaces the adapter's exportToFile, which copied the whole SQLite
  file (VACUUM INTO) or ran pg_dump of the whole Postgres database.
- SQLite import: reads the one brain a source file holds; a file whose rows
  carry several brain ids imports nothing and errors names them; a file
  older than the brain_id column is read whole.
- Obsidian export: the link prefetch reads this brain's edges and joins
  nodes on (brain_id, id).
- Brain.fullTextRebuild(): the rebuild statement, bound to the brain's rows
  on Postgres; the facade's import rebuild, memory_update, memory_merge and
  the consolidation re-index use it.
- Docs: MEMORY_OPERATIONS (SQLite export and import, Obsidian links, the CSV
  metadata rule from #451, the rebuilds, the file table) and
  MEMORY_SYSTEM_OVERVIEW (the adapter's exporters copy the whole database).
@jddunn jddunn added the track Tracked on the board: one issue per plan or open problem; its pull requests say Part of or Closes label Oct 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

track Tracked on the board: one issue per plan or open problem; its pull requests say Part of or Closes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant