@timmeck/brain 1.1.1 → 1.8.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.
Files changed (139) hide show
  1. package/README.md +225 -50
  2. package/dist/api/server.d.ts +19 -0
  3. package/dist/api/server.js +281 -0
  4. package/dist/api/server.js.map +1 -0
  5. package/dist/brain.d.ts +3 -0
  6. package/dist/brain.js +45 -8
  7. package/dist/brain.js.map +1 -1
  8. package/dist/cli/commands/dashboard.js +2 -0
  9. package/dist/cli/commands/dashboard.js.map +1 -1
  10. package/dist/cli/commands/doctor.d.ts +2 -0
  11. package/dist/cli/commands/doctor.js +118 -0
  12. package/dist/cli/commands/doctor.js.map +1 -0
  13. package/dist/cli/commands/explain.d.ts +2 -0
  14. package/dist/cli/commands/explain.js +76 -0
  15. package/dist/cli/commands/explain.js.map +1 -0
  16. package/dist/cli/commands/projects.d.ts +2 -0
  17. package/dist/cli/commands/projects.js +36 -0
  18. package/dist/cli/commands/projects.js.map +1 -0
  19. package/dist/code/analyzer.d.ts +6 -0
  20. package/dist/code/analyzer.js +35 -0
  21. package/dist/code/analyzer.js.map +1 -1
  22. package/dist/code/matcher.d.ts +11 -1
  23. package/dist/code/matcher.js +49 -0
  24. package/dist/code/matcher.js.map +1 -1
  25. package/dist/code/scorer.d.ts +1 -0
  26. package/dist/code/scorer.js +15 -1
  27. package/dist/code/scorer.js.map +1 -1
  28. package/dist/config.js +31 -0
  29. package/dist/config.js.map +1 -1
  30. package/dist/dashboard/server.d.ts +15 -0
  31. package/dist/dashboard/server.js +124 -0
  32. package/dist/dashboard/server.js.map +1 -0
  33. package/dist/db/migrations/007_feedback.d.ts +2 -0
  34. package/dist/db/migrations/007_feedback.js +12 -0
  35. package/dist/db/migrations/007_feedback.js.map +1 -0
  36. package/dist/db/migrations/008_git_integration.d.ts +2 -0
  37. package/dist/db/migrations/008_git_integration.js +37 -0
  38. package/dist/db/migrations/008_git_integration.js.map +1 -0
  39. package/dist/db/migrations/009_embeddings.d.ts +2 -0
  40. package/dist/db/migrations/009_embeddings.js +7 -0
  41. package/dist/db/migrations/009_embeddings.js.map +1 -0
  42. package/dist/db/migrations/index.js +6 -0
  43. package/dist/db/migrations/index.js.map +1 -1
  44. package/dist/db/repositories/code-module.repository.d.ts +16 -0
  45. package/dist/db/repositories/code-module.repository.js +42 -0
  46. package/dist/db/repositories/code-module.repository.js.map +1 -1
  47. package/dist/db/repositories/error.repository.d.ts +5 -0
  48. package/dist/db/repositories/error.repository.js +27 -0
  49. package/dist/db/repositories/error.repository.js.map +1 -1
  50. package/dist/db/repositories/insight.repository.d.ts +2 -0
  51. package/dist/db/repositories/insight.repository.js +13 -0
  52. package/dist/db/repositories/insight.repository.js.map +1 -1
  53. package/dist/embeddings/engine.d.ts +42 -0
  54. package/dist/embeddings/engine.js +166 -0
  55. package/dist/embeddings/engine.js.map +1 -0
  56. package/dist/hooks/post-tool-use.js +2 -0
  57. package/dist/hooks/post-tool-use.js.map +1 -1
  58. package/dist/hooks/post-write.js +11 -0
  59. package/dist/hooks/post-write.js.map +1 -1
  60. package/dist/index.js +7 -1
  61. package/dist/index.js.map +1 -1
  62. package/dist/ipc/router.d.ts +2 -0
  63. package/dist/ipc/router.js +15 -0
  64. package/dist/ipc/router.js.map +1 -1
  65. package/dist/learning/confidence-scorer.d.ts +16 -0
  66. package/dist/learning/confidence-scorer.js +20 -0
  67. package/dist/learning/confidence-scorer.js.map +1 -1
  68. package/dist/learning/learning-engine.js +12 -5
  69. package/dist/learning/learning-engine.js.map +1 -1
  70. package/dist/matching/error-matcher.d.ts +9 -1
  71. package/dist/matching/error-matcher.js +50 -5
  72. package/dist/matching/error-matcher.js.map +1 -1
  73. package/dist/mcp/http-server.d.ts +14 -0
  74. package/dist/mcp/http-server.js +117 -0
  75. package/dist/mcp/http-server.js.map +1 -0
  76. package/dist/mcp/tools.d.ts +4 -0
  77. package/dist/mcp/tools.js +41 -14
  78. package/dist/mcp/tools.js.map +1 -1
  79. package/dist/services/analytics.service.d.ts +39 -0
  80. package/dist/services/analytics.service.js +111 -0
  81. package/dist/services/analytics.service.js.map +1 -1
  82. package/dist/services/code.service.d.ts +10 -0
  83. package/dist/services/code.service.js +73 -4
  84. package/dist/services/code.service.js.map +1 -1
  85. package/dist/services/error.service.d.ts +17 -1
  86. package/dist/services/error.service.js +90 -12
  87. package/dist/services/error.service.js.map +1 -1
  88. package/dist/services/git.service.d.ts +49 -0
  89. package/dist/services/git.service.js +112 -0
  90. package/dist/services/git.service.js.map +1 -0
  91. package/dist/services/prevention.service.d.ts +7 -0
  92. package/dist/services/prevention.service.js +38 -0
  93. package/dist/services/prevention.service.js.map +1 -1
  94. package/dist/services/research.service.d.ts +1 -0
  95. package/dist/services/research.service.js +4 -0
  96. package/dist/services/research.service.js.map +1 -1
  97. package/dist/services/solution.service.d.ts +10 -0
  98. package/dist/services/solution.service.js +48 -0
  99. package/dist/services/solution.service.js.map +1 -1
  100. package/dist/types/config.types.d.ts +21 -0
  101. package/dist/types/synapse.types.d.ts +1 -1
  102. package/package.json +8 -3
  103. package/src/api/server.ts +321 -0
  104. package/src/brain.ts +50 -8
  105. package/src/cli/commands/dashboard.ts +2 -0
  106. package/src/cli/commands/doctor.ts +118 -0
  107. package/src/cli/commands/explain.ts +83 -0
  108. package/src/cli/commands/projects.ts +42 -0
  109. package/src/code/analyzer.ts +40 -0
  110. package/src/code/matcher.ts +67 -2
  111. package/src/code/scorer.ts +13 -1
  112. package/src/config.ts +24 -0
  113. package/src/dashboard/server.ts +142 -0
  114. package/src/db/migrations/007_feedback.ts +13 -0
  115. package/src/db/migrations/008_git_integration.ts +38 -0
  116. package/src/db/migrations/009_embeddings.ts +8 -0
  117. package/src/db/migrations/index.ts +6 -0
  118. package/src/db/repositories/code-module.repository.ts +53 -0
  119. package/src/db/repositories/error.repository.ts +40 -0
  120. package/src/db/repositories/insight.repository.ts +21 -0
  121. package/src/embeddings/engine.ts +217 -0
  122. package/src/hooks/post-tool-use.ts +2 -0
  123. package/src/hooks/post-write.ts +12 -0
  124. package/src/index.ts +7 -1
  125. package/src/ipc/router.ts +19 -0
  126. package/src/learning/confidence-scorer.ts +33 -0
  127. package/src/learning/learning-engine.ts +13 -5
  128. package/src/matching/error-matcher.ts +55 -4
  129. package/src/mcp/http-server.ts +137 -0
  130. package/src/mcp/tools.ts +52 -14
  131. package/src/services/analytics.service.ts +136 -0
  132. package/src/services/code.service.ts +99 -4
  133. package/src/services/error.service.ts +114 -13
  134. package/src/services/git.service.ts +132 -0
  135. package/src/services/prevention.service.ts +40 -0
  136. package/src/services/research.service.ts +5 -0
  137. package/src/services/solution.service.ts +58 -0
  138. package/src/types/config.types.ts +24 -0
  139. package/src/types/synapse.types.ts +1 -0
package/README.md CHANGED
@@ -9,21 +9,61 @@ Brain is an MCP server that gives Claude Code a persistent memory. It remembers
9
9
  Without Brain, Claude Code starts fresh every session. With Brain:
10
10
 
11
11
  - **Errors are solved faster** — Brain matches new errors against its database and suggests proven solutions with confidence scores
12
+ - **Cross-project learning** — Brain remembers fixes from your other projects and suggests them automatically
12
13
  - **Code is never rewritten** — Before writing new code, Brain checks if similar modules already exist across your projects
13
14
  - **Patterns emerge automatically** — The research engine analyzes your codebase to find trends, gaps, and synergies
14
15
  - **Knowledge compounds** — Every fix, every module, every session makes Brain smarter
16
+ - **Errors are caught automatically** — Hooks detect errors in real-time and report them to Brain without manual intervention
17
+ - **Proactive prevention** — Brain warns you BEFORE an error occurs when it detects code matching known antipatterns
18
+ - **Semantic search** — Local embeddings enable vector-based similarity search alongside TF-IDF matching
19
+ - **Universal access** — REST API and MCP over HTTP make Brain available to any tool, IDE, or CI/CD pipeline
15
20
 
16
21
  ## Features
17
22
 
23
+ ### Core Intelligence
18
24
  - **Error Memory** — Track errors, match against known solutions, learn from successes and failures
19
25
  - **Code Intelligence** — Register and discover reusable code modules across projects
20
26
  - **Hebbian Synapse Network** — Weighted graph connecting errors, solutions, code modules, and concepts. Connections strengthen with use (like biological synapses)
21
27
  - **Spreading Activation** — Explore related knowledge by activating nodes in the synapse network
22
28
  - **Research Engine** — Automated analysis producing actionable insights: trends, gaps, synergies, template candidates
23
- - **Learning Engine** — Pattern extraction, rule generation, confidence decay, antipattern detection
24
- - **Interactive Dashboard** — HTML dashboard with live stats, language distribution, and categorized insights
25
- - **Full CLI** — Query, explore, and manage Brain from the terminal
26
- - **MCP Integration** — 13 tools exposed to Claude Code via Model Context Protocol
29
+ - **Learning Engine** — Pattern extraction, rule generation, confidence decay, antipattern detection with adaptive thresholds
30
+
31
+ ### Smart Matching (v1.3+)
32
+ - **Context Enrichment** — Errors are enriched with task context, working directory, and command information
33
+ - **Error Chain Tracking** — Detects when errors cascade from fix attempts ("this error arose while fixing error #12")
34
+ - **Module Similarity** — Pairwise similarity detection finds duplicate code across projects
35
+ - **Cyclomatic Complexity** — Complexity metrics flow into reusability scores
36
+ - **Source Hash Detection** — Skips re-analysis for unchanged modules, triggers re-analysis on changes
37
+ - **Dependency Synapses** — Internal imports create `depends_on` synapses, enriching the network
38
+
39
+ ### Advanced Intelligence (v1.4+)
40
+ - **Cross-Project Transfer Learning** — Matches errors against resolved errors from ALL projects, not just the current one
41
+ - **Proactive Prevention** — Post-write hook checks new code against known antipatterns before errors occur
42
+ - **Adaptive Thresholds** — Learning thresholds auto-calibrate based on data volume (10 errors vs. 500 errors need different sensitivity)
43
+ - **User Feedback Loop** — Rate insights and rules as useful/not useful to improve future analysis
44
+
45
+ ### Visualization (v1.5+)
46
+ - **Live Dashboard** — SSE-powered real-time dashboard with streaming stats
47
+ - **Health Score** — Single-number indicator of how well Brain is performing
48
+ - **Error Timeline** — Daily error counts over time, per project
49
+ - **Error Explain** — Full "medical record" of any error: solutions, chains, related errors, rules, insights
50
+
51
+ ### Git Integration (v1.6+)
52
+ - **Commit Linking** — Link errors to git commits (introduced_by, fixed_by)
53
+ - **Diff-Aware Context** — Captures current git diff and branch when errors occur
54
+ - **Commit History** — Track which commits introduced errors and which fixed them
55
+
56
+ ### Universal Access (v1.7+)
57
+ - **REST API** — Full HTTP API on port 7777 with RESTful routes + generic RPC endpoint
58
+ - **MCP over HTTP/SSE** — Standard MCP protocol over HTTP for Cursor, Windsurf, Cline, Continue, and other tools
59
+ - **Batch RPC** — Send multiple API calls in a single request
60
+ - **API Key Auth** — Optional authentication via `X-API-Key` header
61
+
62
+ ### Semantic Search (v1.8+)
63
+ - **Local Embeddings** — all-MiniLM-L6-v2 (23MB) runs locally via ONNX, no cloud required
64
+ - **Hybrid Search** — Triple-signal matching: TF-IDF + Vector Similarity + Synapse Boost
65
+ - **Background Sweep** — Embeddings are computed automatically for all entries
66
+ - **Graceful Fallback** — Works without embeddings; vector search enhances but isn't required
27
67
 
28
68
  ## Quick Start
29
69
 
@@ -44,55 +84,76 @@ npm run build
44
84
 
45
85
  ### Setup with Claude Code
46
86
 
47
- Add Brain to your Claude Code MCP configuration (`~/.claude/settings.json`):
87
+ Add Brain's MCP server and auto-detect hook to your Claude Code configuration (`~/.claude/settings.json`):
48
88
 
49
89
  ```json
50
90
  {
51
91
  "mcpServers": {
52
92
  "brain": {
53
- "command": "node",
54
- "args": ["/path/to/brain/dist/mcp/server.js"]
93
+ "command": "brain",
94
+ "args": ["mcp-server"]
55
95
  }
96
+ },
97
+ "hooks": {
98
+ "PostToolUse": [
99
+ {
100
+ "matcher": {
101
+ "tool_name": "Bash"
102
+ },
103
+ "command": "node C:\\Users\\<YOU>\\AppData\\Roaming\\npm\\node_modules\\@timmeck\\brain\\dist\\hooks\\post-tool-use.js"
104
+ }
105
+ ]
56
106
  }
57
107
  }
58
108
  ```
59
109
 
60
- Optionally, add hooks to auto-report errors and solutions:
110
+ > **Note:** Replace `<YOU>` with your Windows username. On macOS/Linux, the path is the global npm prefix (run `npm prefix -g` to find it).
111
+
112
+ ### Setup with Cursor / Windsurf / Cline / Continue
113
+
114
+ Brain v1.7+ supports MCP over HTTP with SSE transport. Add this to your tool's MCP config:
61
115
 
62
116
  ```json
63
117
  {
64
- "hooks": {
65
- "postToolUse": [
66
- {
67
- "matcher": "Bash",
68
- "command": "node /path/to/brain/dist/hooks/post-tool-use.js"
69
- }
70
- ]
118
+ "brain": {
119
+ "url": "http://localhost:7778/sse"
71
120
  }
72
121
  }
73
122
  ```
74
123
 
124
+ Make sure the Brain daemon is running (`brain start`).
125
+
75
126
  ### Start the Daemon
76
127
 
77
128
  ```bash
78
129
  brain start
79
130
  brain status
131
+ brain doctor # verify everything is configured correctly
80
132
  ```
81
133
 
82
- The daemon runs background tasks: learning cycles, research analysis, synapse maintenance, and confidence decay.
134
+ The daemon runs background tasks: learning cycles, research analysis, synapse maintenance, confidence decay, and embedding computation.
135
+
136
+ ### Import Your Projects
137
+
138
+ ```bash
139
+ brain import ./my-project
140
+ brain projects # see all imported projects
141
+ ```
142
+
143
+ Brain scans for source files (TypeScript, JavaScript, Python, Rust, Go, Shell, HTML, CSS, JSON, YAML, TOML, Markdown, SQL, and more) and registers code modules with reusability scores.
83
144
 
84
145
  ## Architecture
85
146
 
86
147
  ```
87
148
  +------------------+ +------------------+ +------------------+
88
- | Claude Code | | CLI | | Dashboard |
89
- | (MCP Client) | | (Commander) | | (HTML) |
149
+ | Claude Code | | Cursor/Windsurf | | Browser/CI/CD |
150
+ | (MCP stdio) | | (MCP HTTP/SSE) | | (REST API) |
90
151
  +--------+---------+ +--------+---------+ +--------+---------+
91
152
  | | |
92
153
  v v v
93
154
  +--------+---------+ +--------+---------+ +--------+---------+
94
- | MCP Server | | IPC Client | | IPC Client |
95
- | (stdio) | | | | |
155
+ | MCP Server | | MCP HTTP/SSE | | REST API |
156
+ | (stdio) | | (port 7778) | | (port 7777) |
96
157
  +--------+---------+ +--------+---------+ +--------+---------+
97
158
  | | |
98
159
  +----------+-------------+------------------------+
@@ -103,19 +164,19 @@ The daemon runs background tasks: learning cycles, research analysis, synapse ma
103
164
  | (Daemon / Services) |
104
165
  +----------+-----------+
105
166
  |
106
- +---------------+----------------+
107
- | | |
108
- v v v
109
- +---+----+ +------+------+ +----+--------+
110
- | Error | | Synapse | | Research |
111
- | Memory | | Network | | Engine |
112
- +---+----+ +------+------+ +----+--------+
113
- | | |
114
- v v v
115
- +---+----+ +------+------+ +----+--------+
116
- | Learn | | Hebbian | | Insights |
117
- | Engine | | Learning | | Generator |
118
- +--------+ +-------------+ +-------------+
167
+ +-------+-------+--------+--------+
168
+ | | | | |
169
+ v v v v v
170
+ +---+--+ +--+---+ +-+-----+ +-+----+ +-+--------+
171
+ |Error | |Code | |Synapse| |Git | |Embedding |
172
+ |Memory| |Brain | |Network| |Intel | |Engine |
173
+ +---+--+ +--+---+ +-+-----+ +-+----+ +-+--------+
174
+ | | | | |
175
+ v v v v v
176
+ +---+--+ +--+---+ +-+-----+ +-+----+ +-+--------+
177
+ |Learn | |Module| |Hebbian| |Commit| |Vector |
178
+ |Engine| |Score | |Learn | |Track | |Search |
179
+ +------+ +------+ +-------+ +------+ +----------+
119
180
  |
120
181
  v
121
182
  +----------+-----------+
@@ -128,12 +189,16 @@ The daemon runs background tasks: learning cycles, research analysis, synapse ma
128
189
 
129
190
  | Component | Purpose |
130
191
  |-----------|---------|
131
- | **Error Memory** | Stores errors with fingerprints, matches new errors against known ones |
192
+ | **Error Memory** | Stores errors with fingerprints, matches new errors against known ones using hybrid search |
132
193
  | **Solution Tracker** | Records solutions with success/fail counts, computes Wilson Score confidence |
133
194
  | **Code Module Registry** | Indexes code across projects — find reusable modules by language, tags, similarity |
134
195
  | **Synapse Network** | Weighted graph connecting all entities. Hebbian rule: "neurons that fire together wire together" |
135
- | **Learning Engine** | Extracts patterns from error/solution history, generates preventive rules |
196
+ | **Learning Engine** | Extracts patterns from error/solution history, generates preventive rules with adaptive thresholds |
136
197
  | **Research Engine** | Analyzes trends, detects knowledge gaps, finds cross-project synergies |
198
+ | **Git Intelligence** | Links errors to commits, tracks which changes introduced or fixed bugs |
199
+ | **Embedding Engine** | Local all-MiniLM-L6-v2 model generates 384-dim vectors for semantic search |
200
+ | **REST API** | HTTP API exposing all 40+ Brain methods as RESTful endpoints |
201
+ | **MCP HTTP Server** | SSE transport enabling non-Claude MCP clients (Cursor, Windsurf, etc.) |
137
202
 
138
203
  ## CLI Commands
139
204
 
@@ -141,22 +206,27 @@ The daemon runs background tasks: learning cycles, research analysis, synapse ma
141
206
  brain start Start the Brain daemon
142
207
  brain stop Stop the daemon
143
208
  brain status Show stats (errors, solutions, modules, synapses, insights)
209
+ brain doctor Health check: daemon, DB, MCP, hooks
210
+ brain projects List all imported projects with module counts
144
211
  brain query <text> Search for errors and solutions
145
212
  brain modules List registered code modules
146
213
  brain insights Show research insights
147
214
  brain network Explore the synapse network
148
- brain export Export Brain data
149
- brain import <file> Import data into Brain
150
- brain dashboard Generate interactive HTML dashboard
215
+ brain learn Trigger a learning cycle manually
216
+ brain explain <id> Full error report: solutions, chains, rules, insights
217
+ brain config View and manage Brain configuration
218
+ brain export Export Brain data as JSON
219
+ brain import <dir> Import a project directory into Brain
220
+ brain dashboard Generate interactive HTML dashboard (--live for SSE)
151
221
  ```
152
222
 
153
223
  ## MCP Tools
154
224
 
155
- These tools are available to Claude Code when Brain is configured as an MCP server:
225
+ These tools are available to Claude Code (and other MCP clients) when Brain is configured:
156
226
 
157
227
  | Tool | Description |
158
228
  |------|-------------|
159
- | `brain_report_error` | Report an error; stores and matches against known errors |
229
+ | `brain_report_error` | Report an error; stores and matches against known errors (hybrid search) |
160
230
  | `brain_query_error` | Search for similar errors and solutions |
161
231
  | `brain_report_solution` | Report a working solution; Brain learns from it |
162
232
  | `brain_report_attempt` | Report a failed attempt; Brain learns what doesn't work |
@@ -166,26 +236,131 @@ These tools are available to Claude Code when Brain is configured as an MCP serv
166
236
  | `brain_explore` | Explore knowledge via spreading activation |
167
237
  | `brain_connections` | Find how two concepts are connected |
168
238
  | `brain_insights` | Get research insights (trends, gaps, synergies) |
239
+ | `brain_rate_insight` | Rate an insight as useful or not useful |
169
240
  | `brain_suggest` | Get suggestions on what to build or improve |
170
241
  | `brain_status` | Current Brain stats |
171
242
  | `brain_notifications` | Get pending notifications |
172
243
 
244
+ ## REST API
245
+
246
+ Brain v1.7+ includes a full REST API on port 7777 (default).
247
+
248
+ ### Generic RPC Endpoint
249
+
250
+ ```bash
251
+ # Call any Brain method
252
+ curl -X POST http://localhost:7777/api/v1/rpc \
253
+ -H "Content-Type: application/json" \
254
+ -d '{"method": "analytics.summary", "params": {}}'
255
+
256
+ # Batch multiple calls
257
+ curl -X POST http://localhost:7777/api/v1/rpc \
258
+ -H "Content-Type: application/json" \
259
+ -d '[
260
+ {"id": 1, "method": "analytics.summary", "params": {}},
261
+ {"id": 2, "method": "synapse.stats", "params": {}}
262
+ ]'
263
+ ```
264
+
265
+ ### RESTful Endpoints
266
+
267
+ ```bash
268
+ # Errors
269
+ GET /api/v1/errors # Query errors
270
+ POST /api/v1/errors # Report error
271
+ GET /api/v1/errors/:id # Get error by ID
272
+ GET /api/v1/errors/:id/match # Find similar errors (hybrid search)
273
+ GET /api/v1/errors/:id/chain # Get error chain
274
+
275
+ # Solutions
276
+ POST /api/v1/solutions # Report solution
277
+ GET /api/v1/solutions?errorId=N # Find solutions for error
278
+ GET /api/v1/solutions/efficiency # Efficiency analysis
279
+
280
+ # Code
281
+ POST /api/v1/code/analyze # Analyze and register code
282
+ POST /api/v1/code/find # Find reusable code
283
+ POST /api/v1/code/similarity # Check code similarity
284
+ GET /api/v1/code/modules # List modules
285
+
286
+ # Analytics
287
+ GET /api/v1/analytics/summary # Brain summary
288
+ GET /api/v1/analytics/health # Health score
289
+ GET /api/v1/analytics/timeline # Error timeline
290
+ GET /api/v1/analytics/explain/:id # Full error explanation
291
+
292
+ # Git
293
+ GET /api/v1/git/context # Current git info
294
+ POST /api/v1/git/link-error # Link error to commit
295
+
296
+ # Meta
297
+ GET /api/v1/health # API health check
298
+ GET /api/v1/methods # List all 40+ available methods
299
+ ```
300
+
301
+ ### Authentication
302
+
303
+ Set an API key via environment variable:
304
+
305
+ ```bash
306
+ BRAIN_API_KEY=your-secret-key brain start
307
+ ```
308
+
309
+ Then include it in requests:
310
+
311
+ ```bash
312
+ curl -H "X-API-Key: your-secret-key" http://localhost:7777/api/v1/analytics/summary
313
+ ```
314
+
315
+ ## Configuration
316
+
317
+ Brain is configured via `config.json` in the data directory or environment variables:
318
+
319
+ | Env Variable | Default | Description |
320
+ |---|---|---|
321
+ | `BRAIN_DATA_DIR` | `~/.brain` | Data directory |
322
+ | `BRAIN_LOG_LEVEL` | `info` | Log level |
323
+ | `BRAIN_API_PORT` | `7777` | REST API port |
324
+ | `BRAIN_API_KEY` | — | API authentication key |
325
+ | `BRAIN_MCP_HTTP_PORT` | `7778` | MCP HTTP/SSE port |
326
+ | `BRAIN_API_ENABLED` | `true` | Enable REST API |
327
+ | `BRAIN_MCP_HTTP_ENABLED` | `true` | Enable MCP HTTP |
328
+ | `BRAIN_EMBEDDINGS_ENABLED` | `true` | Enable local embeddings |
329
+ | `BRAIN_EMBEDDINGS_MODEL` | `Xenova/all-MiniLM-L6-v2` | Embedding model |
330
+
331
+ ## Auto Error Detection
332
+
333
+ When the PostToolUse hook is configured, Brain automatically:
334
+
335
+ 1. **Captures errors** — Detects errors from Bash command output (exit codes, error patterns like `TypeError`, `ENOENT`, `npm ERR!`, `BUILD FAILED`, etc.)
336
+ 2. **Reports to Brain** — Sends the error to the daemon for storage and matching
337
+ 3. **Suggests solutions** — If Brain has seen a similar error before, it outputs a hint via stderr
338
+ 4. **Checks antipatterns** — Warns if the error matches a known antipattern
339
+ 5. **Checks code** — PostWrite hook proactively checks new code against known error patterns
340
+
341
+ This happens silently in the background — no manual intervention needed.
342
+
173
343
  ## How It Learns
174
344
 
175
- 1. **Error Reported** — Claude encounters an error and reports it via `brain_report_error`
176
- 2. **Solution Found** — When the error is fixed, `brain_report_solution` records the fix
177
- 3. **Synapses Form** — Brain creates weighted connections: error <-> solution, error <-> code module
178
- 4. **Confidence Updates** — Wilson Score Interval computes conservative confidence from success/fail history
179
- 5. **Patterns Emerge** — Learning engine extracts recurring patterns and generates preventive rules
180
- 6. **Research Runs** — Background analysis finds trends, gaps, and cross-project synergies
181
- 7. **Next Time** — When a similar error appears, Brain instantly suggests the proven solution
345
+ 1. **Error Reported** — Claude encounters an error and reports it via `brain_report_error` (or the hook catches it automatically)
346
+ 2. **Context Enriched** — Brain captures task context, working directory, command, git branch, and diff
347
+ 3. **Hybrid Matched** — Error is compared against known errors using TF-IDF signals, vector embeddings, and synapse proximity
348
+ 4. **Solution Found** — When the error is fixed, `brain_report_solution` records the fix
349
+ 5. **Synapses Form** — Brain creates weighted connections: error solution, error ↔ code module, module ↔ dependency
350
+ 6. **Confidence Updates** — Wilson Score Interval computes conservative confidence from success/fail history
351
+ 7. **Patterns Emerge** — Learning engine extracts recurring patterns with adaptive thresholds
352
+ 8. **Research Runs** — Background analysis finds trends, gaps, and cross-project synergies
353
+ 9. **Embeddings Computed** — Background sweep generates vector embeddings for semantic search
354
+ 10. **Next Time** — When a similar error appears, Brain instantly suggests the proven solution — even from other projects
182
355
 
183
356
  ## Tech Stack
184
357
 
185
- - **TypeScript** — Full type safety
186
- - **better-sqlite3** — Fast, embedded database
187
- - **MCP SDK** — Model Context Protocol integration
358
+ - **TypeScript** — Full type safety, ES2022 target, ESM modules
359
+ - **better-sqlite3** — Fast, embedded, synchronous database
360
+ - **MCP SDK** — Model Context Protocol integration (stdio + HTTP/SSE transports)
361
+ - **@huggingface/transformers** — Local ONNX-based sentence embeddings (all-MiniLM-L6-v2)
188
362
  - **Commander** — CLI framework
363
+ - **Chalk** — Colored terminal output
189
364
  - **Winston** — Structured logging
190
365
  - **Vitest** — Testing
191
366
 
@@ -0,0 +1,19 @@
1
+ import type { IpcRouter } from '../ipc/router.js';
2
+ export interface ApiServerOptions {
3
+ port: number;
4
+ router: IpcRouter;
5
+ apiKey?: string;
6
+ }
7
+ export declare class ApiServer {
8
+ private options;
9
+ private server;
10
+ private logger;
11
+ private routes;
12
+ constructor(options: ApiServerOptions);
13
+ start(): void;
14
+ stop(): void;
15
+ private handleRequest;
16
+ private buildRoutes;
17
+ private json;
18
+ private readBody;
19
+ }