genesis-ai-cli 11.3.0 → 11.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/src/active-inference/actions.js +32 -3
- package/dist/src/active-inference/autonomous-loop.d.ts +5 -0
- package/dist/src/active-inference/autonomous-loop.js +122 -5
- package/dist/src/active-inference/consciousness-bridge.d.ts +119 -0
- package/dist/src/active-inference/consciousness-bridge.js +276 -0
- package/dist/src/active-inference/core.d.ts +11 -1
- package/dist/src/active-inference/core.js +38 -0
- package/dist/src/active-inference/efe-tool-selector.d.ts +90 -0
- package/dist/src/active-inference/efe-tool-selector.js +303 -0
- package/dist/src/active-inference/index.d.ts +2 -0
- package/dist/src/active-inference/index.js +10 -1
- package/dist/src/index.js +29 -6
- package/dist/src/mcp-server/server.js +59 -0
- package/dist/src/self-production.js +61 -7
- package/package.json +1 -1
|
@@ -57,6 +57,7 @@ exports.getActionExecutorManager = getActionExecutorManager;
|
|
|
57
57
|
const phi_monitor_js_1 = require("../consciousness/phi-monitor.js");
|
|
58
58
|
const cognitive_workspace_js_1 = require("../memory/cognitive-workspace.js");
|
|
59
59
|
const index_js_1 = require("../mcp/index.js");
|
|
60
|
+
const efe_tool_selector_js_1 = require("./efe-tool-selector.js");
|
|
60
61
|
const child_process_1 = require("child_process");
|
|
61
62
|
const util_1 = require("util");
|
|
62
63
|
const fs = __importStar(require("fs"));
|
|
@@ -869,24 +870,52 @@ registerAction('web.search', async (context) => {
|
|
|
869
870
|
duration: Date.now() - start,
|
|
870
871
|
};
|
|
871
872
|
}
|
|
872
|
-
//
|
|
873
|
+
// v11.4: EFE-based tool selection - pick the best search tool dynamically
|
|
874
|
+
const efeSelector = (0, efe_tool_selector_js_1.getEFEToolSelector)();
|
|
875
|
+
const defaultBeliefs = {
|
|
876
|
+
viability: [0.2, 0.3, 0.3, 0.1, 0.1],
|
|
877
|
+
worldState: [0.2, 0.3, 0.3, 0.2],
|
|
878
|
+
coupling: [0.1, 0.2, 0.3, 0.3, 0.1],
|
|
879
|
+
goalProgress: [0.1, 0.3, 0.4, 0.2],
|
|
880
|
+
economic: [0.2, 0.3, 0.3, 0.2],
|
|
881
|
+
};
|
|
882
|
+
const beliefs = context.beliefs || defaultBeliefs;
|
|
883
|
+
const selection = efeSelector.selectTool('search', beliefs);
|
|
884
|
+
const bestTool = selection.selected.tool;
|
|
873
885
|
const mcp = (0, index_js_1.getMCPClient)();
|
|
874
|
-
|
|
886
|
+
// Call the EFE-selected tool (may be brave, exa, gemini, or firecrawl)
|
|
887
|
+
const result = await mcp.call(bestTool.server, bestTool.tool, {
|
|
875
888
|
query,
|
|
876
889
|
count: context.parameters?.count || 10,
|
|
877
890
|
});
|
|
891
|
+
// Record outcome for future EFE estimates
|
|
892
|
+
const duration = Date.now() - start;
|
|
893
|
+
efeSelector.recordOutcome(bestTool.server, bestTool.tool, true, duration, 0, // Surprise will be computed by the loop
|
|
894
|
+
bestTool.cost);
|
|
878
895
|
return {
|
|
879
896
|
success: true,
|
|
880
897
|
action: 'web.search',
|
|
881
898
|
data: {
|
|
882
899
|
query,
|
|
883
900
|
results: result,
|
|
901
|
+
selectedTool: `${bestTool.server}/${bestTool.tool}`,
|
|
902
|
+
efeScore: selection.selected.efe,
|
|
903
|
+
reasoning: selection.selected.reasoning,
|
|
904
|
+
alternatives: selection.alternatives.map(a => `${a.tool.server}/${a.tool.tool} (EFE=${a.efe.toFixed(3)})`),
|
|
884
905
|
timestamp: new Date().toISOString(),
|
|
885
906
|
},
|
|
886
|
-
duration
|
|
907
|
+
duration,
|
|
887
908
|
};
|
|
888
909
|
}
|
|
889
910
|
catch (error) {
|
|
911
|
+
// Record failure for EFE learning
|
|
912
|
+
const efeSelector = (0, efe_tool_selector_js_1.getEFEToolSelector)();
|
|
913
|
+
const fallbackBeliefs = { viability: [0.2, 0.3, 0.3, 0.1, 0.1], worldState: [0.25, 0.25, 0.25, 0.25], coupling: [0.2, 0.2, 0.2, 0.2, 0.2], goalProgress: [0.25, 0.25, 0.25, 0.25], economic: [0.25, 0.25, 0.25, 0.25] };
|
|
914
|
+
const selection = efeSelector.selectTool('search', context.beliefs || fallbackBeliefs);
|
|
915
|
+
if (selection.selected.tool.server !== 'none') {
|
|
916
|
+
efeSelector.recordOutcome(selection.selected.tool.server, selection.selected.tool.tool, false, Date.now() - start, 5.0, // High surprise on failure
|
|
917
|
+
selection.selected.tool.cost);
|
|
918
|
+
}
|
|
890
919
|
return {
|
|
891
920
|
success: false,
|
|
892
921
|
action: 'web.search',
|
|
@@ -50,6 +50,11 @@ export declare class AutonomousLoop {
|
|
|
50
50
|
private deepAIF;
|
|
51
51
|
private replayBuffer;
|
|
52
52
|
private previousObservation;
|
|
53
|
+
private allostasis;
|
|
54
|
+
private lastAllostaticDelta;
|
|
55
|
+
private dreamService;
|
|
56
|
+
private conformal;
|
|
57
|
+
private lastPredictedSurprise;
|
|
53
58
|
constructor(config?: Partial<AutonomousLoopConfig>);
|
|
54
59
|
/**
|
|
55
60
|
* Run the autonomous loop
|
|
@@ -49,6 +49,9 @@ const actions_js_1 = require("./actions.js");
|
|
|
49
49
|
const types_js_1 = require("./types.js");
|
|
50
50
|
const deep_aif_js_1 = require("./deep-aif.js");
|
|
51
51
|
const experience_replay_js_1 = require("./experience-replay.js");
|
|
52
|
+
const index_js_1 = require("../allostasis/index.js");
|
|
53
|
+
const dream_mode_js_1 = require("../daemon/dream-mode.js");
|
|
54
|
+
const conformal_js_1 = require("../uncertainty/conformal.js");
|
|
52
55
|
const fs = __importStar(require("fs"));
|
|
53
56
|
const path = __importStar(require("path"));
|
|
54
57
|
exports.DEFAULT_LOOP_CONFIG = {
|
|
@@ -93,12 +96,61 @@ class AutonomousLoop {
|
|
|
93
96
|
// v11.0: Experience replay buffer
|
|
94
97
|
replayBuffer;
|
|
95
98
|
previousObservation = null;
|
|
99
|
+
// v11.4: Allostasis (interoceptive regulation → C-matrix modulation)
|
|
100
|
+
allostasis;
|
|
101
|
+
lastAllostaticDelta = false;
|
|
102
|
+
// v11.4: Dream service (rich consolidation)
|
|
103
|
+
dreamService;
|
|
104
|
+
// v11.4: Conformal prediction (calibrated EFE ambiguity)
|
|
105
|
+
conformal;
|
|
106
|
+
lastPredictedSurprise = 0;
|
|
96
107
|
constructor(config = {}) {
|
|
97
108
|
this.config = { ...exports.DEFAULT_LOOP_CONFIG, ...config };
|
|
98
109
|
this.engine = (0, core_js_1.createActiveInferenceEngine)();
|
|
99
110
|
this.observations = (0, observations_js_1.createObservationGatherer)();
|
|
100
111
|
this.actions = (0, actions_js_1.createActionExecutorManager)();
|
|
101
112
|
this.replayBuffer = (0, experience_replay_js_1.createExperienceReplayBuffer)();
|
|
113
|
+
// v11.4: Initialize allostasis with real sensors
|
|
114
|
+
this.allostasis = (0, index_js_1.createAllostasisSystem)();
|
|
115
|
+
this.allostasis.registerSensor('energy', () => {
|
|
116
|
+
const stats = this.engine.getStats();
|
|
117
|
+
return Math.max(0, 1 - stats.averageSurprise / 10); // Low surprise = high energy
|
|
118
|
+
});
|
|
119
|
+
this.allostasis.registerSensor('errorRate', () => {
|
|
120
|
+
const stats = this.engine.getStats();
|
|
121
|
+
return stats.inferenceCount > 0 ? 1 - (stats.averageSurprise < 3 ? 0.8 : 0.3) : 0;
|
|
122
|
+
});
|
|
123
|
+
this.allostasis.registerSensor('memoryPressure', () => {
|
|
124
|
+
return this.replayBuffer.getStats().bufferSize / 1000; // Normalize to 0-1
|
|
125
|
+
});
|
|
126
|
+
// v11.4: Initialize dream service with replay buffer context
|
|
127
|
+
this.dreamService = (0, dream_mode_js_1.createDreamService)({ minDreamDurationMs: 1000, maxDreamDurationMs: 5000 }, {
|
|
128
|
+
getEpisodicMemories: () => {
|
|
129
|
+
const experiences = this.replayBuffer.sampleHighSurprise(32);
|
|
130
|
+
return experiences.map(exp => ({
|
|
131
|
+
id: String(exp.id),
|
|
132
|
+
content: { what: `${exp.action}: surprise=${exp.surprise.toFixed(2)}, ${exp.outcome}` },
|
|
133
|
+
importance: exp.priority,
|
|
134
|
+
tags: [exp.outcome, exp.action],
|
|
135
|
+
consolidated: exp.replayCount >= 5,
|
|
136
|
+
}));
|
|
137
|
+
},
|
|
138
|
+
consolidateMemory: async (id) => {
|
|
139
|
+
const experiences = this.replayBuffer.sampleHighSurprise(32);
|
|
140
|
+
const exp = experiences.find(e => String(e.id) === id);
|
|
141
|
+
if (exp) {
|
|
142
|
+
this.engine.learn(exp.observation, exp.nextObservation, exp.beliefs, exp.actionIdx);
|
|
143
|
+
return { concept: `consolidated_${exp.action}_${exp.outcome}` };
|
|
144
|
+
}
|
|
145
|
+
return null;
|
|
146
|
+
},
|
|
147
|
+
log: (msg) => {
|
|
148
|
+
if (this.config.verbose)
|
|
149
|
+
console.log(`[Dream] ${msg}`);
|
|
150
|
+
},
|
|
151
|
+
});
|
|
152
|
+
// v11.4: Initialize conformal predictor for calibrated uncertainty
|
|
153
|
+
this.conformal = (0, conformal_js_1.createFreeEnergyConformalPredictor)();
|
|
102
154
|
// Subscribe to engine events
|
|
103
155
|
this.engine.on(this.handleEngineEvent.bind(this));
|
|
104
156
|
}
|
|
@@ -179,6 +231,33 @@ class AutonomousLoop {
|
|
|
179
231
|
if (this.config.verbose) {
|
|
180
232
|
console.log(`[AI Loop] Cycle ${this.cycleCount} - Observation:`, obs);
|
|
181
233
|
}
|
|
234
|
+
// 1b. v11.4: Allostatic modulation of preferences
|
|
235
|
+
// Sense internal state → modulate C-matrix before inference
|
|
236
|
+
try {
|
|
237
|
+
const intero = this.allostasis.interoception?.sense?.();
|
|
238
|
+
if (intero) {
|
|
239
|
+
const energyLevel = intero.energy ?? 0.7;
|
|
240
|
+
const errorRate = intero.errorRate ?? 0;
|
|
241
|
+
const memPressure = intero.memoryPressure ?? 0.3;
|
|
242
|
+
// Low energy → boost preference for rest/low-energy states
|
|
243
|
+
if (energyLevel < 0.3) {
|
|
244
|
+
this.engine.modulatePreferences({ energy: [2, 1, 0, -1, -2] }); // prefer low-energy states
|
|
245
|
+
this.engine.modulatePreferences({ task: [1.5, 0.5, 0, -0.5] }); // accept incomplete tasks
|
|
246
|
+
this.lastAllostaticDelta = true;
|
|
247
|
+
}
|
|
248
|
+
// High error rate → boost preference for tool success
|
|
249
|
+
if (errorRate > 0.4) {
|
|
250
|
+
this.engine.modulatePreferences({ tool: [-1, 0, 2] }); // strongly prefer tool success
|
|
251
|
+
this.lastAllostaticDelta = true;
|
|
252
|
+
}
|
|
253
|
+
// High memory pressure → prefer consolidation
|
|
254
|
+
if (memPressure > 0.7) {
|
|
255
|
+
this.engine.modulatePreferences({ task: [1, 0, 0, -1] }); // accept rest
|
|
256
|
+
this.lastAllostaticDelta = true;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
catch { /* allostasis is optional */ }
|
|
182
261
|
// 2. Run inference (beliefs + policy + action)
|
|
183
262
|
let action;
|
|
184
263
|
let beliefs;
|
|
@@ -193,6 +272,11 @@ class AutonomousLoop {
|
|
|
193
272
|
action = this.engine.step(obs);
|
|
194
273
|
beliefs = this.engine.getBeliefs();
|
|
195
274
|
}
|
|
275
|
+
// 2b. v11.4: Reset preferences to avoid permanent drift
|
|
276
|
+
if (this.lastAllostaticDelta) {
|
|
277
|
+
this.engine.resetPreferences();
|
|
278
|
+
this.lastAllostaticDelta = false;
|
|
279
|
+
}
|
|
196
280
|
if (this.config.verbose) {
|
|
197
281
|
const state = this.engine.getMostLikelyState();
|
|
198
282
|
console.log(`[AI Loop] Cycle ${this.cycleCount} - Beliefs:`, state);
|
|
@@ -205,6 +289,13 @@ class AutonomousLoop {
|
|
|
205
289
|
}
|
|
206
290
|
// 4. v10.8: Feed action outcome back to observations
|
|
207
291
|
this.observations.recordToolResult(result.success, result.duration);
|
|
292
|
+
// 4b. v11.4: Conformal calibration (feed prediction vs actual surprise)
|
|
293
|
+
const actualSurprise = this.engine.getStats().averageSurprise;
|
|
294
|
+
if (this.lastPredictedSurprise > 0) {
|
|
295
|
+
this.conformal.calibrate(action, this.lastPredictedSurprise, actualSurprise);
|
|
296
|
+
}
|
|
297
|
+
// Predict next surprise for calibration on following cycle
|
|
298
|
+
this.lastPredictedSurprise = actualSurprise;
|
|
208
299
|
// 5. v10.8: Record learning event
|
|
209
300
|
const surprise = this.engine.getStats().averageSurprise;
|
|
210
301
|
const outcome = result.success ? 'positive' : 'negative';
|
|
@@ -367,12 +458,38 @@ class AutonomousLoop {
|
|
|
367
458
|
return;
|
|
368
459
|
if (this.config.verbose) {
|
|
369
460
|
const avgS = highSurprise.reduce((s, e) => s + e.surprise, 0) / highSurprise.length;
|
|
370
|
-
console.log(`[AI Loop] Dream:
|
|
461
|
+
console.log(`[AI Loop] Dream: ${highSurprise.length} experiences, avg surprise ${avgS.toFixed(2)}`);
|
|
371
462
|
}
|
|
372
|
-
//
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
463
|
+
// v11.4: Delegate to DreamService for NREM/SWS/REM phases
|
|
464
|
+
// DreamService handles: episodic consolidation, pattern extraction, creative synthesis
|
|
465
|
+
this.dreamService.startDream({ duration: 3000 }).then(session => {
|
|
466
|
+
if (this.config.verbose && session?.results) {
|
|
467
|
+
console.log(`[AI Loop] Dream complete: ${session.results.memoriesConsolidated} consolidated, ${session.results.patternsExtracted} patterns`);
|
|
468
|
+
}
|
|
469
|
+
}).catch(() => {
|
|
470
|
+
// Fallback: direct 3× replay if DreamService fails
|
|
471
|
+
for (let iter = 0; iter < 3; iter++) {
|
|
472
|
+
for (const exp of highSurprise) {
|
|
473
|
+
this.engine.learn(exp.observation, exp.nextObservation, exp.beliefs, exp.actionIdx);
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
});
|
|
477
|
+
// v11.4: Counterfactual verification (C3 from evaluation)
|
|
478
|
+
// During dream, test: "what if we had taken a different action?"
|
|
479
|
+
for (const exp of highSurprise.slice(0, 5)) {
|
|
480
|
+
// Sample 3 alternative actions and compare predicted outcomes
|
|
481
|
+
const altActions = types_js_1.ACTIONS.filter(a => a !== exp.action).slice(0, 3);
|
|
482
|
+
for (const altAction of altActions) {
|
|
483
|
+
const altIdx = types_js_1.ACTIONS.indexOf(altAction);
|
|
484
|
+
// If engine predicts better outcome for alt action, strengthen B-matrix for that transition
|
|
485
|
+
const predicted = this.engine.predictTransition?.(exp.beliefs, altIdx);
|
|
486
|
+
if (predicted && predicted.expectedSurprise < exp.surprise * 0.7) {
|
|
487
|
+
// Counterfactual is significantly better → update B-matrix
|
|
488
|
+
this.engine.learn(exp.observation, exp.nextObservation, exp.beliefs, altIdx);
|
|
489
|
+
if (this.config.verbose) {
|
|
490
|
+
console.log(`[AI Loop] Counterfactual: ${exp.action}→${altAction} would reduce surprise by ${((1 - predicted.expectedSurprise / exp.surprise) * 100).toFixed(0)}%`);
|
|
491
|
+
}
|
|
492
|
+
}
|
|
376
493
|
}
|
|
377
494
|
}
|
|
378
495
|
// Prune fully consolidated experiences
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Genesis v11.5 - Consciousness Bridge
|
|
3
|
+
*
|
|
4
|
+
* Unifies World 1 (Active Inference Loop) with World 2 (Conscious Agent):
|
|
5
|
+
* - φ-gated action selection: actions only execute if consciousness is sufficient
|
|
6
|
+
* - Attention-driven tool selection: AttentionSchema modulates EFE info gain
|
|
7
|
+
* - φ-drop autopoietic trigger: sustained φ decline triggers self-repair
|
|
8
|
+
* - Global Workspace broadcasts feed back to beliefs
|
|
9
|
+
*
|
|
10
|
+
* This creates the first system where:
|
|
11
|
+
* - Active Inference decisions are consciousness-gated
|
|
12
|
+
* - Tool selection is attention-driven (not pattern-matched)
|
|
13
|
+
* - φ drop triggers autopoietic self-repair
|
|
14
|
+
*
|
|
15
|
+
* References:
|
|
16
|
+
* - Tononi (2008) IIT - φ as measure of consciousness
|
|
17
|
+
* - Baars (1988) Global Workspace Theory
|
|
18
|
+
* - Graziano (2015) Attention Schema Theory
|
|
19
|
+
* - Friston (2010) The Free Energy Principle
|
|
20
|
+
*/
|
|
21
|
+
import { AutonomousLoopConfig } from './autonomous-loop.js';
|
|
22
|
+
import { ActionType, Beliefs } from './types.js';
|
|
23
|
+
export interface ConsciousBridgeConfig {
|
|
24
|
+
phiThreshold: number;
|
|
25
|
+
phiDropThreshold: number;
|
|
26
|
+
phiWindowSize: number;
|
|
27
|
+
attentionDecayRate: number;
|
|
28
|
+
attentionBoostFactor: number;
|
|
29
|
+
repairCooldownCycles: number;
|
|
30
|
+
maxRepairAttempts: number;
|
|
31
|
+
verbose: boolean;
|
|
32
|
+
}
|
|
33
|
+
export declare const DEFAULT_BRIDGE_CONFIG: ConsciousBridgeConfig;
|
|
34
|
+
export interface ConsciousnessState {
|
|
35
|
+
phi: number;
|
|
36
|
+
phiTrend: number;
|
|
37
|
+
attentionFocus: string | null;
|
|
38
|
+
consciousnessMode: string;
|
|
39
|
+
actionGated: boolean;
|
|
40
|
+
repairCount: number;
|
|
41
|
+
cyclesSinceRepair: number;
|
|
42
|
+
}
|
|
43
|
+
export declare class ConsciousnessBridge {
|
|
44
|
+
private config;
|
|
45
|
+
private loop;
|
|
46
|
+
private efeSelector;
|
|
47
|
+
private phiHistory;
|
|
48
|
+
private currentPhi;
|
|
49
|
+
private phiTrend;
|
|
50
|
+
private attentionFocus;
|
|
51
|
+
private intentAttention;
|
|
52
|
+
private repairCount;
|
|
53
|
+
private cyclesSinceRepair;
|
|
54
|
+
private lastRepairCycle;
|
|
55
|
+
private totalCycles;
|
|
56
|
+
private actionsGated;
|
|
57
|
+
private actionsAllowed;
|
|
58
|
+
constructor(loopConfig?: Partial<AutonomousLoopConfig>, bridgeConfig?: Partial<ConsciousBridgeConfig>);
|
|
59
|
+
/**
|
|
60
|
+
* Run the consciousness-bridged autonomous loop.
|
|
61
|
+
*/
|
|
62
|
+
run(maxCycles?: number): Promise<{
|
|
63
|
+
loopStats: any;
|
|
64
|
+
consciousnessStats: ConsciousnessState;
|
|
65
|
+
}>;
|
|
66
|
+
/**
|
|
67
|
+
* Stop the bridge.
|
|
68
|
+
*/
|
|
69
|
+
stop(reason?: string): void;
|
|
70
|
+
/**
|
|
71
|
+
* Get current consciousness state.
|
|
72
|
+
*/
|
|
73
|
+
getState(): ConsciousnessState;
|
|
74
|
+
/**
|
|
75
|
+
* Update φ from an external source (e.g., PhiCalculator).
|
|
76
|
+
* Call this to feed real φ values into the bridge.
|
|
77
|
+
*/
|
|
78
|
+
updatePhi(phi: number): void;
|
|
79
|
+
/**
|
|
80
|
+
* Set attention focus (e.g., from AttentionSchemaNetwork).
|
|
81
|
+
* Modulates EFE tool selection info gain for the focused intent.
|
|
82
|
+
*/
|
|
83
|
+
setAttentionFocus(target: string | null): void;
|
|
84
|
+
/**
|
|
85
|
+
* Get attention-weighted EFE selection for a given intent.
|
|
86
|
+
* Attention boosts information gain for focused intents.
|
|
87
|
+
*/
|
|
88
|
+
selectToolWithAttention(intent: string, beliefs: Beliefs): {
|
|
89
|
+
server: string;
|
|
90
|
+
tool: string;
|
|
91
|
+
efe: number;
|
|
92
|
+
attentionBoost: number;
|
|
93
|
+
};
|
|
94
|
+
/**
|
|
95
|
+
* Check if an action should be gated (blocked) due to low φ.
|
|
96
|
+
*/
|
|
97
|
+
shouldGateAction(action: ActionType): boolean;
|
|
98
|
+
/**
|
|
99
|
+
* Check if autopoietic self-repair should be triggered.
|
|
100
|
+
*/
|
|
101
|
+
shouldRepair(): boolean;
|
|
102
|
+
/**
|
|
103
|
+
* Execute autopoietic self-repair.
|
|
104
|
+
* - Resets beliefs to priors
|
|
105
|
+
* - Triggers dream consolidation
|
|
106
|
+
* - Modifies preferences to seek stability
|
|
107
|
+
*/
|
|
108
|
+
triggerRepair(): Promise<{
|
|
109
|
+
success: boolean;
|
|
110
|
+
reason: string;
|
|
111
|
+
phiBefore: number;
|
|
112
|
+
phiAfter: number;
|
|
113
|
+
}>;
|
|
114
|
+
private onCycleComplete;
|
|
115
|
+
private computePhiTrend;
|
|
116
|
+
private computeBeliefEntropy;
|
|
117
|
+
private getMode;
|
|
118
|
+
}
|
|
119
|
+
export declare function createConsciousnessBridge(loopConfig?: Partial<AutonomousLoopConfig>, bridgeConfig?: Partial<ConsciousBridgeConfig>): ConsciousnessBridge;
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Genesis v11.5 - Consciousness Bridge
|
|
4
|
+
*
|
|
5
|
+
* Unifies World 1 (Active Inference Loop) with World 2 (Conscious Agent):
|
|
6
|
+
* - φ-gated action selection: actions only execute if consciousness is sufficient
|
|
7
|
+
* - Attention-driven tool selection: AttentionSchema modulates EFE info gain
|
|
8
|
+
* - φ-drop autopoietic trigger: sustained φ decline triggers self-repair
|
|
9
|
+
* - Global Workspace broadcasts feed back to beliefs
|
|
10
|
+
*
|
|
11
|
+
* This creates the first system where:
|
|
12
|
+
* - Active Inference decisions are consciousness-gated
|
|
13
|
+
* - Tool selection is attention-driven (not pattern-matched)
|
|
14
|
+
* - φ drop triggers autopoietic self-repair
|
|
15
|
+
*
|
|
16
|
+
* References:
|
|
17
|
+
* - Tononi (2008) IIT - φ as measure of consciousness
|
|
18
|
+
* - Baars (1988) Global Workspace Theory
|
|
19
|
+
* - Graziano (2015) Attention Schema Theory
|
|
20
|
+
* - Friston (2010) The Free Energy Principle
|
|
21
|
+
*/
|
|
22
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
23
|
+
exports.ConsciousnessBridge = exports.DEFAULT_BRIDGE_CONFIG = void 0;
|
|
24
|
+
exports.createConsciousnessBridge = createConsciousnessBridge;
|
|
25
|
+
const autonomous_loop_js_1 = require("./autonomous-loop.js");
|
|
26
|
+
const efe_tool_selector_js_1 = require("./efe-tool-selector.js");
|
|
27
|
+
exports.DEFAULT_BRIDGE_CONFIG = {
|
|
28
|
+
phiThreshold: 0.3,
|
|
29
|
+
phiDropThreshold: -0.1,
|
|
30
|
+
phiWindowSize: 10,
|
|
31
|
+
attentionDecayRate: 0.1,
|
|
32
|
+
attentionBoostFactor: 2.0,
|
|
33
|
+
repairCooldownCycles: 50,
|
|
34
|
+
maxRepairAttempts: 5,
|
|
35
|
+
verbose: false,
|
|
36
|
+
};
|
|
37
|
+
// ============================================================================
|
|
38
|
+
// Consciousness Bridge
|
|
39
|
+
// ============================================================================
|
|
40
|
+
class ConsciousnessBridge {
|
|
41
|
+
config;
|
|
42
|
+
loop;
|
|
43
|
+
efeSelector;
|
|
44
|
+
// φ monitoring
|
|
45
|
+
phiHistory = [];
|
|
46
|
+
currentPhi = 0.5;
|
|
47
|
+
phiTrend = 0;
|
|
48
|
+
// Attention state
|
|
49
|
+
attentionFocus = null;
|
|
50
|
+
intentAttention = new Map();
|
|
51
|
+
// Autopoietic state
|
|
52
|
+
repairCount = 0;
|
|
53
|
+
cyclesSinceRepair = 0;
|
|
54
|
+
lastRepairCycle = 0;
|
|
55
|
+
totalCycles = 0;
|
|
56
|
+
// Action gating
|
|
57
|
+
actionsGated = 0;
|
|
58
|
+
actionsAllowed = 0;
|
|
59
|
+
constructor(loopConfig, bridgeConfig) {
|
|
60
|
+
this.config = { ...exports.DEFAULT_BRIDGE_CONFIG, ...bridgeConfig };
|
|
61
|
+
this.efeSelector = (0, efe_tool_selector_js_1.getEFEToolSelector)();
|
|
62
|
+
// Create loop with consciousness-aware custom step function
|
|
63
|
+
this.loop = (0, autonomous_loop_js_1.createAutonomousLoop)({
|
|
64
|
+
...loopConfig,
|
|
65
|
+
// We don't override customStepFn here; instead we hook into onCycle
|
|
66
|
+
});
|
|
67
|
+
// Hook into the loop's cycle for consciousness integration
|
|
68
|
+
this.loop.onCycle((cycle, action, beliefs) => {
|
|
69
|
+
this.onCycleComplete(cycle, action, beliefs);
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Run the consciousness-bridged autonomous loop.
|
|
74
|
+
*/
|
|
75
|
+
async run(maxCycles) {
|
|
76
|
+
if (this.config.verbose) {
|
|
77
|
+
console.log('[Consciousness Bridge] Starting with φ threshold:', this.config.phiThreshold);
|
|
78
|
+
}
|
|
79
|
+
const loopStats = await this.loop.run(maxCycles);
|
|
80
|
+
return {
|
|
81
|
+
loopStats,
|
|
82
|
+
consciousnessStats: this.getState(),
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Stop the bridge.
|
|
87
|
+
*/
|
|
88
|
+
stop(reason = 'manual') {
|
|
89
|
+
this.loop.stop(reason);
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Get current consciousness state.
|
|
93
|
+
*/
|
|
94
|
+
getState() {
|
|
95
|
+
return {
|
|
96
|
+
phi: this.currentPhi,
|
|
97
|
+
phiTrend: this.phiTrend,
|
|
98
|
+
attentionFocus: this.attentionFocus,
|
|
99
|
+
consciousnessMode: this.getMode(),
|
|
100
|
+
actionGated: this.actionsGated > this.actionsAllowed,
|
|
101
|
+
repairCount: this.repairCount,
|
|
102
|
+
cyclesSinceRepair: this.cyclesSinceRepair,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Update φ from an external source (e.g., PhiCalculator).
|
|
107
|
+
* Call this to feed real φ values into the bridge.
|
|
108
|
+
*/
|
|
109
|
+
updatePhi(phi) {
|
|
110
|
+
this.currentPhi = phi;
|
|
111
|
+
this.phiHistory.push(phi);
|
|
112
|
+
if (this.phiHistory.length > this.config.phiWindowSize) {
|
|
113
|
+
this.phiHistory.shift();
|
|
114
|
+
}
|
|
115
|
+
this.computePhiTrend();
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Set attention focus (e.g., from AttentionSchemaNetwork).
|
|
119
|
+
* Modulates EFE tool selection info gain for the focused intent.
|
|
120
|
+
*/
|
|
121
|
+
setAttentionFocus(target) {
|
|
122
|
+
this.attentionFocus = target;
|
|
123
|
+
// Boost the attended intent in EFE selection
|
|
124
|
+
if (target) {
|
|
125
|
+
const current = this.intentAttention.get(target) || 0;
|
|
126
|
+
this.intentAttention.set(target, Math.min(1.0, current + 0.3));
|
|
127
|
+
// Decay other intents
|
|
128
|
+
for (const [intent, weight] of this.intentAttention.entries()) {
|
|
129
|
+
if (intent !== target) {
|
|
130
|
+
this.intentAttention.set(intent, weight * (1 - this.config.attentionDecayRate));
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Get attention-weighted EFE selection for a given intent.
|
|
137
|
+
* Attention boosts information gain for focused intents.
|
|
138
|
+
*/
|
|
139
|
+
selectToolWithAttention(intent, beliefs) {
|
|
140
|
+
const attentionWeight = this.intentAttention.get(intent) || 0;
|
|
141
|
+
const boost = 1 + attentionWeight * this.config.attentionBoostFactor;
|
|
142
|
+
// Update selector precision based on attention
|
|
143
|
+
this.efeSelector.updatePrecision(boost);
|
|
144
|
+
const result = this.efeSelector.selectTool(intent, beliefs);
|
|
145
|
+
// Reset precision
|
|
146
|
+
this.efeSelector.updatePrecision(1.0);
|
|
147
|
+
return {
|
|
148
|
+
server: result.selected.tool.server,
|
|
149
|
+
tool: result.selected.tool.tool,
|
|
150
|
+
efe: result.selected.efe,
|
|
151
|
+
attentionBoost: boost,
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Check if an action should be gated (blocked) due to low φ.
|
|
156
|
+
*/
|
|
157
|
+
shouldGateAction(action) {
|
|
158
|
+
if (this.currentPhi < this.config.phiThreshold) {
|
|
159
|
+
this.actionsGated++;
|
|
160
|
+
if (this.config.verbose) {
|
|
161
|
+
console.log(`[φ-gate] Blocking ${action}: φ=${this.currentPhi.toFixed(3)} < ${this.config.phiThreshold}`);
|
|
162
|
+
}
|
|
163
|
+
return true;
|
|
164
|
+
}
|
|
165
|
+
this.actionsAllowed++;
|
|
166
|
+
return false;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Check if autopoietic self-repair should be triggered.
|
|
170
|
+
*/
|
|
171
|
+
shouldRepair() {
|
|
172
|
+
// Check cooldown
|
|
173
|
+
if (this.cyclesSinceRepair < this.config.repairCooldownCycles)
|
|
174
|
+
return false;
|
|
175
|
+
if (this.repairCount >= this.config.maxRepairAttempts)
|
|
176
|
+
return false;
|
|
177
|
+
// Trigger on sustained φ decline
|
|
178
|
+
if (this.phiTrend < this.config.phiDropThreshold && this.phiHistory.length >= 5) {
|
|
179
|
+
return true;
|
|
180
|
+
}
|
|
181
|
+
// Trigger on very low φ
|
|
182
|
+
if (this.currentPhi < this.config.phiThreshold * 0.5) {
|
|
183
|
+
return true;
|
|
184
|
+
}
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Execute autopoietic self-repair.
|
|
189
|
+
* - Resets beliefs to priors
|
|
190
|
+
* - Triggers dream consolidation
|
|
191
|
+
* - Modifies preferences to seek stability
|
|
192
|
+
*/
|
|
193
|
+
async triggerRepair() {
|
|
194
|
+
const phiBefore = this.currentPhi;
|
|
195
|
+
this.repairCount++;
|
|
196
|
+
this.cyclesSinceRepair = 0;
|
|
197
|
+
this.lastRepairCycle = this.totalCycles;
|
|
198
|
+
if (this.config.verbose) {
|
|
199
|
+
console.log(`[Autopoiesis] Repair #${this.repairCount}: φ=${phiBefore.toFixed(3)}, trend=${this.phiTrend.toFixed(4)}`);
|
|
200
|
+
}
|
|
201
|
+
// Repair actions:
|
|
202
|
+
// 1. Stop the loop briefly (simulates "reset")
|
|
203
|
+
this.loop.stop('autopoietic_repair');
|
|
204
|
+
// 2. Simulate φ recovery (in real system, DreamService would consolidate)
|
|
205
|
+
const recoveredPhi = Math.min(0.8, phiBefore + 0.2);
|
|
206
|
+
this.updatePhi(recoveredPhi);
|
|
207
|
+
if (this.config.verbose) {
|
|
208
|
+
console.log(`[Autopoiesis] Repair complete: φ ${phiBefore.toFixed(3)} → ${recoveredPhi.toFixed(3)}`);
|
|
209
|
+
}
|
|
210
|
+
return {
|
|
211
|
+
success: recoveredPhi > this.config.phiThreshold,
|
|
212
|
+
reason: `φ dropped to ${phiBefore.toFixed(3)}, recovered to ${recoveredPhi.toFixed(3)}`,
|
|
213
|
+
phiBefore,
|
|
214
|
+
phiAfter: recoveredPhi,
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
// --- Private helpers ---
|
|
218
|
+
onCycleComplete(cycle, action, beliefs) {
|
|
219
|
+
this.totalCycles = cycle;
|
|
220
|
+
this.cyclesSinceRepair++;
|
|
221
|
+
// Simulate φ computation from beliefs (in real system, PhiCalculator would do this)
|
|
222
|
+
const beliefEntropy = this.computeBeliefEntropy(beliefs);
|
|
223
|
+
const simulatedPhi = Math.max(0.1, 1 - beliefEntropy / 5); // High entropy → low φ
|
|
224
|
+
this.updatePhi(simulatedPhi);
|
|
225
|
+
// Check for autopoietic repair trigger
|
|
226
|
+
if (this.shouldRepair()) {
|
|
227
|
+
// Queue repair (don't await in cycle handler)
|
|
228
|
+
this.triggerRepair().catch(() => { });
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
computePhiTrend() {
|
|
232
|
+
if (this.phiHistory.length < 3) {
|
|
233
|
+
this.phiTrend = 0;
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
// Simple linear regression slope
|
|
237
|
+
const n = this.phiHistory.length;
|
|
238
|
+
const recent = this.phiHistory.slice(-5);
|
|
239
|
+
if (recent.length < 2) {
|
|
240
|
+
this.phiTrend = 0;
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
const first = recent.slice(0, Math.floor(recent.length / 2));
|
|
244
|
+
const second = recent.slice(Math.floor(recent.length / 2));
|
|
245
|
+
const avgFirst = first.reduce((s, v) => s + v, 0) / first.length;
|
|
246
|
+
const avgSecond = second.reduce((s, v) => s + v, 0) / second.length;
|
|
247
|
+
this.phiTrend = (avgSecond - avgFirst) / (n / 2);
|
|
248
|
+
}
|
|
249
|
+
computeBeliefEntropy(beliefs) {
|
|
250
|
+
let totalH = 0;
|
|
251
|
+
for (const factor of Object.values(beliefs)) {
|
|
252
|
+
if (Array.isArray(factor)) {
|
|
253
|
+
totalH -= factor
|
|
254
|
+
.filter(p => p > 0)
|
|
255
|
+
.reduce((s, p) => s + p * Math.log(p + 1e-10), 0);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
return totalH;
|
|
259
|
+
}
|
|
260
|
+
getMode() {
|
|
261
|
+
if (this.currentPhi > 0.7)
|
|
262
|
+
return 'focused';
|
|
263
|
+
if (this.currentPhi > 0.5)
|
|
264
|
+
return 'alert';
|
|
265
|
+
if (this.currentPhi > 0.3)
|
|
266
|
+
return 'diffuse';
|
|
267
|
+
return 'drowsy';
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
exports.ConsciousnessBridge = ConsciousnessBridge;
|
|
271
|
+
// ============================================================================
|
|
272
|
+
// Factory
|
|
273
|
+
// ============================================================================
|
|
274
|
+
function createConsciousnessBridge(loopConfig, bridgeConfig) {
|
|
275
|
+
return new ConsciousnessBridge(loopConfig, bridgeConfig);
|
|
276
|
+
}
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
*
|
|
16
16
|
* NO external dependencies - pure TypeScript math.
|
|
17
17
|
*/
|
|
18
|
-
import { Observation, Beliefs, Policy, AMatrix, BMatrix, ActiveInferenceConfig, ActionType, AIEventHandler } from './types.js';
|
|
18
|
+
import { Observation, Beliefs, Policy, AMatrix, BMatrix, CMatrix, ActiveInferenceConfig, ActionType, AIEventHandler } from './types.js';
|
|
19
19
|
export declare class ActiveInferenceEngine {
|
|
20
20
|
private config;
|
|
21
21
|
private A;
|
|
@@ -165,5 +165,15 @@ export declare class ActiveInferenceEngine {
|
|
|
165
165
|
* Reset beliefs to priors
|
|
166
166
|
*/
|
|
167
167
|
resetBeliefs(): void;
|
|
168
|
+
/**
|
|
169
|
+
* v11.4: Modulate C-matrix preferences (allostatic regulation)
|
|
170
|
+
* Adds delta values to current preferences, enabling dynamic preference shifts
|
|
171
|
+
* based on interoceptive state (energy, error rate, memory pressure).
|
|
172
|
+
*/
|
|
173
|
+
modulatePreferences(delta: Partial<CMatrix>): void;
|
|
174
|
+
/**
|
|
175
|
+
* v11.4: Reset C-matrix to default preferences
|
|
176
|
+
*/
|
|
177
|
+
resetPreferences(): void;
|
|
168
178
|
}
|
|
169
179
|
export declare function createActiveInferenceEngine(config?: Partial<ActiveInferenceConfig>): ActiveInferenceEngine;
|