@timmeck/brain 3.19.0 → 3.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,7 +5,9 @@
5
5
  [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
6
6
  [![GitHub stars](https://img.shields.io/github/stars/timmeck/brain-ecosystem?style=social)](https://github.com/timmeck/brain-ecosystem)
7
7
 
8
- **Adaptive Error Memory, Code Intelligence & Persistent Context MCP Server for Claude Code**
8
+ **Autonomous Error Memory, Code Intelligence & Self-Improving Research System for Claude Code**
9
+
10
+ Brain is an MCP server that gives Claude Code a persistent, self-improving memory. It remembers errors, learns solutions, tracks code modules, and runs 9 autonomous research engines in feedback loops. It observes itself, detects anomalies, forms hypotheses, tests them statistically, distills confirmed knowledge into principles, and generates code using its accumulated wisdom. It even dreams — consolidating memories during idle periods like biological sleep.
9
11
 
10
12
  ## Quick Start
11
13
 
@@ -14,226 +16,142 @@ npm install -g @timmeck/brain
14
16
  brain setup
15
17
  ```
16
18
 
17
- That's it. One command configures MCP, hooks, and starts the daemon. Brain is now learning from every error you encounter.
18
-
19
- ## What Brain Does
19
+ That's it. One command configures MCP, hooks, and starts the daemon.
20
20
 
21
- ### Before Brain: Every session starts from zero
21
+ ## Features
22
22
 
23
- ```
24
- You: Fix this TypeError
25
- Claude: *investigates from scratch, tries 3 approaches, 15 minutes later finds the fix*
23
+ ### Error Memory & Code Intelligence
24
+ - **Error Memory** — Track errors, match against known solutions with hybrid search (TF-IDF + vector + synapse boost)
25
+ - **Code Intelligence** Register and discover reusable code modules across all projects
26
+ - **Proactive Prevention** — Warns before errors occur when code matches known antipatterns
27
+ - **Cross-Project Learning** — Solutions from project A help solve errors in project B
28
+ - **Auto Error Detection** — PostToolUse hook catches errors in real-time
29
+ - **Git Integration** — Links errors to commits, tracks which changes introduced or fixed bugs
26
30
 
27
- Next day, same error in another project:
28
- Claude: *investigates from scratch again*
29
- ```
31
+ ### Persistent Memory
32
+ - **Memory System** Remember preferences, decisions, context, facts, goals, and lessons across sessions
33
+ - **Session Tracking** — Auto-tracks conversation sessions with goals, summaries, and outcomes
34
+ - **Decision History** — Record architecture/design decisions with alternatives and rationale
35
+ - **Semantic Changelog** — Track what changed, why, and how it connects to errors and decisions
36
+ - **Task/Goal Tracking** — Manage tasks with priorities, subtasks, and full context aggregation
37
+ - **Semantic Search** — Local all-MiniLM-L6-v2 embeddings (23MB, no cloud required)
38
+
39
+ ### Autonomous Research (9 Engines)
40
+
41
+ The research orchestrator runs every 5 minutes, coordinating all engines in feedback loops:
42
+
43
+ | Engine | What It Does |
44
+ |--------|-------------|
45
+ | **SelfObserver** | Observes Brain's own performance and generates insights |
46
+ | **AnomalyDetective** | Detects statistical outliers using Z-scores |
47
+ | **CrossDomainEngine** | Finds correlations between events across brains |
48
+ | **AdaptiveStrategy** | Adjusts strategies, reverts if performance drops |
49
+ | **ExperimentEngine** | A/B tests on Brain's own parameters every 5 cycles |
50
+ | **KnowledgeDistiller** | Extracts principles from confirmed hypotheses (17+ distilled) |
51
+ | **ResearchAgenda** | Prioritizes what to research next |
52
+ | **CounterfactualEngine** | "What if" analysis for hypothetical interventions |
53
+ | **Journal** | Logs all discoveries, experiments, breakthroughs |
54
+
55
+ ### Self-Improvement Loop
56
+ - **Hypothesis Engine** — Forms hypotheses from observed patterns, tests them statistically
57
+ - **Auto-Experiments** — Tests its own parameters (Z-Threshold, Decay Rate, Research Interval)
58
+ - **Self-Metrics** — Tracks own cycle data: anomaly_count, insight_count, cycle_duration_ms
59
+ - **Frustration Detection** — If a suggestion is ignored 3x, generates alternative approaches
60
+ - **Improvement Requests** — Writes "Tell Claude:" suggestions to `~/.brain/improvement-requests.md`
61
+ - **Knowledge Distillation** — Confirmed hypotheses become reusable principles
62
+
63
+ ### Dream Mode
64
+ - **Memory Replay** — Spreading Activation strengthens active memory pathways
65
+ - **Synapse Pruning** — Weak connections (weight < 0.15) are deleted
66
+ - **Memory Compression** — Similar memories are clustered and merged
67
+ - **Importance Decay** — Old memories gradually lose importance, eventually archived
68
+ - **Triggers** — Every 20 cycles, after 5 minutes idle, or manually
69
+
70
+ ### Consciousness Dashboard (`:7784`)
71
+ - **Neural Graph** — Force-directed visualization of the synapse network (Canvas 2D physics)
72
+ - **Thought Stream** — Real-time feed of every engine's activity
73
+ - **Engine Status** — Live status cards for all 16 engines
74
+ - **Brain Insights** — Notable discoveries and breakthroughs
75
+ - **Trigger Cycle** — Button to manually trigger a feedback cycle
76
+
77
+ ### Prediction Engine
78
+ - **Holt-Winters** — Double Exponential Smoothing for metric forecasting
79
+ - **EWMA Fallback** — When insufficient data for Holt-Winters
80
+ - **Auto-Calibration** — Confidence calibrated against actual outcomes
81
+ - **Self-Resolving** — Predictions are checked against reality and scored
82
+
83
+ ### AutoResponder
84
+ - **Anomaly Response** — Automatically adjusts parameters when anomalies are detected
85
+ - **Configurable Rules** — Define which anomalies trigger which actions
86
+ - **Cooldown System** — Prevents response storms
87
+ - **Journal Logging** — Every auto-response is logged for review
88
+
89
+ ### Code Generation & Mining
90
+ - **CodeGenerator** — Claude API integration, uses brain knowledge (principles, anti-patterns, strategies, patterns) as context
91
+ - **Human-in-the-Loop** — Generated code is reviewed: approve or reject with notes
92
+ - **CodeMiner** — Mines GitHub repos (README, package.json, directory trees) for pattern learning
93
+ - **PatternExtractor** — Extracts dependency, tech stack, structure, and README patterns from mined repos
94
+ - **CodeGen Dashboard** — Web UI at http://localhost:7787 for reviewing and managing code generations
95
+ - **Signal Scanner** — Tracks GitHub trending repos, Hacker News mentions, crypto signals
96
+
97
+ ### Dashboards
98
+
99
+ | Dashboard | Port | What It Shows |
100
+ |-----------|------|--------------|
101
+ | **Consciousness** | 7784 | Neural graph, thought stream, engine status |
102
+ | **CodeGen** | 7787 | Code generations, approve/reject, mined patterns |
30
103
 
31
- ### After Brain: Errors get solved faster every time
104
+ ## Architecture
32
105
 
33
106
  ```
34
- You: Fix this TypeError
35
- Claude: *Brain found 3 similar errors. Solution with 94% confidence:
36
- "Add null check before accessing .length — this pattern occurs
37
- in array-processing modules across 4 of your projects."*
38
- Fixed in 30 seconds.
39
- ```
40
-
41
- ### Before Brain: Duplicate code everywhere
42
-
107
+ Claude Code / Cursor / Browser
108
+ |
109
+ MCP / HTTP / REST
110
+ |
111
+ +----+----+
112
+ | BrainCore|
113
+ +----+----+
114
+ |
115
+ +------+------+------+------+------+
116
+ | | | | | |
117
+ Error Code Synapse Memory Git Embedding
118
+ Memory Intel Network System Intel Engine
119
+ | | | | | |
120
+ +------+------+------+------+------+
121
+ |
122
+ +------+------+------+------+------+
123
+ | | | | | |
124
+ Research Dream Pred. Auto Code Signal
125
+ Orch. Engine Engine Respond Gen Scanner
126
+ | |
127
+ +-- 9 Engines in Feedback Loops ----+
128
+ |
129
+ SQLite (better-sqlite3, WAL mode)
43
130
  ```
44
- You: Write a retry wrapper with exponential backoff
45
- Claude: *writes a new implementation*
46
131
 
47
- Meanwhile, you already have 3 retry wrappers across different projects.
48
- ```
132
+ ## MCP Tools (69 tools)
49
133
 
50
- ### After Brain: Code is never rewritten
134
+ **Error & Code**: brain_report_error, brain_query_error, brain_report_solution, brain_report_attempt, brain_find_reusable_code, brain_register_code, brain_check_code_similarity
51
135
 
52
- ```
53
- You: Write a retry wrapper
54
- Claude: *Brain found a reusable module: src/utils/retry.ts (project: api-server)
55
- Reusability score: 0.92, used in 4 projects, 12 imports*
56
- ```
136
+ **Memory & Sessions**: brain_remember, brain_recall, brain_session_start, brain_session_end, brain_session_history
57
137
 
58
- ### Before Brain: Errors keep recurring
138
+ **Decisions, Changes, Tasks, Docs**: brain_record_decision, brain_query_decisions, brain_record_change, brain_query_changes, brain_add_task, brain_update_task, brain_list_tasks, brain_task_context, brain_index_project, brain_query_docs, brain_project_context
59
139
 
60
- ```
61
- Week 1: ECONNRESET on API call → fix with retry
62
- Week 2: Same ECONNRESET → debug from scratch
63
- Week 3: Same pattern in different service → no idea it's related
64
- ```
140
+ **Research & Learning**: brain_explore, brain_connections, brain_insights, brain_rate_insight, brain_suggest, brain_explain_learning, brain_override_rule, brain_get_suggestions
65
141
 
66
- ### After Brain: Patterns emerge, prevention kicks in
142
+ **9 Research Engines** (5 tools each): self_observer, anomaly_detective, cross_domain, adaptive_strategy, experiment, knowledge_distiller, research_agenda, counterfactual, journal — each with _status, _list, _get, _summary, _config
67
143
 
68
- ```
69
- Brain: "⚠ Warning: This code matches antipattern #7 — missing connection
70
- timeout on HTTP client. This has caused ECONNRESET in 3 projects.
71
- Suggested fix: add timeout: 5000 to request config."
72
- ```
144
+ **Dream Mode**: brain_dream_status, brain_dream_consolidate, brain_dream_history
73
145
 
74
- ## Features
146
+ **Consciousness**: brain_consciousness_status, brain_consciousness_thoughts
75
147
 
76
- - **Error Memory** — Track errors, match against known solutions with hybrid search (TF-IDF + vector + synapse boost)
77
- - **Code Intelligence** — Register and discover reusable code modules across all projects
78
- - **Persistent Memory** — Remember preferences, decisions, context, facts, goals, and lessons across sessions (new in v2.2)
79
- - **Session Tracking** — Auto-tracks conversation sessions with goals, summaries, and outcomes (new in v2.2)
80
- - **Decision History** — Record architecture/design decisions with alternatives and rationale (new in v2.2)
81
- - **Semantic Changelog** — Track what changed, why, and how it connects to errors and decisions (new in v2.2)
82
- - **Task/Goal Tracking** — Manage tasks with priorities, subtasks, and full context aggregation (new in v2.2)
83
- - **Project Doc Index** — Auto-index README, CLAUDE.md, package.json, tsconfig.json for instant project context (new in v2.2)
84
- - **Hebbian Synapse Network** — Weighted graph where connections strengthen with use ("neurons that fire together wire together")
85
- - **Auto Error Detection** — PostToolUse hook catches errors in real-time, no manual reporting needed
86
- - **Auto Context Capture** — Hooks auto-capture significant commands as context memories (new in v2.2)
87
- - **Cross-Project Learning** — Solutions from project A help solve errors in project B
88
- - **Proactive Prevention** — Warns before errors occur when code matches known antipatterns
89
- - **Semantic Search** — Local all-MiniLM-L6-v2 embeddings (23MB, no cloud required) for vector similarity
90
- - **Learning Engine** — Extracts patterns, generates rules, detects antipatterns with adaptive thresholds
91
- - **Research Engine** — Automated trend analysis, gap detection, cross-project synergy mapping
92
- - **Dream Mode** — Offline memory consolidation: replay, prune, compress, decay during idle periods (new in v3.10)
93
- - **Consciousness Dashboard** — Live neural graph visualization at http://localhost:7784 with real-time thought stream, engine status, and Brain Insights panel (new in v3.11)
94
- - **Prediction Engine** — Holt-Winters forecasting that predicts outcomes, measures against reality, and auto-calibrates confidence over time (new in v3.12)
95
- - **AutoResponder** — Automatically reacts to detected anomalies by adjusting parameters, escalating critical issues, and logging all actions (new in v3.13)
96
- - **Self-Improvement Loop** — Brain analyzes its own state and generates concrete improvement suggestions — writes "Tell Claude:" commands to ~/.brain/improvement-requests.md (new in v3.13)
97
- - **Git Integration** — Links errors to commits, tracks which changes introduced or fixed bugs
98
- - **Universal Access** — MCP (stdio + HTTP/SSE), REST API, works with Claude Code, Cursor, Windsurf, Cline
148
+ **Prediction**: brain_predict, brain_prediction_accuracy, brain_predictions_list
99
149
 
100
- ## Architecture
150
+ **AutoResponder**: brain_responder_status, brain_responder_history, brain_responder_rules
101
151
 
102
- ```
103
- +------------------+ +------------------+ +------------------+
104
- | Claude Code | | Cursor/Windsurf | | Browser/CI/CD |
105
- | (MCP stdio) | | (MCP HTTP/SSE) | | (REST API) |
106
- +--------+---------+ +--------+---------+ +--------+---------+
107
- | | |
108
- v v v
109
- +--------+---------+ +--------+---------+ +--------+---------+
110
- | MCP Server | | MCP HTTP/SSE | | REST API |
111
- | (stdio) | | (port 7778) | | (port 7777) |
112
- +--------+---------+ +--------+---------+ +--------+---------+
113
- | | |
114
- +----------+-------------+------------------------+
115
- |
116
- v
117
- +----------+-----------+
118
- | BrainCore |
119
- | (Daemon / Services) |
120
- +----------+-----------+
121
- |
122
- +-------+-------+--------+--------+--------+
123
- | | | | | |
124
- v v v v v v
125
- +---+--+ +--+---+ +-+-----+ +-+----+ +-+----+ +-+--------+
126
- |Error | |Code | |Synapse| |Git | |Memory| |Embedding |
127
- |Memory| |Brain | |Network| |Intel | |Brain | |Engine |
128
- +---+--+ +--+---+ +-+-----+ +-+----+ +-+----+ +-+--------+
129
- | | | | | |
130
- v v v v v v
131
- +---+--+ +--+---+ +-+-----+ +-+----+ +-+----+ +-+--------+
132
- |Learn | |Module| |Hebbian| |Commit| |Tasks | |Vector |
133
- |Engine| |Score | |Learn | |Track | |Docs | |Search |
134
- +------+ +------+ +-------+ +------+ +------+ +----------+
135
- | | | | | |
136
- v v v v v v
137
- +---+--+ +--+---+ +-+-----+ +-+----+ +-+----+ +-+--------+
138
- |Dream | |Pred. | |Auto | |Think | |Consc.| |Self- |
139
- |Mode | |Engine| |Respond| |Stream| |Dash | |Improve |
140
- +------+ +------+ +-------+ +------+ +------+ +----------+
141
- |
142
- v
143
- +----------+-----------+
144
- | SQLite (DB) |
145
- | better-sqlite3 |
146
- +----------------------+
147
-
148
- Cross-brain peering via IPC named pipes (\\.\pipe\brain-*, /tmp/brain-*)
149
- ```
152
+ **CodeGen**: brain_generate_code, brain_codegen_status, brain_codegen_review, brain_codeminer_status, brain_codeminer_patterns
150
153
 
151
- ### Core Components
152
-
153
- | Component | Purpose |
154
- |-----------|---------|
155
- | **Error Memory** | Stores errors with fingerprints, matches new errors against known ones using hybrid search |
156
- | **Solution Tracker** | Records solutions with success/fail counts, computes Wilson Score confidence |
157
- | **Code Module Registry** | Indexes code across projects — find reusable modules by language, tags, similarity |
158
- | **Memory Brain** | Persistent memory for preferences, decisions, context, facts, goals, and lessons (new in v2.2) |
159
- | **Session Tracker** | Tracks conversation sessions with goals, summaries, and outcomes (new in v2.2) |
160
- | **Decision History** | Records architecture/design decisions with alternatives and rationale (new in v2.2) |
161
- | **Semantic Changelog** | Tracks file changes with context: what, why, related errors/decisions (new in v2.2) |
162
- | **Task Manager** | Task/goal tracking with priorities, subtasks, and full context aggregation (new in v2.2) |
163
- | **Project Doc Index** | Auto-indexes README, CLAUDE.md, package.json for instant project context (new in v2.2) |
164
- | **Synapse Network** | Weighted graph connecting all entities. Hebbian rule: "neurons that fire together wire together" |
165
- | **Learning Engine** | Extracts patterns from error/solution history, generates preventive rules with adaptive thresholds |
166
- | **Research Engine** | Analyzes trends, detects knowledge gaps, finds cross-project synergies |
167
- | **Git Intelligence** | Links errors to commits, tracks which changes introduced or fixed bugs |
168
- | **Embedding Engine** | Local all-MiniLM-L6-v2 model generates 384-dim vectors for semantic search |
169
- | **REST API** | HTTP API exposing all 60+ Brain methods as RESTful endpoints |
170
- | **MCP HTTP Server** | SSE transport enabling non-Claude MCP clients (Cursor, Windsurf, etc.) |
171
-
172
- ## MCP Tools
173
-
174
- These tools are available to Claude Code (and other MCP clients) when Brain is configured:
175
-
176
- | Tool | Description |
177
- |------|-------------|
178
- | **Error Brain** | |
179
- | `brain_report_error` | Report an error; stores and matches against known errors (hybrid search) |
180
- | `brain_query_error` | Search for similar errors and solutions |
181
- | `brain_report_solution` | Report a working solution; Brain learns from it |
182
- | `brain_report_attempt` | Report a failed attempt; Brain learns what doesn't work |
183
- | **Code Brain** | |
184
- | `brain_find_reusable_code` | Search for reusable code modules |
185
- | `brain_register_code` | Register a code module as reusable |
186
- | `brain_check_code_similarity` | Check if similar code exists before writing new code |
187
- | **Memory Brain** (new in v2.2) | |
188
- | `brain_remember` | Store a memory (preference, decision, context, fact, goal, lesson) |
189
- | `brain_recall` | Search memories by natural language query |
190
- | `brain_session_start` | Start a session to track what happens in a conversation |
191
- | `brain_session_end` | End session with summary and outcome |
192
- | `brain_session_history` | Recall past sessions ("what was I working on?") |
193
- | **Decision & Changelog** (new in v2.2) | |
194
- | `brain_record_decision` | Record architecture/design decision with alternatives |
195
- | `brain_query_decisions` | Search past decisions ("why did we choose X?") |
196
- | `brain_record_change` | Record semantic file change (what + why) |
197
- | `brain_query_changes` | Search changelog ("what changed in file X?") |
198
- | **Task Tracking** (new in v2.2) | |
199
- | `brain_add_task` | Add a task/goal with priority and tags |
200
- | `brain_update_task` | Update task status, add notes |
201
- | `brain_list_tasks` | List tasks by status/project |
202
- | `brain_task_context` | Full context: task + related memories, decisions, changes |
203
- | **Project Docs** (new in v2.2) | |
204
- | `brain_index_project` | Scan and index project documentation |
205
- | `brain_query_docs` | Search indexed documentation |
206
- | `brain_project_context` | Full context: docs + tasks + decisions + changes |
207
- | **Synapse & Research** | |
208
- | `brain_explore` | Explore knowledge via spreading activation |
209
- | `brain_connections` | Find how two concepts are connected |
210
- | `brain_insights` | Get research insights (trends, gaps, synergies) |
211
- | `brain_rate_insight` | Rate an insight as useful or not useful |
212
- | `brain_suggest` | Get suggestions on what to build or improve |
213
- | **Learning Explainability** (new in v3.0) | |
214
- | `brain_explain_learning` | Show active learned rules with confidence scores and source data |
215
- | `brain_override_rule` | Override rules — boost, suppress, or delete with rationale |
216
- | **Dream Mode** (new in v3.10) | |
217
- | `brain_dream_status` | Dream engine status and lifetime consolidation stats |
218
- | `brain_dream_consolidate` | Manually trigger a dream consolidation cycle |
219
- | `brain_dream_history` | View past dream consolidation cycles |
220
- | **Consciousness** (new in v3.11) | |
221
- | `brain_consciousness_status` | Live consciousness stats: thoughts, engines, breakthroughs |
222
- | `brain_consciousness_thoughts` | Recent thoughts from all engines with significance levels |
223
- | **Prediction Engine** (new in v3.12) | |
224
- | `brain_predict` | Generate a prediction for a metric using Holt-Winters/EWMA forecasting |
225
- | `brain_prediction_accuracy` | Prediction accuracy stats per domain with calibration score |
226
- | `brain_predictions_list` | List pending/resolved predictions with outcomes |
227
- | **AutoResponder** (new in v3.13) | |
228
- | `brain_responder_status` | AutoResponder status: actions taken, success rate, rules |
229
- | `brain_responder_history` | History of automatic responses to anomalies |
230
- | `brain_responder_rules` | Active response rules that Brain uses to react to anomalies |
231
- | **Status & Ecosystem** | |
232
- | `brain_status` | Current Brain stats (now includes memory and session counts) |
233
- | `brain_notifications` | Get pending notifications |
234
- | `brain_ecosystem_status` | Get status of all brains in the ecosystem |
235
- | `brain_query_peer` | Query another brain in the ecosystem (method + params) |
236
- | `brain_error_trading_context` | Correlate an error with trading outcomes from Trading Brain |
154
+ **Ecosystem**: brain_status, brain_notifications, brain_ecosystem_status, brain_query_peer, brain_error_trading_context
237
155
 
238
156
  ## CLI Commands
239
157
 
@@ -241,102 +159,23 @@ These tools are available to Claude Code (and other MCP clients) when Brain is c
241
159
  brain setup One-command setup: MCP + hooks + daemon
242
160
  brain start Start the Brain daemon
243
161
  brain stop Stop the daemon
244
- brain status Show stats (errors, solutions, modules, synapses, insights)
162
+ brain status Show stats
245
163
  brain doctor Health check: daemon, DB, MCP, hooks
246
- brain projects List all imported projects with module counts
247
164
  brain query <text> Search for errors and solutions
248
165
  brain modules List registered code modules
249
166
  brain insights Show research insights
250
167
  brain network Explore the synapse network
251
- brain learn Trigger a learning cycle manually
252
- brain explain <id> Full error report: solutions, chains, rules, insights
253
- brain rules List active learned rules with confidence bars (new in v3.0)
254
- brain synapses Show strongest synapse connections in the network (new in v3.0)
255
- brain config View and manage Brain configuration
168
+ brain learn Trigger a learning cycle
169
+ brain explain <id> Full error report
170
+ brain rules List active learned rules
171
+ brain synapses Show strongest synapse connections
172
+ brain config View and manage configuration
256
173
  brain export Export Brain data as JSON
257
- brain import <dir> Import a project directory into Brain
258
- brain dashboard Generate interactive HTML dashboard (--live for SSE)
259
- brain peers Show status of peer brains in the ecosystem
260
- ```
261
-
262
- ## REST API
263
-
264
- Brain includes a full REST API on port 7777 (default).
265
-
266
- ### Generic RPC Endpoint
267
-
268
- ```bash
269
- # Call any Brain method
270
- curl -X POST http://localhost:7777/api/v1/rpc \
271
- -H "Content-Type: application/json" \
272
- -d '{"method": "analytics.summary", "params": {}}'
273
-
274
- # Batch multiple calls
275
- curl -X POST http://localhost:7777/api/v1/rpc \
276
- -H "Content-Type: application/json" \
277
- -d '[
278
- {"id": 1, "method": "analytics.summary", "params": {}},
279
- {"id": 2, "method": "synapse.stats", "params": {}}
280
- ]'
281
- ```
282
-
283
- ### RESTful Endpoints
284
-
285
- ```bash
286
- # Errors
287
- GET /api/v1/errors # Query errors
288
- POST /api/v1/errors # Report error
289
- GET /api/v1/errors/:id # Get error by ID
290
- GET /api/v1/errors/:id/match # Find similar errors (hybrid search)
291
- GET /api/v1/errors/:id/chain # Get error chain
292
-
293
- # Solutions
294
- POST /api/v1/solutions # Report solution
295
- GET /api/v1/solutions?errorId=N # Find solutions for error
296
- GET /api/v1/solutions/efficiency # Efficiency analysis
297
-
298
- # Code
299
- POST /api/v1/code/analyze # Analyze and register code
300
- POST /api/v1/code/find # Find reusable code
301
- POST /api/v1/code/similarity # Check code similarity
302
- GET /api/v1/code/modules # List modules
303
-
304
- # Analytics
305
- GET /api/v1/analytics/summary # Brain summary
306
- GET /api/v1/analytics/health # Health score
307
- GET /api/v1/analytics/timeline # Error timeline
308
- GET /api/v1/analytics/explain/:id # Full error explanation
309
-
310
- # Git
311
- GET /api/v1/git/context # Current git info
312
- POST /api/v1/git/link-error # Link error to commit
313
-
314
- # Meta
315
- GET /api/v1/health # API health check
316
- GET /api/v1/methods # List all 60+ available methods
317
- ```
318
-
319
- ### Authentication
320
-
321
- ```bash
322
- BRAIN_API_KEY=your-secret-key brain start
323
- curl -H "X-API-Key: your-secret-key" http://localhost:7777/api/v1/analytics/summary
174
+ brain import <dir> Import a project directory
175
+ brain dashboard Generate interactive HTML dashboard
176
+ brain peers Show peer brains in the ecosystem
324
177
  ```
325
178
 
326
- ## Setup with Cursor / Windsurf / Cline / Continue
327
-
328
- Brain supports MCP over HTTP with SSE transport:
329
-
330
- ```json
331
- {
332
- "brain": {
333
- "url": "http://localhost:7778/sse"
334
- }
335
- }
336
- ```
337
-
338
- Make sure the Brain daemon is running (`brain start`).
339
-
340
179
  ## Configuration
341
180
 
342
181
  | Env Variable | Default | Description |
@@ -346,74 +185,21 @@ Make sure the Brain daemon is running (`brain start`).
346
185
  | `BRAIN_API_PORT` | `7777` | REST API port |
347
186
  | `BRAIN_API_KEY` | — | API authentication key |
348
187
  | `BRAIN_MCP_HTTP_PORT` | `7778` | MCP HTTP/SSE port |
349
- | `BRAIN_API_ENABLED` | `true` | Enable REST API |
350
- | `BRAIN_MCP_HTTP_ENABLED` | `true` | Enable MCP HTTP |
351
188
  | `BRAIN_EMBEDDINGS_ENABLED` | `true` | Enable local embeddings |
352
- | `BRAIN_EMBEDDINGS_MODEL` | `Xenova/all-MiniLM-L6-v2` | Embedding model |
353
- | `BRAIN_CONSCIOUSNESS_PORT` | `7784` | Consciousness dashboard port |
354
-
355
- ## How It Learns
356
-
357
- 1. **Error Reported** — Claude encounters an error (hook catches it automatically or via `brain_report_error`)
358
- 2. **Context Enriched** — Brain captures task context, working directory, command, git branch, and diff
359
- 3. **Hybrid Matched** — Error is compared against known errors using TF-IDF signals, vector embeddings, and synapse proximity
360
- 4. **Solution Found** — When the error is fixed, `brain_report_solution` records the fix
361
- 5. **Synapses Form** — Brain creates weighted connections: error ↔ solution, error ↔ code module, module ↔ dependency
362
- 6. **Confidence Updates** — Wilson Score Interval computes conservative confidence from success/fail history
363
- 7. **Patterns Emerge** — Learning engine extracts recurring patterns with adaptive thresholds
364
- 8. **Research Runs** — Background analysis finds trends, gaps, and cross-project synergies
365
- 9. **Embeddings Computed** — Background sweep generates vector embeddings for semantic search
366
- 10. **Next Time** — When a similar error appears, Brain instantly suggests the proven solution — even from other projects
367
- 11. **Predictions Form** — Prediction Engine forecasts future error rates with Holt-Winters smoothing
368
- 12. **Auto-Response** — AutoResponder detects anomalies and adjusts Brain parameters automatically
369
- 13. **Self-Improvement** — Brain analyzes its own weaknesses and generates improvement suggestions
370
-
371
- ## How It Remembers (v2.2)
372
-
373
- Brain now maintains **persistent context** across sessions:
374
-
375
- 1. **Session Auto-Start** — PreToolUse hook auto-starts a session per working directory
376
- 2. **Context Captured** — Significant commands (npm, git, test, build, deploy) are auto-remembered as context
377
- 3. **Preferences Stored** — User preferences (test framework, code style, tools) are stored with key-based upsert
378
- 4. **Decisions Recorded** — Architecture decisions with alternatives and rationale for "why did we choose X?"
379
- 5. **Changes Tracked** — Semantic changelog links file changes to errors and decisions
380
- 6. **Tasks Managed** — Goals and tasks with priorities, subtasks, and full context aggregation
381
- 7. **Docs Indexed** — README, CLAUDE.md, package.json indexed for instant project context
382
- 8. **Everything Connected** — All new entities join the synapse network, enabling cross-entity discovery
189
+ | `ANTHROPIC_API_KEY` | | Enables CodeGenerator + CodeGen Dashboard |
190
+ | `GITHUB_TOKEN` | | Enables CodeMiner + Signal Scanner |
383
191
 
384
192
  ## Brain Ecosystem
385
193
 
386
- Brain is part of the **[Brain Ecosystem](https://github.com/timmeck/brain-ecosystem)** a monorepo of MCP servers that give Claude Code persistent, self-learning memory.
387
-
388
- | Brain | Purpose | Ports |
389
- |-------|---------|-------|
390
- | **Brain** v3.13.0 | Error memory, code intelligence, persistent context & autonomous research | **7777** / 7778 / 7784 |
391
- | [Trading Brain](https://github.com/timmeck/brain-ecosystem/tree/main/packages/trading-brain) v2.13.0 | Adaptive trading intelligence with memory, sessions & autonomous research | 7779 / 7780 |
392
- | [Marketing Brain](https://github.com/timmeck/brain-ecosystem/tree/main/packages/marketing-brain) v1.14.0 | Content strategy, engagement, campaigns & autonomous research | 7781 / 7782 / 7783 |
393
- | [Brain Core](https://github.com/timmeck/brain-ecosystem/tree/main/packages/brain-core) v2.12.0 | Shared infrastructure (IPC, MCP, REST, CLI, math, synapses, memory, research) | — |
394
- | [Brain Hub](https://timmeck.github.io/brain-hub/) | Ecosystem landing page | — |
395
-
396
- All packages live in the [brain-ecosystem](https://github.com/timmeck/brain-ecosystem) monorepo with npm workspaces. [Brain Core](https://www.npmjs.com/package/@timmeck/brain-core) provides shared infrastructure (IPC, MCP, REST API, CLI, math, synapse algorithms, memory types) used by all brains, eliminating ~2,800 lines of duplicated code.
397
-
398
- ### Cross-Brain Communication
399
-
400
- Brains discover and query each other at runtime via IPC named pipes. Use `brain peers` to see online peers, or the `brain_query_peer` / `brain_ecosystem_status` MCP tools to access peer data from Claude Code. Brains also push event notifications to each other — when Brain reports an error, Trading Brain and Marketing Brain are notified automatically.
401
-
402
- ## Tech Stack
403
-
404
- - **TypeScript** — Full type safety, ES2022 target, ESM modules
405
- - **better-sqlite3** — Fast, embedded, synchronous database
406
- - **MCP SDK** — Model Context Protocol integration (stdio + HTTP/SSE transports)
407
- - **@huggingface/transformers** — Local ONNX-based sentence embeddings (all-MiniLM-L6-v2)
408
- - **Commander** — CLI framework
409
- - **Chalk** — Colored terminal output
410
- - **Winston** — Structured logging
411
- - **Vitest** — Testing
194
+ | Brain | Version | Purpose | Ports |
195
+ |-------|---------|---------|-------|
196
+ | **Brain** | v3.19.0 | Error memory, code intelligence, autonomous research & code generation | **7777** / 7778 / 7784 / 7787 |
197
+ | [Trading Brain](../trading-brain) | v2.13.0 | Adaptive trading intelligence with signal learning & backtesting | 7779 / 7780 / 7785 |
198
+ | [Marketing Brain](../marketing-brain) | v1.14.0 | Content strategy, engagement & cross-platform optimization | 7781 / 7782 / 7783 / 7786 |
199
+ | [Brain Core](../brain-core) | v2.18.0 | Shared infrastructure (9 engines, synapses, IPC, MCP, dream, consciousness, codegen) | |
412
200
 
413
201
  ## Support
414
202
 
415
- If Brain helps you, consider giving it a star — it helps others discover the project and keeps development going.
416
-
417
203
  [![Star this repo](https://img.shields.io/github/stars/timmeck/brain-ecosystem?style=social)](https://github.com/timmeck/brain-ecosystem)
418
204
  [![Sponsor](https://img.shields.io/badge/Sponsor-Support%20Development-ea4aaa)](https://github.com/sponsors/timmeck)
419
205
 
package/dist/brain.d.ts CHANGED
@@ -15,6 +15,8 @@ export declare class BrainCore {
15
15
  private orchestrator;
16
16
  private consciousnessServer;
17
17
  private codegenServer;
18
+ private attentionEngine;
19
+ private transferEngine;
18
20
  private cleanupTimer;
19
21
  private config;
20
22
  private configPath?;
package/dist/brain.js CHANGED
@@ -55,7 +55,7 @@ import { McpHttpServer } from './mcp/http-server.js';
55
55
  // Embeddings
56
56
  import { EmbeddingEngine } from './embeddings/engine.js';
57
57
  // Cross-Brain
58
- import { CrossBrainClient, CrossBrainNotifier, CrossBrainSubscriptionManager, CrossBrainCorrelator, EcosystemService, WebhookService, ExportService, BackupService, AutonomousResearchScheduler, ResearchOrchestrator, DataMiner, BrainDataMinerAdapter, ScannerDataMinerAdapter, DreamEngine, ThoughtStream, ConsciousnessServer, PredictionEngine, SignalScanner, CodeMiner, PatternExtractor, ContextBuilder, CodeGenerator, CodegenServer } from '@timmeck/brain-core';
58
+ import { CrossBrainClient, CrossBrainNotifier, CrossBrainSubscriptionManager, CrossBrainCorrelator, EcosystemService, WebhookService, ExportService, BackupService, AutonomousResearchScheduler, ResearchOrchestrator, DataMiner, BrainDataMinerAdapter, ScannerDataMinerAdapter, DreamEngine, ThoughtStream, ConsciousnessServer, PredictionEngine, SignalScanner, CodeMiner, PatternExtractor, ContextBuilder, CodeGenerator, CodegenServer, AttentionEngine, TransferEngine } from '@timmeck/brain-core';
59
59
  export class BrainCore {
60
60
  db = null;
61
61
  ipcServer = null;
@@ -73,6 +73,8 @@ export class BrainCore {
73
73
  orchestrator = null;
74
74
  consciousnessServer = null;
75
75
  codegenServer = null;
76
+ attentionEngine = null;
77
+ transferEngine = null;
76
78
  cleanupTimer = null;
77
79
  config = null;
78
80
  configPath;
@@ -244,6 +246,19 @@ export class BrainCore {
244
246
  this.orchestrator.setThoughtStream(thoughtStream);
245
247
  dreamEngine.setThoughtStream(thoughtStream);
246
248
  predictionEngine.setThoughtStream(thoughtStream);
249
+ // 11j.5 Attention Engine — dynamic focus & resource allocation
250
+ const attentionEngine = new AttentionEngine(this.db, { brainName: 'brain' });
251
+ attentionEngine.setThoughtStream(thoughtStream);
252
+ this.orchestrator.setAttentionEngine(attentionEngine);
253
+ this.attentionEngine = attentionEngine;
254
+ services.attentionEngine = attentionEngine;
255
+ // 11j.6 Transfer Engine — cross-domain knowledge transfer
256
+ const transferEngine = new TransferEngine(this.db, { brainName: 'brain' });
257
+ transferEngine.setThoughtStream(thoughtStream);
258
+ transferEngine.seedDefaultRules();
259
+ this.orchestrator.setTransferEngine(transferEngine);
260
+ this.transferEngine = transferEngine;
261
+ services.transferEngine = transferEngine;
247
262
  this.consciousnessServer = new ConsciousnessServer({
248
263
  port: 7784,
249
264
  thoughtStream,
@@ -417,6 +432,7 @@ export class BrainCore {
417
432
  this.cleanupTimer = null;
418
433
  }
419
434
  this.subscriptionManager?.disconnectAll();
435
+ this.attentionEngine?.stop();
420
436
  this.codegenServer?.stop();
421
437
  this.consciousnessServer?.stop();
422
438
  this.orchestrator?.stop();