Overview Setup Guide Installation Usage CLI Reference API Architecture Use Cases Comparisons Benchmarks Troubleshooting FAQ
neuralmind.uk / Docs / Brain-Like Learning Guide Edit this page on GitHub ↗

Brain-Like Learning Guide

How NeuralMind improves retrieval relevance by learning from how you actually use your codebase

Overview

NeuralMind’s learning system improves automatically as you use it. The more you query, edit, and run tools over your code, the smarter recall gets — with no manual step to remember.

As of v3.9.0 the learning system combines six modern brain-inspired techniques in the synapse layer. It learns continuously from queries, edits, and tool calls, reinforces the edges between code nodes that fire together, and lets unused edges decay so recall tracks current usage instead of a stale snapshot.

The Learning Cycle

┌──────────────────────────────────────────────────────────┐
│ 1. Observe                                                │
│    Every query, tool call, and file edit co-activates a   │
│    set of code nodes.                                     │
│    ↓ The synapse layer reinforces edges between them      │
├──────────────────────────────────────────────────────────┤
│ 2. Recall                                                 │
│    A new query lights up the relevant nodes; activation   │
│    spreads across the learned graph.                      │
│    ↓ Related code surfaces that vector search would miss  │
├──────────────────────────────────────────────────────────┤
│ 3. Decay                                                  │
│    Unused edges age out automatically; long-term          │
│    potentiation protects frequently-used connections.     │
│    ↓ Recall tracks current usage, not a stale batch       │
├──────────────────────────────────────────────────────────┤
│ 4. Continuous improvement                                 │
│    No `neuralmind learn` step — the graph grows as you    │
│    work.                                                   │
└──────────────────────────────────────────────────────────┘

v3.9.0: Six SOTA Synapse Dynamics

1. Lateral Inhibition (SYNAPSE paper, arXiv 2025)

When one concept activates, it suppresses competing activations rather than only boosting neighbors. Prevents “attention dilution” in large codebases where many clusters are partially relevant.

2. Synaptic Tagging & Capture (STC) (PNAS Nexus 2022)

Not every co-activation is meaningful. Two-phase model:

3. Non-Monotonic Plasticity (SAMPL model, bioRxiv)

Memory retrieval both enhances the retrieved item AND weakens related but non-retrieved items (retrieval-induced forgetting). Prevents the “everything is vaguely associated with everything” problem.

4. Resource-Dependent Heterosynaptic STDP (Frontiers 2025)

Each node has a finite local resource pool. Strengthening edge (A,B) consumes resources from A’s pool, naturally weakening competing edges (A,C), (A,D). Creates synaptic competition without global normalization.

5. Feeling-of-Knowing (FOK) Gating (SYNAPSE paper)

Confidence gate on retrieval. If peak activation after spreading doesn’t exceed an adaptive threshold, returns empty rather than weakly-associated noise. Prevents hallucination of irrelevant context.

6. Replay-Based Consolidation (bioRxiv 2025)

Replay queue captures recent co-activation sequences. During idle periods, replays them to strengthen associations without new input. Interleaves recent + old patterns to prevent catastrophic forgetting.

v3.9.0: Adversarial Retrieval Enhancements

For “how does X implement Y” queries, retrieval leans toward implementation code rather than docstrings.

On by default — both re-rank the hits retrieval already returned, so they cannot spend extra context:

  1. Intent-aware classification: “how does X implement Y” → code intent, which multiplies code hits by NEURALMIND_CODE_BOOST (3.0) and doc hits by 0.5. The keyword heuristic alone scored this on “how does” and called it docs; matching the question shape is what fixed it.
  2. Code-signal boost: Extracts identifiers, boosts matching source files.

Off by default, behind NEURALMIND_RETRIEVAL_EXPANSION=1 — these pull in nodes vector search did not return, and so must displace a hit to make room:

  1. Synapse-seeded expansion: Spreads activation from query-matched nodes
  2. Dependency graph traversal: Finds callers/callees/imports
  3. Code snippet extraction: Shows actual source code with line numbers

Fixes 3–5 are disabled because they were measured and lost facts: on the reference fixture they took the faithfulness delta from +0.041 to -0.065, under the gate’s +0.000 floor. Rebuilding them to be budget-neutral made it -0.107 — worse — because displacement evicts a real hit for every candidate pulled in, so a candidate that is worse than what it replaces now costs an answer rather than only tokens. Their candidates are substring matches over identifiers, and on that fixture they lose to the vector hits they displace. Candidate quality is the open problem; the budget discipline is already there waiting for it.

Step-by-Step Workflow

Step 1: Enable Memory Logging

First-time only. When you run your first query, you’ll be prompted:

$ neuralmind query . "How does authentication work?"

Enable local NeuralMind memory logging to improve retrieval over time? [y/N]: y

✅ Consent saved to ~/.neuralmind/memory_consent.json

To disable: Set NEURALMIND_MEMORY=0 (query event logging) and/or NEURALMIND_SYNAPSE_INJECT=0 (prompt-time synapse recall).

Step 2: Install hooks and (optionally) the watcher

The synapse layer learns the most when it can observe your work. Install the lifecycle hooks once, and optionally run the file watcher for always-on learning from edits:

# One-time: install the lifecycle hooks (idempotent — safe to re-run)
neuralmind install-hooks .

# Optional: always-on learning from file edits
neuralmind watch &

Step 3: Use NeuralMind Naturally

Just query and edit as usual. Co-activations are recorded automatically.

# Daily usage - these all reinforce the synapse graph
neuralmind query . "How does authentication work?"
neuralmind query . "What are the API endpoints?"
neuralmind query . "How is data validated?"
neuralmind query . "Where's the database logic?"
neuralmind query . "What's the error handling?"

Each query also logs (when memory is enabled):

The query event log is a local, auditable record; the synapse layer is what turns that activity into better recall.

Step 4: Automatic Improvements

On later queries, the synapse layer surfaces associations it has learned — including related code that pure vector search would not have found, because the relationship is behavioral (learned from co-activation), not textual. Synapse-driven hits are labelled in the L3 output — a [recalled] tag for code surfaced purely via the learned graph, and a (+X.XX synapse) annotation on hits whose score the graph boosted:

$ neuralmind query . "How does auth work?"

## Search Results

1. **authenticate** (score: 0.91)
   Type: function
   File: auth.py

2. **validate_user** (score: 0.85 (+0.25 synapse))  ← boosted by the learned graph
   Type: function
   File: auth.py

3. **check_permissions** [recalled] (score: 0.23)  ← surfaced purely via the graph
   Type: function
   File: middleware.py

Real-world data point: across a major rebuild of a private ~9,300-node TypeScript SaaS platform, personal synapse edges grew 36 → 135 as the layer learned the new code’s co-activations — see the field report.

Step 5: Continuous Improvement

There is no weekly neuralmind learn step to run. The synapse store grows continuously as you work, and SessionStart runs decay so weights age between sessions. Inspect what’s been learned at any time:

neuralmind stats .            # includes a synapse breakdown
neuralmind memory inspect .   # contribution by namespace
cat .neuralmind/SYNAPSE_MEMORY.md

How synapse learning happens

Four paths keep the synapse graph current. Three strengthen pairwise edges between co-active nodes (Hebbian: “nodes that fire together wire together”), and SessionStart ages them:

  1. Every mind.query() — top search hits + loaded communities reinforce.
  2. PostToolUse hook on Edit/Write — when the agent’s new code reuses existing symbols, their edges are reinforced (reuse feedback).
  3. SessionStart hook — runs decay so weights age between sessions, then exports memory.
  4. neuralmind watch daemon — debounces file edits into co-activation batches; co-edited files wire together.

The UserPromptSubmit hook only reads the graph: it adds the files the prompt matches and the code linked to them to the prompt, and strengthens nothing.

What trains which part (v4.13.0+ table)

Surface Edges (co-activation) Transitions (A → B) Turn it off
neuralmind query, the MCP neuralmind_query tool, the daemon Strengthened by the hits and communities each answer uses Never --no-learn, NEURALMIND_NO_LEARN=1
Claude Code PostToolUse hook on Read; Hermes plugin read_file of a file inside the project — One per file read after another NEURALMIND_NO_LEARN=1
Claude Code PostToolUse hook on Edit/Write, Hermes plugin edits Reuse feedback: symbols the new code reuses One per file edited after another NEURALMIND_REUSE_FEEDBACK=0 or NEURALMIND_NO_LEARN=1 (both)
neuralmind watch Files changed together wire together One per consecutive pair of files in a batch of changes stop the watcher
neuralmind build Seeded from the code graph’s structure (and from ingested business documents) Never —
SessionStart, neuralmind wakeup, prompt-time recall (UserPromptSubmit, Hermes pre_llm_call) Never (SessionStart runs decay) Never —

So a project that is queried a lot but whose files are edited outside an agent with these hooks, and with no watcher, gains edges and stays at 0 transitions, and neuralmind next has nothing to say.

Seeing it learn (v4.13.0+)

The synapse layer has been namespace-aware since v0.24.0: branch:<name> / personal / shared / ephemeral memory live separately in the same store, with a transparent merged read view. See the memory namespaces commands.

What the synapse layer learns

The store is a weighted graph in SQLite (.neuralmind/synapses.db) with two parts:

Weights follow a Hebbian + decay + LTP (long-term potentiation) model: co-activation strengthens an edge, disuse decays it, and frequently-used edges are protected by an LTP floor so they don’t evaporate.

Surface in Claude Code

Each SessionStart re-exports the synapse memory as markdown to:

Privacy & Data

✅ Local — All learning happens on your machine ✅ No Telemetry — No usage data is sent anywhere ✅ User Control — One-time consent, can disable anytime ✅ Persistent — Memory stays in your .neuralmind/ directory

Write policy — who may write what

Agents learn in their own store; the human and team layers change only through an explicit, git-committed bundle — never the agent writing them directly. Concretely:

This means an association the agent learned can never silently become team-trusted knowledge — promotion requires an explicit, reviewable commit. See the repo-root positioning note TRINODE.md for the full trust-boundary rationale.

File Locations

~/.neuralmind/
├── memory_consent.json              # Consent flag (once per user)
└── memory/
    └── query_events.jsonl           # Global event log

project/.neuralmind/
├── memory/
│   └── query_events.jsonl           # Project-specific events
└── synapses.db                      # SQLite-backed Hebbian synapse store

Environment Variables

# Disable query event logging
export NEURALMIND_MEMORY=0

# Disable prompt-time synapse recall injection
export NEURALMIND_SYNAPSE_INJECT=0

# Disable the auto-memory export
export NEURALMIND_SYNAPSE_EXPORT=0

You can also disable the layer entirely in Python with NeuralMind(..., enable_synapses=False), or wipe the learned graph at any time with mind.synapses.reset().

Troubleshooting

“No query events found”

Problem: neuralmind stats . or neuralmind memory inspect . shows nothing learned.

Solution:

  1. Have you run at least one query, or installed the hooks / watcher?
  2. Did you consent to memory logging? You should see the prompt on first query.
  3. Check the memory file exists: ls -la project/.neuralmind/memory/query_events.jsonl
  4. Check NEURALMIND_MEMORY is not set to 0.

Problem: You see no synapse-recalled hits in search results.

Solution:

  1. The synapse graph needs to warm up — query, edit, and run tools over a few sessions, or run neuralmind watch . to learn from edits.
  2. Check NEURALMIND_SYNAPSE_INJECT is not set to 0.
  3. Inspect the store: neuralmind stats . and cat .neuralmind/SYNAPSE_MEMORY.md.

Best Practices

1. Natural Usage

✅ DO: Ask questions and edit code naturally as you work
neuralmind query . "How does user login work?"

❌ DON'T: Artificially create queries just to "train" the layer

2. Let the watcher run

✅ DO: Run neuralmind watch . so co-edits feed the synapse graph
neuralmind watch &

❌ DON'T: Expect rich recall from a cold store on day one

3. Meaningful Questions

✅ DO: Ask varied questions about your codebase
- "How does auth work?"
- "What are the API routes?"
- "How is data validated?"

❌ DON'T: Ask the exact same question repeatedly

4. Inspecting what’s learned

✅ DO: Use the built-in inspectors to understand your code's associations
neuralmind stats .
neuralmind memory inspect .

❌ DON'T: Hand-edit synapses.db (it's managed by the layer)

Performance Impact

Learning has negligible overhead:

The untraced hot path pays nothing for trace/attribution machinery.

The old reranker (removed in v0.25.0)

Before v0.25.0, NeuralMind also shipped a learned_patterns cooccurrence reranker. You ran neuralmind learn . to analyze logged query events, which wrote .neuralmind/learned_patterns.json, and the next query re-ordered its L3 hits by a +0.3 cooccurrence boost.

It was removed after a 2×2 A/B on the benchmark fixture showed it added 0.0 points to top-k hit rate whether the synapse layer was on or off (77.2% → 77.2% cold, 83.3% → 83.3% warm — these are the levels that one run produced; the absolute hit rates move between runs, so the finding is the 0.0-point delta, not the levels), while the synapse layer alone moved it. The reranker was also runtime-inert on the warm path — the synapse boost re-sort discarded its ordering anyway — it required the manual neuralmind learn step to populate, and its JSON captured a snapshot that went stale between runs. The synapse layer is strictly better on all three counts: automatic instead of manual, decaying instead of staling, and the only mechanism with measured lift.

What this means for you:

See the v0.25.0 release notes for the full evidence and migration notes.

What’s Coming

See Also