@timmeck/brain-core
v2.27.0
Published
Shared core infrastructure for the Brain ecosystem — IPC, MCP, CLI, DB connection, and utilities
Maintainers
Readme
Brain Core
Shared infrastructure for the Brain Ecosystem — 9 research engines, synapses, IPC, MCP, dream mode, consciousness, prediction, code generation, and more.
Brain Core is the nervous system that powers all three Brain MCP servers (Brain, Trading Brain, Marketing Brain). All packages live in the brain-ecosystem monorepo.
What's Included
Communication & API
| Module | Description | |--------|-------------| | IPC Protocol | Length-prefixed JSON frames over named pipes / Unix sockets | | IPC Server | Named pipe server with auto-recovery of stale pipes | | IPC Client | Request/response with timeouts and notification support | | MCP Server | Stdio transport for Claude Code with auto-daemon-start | | MCP HTTP Server | SSE transport for Cursor, Windsurf, Cline, Continue | | REST API Server | HTTP server with CORS, auth, SSE events, batch RPC | | IPC Validation | Parameter validation (string 10KB, array 1000, depth 10) | | IPC Errors | Structured errors: IpcError, ValidationError, NotFoundError, TimeoutError | | Security Middleware | RateLimiter (token bucket), body size limits, security headers |
Synapse Network & Learning
| Module | Description | |--------|-------------| | Hebbian Learning | Weighted graph — "neurons that fire together wire together" | | Synapse Decay | Exponential half-life decay for freshness | | Spreading Activation | BFS-based energy propagation through the graph | | A Pathfinding* | Find shortest paths between nodes | | BaseSynapseManager | Abstract manager with strengthen/weaken/activate/findPath/decay | | BaseLearningEngine | Abstract timer-managed learning engine | | BaseResearchEngine | Abstract timer-managed research engine | | BaseMemoryEngine | Abstract memory engine for expiry/consolidation/decay | | Wilson Score | Statistical confidence intervals for win rates | | Time Decay | Exponential half-life decay for rule freshness |
9 Autonomous Research Engines
| Engine | Description | |--------|-------------| | SelfObserver | Brain observes its own performance metrics and generates insights | | AnomalyDetective | Detects statistical outliers using Z-scores and drift analysis | | CrossDomainEngine | Finds correlations between events across different brains | | AdaptiveStrategy | Adjusts strategies based on outcomes, reverts if performance drops | | ExperimentEngine | Designs and runs A/B tests on brain parameters | | KnowledgeDistiller | Extracts principles from confirmed hypotheses | | ResearchAgenda | Prioritizes what should be researched next | | CounterfactualEngine | "What if" analysis — estimates impact of hypothetical interventions | | ResearchJournal | Logs all discoveries, experiments, and breakthroughs |
Orchestration & Autonomy
| Module | Description | |--------|-------------| | ResearchOrchestrator | Feedback loops between all 9 engines, runs every 5 minutes | | DataMiner | Bootstraps historical DB data into engines with adapter pattern | | AutonomousResearchScheduler | Self-directed research cycle execution | | MetaLearningEngine | Hyper-parameter optimization with Bayesian exploration | | CausalGraph | Granger causality analysis for event relationships | | HypothesisEngine | Forms and tests hypotheses (temporal, correlation, threshold, frequency) | | AutoResponder | Anomaly → automatic parameter adjustment, escalation, resolution | | PredictionEngine | Holt-Winters + EWMA forecasting with auto-calibration |
Dream Mode & Consciousness
| Module | Description | |--------|-------------| | DreamEngine | Offline memory consolidation — replay, prune, compress, decay | | DreamConsolidator | 4 phases: Memory Replay, Synapse Pruning, Compression, Importance Decay | | ThoughtStream | Circular buffer capturing every engine's thoughts in real-time | | ConsciousnessServer | HTTP + SSE server with live neural dashboard (force-directed graph) |
Code Generation & Mining
| Module | Description | |--------|-------------| | CodeGenerator | Claude API integration — generates code using brain knowledge as context | | ContextBuilder | Builds system prompts from principles, anti-patterns, strategies, patterns | | CodeMiner | Mines GitHub repos: README, package.json, directory structures | | PatternExtractor | Extracts dependency, tech stack, structure, and README patterns | | CodegenServer | HTTP + SSE dashboard for code review with approve/reject workflow | | SignalScanner | GitHub trending repos, Hacker News, crypto signal tracking |
Cross-Brain & Services
| Module | Description | |--------|-------------| | CrossBrainClient | Discover and query peer brains over IPC | | CrossBrainNotifier | Push event notifications to peers | | CrossBrainCorrelator | Correlate events across brains (error-trade-loss, publish-during-errors) | | EcosystemService | Aggregated status, health score 0–100, analytics | | WebhookService | HMAC-SHA256 signed webhooks with exponential retry | | ExportService | JSON/CSV export with date range and column filters | | BackupService | Timestamped SQLite backups with integrity verification |
Utilities
| Module | Description |
|--------|-------------|
| DB Connection | SQLite (better-sqlite3) with WAL mode, foreign keys, caching |
| Logger | Winston-based structured logging with file rotation |
| Event Bus | Generic typed event emitter |
| CLI Colors | Shared color palette, formatting helpers (header, table, badges) |
| Config Loader | deepMerge() + loadConfigFile() for layered config |
| Embedding Engine | Local vector embeddings with @huggingface/transformers |
| Memory Types | Shared types for Memory, Session, Remember/Recall interfaces |
Installation
npm install @timmeck/brain-coreUsage
Building a new Brain
import {
createConnection, IpcServer, startMcpServer,
ResearchOrchestrator, DreamEngine, ThoughtStream,
ConsciousnessServer, PredictionEngine,
} from '@timmeck/brain-core';
// 1. Database
const db = createConnection('~/.my-brain/my-brain.db');
// 2. Research Orchestrator (all 9 engines)
const orchestrator = new ResearchOrchestrator(db, { brainName: 'my-brain' });
orchestrator.start();
// 3. Dream Mode
const dreamEngine = new DreamEngine(db, { brainName: 'my-brain' });
orchestrator.setDreamEngine(dreamEngine);
dreamEngine.start();
// 4. Consciousness
const thoughtStream = new ThoughtStream();
orchestrator.setThoughtStream(thoughtStream);
const consciousness = new ConsciousnessServer({ port: 7790, thoughtStream, ... });
consciousness.start();
// 5. Predictions
const prediction = new PredictionEngine(db, { brainName: 'my-brain' });
orchestrator.setPredictionEngine(prediction);
prediction.start();Architecture
@timmeck/brain-core
├── IPC ────────── protocol, server, client, validation, errors
├── MCP ────────── stdio server, HTTP/SSE server
├── API ────────── BaseApiServer, RateLimiter, security middleware
├── Synapses ───── Hebbian, Decay, Activation, Pathfinder, BaseSynapseManager
├── Research ───── ResearchOrchestrator, DataMiner, 9 Engines
│ ├── Engines ── SelfObserver, AnomalyDetective, Experiment, Adaptive, Agenda
│ ├── Engines ── KnowledgeDistiller, Counterfactual, CrossDomain, Journal
│ └── AutoResp ─ AutoResponder (anomaly → action)
├── Dream ──────── DreamEngine, DreamConsolidator
├── Consciousness ThoughtStream, ConsciousnessServer
├── Prediction ─── PredictionEngine, Holt-Winters, EWMA, Calibration
├── CodeGen ────── CodeGenerator, CodeMiner, PatternExtractor, ContextBuilder, CodegenServer
├── Scanner ────── SignalScanner, GitHubCollector, HnCollector, CryptoCollector
├── Autonomous ─── AutonomousResearchScheduler, MetaLearningEngine
├── Causal ─────── CausalGraph (Granger causality)
├── Hypothesis ─── HypothesisEngine
├── Cross-Brain ── Client, Notifier, Correlator, Subscriptions
├── Ecosystem ──── EcosystemService, health scoring
├── Webhooks ───── WebhookService (HMAC, retry, history)
├── Export ─────── ExportService (JSON/CSV)
├── Backup ─────── BackupService (timestamped, integrity check)
├── Memory ─────── BaseMemoryEngine, types, interfaces
├── Math ──────── Wilson Score, Time Decay
├── Config ─────── deepMerge, loadConfigFile
├── Dashboard ──── DashboardServer, Hub, Research dashboard
├── CLI ────────── colors, formatting
├── DB ─────────── SQLite connection (WAL mode)
└── Utils ─────── hash, logger, paths, eventsBrain Ecosystem
| Brain | Version | Purpose | Ports | |-------|---------|---------|-------| | Brain | v3.19.0 | Error memory, code intelligence, autonomous research & code generation | 7777/7778/7784/7787 | | Trading Brain | v2.13.0 | Adaptive trading intelligence with signal learning & backtesting | 7779/7780/7785 | | Marketing Brain | v1.14.0 | Content strategy, engagement & cross-platform optimization | 7781/7782/7783/7786 | | Brain Core | v2.18.0 | Shared infrastructure (this package) | — |
