@timmeck/brain-core 2.31.1 → 2.32.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.
@@ -36,6 +36,8 @@ import type { GoalEngine } from '../goals/goal-engine.js';
36
36
  import type { EvolutionEngine } from '../metacognition/evolution-engine.js';
37
37
  import type { ReasoningEngine } from '../reasoning/reasoning-engine.js';
38
38
  import type { EmotionalModel } from '../emotional/emotional-model.js';
39
+ import type { SelfScanner } from '../self-scanner/self-scanner.js';
40
+ import type { SelfModificationEngine } from '../self-modification/self-modification-engine.js';
39
41
  import { AutoResponder } from './auto-responder.js';
40
42
  export interface ResearchOrchestratorConfig {
41
43
  brainName: string;
@@ -60,6 +62,7 @@ export declare class ResearchOrchestrator {
60
62
  readonly journal: ResearchJournal;
61
63
  readonly autoResponder: AutoResponder;
62
64
  readonly hypothesisEngine: HypothesisEngine;
65
+ readonly causalGraph: CausalGraph | null;
63
66
  private dataMiner;
64
67
  private dreamEngine;
65
68
  private thoughtStream;
@@ -85,6 +88,8 @@ export declare class ResearchOrchestrator {
85
88
  private evolutionEngine;
86
89
  private reasoningEngine;
87
90
  private emotionalModel;
91
+ private selfScanner;
92
+ private selfModificationEngine;
88
93
  private brainName;
89
94
  private feedbackTimer;
90
95
  private cycleCount;
@@ -145,6 +150,10 @@ export declare class ResearchOrchestrator {
145
150
  /** Set the ReasoningEngine — multi-step logical inference chains. */
146
151
  setReasoningEngine(engine: ReasoningEngine): void;
147
152
  setEmotionalModel(model: EmotionalModel): void;
153
+ /** Set the SelfScanner — indexes own source code for self-modification context. */
154
+ setSelfScanner(scanner: SelfScanner): void;
155
+ /** Set the SelfModificationEngine — generates and applies code changes autonomously. */
156
+ setSelfModificationEngine(engine: SelfModificationEngine): void;
148
157
  /** Set the PredictionEngine — wires journal into it. */
149
158
  setPredictionEngine(engine: PredictionEngine): void;
150
159
  /** Start the autonomous feedback loop timer. */
@@ -191,6 +200,8 @@ export declare class ResearchOrchestrator {
191
200
  /** Append improvement suggestions to ~/.brain/improvement-requests.md.
192
201
  * Skips writing if suggestions are identical to the last write (dedup). */
193
202
  private writeSuggestionsToFile;
203
+ /** Find a concrete self-improvement suggestion that maps to specific files. */
204
+ private findActionableSuggestion;
194
205
  /** Get a comprehensive research summary for dashboards/API. */
195
206
  getSummary(): Record<string, unknown>;
196
207
  }
@@ -26,6 +26,7 @@ export class ResearchOrchestrator {
26
26
  journal;
27
27
  autoResponder;
28
28
  hypothesisEngine;
29
+ causalGraph;
29
30
  dataMiner = null;
30
31
  dreamEngine = null;
31
32
  thoughtStream = null;
@@ -51,6 +52,8 @@ export class ResearchOrchestrator {
51
52
  evolutionEngine = null;
52
53
  reasoningEngine = null;
53
54
  emotionalModel = null;
55
+ selfScanner = null;
56
+ selfModificationEngine = null;
54
57
  brainName;
55
58
  feedbackTimer = null;
56
59
  cycleCount = 0;
@@ -69,11 +72,12 @@ export class ResearchOrchestrator {
69
72
  this.distillEvery = config.distillEvery ?? 5;
70
73
  this.agendaEvery = config.agendaEvery ?? 3;
71
74
  this.reflectEvery = config.reflectEvery ?? 10;
75
+ this.causalGraph = causalGraph ?? null;
72
76
  this.selfObserver = new SelfObserver(db, { brainName: config.brainName });
73
77
  this.adaptiveStrategy = new AdaptiveStrategyEngine(db, { brainName: config.brainName });
74
78
  this.experimentEngine = new ExperimentEngine(db, { brainName: config.brainName });
75
79
  this.crossDomain = new CrossDomainEngine(db);
76
- this.counterfactual = new CounterfactualEngine(db, causalGraph ?? null);
80
+ this.counterfactual = new CounterfactualEngine(db, this.causalGraph);
77
81
  this.knowledgeDistiller = new KnowledgeDistiller(db, { brainName: config.brainName });
78
82
  this.researchAgenda = new ResearchAgendaEngine(db, { brainName: config.brainName });
79
83
  this.anomalyDetective = new AnomalyDetective(db, { brainName: config.brainName });
@@ -164,6 +168,10 @@ export class ResearchOrchestrator {
164
168
  /** Set the ReasoningEngine — multi-step logical inference chains. */
165
169
  setReasoningEngine(engine) { this.reasoningEngine = engine; }
166
170
  setEmotionalModel(model) { this.emotionalModel = model; }
171
+ /** Set the SelfScanner — indexes own source code for self-modification context. */
172
+ setSelfScanner(scanner) { this.selfScanner = scanner; }
173
+ /** Set the SelfModificationEngine — generates and applies code changes autonomously. */
174
+ setSelfModificationEngine(engine) { this.selfModificationEngine = engine; }
167
175
  /** Set the PredictionEngine — wires journal into it. */
168
176
  setPredictionEngine(engine) {
169
177
  this.predictionEngine = engine;
@@ -1242,6 +1250,54 @@ export class ResearchOrchestrator {
1242
1250
  this.log.warn(`[orchestrator] Step 38 error: ${err.message}`);
1243
1251
  }
1244
1252
  }
1253
+ // Step 39: SelfScanner — index own source code (every 20 cycles)
1254
+ if (this.selfScanner && this.cycleCount % 20 === 0) {
1255
+ try {
1256
+ ts?.emit('self-scanner', 'analyzing', 'Step 39: Scanning own source code...', 'routine');
1257
+ const scanResult = this.selfScanner.scan(this.selfModificationEngine ? this.selfModificationEngine.config?.projectRoot || '.' : '.');
1258
+ this.log.info(`[orchestrator] SelfScanner: ${scanResult.totalFiles} files (${scanResult.newFiles} new, ${scanResult.updatedFiles} updated, ${scanResult.durationMs}ms)`);
1259
+ if (this.metaCognitionLayer)
1260
+ this.metaCognitionLayer.recordStep('self_scanner', this.cycleCount, { insights: scanResult.totalFiles, thoughts: scanResult.totalEntities });
1261
+ }
1262
+ catch (err) {
1263
+ this.log.warn(`[orchestrator] Step 39 error: ${err.message}`);
1264
+ }
1265
+ }
1266
+ // Step 40: SelfModification — propose and test code changes (every 20 cycles)
1267
+ if (this.selfModificationEngine && this.cycleCount % 20 === 0) {
1268
+ try {
1269
+ // Skip if there are already pending modifications
1270
+ const pending = this.selfModificationEngine.getPending();
1271
+ if (pending.length === 0) {
1272
+ ts?.emit('self-modification', 'analyzing', 'Step 40: Looking for self-improvement opportunities...', 'routine');
1273
+ const suggestion = this.findActionableSuggestion();
1274
+ if (suggestion) {
1275
+ const mod = this.selfModificationEngine.proposeModification(suggestion.title, suggestion.problem, suggestion.targetFiles, 'orchestrator');
1276
+ ts?.emit('self-modification', 'discovering', `Self-modification proposed: ${mod.title}`, 'notable');
1277
+ // Try to generate + test
1278
+ try {
1279
+ await this.selfModificationEngine.generateCode(mod.id);
1280
+ this.selfModificationEngine.testModification(mod.id);
1281
+ const tested = this.selfModificationEngine.getModification(mod.id);
1282
+ if (tested?.status === 'ready') {
1283
+ ts?.emit('self-modification', 'discovering', `Self-modification ready for review: ${mod.title}`, 'breakthrough');
1284
+ }
1285
+ }
1286
+ catch (genErr) {
1287
+ this.log.warn(`[orchestrator] Step 40 generation/test failed: ${genErr.message}`);
1288
+ }
1289
+ }
1290
+ if (this.metaCognitionLayer)
1291
+ this.metaCognitionLayer.recordStep('self_modification', this.cycleCount, { insights: suggestion ? 1 : 0 });
1292
+ }
1293
+ else {
1294
+ ts?.emit('self-modification', 'reflecting', `Step 40: ${pending.length} pending modification(s) awaiting review`, 'routine');
1295
+ }
1296
+ }
1297
+ catch (err) {
1298
+ this.log.warn(`[orchestrator] Step 40 error: ${err.message}`);
1299
+ }
1300
+ }
1245
1301
  const duration = Date.now() - start;
1246
1302
  ts?.emit('orchestrator', 'reflecting', `Feedback Cycle #${this.cycleCount} complete (${duration}ms)`);
1247
1303
  this.log.info(`[orchestrator] ─── Feedback Cycle #${this.cycleCount} complete (${duration}ms) ───`);
@@ -1971,6 +2027,60 @@ export class ResearchOrchestrator {
1971
2027
  // Don't let file writing break the feedback cycle
1972
2028
  }
1973
2029
  }
2030
+ /** Find a concrete self-improvement suggestion that maps to specific files. */
2031
+ findActionableSuggestion() {
2032
+ const suggestions = this.generateSelfImprovementSuggestions();
2033
+ if (suggestions.length === 0 || !this.selfScanner)
2034
+ return null;
2035
+ // Engine name → module file mapping heuristics
2036
+ const engineMap = {
2037
+ SelfObserver: ['research/self-observer'],
2038
+ PredictionEngine: ['prediction/prediction-engine'],
2039
+ AutoResponder: ['research/auto-responder'],
2040
+ DreamEngine: ['dream/dream-engine'],
2041
+ CuriosityEngine: ['curiosity/curiosity-engine'],
2042
+ EmergenceEngine: ['emergence/emergence-engine'],
2043
+ DebateEngine: ['debate/debate-engine'],
2044
+ MetaCognitionLayer: ['metacognition/meta-cognition-layer'],
2045
+ NarrativeEngine: ['narrative/narrative-engine'],
2046
+ AttentionEngine: ['attention/attention-engine'],
2047
+ TransferEngine: ['transfer/transfer-engine'],
2048
+ ReasoningEngine: ['reasoning/reasoning-engine'],
2049
+ EmotionalModel: ['emotional/emotional-model'],
2050
+ GoalEngine: ['goals/goal-engine'],
2051
+ EvolutionEngine: ['metacognition/evolution-engine'],
2052
+ MemoryPalace: ['memory-palace/memory-palace'],
2053
+ };
2054
+ for (const suggestion of suggestions) {
2055
+ // Find engine names in suggestion text
2056
+ for (const [engineName, filePaths] of Object.entries(engineMap)) {
2057
+ if (suggestion.toLowerCase().includes(engineName.toLowerCase())) {
2058
+ // Find the actual file via SelfScanner
2059
+ const entities = this.selfScanner.getEntities({ entityName: engineName, entityType: 'class' });
2060
+ if (entities.length > 0) {
2061
+ const targetFiles = entities.map(e => e.file_path).slice(0, 2);
2062
+ return {
2063
+ title: `Improve ${engineName}`,
2064
+ problem: suggestion,
2065
+ targetFiles,
2066
+ };
2067
+ }
2068
+ // Fall back to known paths
2069
+ const knownTargets = filePaths
2070
+ .map(fp => `packages/brain-core/src/${fp}.ts`)
2071
+ .filter(fp => this.selfScanner.getFileContent(fp) !== null);
2072
+ if (knownTargets.length > 0) {
2073
+ return {
2074
+ title: `Improve ${engineName}`,
2075
+ problem: suggestion,
2076
+ targetFiles: knownTargets,
2077
+ };
2078
+ }
2079
+ }
2080
+ }
2081
+ }
2082
+ return null;
2083
+ }
1974
2084
  /** Get a comprehensive research summary for dashboards/API. */
1975
2085
  getSummary() {
1976
2086
  return {
@@ -2006,6 +2116,8 @@ export class ResearchOrchestrator {
2006
2116
  goals: this.goalEngine?.getStatus() ?? null,
2007
2117
  reasoning: this.reasoningEngine?.getStatus() ?? null,
2008
2118
  emotional: this.emotionalModel?.getStatus() ?? null,
2119
+ selfScanner: this.selfScanner?.getStatus() ?? null,
2120
+ selfModification: this.selfModificationEngine?.getStatus() ?? null,
2009
2121
  };
2010
2122
  }
2011
2123
  }