@timmeck/brain-core 2.3.0 → 2.5.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/dist/causal/engine.d.ts +98 -0
- package/dist/causal/engine.js +265 -0
- package/dist/causal/engine.js.map +1 -0
- package/dist/hypothesis/engine.d.ts +104 -0
- package/dist/hypothesis/engine.js +386 -0
- package/dist/hypothesis/engine.js.map +1 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -1
- package/dist/meta-learning/engine.d.ts +108 -0
- package/dist/meta-learning/engine.js +275 -0
- package/dist/meta-learning/engine.js.map +1 -0
- package/dist/research/autonomous-scheduler.d.ts +124 -0
- package/dist/research/autonomous-scheduler.js +411 -0
- package/dist/research/autonomous-scheduler.js.map +1 -0
- package/package.json +6 -2
- package/tsconfig.tsbuildinfo +1 -0
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
import { getLogger } from '../utils/logger.js';
|
|
2
|
+
// ── Migration ───────────────────────────────────────────
|
|
3
|
+
export function runMetaLearningMigration(db) {
|
|
4
|
+
db.exec(`
|
|
5
|
+
CREATE TABLE IF NOT EXISTS meta_learning_snapshots (
|
|
6
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
7
|
+
cycle INTEGER NOT NULL,
|
|
8
|
+
params TEXT NOT NULL,
|
|
9
|
+
metrics TEXT NOT NULL,
|
|
10
|
+
score REAL NOT NULL,
|
|
11
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
12
|
+
);
|
|
13
|
+
|
|
14
|
+
CREATE TABLE IF NOT EXISTS meta_learning_optimizations (
|
|
15
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
16
|
+
param_name TEXT NOT NULL,
|
|
17
|
+
old_value REAL NOT NULL,
|
|
18
|
+
new_value REAL NOT NULL,
|
|
19
|
+
reason TEXT NOT NULL,
|
|
20
|
+
improvement REAL,
|
|
21
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
22
|
+
);
|
|
23
|
+
|
|
24
|
+
CREATE INDEX IF NOT EXISTS idx_meta_snapshots_score ON meta_learning_snapshots(score);
|
|
25
|
+
CREATE INDEX IF NOT EXISTS idx_meta_snapshots_cycle ON meta_learning_snapshots(cycle);
|
|
26
|
+
`);
|
|
27
|
+
}
|
|
28
|
+
// ── Engine ───────────────────────────────────────────────
|
|
29
|
+
/**
|
|
30
|
+
* Meta-Learning Engine: observes learning cycle outcomes over time
|
|
31
|
+
* and auto-tunes hyperparameters using gradient-free optimization.
|
|
32
|
+
*
|
|
33
|
+
* Research approach: Bayesian-inspired parameter search.
|
|
34
|
+
* - After each learning cycle, record a snapshot (params + metrics + effectiveness score)
|
|
35
|
+
* - Periodically analyze: which parameter configurations produced the best scores?
|
|
36
|
+
* - Use perturbation: try small changes to parameters, measure improvement, keep what works
|
|
37
|
+
* - Implements "explore vs exploit": 80% exploit best known, 20% explore new configurations
|
|
38
|
+
*/
|
|
39
|
+
export class MetaLearningEngine {
|
|
40
|
+
db;
|
|
41
|
+
params;
|
|
42
|
+
logger = getLogger();
|
|
43
|
+
cycleCount = 0;
|
|
44
|
+
analyzeInterval; // analyze every N cycles
|
|
45
|
+
explorationRate; // % of cycles spent exploring (0-1)
|
|
46
|
+
constructor(db, params, config) {
|
|
47
|
+
this.db = db;
|
|
48
|
+
this.params = params;
|
|
49
|
+
runMetaLearningMigration(db);
|
|
50
|
+
this.analyzeInterval = config?.analyzeInterval ?? 5;
|
|
51
|
+
this.explorationRate = config?.explorationRate ?? 0.2;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Record a learning cycle's outcome. Called after each learning cycle.
|
|
55
|
+
* @param metrics - the raw metrics from the cycle (e.g. newPatterns, updatedRules, prunedRules)
|
|
56
|
+
* @param score - a composite effectiveness score (higher = better)
|
|
57
|
+
*/
|
|
58
|
+
recordSnapshot(metrics, score) {
|
|
59
|
+
this.cycleCount++;
|
|
60
|
+
const currentParams = {};
|
|
61
|
+
for (const p of this.params) {
|
|
62
|
+
currentParams[p.name] = p.value;
|
|
63
|
+
}
|
|
64
|
+
this.db.prepare(`
|
|
65
|
+
INSERT INTO meta_learning_snapshots (cycle, params, metrics, score)
|
|
66
|
+
VALUES (?, ?, ?, ?)
|
|
67
|
+
`).run(this.cycleCount, JSON.stringify(currentParams), JSON.stringify(metrics), score);
|
|
68
|
+
const snapshot = {
|
|
69
|
+
cycle: this.cycleCount,
|
|
70
|
+
params: currentParams,
|
|
71
|
+
metrics,
|
|
72
|
+
score,
|
|
73
|
+
};
|
|
74
|
+
this.logger.debug(`Meta-learning snapshot #${this.cycleCount}: score=${score.toFixed(3)}`);
|
|
75
|
+
return snapshot;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Analyze snapshots and recommend parameter changes.
|
|
79
|
+
* Uses a simplified approach inspired by Bayesian optimization:
|
|
80
|
+
* - Group snapshots by parameter ranges
|
|
81
|
+
* - Find which ranges produced the best average scores
|
|
82
|
+
* - Recommend moving towards those ranges
|
|
83
|
+
*/
|
|
84
|
+
analyze() {
|
|
85
|
+
const snapshots = this.getSnapshots(50); // last 50 cycles
|
|
86
|
+
if (snapshots.length < 5)
|
|
87
|
+
return []; // need minimum data
|
|
88
|
+
const recommendations = [];
|
|
89
|
+
for (const param of this.params) {
|
|
90
|
+
const rec = this.analyzeParameter(param, snapshots);
|
|
91
|
+
if (rec)
|
|
92
|
+
recommendations.push(rec);
|
|
93
|
+
}
|
|
94
|
+
return recommendations;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Apply recommendations: perturb parameters towards better configurations.
|
|
98
|
+
* Returns the parameters that were changed.
|
|
99
|
+
*/
|
|
100
|
+
optimize() {
|
|
101
|
+
const recommendations = this.analyze();
|
|
102
|
+
const applied = [];
|
|
103
|
+
for (const rec of recommendations) {
|
|
104
|
+
if (rec.confidence < 0.3)
|
|
105
|
+
continue; // skip low-confidence recommendations
|
|
106
|
+
if (Math.abs(rec.expectedImprovement) < 0.01)
|
|
107
|
+
continue; // skip negligible improvements
|
|
108
|
+
const param = this.params.find(p => p.name === rec.name);
|
|
109
|
+
if (!param)
|
|
110
|
+
continue;
|
|
111
|
+
// Explore vs exploit: sometimes try random perturbations
|
|
112
|
+
const exploring = Math.random() < this.explorationRate;
|
|
113
|
+
let newValue;
|
|
114
|
+
if (exploring) {
|
|
115
|
+
// Random perturbation within bounds
|
|
116
|
+
const range = param.max - param.min;
|
|
117
|
+
newValue = param.value + (Math.random() - 0.5) * range * 0.2;
|
|
118
|
+
}
|
|
119
|
+
else {
|
|
120
|
+
// Move towards recommended value
|
|
121
|
+
newValue = rec.recommendedValue;
|
|
122
|
+
}
|
|
123
|
+
// Clamp to bounds
|
|
124
|
+
newValue = Math.max(param.min, Math.min(param.max, newValue));
|
|
125
|
+
// Record optimization
|
|
126
|
+
this.db.prepare(`
|
|
127
|
+
INSERT INTO meta_learning_optimizations (param_name, old_value, new_value, reason, improvement)
|
|
128
|
+
VALUES (?, ?, ?, ?, ?)
|
|
129
|
+
`).run(param.name, param.value, newValue, exploring ? 'exploration' : 'exploitation', rec.expectedImprovement);
|
|
130
|
+
this.logger.info(`Meta-learning: ${param.name} ${param.value.toFixed(4)} → ${newValue.toFixed(4)} (${exploring ? 'explore' : 'exploit'}, expected +${(rec.expectedImprovement * 100).toFixed(1)}%)`);
|
|
131
|
+
param.value = newValue;
|
|
132
|
+
rec.recommendedValue = newValue;
|
|
133
|
+
applied.push(rec);
|
|
134
|
+
}
|
|
135
|
+
return applied;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Run analysis + optimization if it's time. Call this after every learning cycle.
|
|
139
|
+
*/
|
|
140
|
+
step(metrics, score) {
|
|
141
|
+
const snapshot = this.recordSnapshot(metrics, score);
|
|
142
|
+
let optimized = [];
|
|
143
|
+
if (this.cycleCount > 0 && this.cycleCount % this.analyzeInterval === 0) {
|
|
144
|
+
optimized = this.optimize();
|
|
145
|
+
}
|
|
146
|
+
return { snapshot, optimized };
|
|
147
|
+
}
|
|
148
|
+
/** Get current parameter values. */
|
|
149
|
+
getParams() {
|
|
150
|
+
const result = {};
|
|
151
|
+
for (const p of this.params) {
|
|
152
|
+
result[p.name] = p.value;
|
|
153
|
+
}
|
|
154
|
+
return result;
|
|
155
|
+
}
|
|
156
|
+
/** Update a parameter value externally (e.g. user override). */
|
|
157
|
+
setParam(name, value) {
|
|
158
|
+
const param = this.params.find(p => p.name === name);
|
|
159
|
+
if (!param)
|
|
160
|
+
return false;
|
|
161
|
+
param.value = Math.max(param.min, Math.min(param.max, value));
|
|
162
|
+
return true;
|
|
163
|
+
}
|
|
164
|
+
/** Get learning effectiveness status. */
|
|
165
|
+
getStatus() {
|
|
166
|
+
const snapshots = this.getSnapshots(100);
|
|
167
|
+
const optimizations = this.db.prepare('SELECT COUNT(*) as count FROM meta_learning_optimizations').get();
|
|
168
|
+
const scores = snapshots.map(s => s.score);
|
|
169
|
+
const currentScore = scores.length > 0 ? scores[0] : 0;
|
|
170
|
+
const bestScore = scores.length > 0 ? Math.max(...scores) : 0;
|
|
171
|
+
const worstScore = scores.length > 0 ? Math.min(...scores) : 0;
|
|
172
|
+
// Trend detection: compare average of last 5 vs previous 5
|
|
173
|
+
let trend = 'stable';
|
|
174
|
+
if (scores.length >= 10) {
|
|
175
|
+
const recent = scores.slice(0, 5).reduce((a, b) => a + b, 0) / 5;
|
|
176
|
+
const previous = scores.slice(5, 10).reduce((a, b) => a + b, 0) / 5;
|
|
177
|
+
const delta = recent - previous;
|
|
178
|
+
if (delta > 0.05)
|
|
179
|
+
trend = 'improving';
|
|
180
|
+
else if (delta < -0.05)
|
|
181
|
+
trend = 'declining';
|
|
182
|
+
}
|
|
183
|
+
return {
|
|
184
|
+
totalSnapshots: snapshots.length,
|
|
185
|
+
totalOptimizations: optimizations.count,
|
|
186
|
+
bestScore,
|
|
187
|
+
worstScore,
|
|
188
|
+
currentScore,
|
|
189
|
+
trend,
|
|
190
|
+
recommendations: this.analyze(),
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
/** Get optimization history. */
|
|
194
|
+
getHistory(limit = 20) {
|
|
195
|
+
return this.db.prepare('SELECT * FROM meta_learning_optimizations ORDER BY created_at DESC LIMIT ?').all(limit);
|
|
196
|
+
}
|
|
197
|
+
// ── Private ─────────────────────────────────────────
|
|
198
|
+
getSnapshots(limit) {
|
|
199
|
+
const rows = this.db.prepare('SELECT * FROM meta_learning_snapshots ORDER BY cycle DESC LIMIT ?').all(limit);
|
|
200
|
+
return rows.map(r => ({
|
|
201
|
+
id: r.id,
|
|
202
|
+
cycle: r.cycle,
|
|
203
|
+
params: JSON.parse(r.params),
|
|
204
|
+
metrics: JSON.parse(r.metrics),
|
|
205
|
+
score: r.score,
|
|
206
|
+
created_at: r.created_at,
|
|
207
|
+
}));
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Analyze a single parameter's effect on learning effectiveness.
|
|
211
|
+
*
|
|
212
|
+
* Algorithm:
|
|
213
|
+
* 1. Divide the parameter's range into bins
|
|
214
|
+
* 2. For each bin, calculate the average score of snapshots in that bin
|
|
215
|
+
* 3. Find the bin with the highest average score
|
|
216
|
+
* 4. Recommend moving towards the center of that bin
|
|
217
|
+
*/
|
|
218
|
+
analyzeParameter(param, snapshots) {
|
|
219
|
+
const numBins = 5;
|
|
220
|
+
const range = param.max - param.min;
|
|
221
|
+
if (range <= 0)
|
|
222
|
+
return null;
|
|
223
|
+
const binSize = range / numBins;
|
|
224
|
+
// Accumulate scores per bin
|
|
225
|
+
const bins = Array.from({ length: numBins }, () => ({ sum: 0, count: 0 }));
|
|
226
|
+
for (const snap of snapshots) {
|
|
227
|
+
const val = snap.params[param.name];
|
|
228
|
+
if (val === undefined)
|
|
229
|
+
continue;
|
|
230
|
+
const binIdx = Math.min(numBins - 1, Math.floor((val - param.min) / binSize));
|
|
231
|
+
bins[binIdx].sum += snap.score;
|
|
232
|
+
bins[binIdx].count++;
|
|
233
|
+
}
|
|
234
|
+
// Find best bin (minimum 2 samples)
|
|
235
|
+
let bestBin = -1;
|
|
236
|
+
let bestAvg = -Infinity;
|
|
237
|
+
let totalSamples = 0;
|
|
238
|
+
for (let i = 0; i < numBins; i++) {
|
|
239
|
+
if (bins[i].count < 2)
|
|
240
|
+
continue;
|
|
241
|
+
const avg = bins[i].sum / bins[i].count;
|
|
242
|
+
totalSamples += bins[i].count;
|
|
243
|
+
if (avg > bestAvg) {
|
|
244
|
+
bestAvg = avg;
|
|
245
|
+
bestBin = i;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
if (bestBin === -1)
|
|
249
|
+
return null; // not enough data
|
|
250
|
+
// Calculate recommended value (center of best bin)
|
|
251
|
+
const recommended = param.min + (bestBin + 0.5) * binSize;
|
|
252
|
+
// Skip if current value is already in or near the best bin
|
|
253
|
+
const currentBin = Math.min(numBins - 1, Math.floor((param.value - param.min) / binSize));
|
|
254
|
+
if (currentBin === bestBin)
|
|
255
|
+
return null;
|
|
256
|
+
// Estimate improvement
|
|
257
|
+
const currentBinAvg = bins[currentBin].count > 0
|
|
258
|
+
? bins[currentBin].sum / bins[currentBin].count
|
|
259
|
+
: 0;
|
|
260
|
+
const expectedImprovement = currentBinAvg > 0
|
|
261
|
+
? (bestAvg - currentBinAvg) / currentBinAvg
|
|
262
|
+
: 0;
|
|
263
|
+
// Confidence: based on sample count in best bin
|
|
264
|
+
const confidence = Math.min(1, bins[bestBin].count / 10);
|
|
265
|
+
return {
|
|
266
|
+
name: param.name,
|
|
267
|
+
currentValue: param.value,
|
|
268
|
+
recommendedValue: recommended,
|
|
269
|
+
expectedImprovement,
|
|
270
|
+
confidence,
|
|
271
|
+
evidence: totalSamples,
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
//# sourceMappingURL=engine.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"engine.js","sourceRoot":"","sources":["../../src/meta-learning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
|
|
1
|
+
import type Database from 'better-sqlite3';
|
|
2
|
+
import { MetaLearningEngine } from '../meta-learning/engine.js';
|
|
3
|
+
import type { HyperParameter } from '../meta-learning/engine.js';
|
|
4
|
+
import { CausalGraph } from '../causal/engine.js';
|
|
5
|
+
import { HypothesisEngine } from '../hypothesis/engine.js';
|
|
6
|
+
export interface ResearchDiscovery {
|
|
7
|
+
id?: number;
|
|
8
|
+
type: 'causal_chain' | 'confirmed_hypothesis' | 'parameter_optimization' | 'anomaly' | 'root_cause';
|
|
9
|
+
title: string;
|
|
10
|
+
description: string;
|
|
11
|
+
confidence: number;
|
|
12
|
+
impact: number;
|
|
13
|
+
source: string;
|
|
14
|
+
data: Record<string, unknown>;
|
|
15
|
+
created_at?: string;
|
|
16
|
+
}
|
|
17
|
+
export interface ResearchCycleReport {
|
|
18
|
+
cycle: number;
|
|
19
|
+
timestamp: number;
|
|
20
|
+
causalEdgesFound: number;
|
|
21
|
+
causalChainsFound: number;
|
|
22
|
+
hypothesesGenerated: number;
|
|
23
|
+
hypothesesTested: number;
|
|
24
|
+
hypothesesConfirmed: number;
|
|
25
|
+
hypothesesRejected: number;
|
|
26
|
+
parametersOptimized: number;
|
|
27
|
+
discoveriesProduced: number;
|
|
28
|
+
duration: number;
|
|
29
|
+
}
|
|
30
|
+
export interface AutonomousResearchConfig {
|
|
31
|
+
/** How often to run the full research cycle (ms). Default: 600_000 (10 min) */
|
|
32
|
+
intervalMs?: number;
|
|
33
|
+
/** Initial delay before first cycle (ms). Default: 30_000 (30s) */
|
|
34
|
+
initialDelayMs?: number;
|
|
35
|
+
/** Brain name for event attribution. */
|
|
36
|
+
brainName: string;
|
|
37
|
+
/** Hyperparameters for meta-learning. */
|
|
38
|
+
hyperParams?: HyperParameter[];
|
|
39
|
+
/** Minimum causal edge strength to produce a discovery. Default: 0.3 */
|
|
40
|
+
minCausalStrength?: number;
|
|
41
|
+
/** Maximum discoveries per cycle. Default: 10 */
|
|
42
|
+
maxDiscoveriesPerCycle?: number;
|
|
43
|
+
}
|
|
44
|
+
export declare function runResearchDiscoveryMigration(db: Database.Database): void;
|
|
45
|
+
/**
|
|
46
|
+
* Autonomous Research Scheduler: orchestrates the three research engines
|
|
47
|
+
* into a self-running discovery pipeline.
|
|
48
|
+
*
|
|
49
|
+
* Flow:
|
|
50
|
+
* 1. External code calls onLearningCycleComplete() after each learning cycle
|
|
51
|
+
* → feeds metrics into MetaLearningEngine
|
|
52
|
+
* → records causal events
|
|
53
|
+
* → records observations for hypothesis engine
|
|
54
|
+
*
|
|
55
|
+
* 2. On a timer (every intervalMs), runs a full research cycle:
|
|
56
|
+
* a. Run causal analysis → detect cause-effect relationships
|
|
57
|
+
* b. Auto-generate hypotheses from observation patterns
|
|
58
|
+
* c. Test all pending hypotheses
|
|
59
|
+
* d. Run meta-learning optimization (if enough data)
|
|
60
|
+
* e. Produce discoveries from confirmed hypotheses + causal chains
|
|
61
|
+
* f. Store everything in SQLite
|
|
62
|
+
*/
|
|
63
|
+
export declare class AutonomousResearchScheduler {
|
|
64
|
+
private db;
|
|
65
|
+
private logger;
|
|
66
|
+
private timer;
|
|
67
|
+
private delayTimer;
|
|
68
|
+
private cycleCount;
|
|
69
|
+
private running;
|
|
70
|
+
readonly metaLearning: MetaLearningEngine;
|
|
71
|
+
readonly causalGraph: CausalGraph;
|
|
72
|
+
readonly hypothesisEngine: HypothesisEngine;
|
|
73
|
+
private brainName;
|
|
74
|
+
private intervalMs;
|
|
75
|
+
private initialDelayMs;
|
|
76
|
+
private minCausalStrength;
|
|
77
|
+
private maxDiscoveriesPerCycle;
|
|
78
|
+
constructor(db: Database.Database, config: AutonomousResearchConfig);
|
|
79
|
+
/** Start the autonomous research timer. */
|
|
80
|
+
start(): void;
|
|
81
|
+
/** Stop the autonomous research timer. */
|
|
82
|
+
stop(): void;
|
|
83
|
+
/**
|
|
84
|
+
* Call this after each learning cycle completes.
|
|
85
|
+
* Feeds the cycle results into all three research engines.
|
|
86
|
+
*/
|
|
87
|
+
onLearningCycleComplete(metrics: Record<string, number>, score: number, eventType?: string): void;
|
|
88
|
+
/**
|
|
89
|
+
* Record a domain event for causal + hypothesis tracking.
|
|
90
|
+
* Call this from event listeners in each brain.
|
|
91
|
+
*/
|
|
92
|
+
recordEvent(eventType: string, data?: Record<string, unknown>): void;
|
|
93
|
+
/**
|
|
94
|
+
* Run one full autonomous research cycle.
|
|
95
|
+
* This is the core algorithm — the system thinking about itself.
|
|
96
|
+
*/
|
|
97
|
+
runCycle(): ResearchCycleReport;
|
|
98
|
+
/** Get all discoveries, optionally filtered by type. */
|
|
99
|
+
getDiscoveries(type?: string, limit?: number): ResearchDiscovery[];
|
|
100
|
+
/** Get cycle reports. */
|
|
101
|
+
getCycleReports(limit?: number): ResearchCycleReport[];
|
|
102
|
+
/** Get a comprehensive research status. */
|
|
103
|
+
getStatus(): {
|
|
104
|
+
cyclesCompleted: number;
|
|
105
|
+
totalDiscoveries: number;
|
|
106
|
+
discoveryBreakdown: Record<string, number>;
|
|
107
|
+
metaLearningStatus: ReturnType<MetaLearningEngine['getStatus']>;
|
|
108
|
+
causalAnalysis: ReturnType<CausalGraph['getAnalysis']>;
|
|
109
|
+
hypothesisSummary: ReturnType<HypothesisEngine['getSummary']>;
|
|
110
|
+
lastCycleReport: ResearchCycleReport | null;
|
|
111
|
+
isRunning: boolean;
|
|
112
|
+
};
|
|
113
|
+
private safeRunCycle;
|
|
114
|
+
/**
|
|
115
|
+
* Produce discoveries from research findings.
|
|
116
|
+
* This is where data becomes insight.
|
|
117
|
+
*/
|
|
118
|
+
private produceDiscoveries;
|
|
119
|
+
private findSignificantRoots;
|
|
120
|
+
private isDuplicateDiscovery;
|
|
121
|
+
private storeDiscovery;
|
|
122
|
+
private storeCycleReport;
|
|
123
|
+
private emptyReport;
|
|
124
|
+
}
|