Brainbox

io.github.thebasedcapital由 GitHub 帳號 thebasedcapital 發布v0.1.6更新於 Oct 24, 2026

Hebbian memory for AI agents. Learns file patterns, predicts next tools, saves tokens.

已驗證STDIO僅桌面知識與記憶開發者工具

概覽

AI 產生的概覽

為程式開發助理提供本機程序記憶:記錄檔案、工具與錯誤模式,並在助理搜尋前召回可能需要的檔案。

可以做什麼
BrainBox 觀察程式開發助理實際執行的動作並存入本機 SQLite 圖:哪些檔案會被一起讀取與編輯、哪些錯誤由哪些修改修好、哪些工具鏈會被重複使用。在後續任務中,它會提前召回相關檔案、預測下一個工具,並可提供錯誤到修正的程序。它提供 record、recall、explain、error、resolve、predict_next、stats、decay 八個 MCP 工具,並附有命令列工具。
適用情境
適合在同一個程式庫中反覆工作、助理需要反覆搜尋相同檔案而耗費大量 token 的情境。它面向程式開發助理,並可從 git 歷史與程式碼圖初始化以縮短冷啟動。
執行需求
以 npm 套件 brainbox-hebbian 透過 stdio 在本機執行。需要 macOS 或 Linux 上的 Node.js 22 或更新版本;選用的 FSEvents 檔案監看常駐程式僅支援 macOS。未宣告帳號、API 金鑰或環境變數。嵌入為選用功能,需要下載模型;未啟用時召回會退化為關鍵字搜尋。
安裝前請注意
安裝程式會把鉤子加入 Claude Code 設定檔並註冊 MCP 伺服器,還會在背景下載嵌入模型。它會把檔案讀取、編輯、搜尋與命令等助理活動記錄到本機資料庫,啟用前請確認記錄範圍。macOS 常駐程式需明確選擇啟用,會監看整個檔案系統。解除安裝會移除鉤子與伺服器,但保留資料庫。

安裝

在 SourceWeft 中

  1. 開啟 儀表板中的 Brainbox,將其新增到工作區。
  2. 為需要使用其工具的對話啟用該服務。

Desktop only,透過 STDIO。 STDIO 服務會啟動本機處理程序,因此需要 SourceWeft 桌面主機。

其他 MCP 客戶端

參照 儲存庫 中的啟動說明。

README

[BrainBox — muscle memory for coding agents]

[npm version] [GitHub stars] [Node 22+] [MCP: 8 tools] [Zero cost, local, SQLite] [MIT license]

Install · How it works · Results · Research · Integrations · Whitepaper

BrainBox is procedural memory for AI coding agents. It watches what the agent actually does and remembers it:

  • which files get read and edited together
  • which errors were fixed by which edits
  • which tool chains the agent repeats

On the next task it puts the right files in front of the agent before it starts searching.

Not a vector database. Not RAG. Hebbian learning on a local SQLite graph. Zero API cost, no GPU, nothing leaves your machine.

Session 1   agent greps for auth.ts, reads it, edits it            ~2,000 tokens of searchingSession 5   BrainBox recalls auth.ts + session.ts up front         search skippedSession 20  auth.ts → session.ts → token.ts is a superhighway      instant recall

Paper

[DOI]

BrainBox: Local Behavioral Memory for Coding Agents (Bhavesh B, 2026). The DOI above covers all versions and resolves to the latest. Latest version: v0.2, doi:10.5281/zenodo.23250505.

bibtex
@misc{b2026brainbox,  author    = {B, Bhavesh},  title     = {BrainBox: Local Behavioral Memory for Coding Agents},  year      = {2026},  publisher = {Zenodo},  version   = {v0.2},  doi       = {10.5281/zenodo.23250505},  url       = {https://doi.org/10.5281/zenodo.23250505}}

Install

bash
npm install brainbox-hebbian

That's it. The postinstall script:

  1. Adds a PostToolUse hook to ~/.claude/settings.json. It learns from every file read, edit, search and command.
  2. Adds a UserPromptSubmit hook. It injects compact recall into prompts, or stays silent once it has learned you ignore it.
  3. Adds a SessionEnd hook. It scores which recalled files you actually opened or edited and compiles procedures.
  4. Registers the MCP server via claude mcp add, with 8 tools: record, recall, explain, error, resolve, predict_next, stats, decay.
  5. Creates ~/.brainbox/ and starts a background download of the embedding model.

Hooks never download models. Until the model is cached (brainbox models pull), recall runs lexical-only. Embeddings come from the optional @huggingface/transformers dependency; if its native modules can't install on your machine (for example, sharp with a system libvips and no build tools), BrainBox still installs and runs with keyword search. brainbox models status shows which mode you are in.

Kill the cold start by seeding from git history and the code graph:

bash
brainbox bootstrap --repo /path/to/project --imports

Uninstall: brainbox uninstall removes the hooks and the MCP server and keeps your database.

How it works

[BrainBox pipeline: tool calls → learn → recall → policy → inject, with a feedback loop]

Every tool call is a neuron firing. Files, tools and errors become neurons, and things accessed close together become synapses. A prompt triggers recall, which fuses several ranking channels. A learned policy decides whether injecting is worth the tokens. Feedback on what you actually opened or edited flows back into the graph.

Fire together, wire together

[Hebbian learning: co-accessed files strengthen their synapse across sessions]

Access auth.ts then session.ts across sessions and their synapse strengthens. SNAP plasticity makes strong synapses grow more slowly, so no single connection takes over. Links are directional (STDP): what you open next matters more than what came before.

Spreading activation

[Spreading activation from a seed file over three hops with fan-effect damping]

Recalling one file activates its neighbours for up to 3 hops. Each hop is damped by 1/√degree, so hub files don't flood the results. Each result carries the channel and the edge that produced it. brainbox_explain shows you exactly why a file was recalled.

Superhighways and decay

[Frequently used paths myelinate into superhighways while unused edges decay]

Paths you use often are myelinated into instant-recall superhighways. Recency and frequency follow the ACT-R base-level equation, B = ln Σ tⱼ^-0.5, and unused connections fade. Files recalled but ignored weaken only the edge that surfaced them.

Error → fix immune system

[An error fingerprint is linked to the edits that fixed it and recalled the next time]

When a failed command is followed by edits and a passing rerun, BrainBox stores an error→fix procedure. The procedure is keyed by the error's fingerprint and tracks helpful/harmful outcomes. The next time that error appears, the fix files are recalled at once. Procedures are shown to the agent as quoted observations, never as instructions.

Results

[v0.2 vs v0.1 vs best baseline on real agent trajectories]

brainbox eval replays real coding-agent trajectories in time order. Each task is scored on a fresh in-memory DB trained only on earlier tasks from the same repo, and every system ranks the same candidate set.

v0.1 lost to plain recency on next-file prediction. On the held-out SWE tasks the gap was −.207, 95% CI −.312…−.118. v0.2 is statistically tied with recency there. Next-tool prediction now beats every baseline significantly, and files-read recall leads on both data sources.

Known gap: on local sessions, ranking by edit frequency alone still beats BrainBox for edited files (Δ −.089, CI −.185…0).

Fitting the lexical and Hebbian channel weights to zero scored higher on dev, but recall then ignored the query, so the shipped weights keep them.

Full table, protocol and commands

Probes:

  • P1: files edited or read for the task (query = task text)
  • P2: next file, step by step
  • P3: next tool (top 3)

Baselines: recency, frequency, BM25, EdgeBank and random. Confidence intervals are paired bootstrap 95% CIs, resampled by trajectory.

Datasets:

  • Ranking weights were fit only on the dev repos (sqlglot, dvc, streamlink).
  • SWE test is 40 held-out tasks from Pillow and conan.
  • Local is 97 agent sessions across 5 projects, never used for fitting.

Scores are MRR (P3: MRR@3), with embeddings off.

ProbeSWE test: v0.1v0.2best baselinelocal: v0.1v0.2best baseline
P1 edited files.307.307.216 BM25.737.703.791 frequency
P1 read files.191.267.206 BM25.372.555.547 BM25
P2 next file.223.409.430 recency (Δ CI −.049…+.003).634.702.701 recency (tie)
P3 next tool.479.767.748 frequency (Δ +.019, CI +.012…+.027).257.686.662 recency (Δ CI +.010…+.036)
bash
npm run eval -- --source nebius --repos 5 --max-tasks-per-repo 20 --split test --embeddings off --engine newnpm run eval -- --source omp    --repos 5 --max-tasks-per-repo 20 --embeddings off --engine old   # v0.1 engine (needs a worktree, see src/eval)

Code search: on a 30-query code-search set, the default jina-embeddings-v2-base-code reaches Recall@5 0.867, against 0.667 for the previous MiniLM.

Built on research

[Recent papers mapped to the BrainBox subsystems they shaped]

Each v0.2 change maps to a recent paper and was measured with the replay eval:

SubsystemWhat changedSource
RankingACT-R base-level activation replaces fixed decay. Recurrence and popularity candidates are added. Weighted reciprocal-rank fusion with weights fit on held-out dev repos. Directional STDP; n-gram tool prediction.ACT-R 2505.05083 · Base3 2506.12764 · 2502.04910
Code searchcAST-style AST chunks. FTS5 BM25 + sqlite-vec KNN, fused with RRF (k=60). Incremental by content hash.cAST 2506.15655
Injection policyA contextual UCB1 bandit picks SILENT / TOP1 / TOP3 / TOP5. Reward = files you open or edit, minus token cost.MemCon 2607.13591
AttributionEvery recall is logged with the synapse that produced it; ignored recalls weaken only that edge.MemTrace 2605.28732
Compact injectionInjects a compact path:start-end — why list; deleted files are never injected.FastContext 2606.14066
ProceduresDeterministic mining of failed command → edits → passing rerun, plus multi-session workflows, with helpful/harmful counters.ACE 2510.04618 · Mem^p 2508.06433
Code graphTree-sitter import / call / inheritance edges (TS/JS, Python, Rust, Swift, Go), seeded as weak priors (≤ 0.35) that learned co-access outranks.—
EvaluationOffline replay of SWE-rebench OpenHands trajectories and local sessions, with baselines and paired CIs.SWE-rebench trajectories

Also in 0.2:

  • Builds on Node 22–26 (better-sqlite3 v13).
  • Hooks are written in Claude Code's nested settings format.
  • The hook DB lock wait is capped at 100 ms.
  • Procedure compilation is 470× faster on large histories.

Integrations

MCP server (any agent)

bash
# 8 tools: record, recall (detail: compact|full), explain, error, resolve, predict_next, stats, decaynpx tsx node_modules/brainbox-hebbian/src/mcp.ts

Kilo / OpenCode (native plugin)

Add to ~/.config/kilo/config.json:

json
{  "plugin": ["node_modules/brainbox-hebbian/src/kilo-plugin.ts"]}

OpenClaw (NeuroVault)

BrainBox can run as an OpenClaw memory slot plugin. See NeuroVault for the reference implementation.

AspectClaude CodeOpenClaw
Tool namesPascalCase (Read)Lowercase (read)
Context injectionUserPromptSubmit hookbefore_agent_start lifecycle
Learning triggerPostToolUse hookafter_tool_call lifecycle
Embeddingsjina-embeddings-v2-base-code (configurable)Keyword-only (lower confidence gate)

macOS daemon (opt-in)

A system-wide FSEvents file watcher that learns from VS Code, Xcode, vim and the shell, not just agents. It installs a LaunchAgent, so it requires an explicit opt-in:

bash
brainbox daemon install   # installs LaunchAgent, starts watchingbrainbox daemon statusbrainbox daemon uninstall

CLI

bash
brainbox recall "authentication login"brainbox record src/auth.ts --query "authentication"brainbox stats                 # includes stale-embedding counts + re-index commandsbrainbox error "TypeError: cannot read 'token'"brainbox predict Readbrainbox bootstrap --repo . --imports [--since <git-rev>]   # git history + tree-sitter code graphbrainbox extract-snippets [--force] [--no-embed]           # AST chunks → FTS5 + sqlite-vecbrainbox embed [--force]       # embed neurons with the active modelbrainbox models pull|status    # fetch / inspect the embedding modelbrainbox procedures [list|compile|show <id>|deprecate <id>]brainbox sleep                 # consolidation + procedure compilationbrainbox eval --source nebius|omp [...]                   # offline replay evaluationbrainbox hubs | stale | projects | sessions | streaks | graph | highways | decay
Configuration
VariablePurposeDefault
BRAINBOX_DBSQLite path~/.brainbox/brainbox.db
BRAINBOX_DB_TIMEOUT_MSSQLite busy timeout5000 (hooks use 100)
BRAINBOX_EMBED_MODELminilm | jina-code | gemma | gemma-q4jina-code
BRAINBOX_MODEL_CACHEModel cache directoryTransformers.js default
BRAINBOX_EMBEDDINGSoff disables embeddings entirelyon
BRAINBOX_POLICYoff disables the learned injection policy (always TOP5)on
BRAINBOX_SESSION_IDOverride session id for CLI/adaptersderived
BRAINBOX_HOOKSet by hook entrypoints: local-only models, 1.2 s embedding deadlineunset

Gemma profiles are subject to the Gemma Terms of Use.

Algorithm details
ComponentMechanism (defaults in DEFAULT_ENGINE_OPTIONS)
Synapse formationSequential window (25 items), positional decay; directional STDP (later→earlier edge × 0.5)
StrengtheningSNAP sigmoid plasticity (midpoint 0.5, steepness 8); BCM myelination, 0.95 ceiling
Recency / frequencyACT-R base level B = ln Σ (Δt_h)^-0.5 over the last 50 accesses
File rankingWeighted reciprocal-rank fusion. Channel weights: lexical (FTS5, scaled by verbatim query-term coverage) 4, Hebbian evidence 4, code snippets 4, frequency 2, recency 1, base level 0.5, recurrence 0.2. Session recency gets weight 30 when the query matches the current session.
Spreading3-hop BFS, fan-out cap 10, fan effect 1/sqrt(degree)
Tool predictionLongest-suffix n-grams (n ≤ 3, min support 4) fused with frequency (0.5)
Code searchAST chunks; FTS5 BM25 + sqlite-vec KNN, RRF k=60
Structural priorsimport 0.2, call ≤ 0.35, inherit 0.3; never override learned co-access
Injection policyUCB1 over SILENT/TOP1/TOP3/TOP5; reward = rank-weighted opens/edits − 2 per 1k tokens
Anti-recallIgnored recalls weaken only the producing edge; 1 - (1 - 0.1)^streak, floor 0.1
Error learning2x boosted learning rate; error→fix procedures from failed→edited→passing reruns

The paper's source (v0.2, doi:10.5281/zenodo.23250505) describes the implementation and coverage-conditioned replay results, including uncertainty and provenance limitations. See paper build and evidence notes for the bibliography, aggregate evidence, LaTeX and PDF build.

Architecture
src/  hebbian.ts       # Engine: record, recall (rank fusion), STDP, n-gram tool prediction, decay, anti-recall  db.ts            # SQLite schema + migrations  policy.ts        # Recall event log + contextual UCB1 injection policy  adapter.ts       # Shared recall/injection orchestration for all hosts  snippets.ts      # AST chunking, FTS5 + sqlite-vec hybrid search  embeddings.ts    # Embedding model profiles, hook-safe loading  codegraph.ts     # Tree-sitter import/call/inherit graph  procedures.ts    # Procedural playbook mining + matching  bootstrap.ts     # Git history / code graph / session seeding  installer.ts     # Hooks + MCP registration, model prefetch  mcp.ts           # MCP server (8 tools)  hook.ts          # PostToolUse + SessionEnd hook  prompt-hook.ts   # UserPromptSubmit hook  kilo-plugin.ts   # Kilo/OpenCode native plugin  daemon.ts        # FSEvents file watcher (macOS, opt-in)  cli.ts           # CLI  eval/            # Offline trajectory replay evaluation  testkit.ts       # Test harness; test.ts + tests/*.test.tsscripts/visuals/   # JS generators for the README figures (tbcresearch.org ink style, light + dark)

Development

bash
npm test                      # 147 testsnpx tsx src/test.ts "Ranking" # filter by suite/test namenpm run visuals               # regenerate assets/*.svg (light + dark) from scripts/visuals/scenes/*.mjsbash scripts/visuals/social.sh  # render assets/social-preview.png for GitHub's social preview

Requirements: Node.js 22+, on macOS or Linux. The FSEvents daemon is macOS-only; everything else is cross-platform.


If BrainBox saved your agent some searching, give it a ⭐ so others can find it.
Built by @thebasedcapital · MIT License

來源:README.md,提交 2585acb

工具

0
SourceWeft 尚未在沙箱中啟動過該軟體包,因此其工具未知。

版本歷史

1
  1. v0.1.6最新Sep 16, 2026

評分

已滿足適用檢查項的 50%

該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。

  • 近 30 天內可連通25 分

    請保持端點能夠回應 MCP 握手;SourceWeft 每 30 天探測一次。

  • 已宣告認證方式10 分

    請在註冊中心條目中宣告憑證請求標頭,或保持端點能夠回應探測,以便判定其認證方式。

  • 已列出工具15 分

    請讓伺服器在無憑證時回應 tools/list,或發布可在沙箱中無憑證啟動的軟體包。

  • 描述必需15 分
  • 圖示10 分
  • 文件15 分
  • 授權條款10 分