@timmeck/brain-core 2.36.53 → 2.36.55

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 (46) hide show
  1. package/command-center.html +53 -0
  2. package/dist/causal/causal-planner.d.ts +45 -0
  3. package/dist/causal/causal-planner.js +135 -0
  4. package/dist/causal/causal-planner.js.map +1 -0
  5. package/dist/creative/creative-engine.d.ts +81 -0
  6. package/dist/creative/creative-engine.js +289 -0
  7. package/dist/creative/creative-engine.js.map +1 -0
  8. package/dist/creative/index.d.ts +2 -0
  9. package/dist/creative/index.js +2 -0
  10. package/dist/creative/index.js.map +1 -0
  11. package/dist/dream/dream-engine.js +3 -5
  12. package/dist/dream/dream-engine.js.map +1 -1
  13. package/dist/goals/research-roadmap.d.ts +73 -0
  14. package/dist/goals/research-roadmap.js +231 -0
  15. package/dist/goals/research-roadmap.js.map +1 -0
  16. package/dist/guardrails/guardrail-engine.d.ts +82 -0
  17. package/dist/guardrails/guardrail-engine.js +279 -0
  18. package/dist/guardrails/guardrail-engine.js.map +1 -0
  19. package/dist/guardrails/index.d.ts +2 -0
  20. package/dist/guardrails/index.js +2 -0
  21. package/dist/guardrails/index.js.map +1 -0
  22. package/dist/index.d.ts +12 -2
  23. package/dist/index.js +10 -0
  24. package/dist/index.js.map +1 -1
  25. package/dist/llm/anthropic-provider.d.ts +2 -0
  26. package/dist/llm/anthropic-provider.js +27 -2
  27. package/dist/llm/anthropic-provider.js.map +1 -1
  28. package/dist/llm/index.d.ts +2 -2
  29. package/dist/llm/ollama-provider.d.ts +3 -0
  30. package/dist/llm/ollama-provider.js +28 -6
  31. package/dist/llm/ollama-provider.js.map +1 -1
  32. package/dist/llm/provider.d.ts +3 -1
  33. package/dist/llm/provider.js.map +1 -1
  34. package/dist/llm/structured-output.d.ts +6 -1
  35. package/dist/llm/structured-output.js.map +1 -1
  36. package/dist/mcp/vision-tools.d.ts +64 -0
  37. package/dist/mcp/vision-tools.js +106 -0
  38. package/dist/mcp/vision-tools.js.map +1 -0
  39. package/dist/narrative/narrative-engine.js +6 -0
  40. package/dist/narrative/narrative-engine.js.map +1 -1
  41. package/dist/research/research-orchestrator.d.ts +12 -0
  42. package/dist/research/research-orchestrator.js +118 -3
  43. package/dist/research/research-orchestrator.js.map +1 -1
  44. package/dist/self-modification/self-modification-engine.js +14 -1
  45. package/dist/self-modification/self-modification-engine.js.map +1 -1
  46. package/package.json +1 -1
@@ -581,6 +581,19 @@ canvas{display:block;width:100%;height:100%}
581
581
  <div id="featureWishlist" style="margin-top:12px"></div>
582
582
  </div>
583
583
 
584
+ <!-- Goals -->
585
+ <div class="section">
586
+ <div class="section-title"><span class="icon">&#x1F3AF;</span> Goals — <span data-t="Forschungsziele">Forschungsziele</span></div>
587
+ <p style="font-size:12px;color:var(--text-dim);margin-bottom:12px" data-t="Brain setzt sich autonome Ziele und verfolgt deren Fortschritt. Erreichte Ziele werden automatisch härter neu erstellt.">Brain setzt sich autonome Ziele und verfolgt deren Fortschritt. Erreichte Ziele werden automatisch härter neu erstellt.</p>
588
+ <div class="grid grid-4">
589
+ <div class="card" style="text-align:center"><div class="card-value" id="int-goals-active" style="color:var(--cyan)">0</div><div class="card-sub" data-t="Aktiv">Aktiv</div></div>
590
+ <div class="card" style="text-align:center"><div class="card-value" id="int-goals-achieved" style="color:var(--green)">0</div><div class="card-sub" data-t="Erreicht">Erreicht</div></div>
591
+ <div class="card" style="text-align:center"><div class="card-value" id="int-goals-failed" style="color:var(--red)">0</div><div class="card-sub" data-t="Gescheitert">Gescheitert</div></div>
592
+ <div class="card" style="text-align:center"><div class="card-value" id="int-goals-total" style="color:var(--text-dim)">0</div><div class="card-sub" data-t="Gesamt">Gesamt</div></div>
593
+ </div>
594
+ <div id="goalsList" style="margin-top:12px"><div class="empty" data-t="Noch keine Goals — werden beim ersten Zyklus erstellt">Noch keine Goals — werden beim ersten Zyklus erstellt</div></div>
595
+ </div>
596
+
584
597
  <!-- Traces / Observability -->
585
598
  <div class="section">
586
599
  <div class="section-title"><span class="icon">&#x1F50D;</span> Observability — <span data-t="Traces & Spans">Traces & Spans</span></div>
@@ -793,6 +806,11 @@ const translations = { en: {
793
806
  'Keine Tool-Daten':'No tool data','Aufrufe':'Calls','Erfolg':'Success',
794
807
  'Proaktive Vorschläge':'Proactive Suggestions','Offen':'Open','Verworfen':'Dismissed','Vorschläge gesamt':'Total Suggestions',
795
808
  'Ø Reward Score':'Avg Reward Score',
809
+ 'Forschungsziele':'Research Goals',
810
+ 'Brain setzt sich autonome Ziele und verfolgt deren Fortschritt. Erreichte Ziele werden automatisch härter neu erstellt.':'Brain sets autonomous goals and tracks their progress. Achieved goals are automatically ratcheted to harder targets.',
811
+ 'Erreicht':'Achieved','Gescheitert':'Failed','Gesamt':'Total',
812
+ 'Datenpunkte':'data points',
813
+ 'Noch keine Goals — werden beim ersten Zyklus erstellt':'No goals yet — will be created on first cycle',
796
814
  'Dein Profil':'Your Profile',
797
815
  'Brain lernt dein Verhalten: Skill-Domains, bevorzugte Tools, Arbeitszeiten.':'Brain learns your behavior: skill domains, preferred tools, working hours.',
798
816
  'Skill-Domains':'Skill Domains','Profil-Keys':'Profile Keys','Zuletzt aktualisiert':'Last Updated',
@@ -1270,6 +1288,41 @@ function renderIntelligence() {
1270
1288
  }
1271
1289
  }
1272
1290
 
1291
+ // Goals
1292
+ if (d.goals) {
1293
+ const g = d.goals;
1294
+ setText('int-goals-active', g.activeGoals || 0);
1295
+ setText('int-goals-achieved', g.achievedGoals || 0);
1296
+ setText('int-goals-failed', g.failedGoals || 0);
1297
+ setText('int-goals-total', g.totalGoals || 0);
1298
+ const el = document.getElementById('goalsList');
1299
+ const list = g.progressList || [];
1300
+ if (list.length) {
1301
+ el.innerHTML = list.map(goal => {
1302
+ const p = goal.progress;
1303
+ const pct = p ? Math.min(100, Math.max(0, p.progressPercent)).toFixed(0) : '0';
1304
+ const trendIcon = !p ? '' : p.trend === 'improving' ? '<span style="color:var(--green)">&#x25B2;</span>' : p.trend === 'declining' ? '<span style="color:var(--red)">&#x25BC;</span>' : '<span style="color:var(--text-dim)">&#x25CF;</span>';
1305
+ const dirLabel = goal.direction === 'lower_is_better' ? '&#x25BC;' : '&#x25B2;';
1306
+ const barColor = p && p.trend === 'improving' ? 'var(--green)' : p && p.trend === 'declining' ? 'var(--red)' : 'var(--yellow)';
1307
+ return `<div class="card" style="padding:10px 12px;margin-bottom:6px">
1308
+ <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:6px">
1309
+ <span style="font-weight:600;color:var(--cyan)">${escHtml(goal.title)}</span>
1310
+ <span style="font-size:11px;color:var(--text-dim)">${trendIcon} ${pct}%</span>
1311
+ </div>
1312
+ <div style="background:var(--surface);border-radius:4px;height:8px;overflow:hidden;margin-bottom:6px">
1313
+ <div style="height:100%;width:${pct}%;background:${barColor};border-radius:4px;transition:width 0.5s ease"></div>
1314
+ </div>
1315
+ <div style="display:flex;justify-content:space-between;font-size:11px;color:var(--text-dim)">
1316
+ <span>${dirLabel} ${escHtml(goal.metricName)}: ${typeof goal.currentValue==='number' && goal.currentValue % 1 !== 0 ? goal.currentValue.toFixed(2) : goal.currentValue} → ${typeof goal.targetValue==='number' && goal.targetValue % 1 !== 0 ? goal.targetValue.toFixed(2) : goal.targetValue}</span>
1317
+ <span>${p ? p.dataPoints : 0} ${t('Datenpunkte')}</span>
1318
+ </div>
1319
+ </div>`;
1320
+ }).join('');
1321
+ } else {
1322
+ el.innerHTML = `<div class="empty">${t('Noch keine Goals — werden beim ersten Zyklus erstellt')}</div>`;
1323
+ }
1324
+ }
1325
+
1273
1326
  // Traces / Observability
1274
1327
  const tr = d.traces;
1275
1328
  if (tr) {
@@ -0,0 +1,45 @@
1
+ import type { CausalGraph } from './engine.js';
2
+ import type { GoalEngine, Goal } from '../goals/goal-engine.js';
3
+ export interface CausalDiagnosis {
4
+ metric: string;
5
+ rootCauses: Array<{
6
+ event: string;
7
+ strength: number;
8
+ lag_ms: number;
9
+ confidence: number;
10
+ }>;
11
+ confounders: string[];
12
+ suggestedInterventions: Intervention[];
13
+ }
14
+ export interface Intervention {
15
+ action: string;
16
+ targetEvent: string;
17
+ expectedEffect: number;
18
+ confidence: number;
19
+ sideEffects: string[];
20
+ }
21
+ export interface PredictedOutcome {
22
+ intervention: Intervention;
23
+ predictedMetricDelta: number;
24
+ confidence: number;
25
+ reasoning: string;
26
+ }
27
+ export declare class CausalPlanner {
28
+ private readonly causalGraph;
29
+ private readonly log;
30
+ private goalEngine;
31
+ constructor(causalGraph: CausalGraph);
32
+ setGoalEngine(engine: GoalEngine): void;
33
+ /** Find root causes for a metric being off-target. */
34
+ diagnose(goalMetric: string): CausalDiagnosis;
35
+ /** Generate intervention suggestions based on causal analysis. */
36
+ suggestInterventions(goalMetric: string): Intervention[];
37
+ private suggestInterventionsFromCauses;
38
+ /** Predict what happens if an intervention is applied. */
39
+ predictOutcome(intervention: Intervention): PredictedOutcome;
40
+ /** Diagnose stagnant goals and suggest causal interventions. */
41
+ diagnoseStagnantGoals(): Array<{
42
+ goal: Goal;
43
+ diagnosis: CausalDiagnosis;
44
+ }>;
45
+ }
@@ -0,0 +1,135 @@
1
+ import { getLogger } from '../utils/logger.js';
2
+ // ── CausalPlanner ────────────────────────────────────────
3
+ export class CausalPlanner {
4
+ causalGraph;
5
+ log = getLogger();
6
+ goalEngine = null;
7
+ constructor(causalGraph) {
8
+ this.causalGraph = causalGraph;
9
+ }
10
+ setGoalEngine(engine) { this.goalEngine = engine; }
11
+ // ── Diagnose ───────────────────────────────────────────
12
+ /** Find root causes for a metric being off-target. */
13
+ diagnose(goalMetric) {
14
+ const causes = this.causalGraph.getCauses(goalMetric);
15
+ // Sort by strength × confidence for strongest causes first
16
+ const ranked = causes
17
+ .sort((a, b) => (b.strength * b.confidence) - (a.strength * a.confidence))
18
+ .slice(0, 10);
19
+ const rootCauses = ranked.map(edge => ({
20
+ event: edge.cause,
21
+ strength: edge.strength,
22
+ lag_ms: edge.lag_ms,
23
+ confidence: edge.confidence,
24
+ }));
25
+ // Find deeper root causes via chains
26
+ const deepRoots = [];
27
+ const allChains = this.causalGraph.findChains();
28
+ for (const cause of rootCauses.slice(0, 3)) {
29
+ // Filter chains that contain our cause and the goalMetric
30
+ const relevant = allChains.filter(c => c.chain.includes(cause.event) && c.chain.includes(goalMetric));
31
+ for (const chain of relevant) {
32
+ if (chain.chain.length > 2) {
33
+ const origin = chain.chain[0];
34
+ if (!rootCauses.some(r => r.event === origin) && !deepRoots.some(r => r.event === origin)) {
35
+ deepRoots.push({
36
+ event: origin,
37
+ strength: chain.totalStrength,
38
+ lag_ms: chain.totalLag,
39
+ confidence: chain.totalStrength, // approximate
40
+ });
41
+ }
42
+ }
43
+ }
44
+ }
45
+ // Find confounders between each cause and the metric
46
+ const confounders = [];
47
+ for (const cause of rootCauses.slice(0, 5)) {
48
+ try {
49
+ const cf = this.causalGraph.detectConfounders(cause.event, goalMetric);
50
+ for (const c of cf) {
51
+ if (!confounders.includes(c))
52
+ confounders.push(c);
53
+ }
54
+ }
55
+ catch { /* no confounders */ }
56
+ }
57
+ const allRootCauses = [...rootCauses, ...deepRoots];
58
+ const interventions = this.suggestInterventionsFromCauses(allRootCauses, goalMetric);
59
+ this.log.info(`[causal-planner] Diagnosed ${goalMetric}: ${allRootCauses.length} root causes, ${confounders.length} confounders`);
60
+ return {
61
+ metric: goalMetric,
62
+ rootCauses: allRootCauses,
63
+ confounders,
64
+ suggestedInterventions: interventions,
65
+ };
66
+ }
67
+ // ── Suggest Interventions ──────────────────────────────
68
+ /** Generate intervention suggestions based on causal analysis. */
69
+ suggestInterventions(goalMetric) {
70
+ const diagnosis = this.diagnose(goalMetric);
71
+ return diagnosis.suggestedInterventions;
72
+ }
73
+ suggestInterventionsFromCauses(rootCauses, targetMetric) {
74
+ const interventions = [];
75
+ for (const cause of rootCauses.slice(0, 5)) {
76
+ // Determine action based on edge direction
77
+ const effects = this.causalGraph.getEffects(cause.event);
78
+ const targetEdge = effects.find(e => e.effect === targetMetric);
79
+ // direction is number: +1 = positive, -1 = negative
80
+ const directionNum = targetEdge?.direction ?? 1;
81
+ const action = directionNum >= 0
82
+ ? `increase_${cause.event}`
83
+ : `decrease_${cause.event}`;
84
+ // Find potential side effects — other things caused by this event
85
+ const sideEffects = effects
86
+ .filter(e => e.effect !== targetMetric)
87
+ .map(e => `${e.direction >= 0 ? '+' : '-'}${e.effect} (strength: ${e.strength.toFixed(2)})`);
88
+ interventions.push({
89
+ action,
90
+ targetEvent: cause.event,
91
+ expectedEffect: cause.strength * directionNum,
92
+ confidence: cause.confidence,
93
+ sideEffects,
94
+ });
95
+ }
96
+ return interventions;
97
+ }
98
+ // ── Predict Outcome ────────────────────────────────────
99
+ /** Predict what happens if an intervention is applied. */
100
+ predictOutcome(intervention) {
101
+ const predictedDelta = intervention.expectedEffect;
102
+ const confidence = intervention.confidence;
103
+ const reasoning = `Direct causal effect of ${intervention.action} on ${intervention.targetEvent}`;
104
+ return {
105
+ intervention,
106
+ predictedMetricDelta: predictedDelta,
107
+ confidence,
108
+ reasoning,
109
+ };
110
+ }
111
+ // ── Goal Integration ───────────────────────────────────
112
+ /** Diagnose stagnant goals and suggest causal interventions. */
113
+ diagnoseStagnantGoals() {
114
+ if (!this.goalEngine)
115
+ return [];
116
+ const results = [];
117
+ const activeGoals = this.goalEngine.listGoals('active');
118
+ for (const goal of activeGoals) {
119
+ const progress = this.goalEngine.getProgress(goal.id);
120
+ if (progress && progress.trend === 'stagnant') {
121
+ try {
122
+ const diagnosis = this.diagnose(goal.metricName);
123
+ if (diagnosis.rootCauses.length > 0) {
124
+ results.push({ goal, diagnosis });
125
+ }
126
+ }
127
+ catch {
128
+ // No causal data for this metric
129
+ }
130
+ }
131
+ }
132
+ return results;
133
+ }
134
+ }
135
+ //# sourceMappingURL=causal-planner.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"causal-planner.js","sourceRoot":"","sources":["../../src/causal/causal-planner.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,SAAS,E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AE,CAAC;YAC/B,MAAM,QAAQ,GAAG,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,IAAI,CAAC,EAAG,CAAC,CAAC;YACvD,IAAI,QAAQ,IAAI,QAAQ,CAAC,KAAK,KAAK,UAAU,EAAE,CAAC;gBAC9C,IAAI,CAAC;oBACH,MAAM,SAAS,GAAG,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;oBACjD,IAAI,SAAS,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;wBACpC,OAAO,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC,CAAC;oBACpC,CAAC;gBACH,CAAC;gBAAC,MAAM,CAAC;oBACP,iCAAiC;gBACnC,CAAC;YACH,CAAC;QACH,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;CACF"}
@@ -0,0 +1,81 @@
1
+ import type Database from 'better-sqlite3';
2
+ import type { KnowledgeDistiller } from '../research/knowledge-distiller.js';
3
+ import type { HypothesisEngine } from '../hypothesis/engine.js';
4
+ import type { ThoughtStream } from '../consciousness/thought-stream.js';
5
+ import type { LLMService } from '../llm/llm-service.js';
6
+ export interface CreativeInsight {
7
+ id?: number;
8
+ type: 'cross_pollination' | 'analogy' | 'speculation' | 'imagination';
9
+ sourceA: {
10
+ domain: string;
11
+ principle: string;
12
+ };
13
+ sourceB: {
14
+ domain: string;
15
+ principle: string;
16
+ };
17
+ insight: string;
18
+ noveltyScore: number;
19
+ plausibility: number;
20
+ status: 'raw' | 'tested' | 'confirmed' | 'rejected';
21
+ createdAt?: string;
22
+ }
23
+ export interface Analogy {
24
+ concept: string;
25
+ analogousConcept: string;
26
+ sourceDomain: string;
27
+ targetDomain: string;
28
+ similarity: number;
29
+ explanation: string;
30
+ }
31
+ export interface SpeculativeHypothesis {
32
+ hypothesis: string;
33
+ basedOn: string[];
34
+ novelty: number;
35
+ plausibility: number;
36
+ }
37
+ export interface CreativeEngineConfig {
38
+ brainName: string;
39
+ /** Max insights per cross-pollination cycle. Default: 5 */
40
+ maxInsightsPerCycle?: number;
41
+ /** Topic overlap threshold (< this = sufficiently different). Default: 0.3 */
42
+ overlapThreshold?: number;
43
+ }
44
+ export interface CreativeEngineStatus {
45
+ totalInsights: number;
46
+ byType: Record<string, number>;
47
+ byStatus: Record<string, number>;
48
+ topInsights: CreativeInsight[];
49
+ }
50
+ export declare function runCreativeMigration(db: Database.Database): void;
51
+ export declare class CreativeEngine {
52
+ private readonly db;
53
+ private readonly config;
54
+ private readonly log;
55
+ private distiller;
56
+ private hypothesisEngine;
57
+ private llmService;
58
+ private ts;
59
+ constructor(db: Database.Database, config: CreativeEngineConfig);
60
+ setKnowledgeDistiller(distiller: KnowledgeDistiller): void;
61
+ setHypothesisEngine(engine: HypothesisEngine): void;
62
+ setLLMService(service: LLMService): void;
63
+ setThoughtStream(stream: ThoughtStream): void;
64
+ /** Cross-pollinate principles from different domains. */
65
+ crossPollinate(): CreativeInsight[];
66
+ /** Find analogies for a concept across different domains. */
67
+ findAnalogies(concept: string): Analogy[];
68
+ /** Generate speculative hypotheses by combining principles. */
69
+ speculate(): SpeculativeHypothesis[];
70
+ /** Generate imaginative scenarios from a premise. */
71
+ imagine(premise: string): CreativeInsight[];
72
+ /** Convert top insights into testable hypotheses. */
73
+ convertTopInsights(minNovelty?: number): number;
74
+ getInsights(limit?: number, status?: string): CreativeInsight[];
75
+ getStatus(): CreativeEngineStatus;
76
+ private loadPrinciples;
77
+ private computeOverlap;
78
+ private tokenize;
79
+ private generateCrossPollination;
80
+ private storeInsight;
81
+ }
@@ -0,0 +1,289 @@
1
+ import { getLogger } from '../utils/logger.js';
2
+ // ── Migration ───────────────────────────────────────────
3
+ export function runCreativeMigration(db) {
4
+ db.exec(`
5
+ CREATE TABLE IF NOT EXISTS creative_insights (
6
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
7
+ type TEXT NOT NULL,
8
+ source_a_domain TEXT NOT NULL,
9
+ source_a_principle TEXT NOT NULL,
10
+ source_b_domain TEXT NOT NULL,
11
+ source_b_principle TEXT NOT NULL,
12
+ insight TEXT NOT NULL,
13
+ novelty_score REAL NOT NULL DEFAULT 0.5,
14
+ plausibility REAL NOT NULL DEFAULT 0.5,
15
+ status TEXT NOT NULL DEFAULT 'raw',
16
+ created_at TEXT DEFAULT (datetime('now'))
17
+ );
18
+ CREATE INDEX IF NOT EXISTS idx_creative_type ON creative_insights(type);
19
+ CREATE INDEX IF NOT EXISTS idx_creative_status ON creative_insights(status);
20
+ CREATE INDEX IF NOT EXISTS idx_creative_novelty ON creative_insights(novelty_score);
21
+ `);
22
+ }
23
+ // ── Engine ──────────────────────────────────────────────
24
+ export class CreativeEngine {
25
+ db;
26
+ config;
27
+ log = getLogger();
28
+ distiller = null;
29
+ hypothesisEngine = null;
30
+ llmService = null;
31
+ ts = null;
32
+ constructor(db, config) {
33
+ this.db = db;
34
+ this.config = {
35
+ brainName: config.brainName,
36
+ maxInsightsPerCycle: config.maxInsightsPerCycle ?? 5,
37
+ overlapThreshold: config.overlapThreshold ?? 0.3,
38
+ };
39
+ runCreativeMigration(db);
40
+ }
41
+ setKnowledgeDistiller(distiller) { this.distiller = distiller; }
42
+ setHypothesisEngine(engine) { this.hypothesisEngine = engine; }
43
+ setLLMService(service) { this.llmService = service; }
44
+ setThoughtStream(stream) { this.ts = stream; }
45
+ // ── Cross-Pollination ──────────────────────────────────
46
+ /** Cross-pollinate principles from different domains. */
47
+ crossPollinate() {
48
+ if (!this.distiller)
49
+ return [];
50
+ const insights = [];
51
+ const principles = this.loadPrinciples();
52
+ // Group by domain
53
+ const byDomain = new Map();
54
+ for (const p of principles) {
55
+ const list = byDomain.get(p.domain) ?? [];
56
+ list.push(p);
57
+ byDomain.set(p.domain, list);
58
+ }
59
+ const domains = [...byDomain.keys()];
60
+ if (domains.length < 2)
61
+ return insights;
62
+ // Cross-pollinate between domains
63
+ for (let i = 0; i < domains.length && insights.length < this.config.maxInsightsPerCycle; i++) {
64
+ for (let j = i + 1; j < domains.length && insights.length < this.config.maxInsightsPerCycle; j++) {
65
+ const domainA = domains[i];
66
+ const domainB = domains[j];
67
+ const principlesA = byDomain.get(domainA);
68
+ const principlesB = byDomain.get(domainB);
69
+ // Pick random pair with low overlap
70
+ const pA = principlesA[Math.floor(Math.random() * principlesA.length)];
71
+ const pB = principlesB[Math.floor(Math.random() * principlesB.length)];
72
+ const overlap = this.computeOverlap(pA.text, pB.text);
73
+ if (overlap < this.config.overlapThreshold) {
74
+ const insight = this.generateCrossPollination(pA, pB, domainA, domainB);
75
+ if (insight) {
76
+ insights.push(insight);
77
+ }
78
+ }
79
+ }
80
+ }
81
+ // Store insights
82
+ for (const insight of insights) {
83
+ this.storeInsight(insight);
84
+ }
85
+ if (insights.length > 0) {
86
+ this.log.info(`[creative] Generated ${insights.length} cross-pollination insights`);
87
+ this.ts?.emit('creative', 'discovering', `Cross-pollination: ${insights.length} new insights`, 'notable');
88
+ }
89
+ return insights;
90
+ }
91
+ // ── Analogy Search ─────────────────────────────────────
92
+ /** Find analogies for a concept across different domains. */
93
+ findAnalogies(concept) {
94
+ const principles = this.loadPrinciples();
95
+ const analogies = [];
96
+ const conceptWords = this.tokenize(concept);
97
+ for (const p of principles) {
98
+ const pWords = this.tokenize(p.text);
99
+ // Look for structural similarity (shared abstract words) but different domains
100
+ const sharedAbstract = conceptWords.filter(w => pWords.includes(w) && w.length > 4);
101
+ const similarity = conceptWords.length > 0
102
+ ? sharedAbstract.length / Math.max(conceptWords.length, pWords.length)
103
+ : 0;
104
+ if (similarity > 0.1 && similarity < 0.6) {
105
+ analogies.push({
106
+ concept,
107
+ analogousConcept: p.text,
108
+ sourceDomain: 'query',
109
+ targetDomain: p.domain,
110
+ similarity,
111
+ explanation: `Shared concepts: ${sharedAbstract.join(', ')}`,
112
+ });
113
+ }
114
+ }
115
+ return analogies
116
+ .sort((a, b) => b.similarity - a.similarity)
117
+ .slice(0, 10);
118
+ }
119
+ // ── Speculation ────────────────────────────────────────
120
+ /** Generate speculative hypotheses by combining principles. */
121
+ speculate() {
122
+ const principles = this.loadPrinciples();
123
+ if (principles.length < 2)
124
+ return [];
125
+ const hypotheses = [];
126
+ // Random principle pairs
127
+ const maxAttempts = Math.min(10, principles.length * (principles.length - 1) / 2);
128
+ const tried = new Set();
129
+ for (let attempt = 0; attempt < maxAttempts && hypotheses.length < 3; attempt++) {
130
+ const a = principles[Math.floor(Math.random() * principles.length)];
131
+ const b = principles[Math.floor(Math.random() * principles.length)];
132
+ if (a.text === b.text)
133
+ continue;
134
+ const key = [a.text, b.text].sort().join('|||');
135
+ if (tried.has(key))
136
+ continue;
137
+ tried.add(key);
138
+ if (a.domain !== b.domain) {
139
+ const hypothesis = `If "${a.text}" (${a.domain}) and "${b.text}" (${b.domain}) both hold, then their combination might reveal a pattern spanning ${a.domain} and ${b.domain}`;
140
+ const novelty = 1 - this.computeOverlap(a.text, b.text);
141
+ const plausibility = 0.3 + Math.random() * 0.4; // moderate plausibility
142
+ hypotheses.push({
143
+ hypothesis,
144
+ basedOn: [a.text, b.text],
145
+ novelty,
146
+ plausibility,
147
+ });
148
+ }
149
+ }
150
+ return hypotheses;
151
+ }
152
+ // ── Imagine ────────────────────────────────────────────
153
+ /** Generate imaginative scenarios from a premise. */
154
+ imagine(premise) {
155
+ const principles = this.loadPrinciples();
156
+ const insights = [];
157
+ // Find principles that relate to the premise
158
+ const relevant = principles.filter(p => this.computeOverlap(premise, p.text) > 0.1);
159
+ for (const p of relevant.slice(0, 3)) {
160
+ const insight = {
161
+ type: 'imagination',
162
+ sourceA: { domain: 'premise', principle: premise },
163
+ sourceB: { domain: p.domain, principle: p.text },
164
+ insight: `Scenario: Given "${premise}", and knowing "${p.text}" from ${p.domain} — what new behaviors could emerge?`,
165
+ noveltyScore: 0.6 + Math.random() * 0.3,
166
+ plausibility: 0.3 + Math.random() * 0.3,
167
+ status: 'raw',
168
+ };
169
+ this.storeInsight(insight);
170
+ insights.push(insight);
171
+ }
172
+ return insights;
173
+ }
174
+ // ── Auto-Convert to Hypotheses ─────────────────────────
175
+ /** Convert top insights into testable hypotheses. */
176
+ convertTopInsights(minNovelty = 0.5) {
177
+ if (!this.hypothesisEngine)
178
+ return 0;
179
+ const top = this.db.prepare("SELECT * FROM creative_insights WHERE status = 'raw' AND novelty_score >= ? ORDER BY novelty_score DESC LIMIT 5").all(minNovelty);
180
+ let converted = 0;
181
+ for (const row of top) {
182
+ try {
183
+ this.hypothesisEngine.propose({
184
+ statement: row.insight,
185
+ type: 'correlation',
186
+ source: 'creative_engine',
187
+ variables: [row.source_a_domain, row.source_b_domain],
188
+ condition: { type: 'correlation', params: { domains: [row.source_a_domain, row.source_b_domain] } },
189
+ });
190
+ this.db.prepare("UPDATE creative_insights SET status = 'tested' WHERE id = ?").run(row.id);
191
+ converted++;
192
+ }
193
+ catch { /* hypothesis already exists or limit */ }
194
+ }
195
+ if (converted > 0) {
196
+ this.ts?.emit('creative', 'discovering', `Converted ${converted} insights to hypotheses`, 'notable');
197
+ }
198
+ return converted;
199
+ }
200
+ // ── Queries ────────────────────────────────────────────
201
+ getInsights(limit = 20, status) {
202
+ const query = status
203
+ ? 'SELECT * FROM creative_insights WHERE status = ? ORDER BY novelty_score DESC LIMIT ?'
204
+ : 'SELECT * FROM creative_insights ORDER BY novelty_score DESC LIMIT ?';
205
+ const rows = (status
206
+ ? this.db.prepare(query).all(status, limit)
207
+ : this.db.prepare(query).all(limit));
208
+ return rows.map(deserializeInsight);
209
+ }
210
+ getStatus() {
211
+ const total = this.db.prepare('SELECT COUNT(*) as cnt FROM creative_insights').get().cnt;
212
+ const byType = {};
213
+ for (const row of this.db.prepare('SELECT type, COUNT(*) as cnt FROM creative_insights GROUP BY type').all()) {
214
+ byType[row.type] = row.cnt;
215
+ }
216
+ const byStatus = {};
217
+ for (const row of this.db.prepare('SELECT status, COUNT(*) as cnt FROM creative_insights GROUP BY status').all()) {
218
+ byStatus[row.status] = row.cnt;
219
+ }
220
+ const topInsights = this.getInsights(5);
221
+ return { totalInsights: total, byType, byStatus, topInsights };
222
+ }
223
+ // ── Private Helpers ────────────────────────────────────
224
+ loadPrinciples() {
225
+ if (!this.distiller)
226
+ return [];
227
+ try {
228
+ const pkg = this.distiller.distill();
229
+ const principles = [];
230
+ for (const p of pkg.principles) {
231
+ principles.push({ text: p.statement, domain: p.domain ?? this.config.brainName });
232
+ }
233
+ return principles;
234
+ }
235
+ catch {
236
+ return [];
237
+ }
238
+ }
239
+ computeOverlap(textA, textB) {
240
+ const wordsA = new Set(this.tokenize(textA));
241
+ const wordsB = new Set(this.tokenize(textB));
242
+ if (wordsA.size === 0 || wordsB.size === 0)
243
+ return 0;
244
+ let shared = 0;
245
+ for (const w of wordsA) {
246
+ if (wordsB.has(w))
247
+ shared++;
248
+ }
249
+ return shared / Math.max(wordsA.size, wordsB.size);
250
+ }
251
+ tokenize(text) {
252
+ return text.toLowerCase().split(/\W+/).filter(w => w.length > 2);
253
+ }
254
+ generateCrossPollination(pA, pB, domainA, domainB) {
255
+ const novelty = 1 - this.computeOverlap(pA.text, pB.text);
256
+ const plausibility = 0.3 + Math.random() * 0.4;
257
+ const insight = `Cross-domain insight: "${pA.text}" from ${domainA} could apply to ${domainB} where "${pB.text}" already holds. Combining these might yield a new pattern.`;
258
+ return {
259
+ type: 'cross_pollination',
260
+ sourceA: { domain: domainA, principle: pA.text },
261
+ sourceB: { domain: domainB, principle: pB.text },
262
+ insight,
263
+ noveltyScore: novelty,
264
+ plausibility,
265
+ status: 'raw',
266
+ };
267
+ }
268
+ storeInsight(insight) {
269
+ const result = this.db.prepare(`
270
+ INSERT INTO creative_insights (type, source_a_domain, source_a_principle, source_b_domain, source_b_principle, insight, novelty_score, plausibility, status)
271
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
272
+ `).run(insight.type, insight.sourceA.domain, insight.sourceA.principle, insight.sourceB.domain, insight.sourceB.principle, insight.insight, insight.noveltyScore, insight.plausibility, insight.status);
273
+ insight.id = Number(result.lastInsertRowid);
274
+ }
275
+ }
276
+ function deserializeInsight(row) {
277
+ return {
278
+ id: row.id,
279
+ type: row.type,
280
+ sourceA: { domain: row.source_a_domain, principle: row.source_a_principle },
281
+ sourceB: { domain: row.source_b_domain, principle: row.source_b_principle },
282
+ insight: row.insight,
283
+ noveltyScore: row.novelty_score,
284
+ plausibility: row.plausibility,
285
+ status: row.status,
286
+ createdAt: row.created_at,
287
+ };
288
+ }
289
+ //# sourceMappingURL=creative-engine.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"creative-engine.js","sourceRoot":"","sources":["../../src/creative/creative-engine.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAmD/C,2DAA2D;AAE3D,MAAM,UAAU,oBAAoB,CAAC,EAAqB;IACxD,EAAE,CAAC,IAAI,CAAC;;;;;;;;;;;;;;;;;GAiBP,CAAC,CAAC;AACL,CAAC;AAED,2DAA2D;AAE3D,MAAM,OAAO,cAAc;IACR,EAAE,CAAoB;IACtB,MAAM,CAAiC;IACvC,GAAG,GAAG,SAAS,EAAE,CAAC;IAC3B,SAAS,GAA8B,IAAI,CAAC;IAC5C,gBAAgB,GAA4B,IAAI,CAAC;IACjD,UAAU,GAAsB,IAAI,CAAC;IACrC,EAAE,GAAyB,IAAI,CAAC;IAExC,YAAY,EAAqB,EAAE,MAA4B;QAC7D,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;QACb,IAAI,CAAC,MAAM,GAAG;YACZ,SAAS,EAAE,MAAM,CAAC,SAAS;YAC3B,mBAAmB,EAAE,MAAM,CAAC,mBAAmB,IAAI,CAAC;YACpD,gBAAgB,EAAE,MAAM,CAAC,gBAAgB,IAAI,GAAG;SACjD,CAAC;QACF,oBAAoB,CAAC,EAAE,CAAC,CAAC;IAC3B,CAAC;IAED,qBAAqB,CAAC,SAA6B,IAAU,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC,CAAC,CAAC;IAC1F,mBAAmB,C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