genesis-ai-cli 7.4.5
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/.env.example +78 -0
- package/README.md +282 -0
- package/dist/src/active-inference/actions.d.ts +75 -0
- package/dist/src/active-inference/actions.js +250 -0
- package/dist/src/active-inference/autonomous-loop.d.ts +103 -0
- package/dist/src/active-inference/autonomous-loop.js +289 -0
- package/dist/src/active-inference/core.d.ts +85 -0
- package/dist/src/active-inference/core.js +555 -0
- package/dist/src/active-inference/demo-autonomous-loop.d.ts +8 -0
- package/dist/src/active-inference/demo-autonomous-loop.js +338 -0
- package/dist/src/active-inference/demo-value-integration.d.ts +8 -0
- package/dist/src/active-inference/demo-value-integration.js +174 -0
- package/dist/src/active-inference/index.d.ts +32 -0
- package/dist/src/active-inference/index.js +88 -0
- package/dist/src/active-inference/integration.d.ts +114 -0
- package/dist/src/active-inference/integration.js +698 -0
- package/dist/src/active-inference/memory-integration.d.ts +51 -0
- package/dist/src/active-inference/memory-integration.js +232 -0
- package/dist/src/active-inference/observations.d.ts +67 -0
- package/dist/src/active-inference/observations.js +147 -0
- package/dist/src/active-inference/test-active-inference.d.ts +8 -0
- package/dist/src/active-inference/test-active-inference.js +320 -0
- package/dist/src/active-inference/test-value-integration.d.ts +6 -0
- package/dist/src/active-inference/test-value-integration.js +168 -0
- package/dist/src/active-inference/types.d.ts +150 -0
- package/dist/src/active-inference/types.js +59 -0
- package/dist/src/active-inference/value-integration.d.ts +164 -0
- package/dist/src/active-inference/value-integration.js +459 -0
- package/dist/src/agents/base-agent.d.ts +53 -0
- package/dist/src/agents/base-agent.js +178 -0
- package/dist/src/agents/builder.d.ts +67 -0
- package/dist/src/agents/builder.js +537 -0
- package/dist/src/agents/critic.d.ts +35 -0
- package/dist/src/agents/critic.js +322 -0
- package/dist/src/agents/ethicist.d.ts +54 -0
- package/dist/src/agents/ethicist.js +393 -0
- package/dist/src/agents/explorer.d.ts +26 -0
- package/dist/src/agents/explorer.js +216 -0
- package/dist/src/agents/feeling.d.ts +41 -0
- package/dist/src/agents/feeling.js +320 -0
- package/dist/src/agents/index.d.ts +111 -0
- package/dist/src/agents/index.js +222 -0
- package/dist/src/agents/memory.d.ts +69 -0
- package/dist/src/agents/memory.js +404 -0
- package/dist/src/agents/message-bus.d.ts +88 -0
- package/dist/src/agents/message-bus.js +267 -0
- package/dist/src/agents/narrator.d.ts +90 -0
- package/dist/src/agents/narrator.js +473 -0
- package/dist/src/agents/planner.d.ts +38 -0
- package/dist/src/agents/planner.js +341 -0
- package/dist/src/agents/predictor.d.ts +73 -0
- package/dist/src/agents/predictor.js +506 -0
- package/dist/src/agents/sensor.d.ts +88 -0
- package/dist/src/agents/sensor.js +377 -0
- package/dist/src/agents/test-agents.d.ts +6 -0
- package/dist/src/agents/test-agents.js +73 -0
- package/dist/src/agents/types.d.ts +194 -0
- package/dist/src/agents/types.js +7 -0
- package/dist/src/brain/index.d.ts +185 -0
- package/dist/src/brain/index.js +843 -0
- package/dist/src/brain/trace.d.ts +91 -0
- package/dist/src/brain/trace.js +327 -0
- package/dist/src/brain/types.d.ts +165 -0
- package/dist/src/brain/types.js +51 -0
- package/dist/src/cli/chat.d.ts +237 -0
- package/dist/src/cli/chat.js +1959 -0
- package/dist/src/cli/dispatcher.d.ts +182 -0
- package/dist/src/cli/dispatcher.js +718 -0
- package/dist/src/cli/human-loop.d.ts +170 -0
- package/dist/src/cli/human-loop.js +543 -0
- package/dist/src/cli/index.d.ts +12 -0
- package/dist/src/cli/index.js +28 -0
- package/dist/src/cli/interactive.d.ts +141 -0
- package/dist/src/cli/interactive.js +757 -0
- package/dist/src/cli/ui.d.ts +205 -0
- package/dist/src/cli/ui.js +632 -0
- package/dist/src/consciousness/attention-schema.d.ts +154 -0
- package/dist/src/consciousness/attention-schema.js +432 -0
- package/dist/src/consciousness/global-workspace.d.ts +149 -0
- package/dist/src/consciousness/global-workspace.js +422 -0
- package/dist/src/consciousness/index.d.ts +186 -0
- package/dist/src/consciousness/index.js +476 -0
- package/dist/src/consciousness/phi-calculator.d.ts +119 -0
- package/dist/src/consciousness/phi-calculator.js +445 -0
- package/dist/src/consciousness/phi-decisions.d.ts +169 -0
- package/dist/src/consciousness/phi-decisions.js +383 -0
- package/dist/src/consciousness/phi-monitor.d.ts +153 -0
- package/dist/src/consciousness/phi-monitor.js +465 -0
- package/dist/src/consciousness/types.d.ts +260 -0
- package/dist/src/consciousness/types.js +44 -0
- package/dist/src/daemon/dream-mode.d.ts +115 -0
- package/dist/src/daemon/dream-mode.js +470 -0
- package/dist/src/daemon/index.d.ts +162 -0
- package/dist/src/daemon/index.js +542 -0
- package/dist/src/daemon/maintenance.d.ts +139 -0
- package/dist/src/daemon/maintenance.js +549 -0
- package/dist/src/daemon/process.d.ts +82 -0
- package/dist/src/daemon/process.js +442 -0
- package/dist/src/daemon/scheduler.d.ts +90 -0
- package/dist/src/daemon/scheduler.js +494 -0
- package/dist/src/daemon/types.d.ts +213 -0
- package/dist/src/daemon/types.js +50 -0
- package/dist/src/epistemic/index.d.ts +74 -0
- package/dist/src/epistemic/index.js +225 -0
- package/dist/src/grounding/epistemic-stack.d.ts +100 -0
- package/dist/src/grounding/epistemic-stack.js +408 -0
- package/dist/src/grounding/feedback.d.ts +98 -0
- package/dist/src/grounding/feedback.js +276 -0
- package/dist/src/grounding/index.d.ts +123 -0
- package/dist/src/grounding/index.js +224 -0
- package/dist/src/grounding/verifier.d.ts +149 -0
- package/dist/src/grounding/verifier.js +484 -0
- package/dist/src/healing/detector.d.ts +110 -0
- package/dist/src/healing/detector.js +436 -0
- package/dist/src/healing/fixer.d.ts +138 -0
- package/dist/src/healing/fixer.js +572 -0
- package/dist/src/healing/index.d.ts +23 -0
- package/dist/src/healing/index.js +43 -0
- package/dist/src/hooks/index.d.ts +135 -0
- package/dist/src/hooks/index.js +317 -0
- package/dist/src/index.d.ts +23 -0
- package/dist/src/index.js +1266 -0
- package/dist/src/kernel/index.d.ts +155 -0
- package/dist/src/kernel/index.js +795 -0
- package/dist/src/kernel/invariants.d.ts +153 -0
- package/dist/src/kernel/invariants.js +355 -0
- package/dist/src/kernel/test-kernel.d.ts +6 -0
- package/dist/src/kernel/test-kernel.js +108 -0
- package/dist/src/kernel/test-real-mcp.d.ts +10 -0
- package/dist/src/kernel/test-real-mcp.js +295 -0
- package/dist/src/llm/index.d.ts +146 -0
- package/dist/src/llm/index.js +428 -0
- package/dist/src/llm/router.d.ts +136 -0
- package/dist/src/llm/router.js +510 -0
- package/dist/src/mcp/index.d.ts +85 -0
- package/dist/src/mcp/index.js +657 -0
- package/dist/src/mcp/resilient.d.ts +139 -0
- package/dist/src/mcp/resilient.js +417 -0
- package/dist/src/memory/cache.d.ts +118 -0
- package/dist/src/memory/cache.js +356 -0
- package/dist/src/memory/cognitive-workspace.d.ts +231 -0
- package/dist/src/memory/cognitive-workspace.js +521 -0
- package/dist/src/memory/consolidation.d.ts +99 -0
- package/dist/src/memory/consolidation.js +443 -0
- package/dist/src/memory/episodic.d.ts +114 -0
- package/dist/src/memory/episodic.js +394 -0
- package/dist/src/memory/forgetting.d.ts +134 -0
- package/dist/src/memory/forgetting.js +324 -0
- package/dist/src/memory/index.d.ts +211 -0
- package/dist/src/memory/index.js +367 -0
- package/dist/src/memory/indexer.d.ts +123 -0
- package/dist/src/memory/indexer.js +479 -0
- package/dist/src/memory/procedural.d.ts +136 -0
- package/dist/src/memory/procedural.js +479 -0
- package/dist/src/memory/semantic.d.ts +132 -0
- package/dist/src/memory/semantic.js +497 -0
- package/dist/src/memory/types.d.ts +193 -0
- package/dist/src/memory/types.js +15 -0
- package/dist/src/orchestrator.d.ts +65 -0
- package/dist/src/orchestrator.js +317 -0
- package/dist/src/persistence/index.d.ts +257 -0
- package/dist/src/persistence/index.js +763 -0
- package/dist/src/pipeline/executor.d.ts +51 -0
- package/dist/src/pipeline/executor.js +695 -0
- package/dist/src/pipeline/index.d.ts +7 -0
- package/dist/src/pipeline/index.js +11 -0
- package/dist/src/self-production.d.ts +67 -0
- package/dist/src/self-production.js +205 -0
- package/dist/src/subagents/executor.d.ts +58 -0
- package/dist/src/subagents/executor.js +283 -0
- package/dist/src/subagents/index.d.ts +37 -0
- package/dist/src/subagents/index.js +53 -0
- package/dist/src/subagents/registry.d.ts +23 -0
- package/dist/src/subagents/registry.js +167 -0
- package/dist/src/subagents/types.d.ts +79 -0
- package/dist/src/subagents/types.js +14 -0
- package/dist/src/tools/bash.d.ts +139 -0
- package/dist/src/tools/bash.js +583 -0
- package/dist/src/tools/edit.d.ts +125 -0
- package/dist/src/tools/edit.js +424 -0
- package/dist/src/tools/git.d.ts +179 -0
- package/dist/src/tools/git.js +504 -0
- package/dist/src/tools/index.d.ts +21 -0
- package/dist/src/tools/index.js +163 -0
- package/dist/src/types.d.ts +145 -0
- package/dist/src/types.js +7 -0
- package/dist/src/world-model/decoder.d.ts +163 -0
- package/dist/src/world-model/decoder.js +517 -0
- package/dist/src/world-model/digital-twin.d.ts +219 -0
- package/dist/src/world-model/digital-twin.js +695 -0
- package/dist/src/world-model/encoder.d.ts +141 -0
- package/dist/src/world-model/encoder.js +564 -0
- package/dist/src/world-model/index.d.ts +221 -0
- package/dist/src/world-model/index.js +772 -0
- package/dist/src/world-model/predictor.d.ts +161 -0
- package/dist/src/world-model/predictor.js +681 -0
- package/dist/src/world-model/test-value-jepa.d.ts +8 -0
- package/dist/src/world-model/test-value-jepa.js +430 -0
- package/dist/src/world-model/types.d.ts +341 -0
- package/dist/src/world-model/types.js +69 -0
- package/dist/src/world-model/value-jepa.d.ts +247 -0
- package/dist/src/world-model/value-jepa.js +622 -0
- package/dist/test/brain.test.d.ts +11 -0
- package/dist/test/brain.test.js +358 -0
- package/dist/test/cli/dispatcher.test.d.ts +4 -0
- package/dist/test/cli/dispatcher.test.js +332 -0
- package/dist/test/cli/human-loop.test.d.ts +4 -0
- package/dist/test/cli/human-loop.test.js +270 -0
- package/dist/test/grounding/feedback.test.d.ts +4 -0
- package/dist/test/grounding/feedback.test.js +462 -0
- package/dist/test/grounding/verifier.test.d.ts +4 -0
- package/dist/test/grounding/verifier.test.js +442 -0
- package/dist/test/grounding.test.d.ts +6 -0
- package/dist/test/grounding.test.js +246 -0
- package/dist/test/healing/detector.test.d.ts +4 -0
- package/dist/test/healing/detector.test.js +266 -0
- package/dist/test/healing/fixer.test.d.ts +4 -0
- package/dist/test/healing/fixer.test.js +369 -0
- package/dist/test/integration.test.d.ts +5 -0
- package/dist/test/integration.test.js +290 -0
- package/dist/test/tools/bash.test.d.ts +4 -0
- package/dist/test/tools/bash.test.js +348 -0
- package/dist/test/tools/edit.test.d.ts +4 -0
- package/dist/test/tools/edit.test.js +350 -0
- package/dist/test/tools/git.test.d.ts +4 -0
- package/dist/test/tools/git.test.js +350 -0
- package/package.json +60 -0
|
@@ -0,0 +1,843 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Genesis Phase 10 - Brain Module
|
|
4
|
+
*
|
|
5
|
+
* The Neural Integration Layer - connects all 17 modules.
|
|
6
|
+
*
|
|
7
|
+
* Based on:
|
|
8
|
+
* - arXiv:2508.13171 (Cognitive Workspace) - 54-60% memory reuse
|
|
9
|
+
* - LangGraph Supervisor Pattern - Command({ goto, update })
|
|
10
|
+
* - IWMT (Integrated World Modeling Theory) - GWT + IIT + Active Inference
|
|
11
|
+
*
|
|
12
|
+
* Architecture:
|
|
13
|
+
* ```
|
|
14
|
+
* ┌─────────────────────────────────────────────────────────────────────┐
|
|
15
|
+
* │ BRAIN │
|
|
16
|
+
* │ │
|
|
17
|
+
* │ ┌──────────────────────────────────────────────────────────────┐ │
|
|
18
|
+
* │ │ COGNITIVE WORKSPACE │ │
|
|
19
|
+
* │ │ Immediate (8K) → Task (64K) → Episodic (256K) → Semantic │ │
|
|
20
|
+
* │ │ recall() / anticipate() / consolidate() │ │
|
|
21
|
+
* │ └──────────────────────────────────────────────────────────────┘ │
|
|
22
|
+
* │ │ │
|
|
23
|
+
* │ ┌──────────────────────────────────────────────────────────────┐ │
|
|
24
|
+
* │ │ SUPERVISOR │ │
|
|
25
|
+
* │ │ memory → llm → grounding → tools → done │ │
|
|
26
|
+
* │ │ Command({ goto, update }) │ │
|
|
27
|
+
* │ └──────────────────────────────────────────────────────────────┘ │
|
|
28
|
+
* │ │ │
|
|
29
|
+
* │ ┌──────────────────────────────────────────────────────────────┐ │
|
|
30
|
+
* │ │ GLOBAL WORKSPACE (φ Monitor) │ │
|
|
31
|
+
* │ │ broadcast() → all modules receive │ │
|
|
32
|
+
* │ └──────────────────────────────────────────────────────────────┘ │
|
|
33
|
+
* │ │ │
|
|
34
|
+
* │ ┌──────────────────────────────────────────────────────────────┐ │
|
|
35
|
+
* │ │ HEALING LOOP │ │
|
|
36
|
+
* │ │ detect() → diagnose() → fix() → verify() → retry() │ │
|
|
37
|
+
* │ └──────────────────────────────────────────────────────────────┘ │
|
|
38
|
+
* └─────────────────────────────────────────────────────────────────────┘
|
|
39
|
+
* ```
|
|
40
|
+
*/
|
|
41
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
42
|
+
if (k2 === undefined) k2 = k;
|
|
43
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
44
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
45
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
46
|
+
}
|
|
47
|
+
Object.defineProperty(o, k2, desc);
|
|
48
|
+
}) : (function(o, m, k, k2) {
|
|
49
|
+
if (k2 === undefined) k2 = k;
|
|
50
|
+
o[k2] = m[k];
|
|
51
|
+
}));
|
|
52
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
53
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
54
|
+
};
|
|
55
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
56
|
+
exports.Brain = void 0;
|
|
57
|
+
exports.createBrain = createBrain;
|
|
58
|
+
exports.getBrain = getBrain;
|
|
59
|
+
exports.resetBrain = resetBrain;
|
|
60
|
+
const types_js_1 = require("./types.js");
|
|
61
|
+
// Module imports
|
|
62
|
+
const cognitive_workspace_js_1 = require("../memory/cognitive-workspace.js");
|
|
63
|
+
const global_workspace_js_1 = require("../consciousness/global-workspace.js");
|
|
64
|
+
const phi_monitor_js_1 = require("../consciousness/phi-monitor.js");
|
|
65
|
+
const index_js_1 = require("../llm/index.js");
|
|
66
|
+
const dispatcher_js_1 = require("../cli/dispatcher.js");
|
|
67
|
+
const index_js_2 = require("../healing/index.js");
|
|
68
|
+
const index_js_3 = require("../grounding/index.js");
|
|
69
|
+
// ============================================================================
|
|
70
|
+
// Brain Class
|
|
71
|
+
// ============================================================================
|
|
72
|
+
class Brain {
|
|
73
|
+
config;
|
|
74
|
+
// Core modules
|
|
75
|
+
workspace;
|
|
76
|
+
globalWorkspace;
|
|
77
|
+
phiMonitor;
|
|
78
|
+
llm;
|
|
79
|
+
dispatcher;
|
|
80
|
+
grounding;
|
|
81
|
+
// State
|
|
82
|
+
running = false;
|
|
83
|
+
currentState = null;
|
|
84
|
+
systemPrompt = ''; // v7.2: Cached system prompt with tools
|
|
85
|
+
// Metrics
|
|
86
|
+
metrics = this.createInitialMetrics();
|
|
87
|
+
// Event handlers
|
|
88
|
+
eventHandlers = new Set();
|
|
89
|
+
constructor(config = {}) {
|
|
90
|
+
this.config = { ...types_js_1.DEFAULT_BRAIN_CONFIG, ...config };
|
|
91
|
+
// Initialize modules
|
|
92
|
+
this.workspace = (0, cognitive_workspace_js_1.getCognitiveWorkspace)({
|
|
93
|
+
maxItems: 7,
|
|
94
|
+
maxTokens: this.config.memory.maxContextTokens,
|
|
95
|
+
});
|
|
96
|
+
this.globalWorkspace = (0, global_workspace_js_1.createGlobalWorkspace)({
|
|
97
|
+
capacity: 7,
|
|
98
|
+
selectionIntervalMs: 100,
|
|
99
|
+
});
|
|
100
|
+
this.phiMonitor = (0, phi_monitor_js_1.createPhiMonitor)({
|
|
101
|
+
minPhi: this.config.consciousness.phiThreshold,
|
|
102
|
+
updateIntervalMs: 5000,
|
|
103
|
+
});
|
|
104
|
+
this.llm = (0, index_js_1.getLLMBridge)();
|
|
105
|
+
this.dispatcher = new dispatcher_js_1.ToolDispatcher({ verbose: false });
|
|
106
|
+
this.grounding = (0, index_js_3.getGroundingSystem)();
|
|
107
|
+
}
|
|
108
|
+
// ============================================================================
|
|
109
|
+
// Lifecycle
|
|
110
|
+
// ============================================================================
|
|
111
|
+
/**
|
|
112
|
+
* Start the brain (initializes consciousness monitoring)
|
|
113
|
+
*/
|
|
114
|
+
async start() {
|
|
115
|
+
if (this.running)
|
|
116
|
+
return;
|
|
117
|
+
this.running = true;
|
|
118
|
+
// v7.2: Build system prompt with available tools
|
|
119
|
+
await this.initializeSystemPrompt();
|
|
120
|
+
// Start consciousness monitoring
|
|
121
|
+
if (this.config.consciousness.enabled) {
|
|
122
|
+
this.phiMonitor.start();
|
|
123
|
+
this.globalWorkspace.start();
|
|
124
|
+
}
|
|
125
|
+
// Start memory curation
|
|
126
|
+
if (this.config.memory.enabled) {
|
|
127
|
+
this.workspace.startAutoCuration();
|
|
128
|
+
}
|
|
129
|
+
this.emit({ type: 'cycle_start', timestamp: new Date(), data: { status: 'brain_started' } });
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* v7.2: Build system prompt with all available tools
|
|
133
|
+
*/
|
|
134
|
+
async initializeSystemPrompt() {
|
|
135
|
+
if (this.systemPrompt)
|
|
136
|
+
return; // Already built
|
|
137
|
+
const tools = this.dispatcher.listToolsWithSchemas();
|
|
138
|
+
// Convert to format expected by buildSystemPrompt
|
|
139
|
+
const mcpTools = tools.mcp;
|
|
140
|
+
const localTools = tools.local;
|
|
141
|
+
this.systemPrompt = await (0, index_js_1.buildSystemPrompt)(mcpTools, localTools, true);
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Stop the brain
|
|
145
|
+
*/
|
|
146
|
+
stop() {
|
|
147
|
+
if (!this.running)
|
|
148
|
+
return;
|
|
149
|
+
this.running = false;
|
|
150
|
+
this.phiMonitor.stop();
|
|
151
|
+
this.globalWorkspace.stop();
|
|
152
|
+
this.workspace.stopAutoCuration();
|
|
153
|
+
this.emit({ type: 'cycle_complete', timestamp: new Date(), data: { status: 'brain_stopped' } });
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Check if brain is running
|
|
157
|
+
*/
|
|
158
|
+
isRunning() {
|
|
159
|
+
return this.running;
|
|
160
|
+
}
|
|
161
|
+
// ============================================================================
|
|
162
|
+
// Main Processing Loop
|
|
163
|
+
// ============================================================================
|
|
164
|
+
/**
|
|
165
|
+
* Process an input through the brain
|
|
166
|
+
*
|
|
167
|
+
* This is the main entry point. It follows the supervisor pattern:
|
|
168
|
+
* memory → llm → grounding → tools → done
|
|
169
|
+
*
|
|
170
|
+
* Each module can route to another via Command({ goto, update })
|
|
171
|
+
*/
|
|
172
|
+
async process(input) {
|
|
173
|
+
const startTime = Date.now();
|
|
174
|
+
// Initialize state
|
|
175
|
+
let state = {
|
|
176
|
+
query: input,
|
|
177
|
+
context: this.createEmptyContext(),
|
|
178
|
+
response: '',
|
|
179
|
+
toolCalls: [],
|
|
180
|
+
toolResults: [],
|
|
181
|
+
phi: this.getCurrentPhi(),
|
|
182
|
+
ignited: false,
|
|
183
|
+
verified: false,
|
|
184
|
+
healingAttempts: 0,
|
|
185
|
+
startTime,
|
|
186
|
+
moduleHistory: [],
|
|
187
|
+
};
|
|
188
|
+
// Initial command: start with memory
|
|
189
|
+
let command = {
|
|
190
|
+
goto: this.config.memory.enabled ? 'memory' : 'llm',
|
|
191
|
+
update: {},
|
|
192
|
+
reason: 'initial',
|
|
193
|
+
};
|
|
194
|
+
this.emit({ type: 'cycle_start', timestamp: new Date(), data: { query: input } });
|
|
195
|
+
// Supervisor loop
|
|
196
|
+
let transitions = 0;
|
|
197
|
+
while (command.goto !== 'done' && transitions < this.config.maxModuleTransitions) {
|
|
198
|
+
// Update state
|
|
199
|
+
state = { ...state, ...command.update };
|
|
200
|
+
state.moduleHistory.push(command.goto);
|
|
201
|
+
// Check timeout
|
|
202
|
+
if (Date.now() - startTime > this.config.maxCycleTime) {
|
|
203
|
+
command = { goto: 'done', update: { response: 'Processing timeout. Please try again.' } };
|
|
204
|
+
break;
|
|
205
|
+
}
|
|
206
|
+
try {
|
|
207
|
+
this.emit({ type: 'module_enter', timestamp: new Date(), data: { module: command.goto }, module: command.goto });
|
|
208
|
+
// Execute module
|
|
209
|
+
command = await this.step(command.goto, state);
|
|
210
|
+
this.emit({ type: 'module_exit', timestamp: new Date(), data: { module: command.goto, nextModule: command.goto }, module: command.goto });
|
|
211
|
+
// Broadcast to global workspace if enabled
|
|
212
|
+
if (this.config.consciousness.broadcastEnabled) {
|
|
213
|
+
this.broadcast(state, command.goto);
|
|
214
|
+
}
|
|
215
|
+
transitions++;
|
|
216
|
+
}
|
|
217
|
+
catch (error) {
|
|
218
|
+
// Healing loop
|
|
219
|
+
if (this.config.healing.enabled && this.config.healing.autoHeal) {
|
|
220
|
+
command = await this.heal(error, state);
|
|
221
|
+
}
|
|
222
|
+
else {
|
|
223
|
+
command = {
|
|
224
|
+
goto: 'done',
|
|
225
|
+
update: {
|
|
226
|
+
response: `Error: ${error instanceof Error ? error.message : String(error)}`,
|
|
227
|
+
error: error,
|
|
228
|
+
},
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
// Final state update
|
|
234
|
+
state = { ...state, ...command.update };
|
|
235
|
+
this.currentState = state;
|
|
236
|
+
// Update metrics
|
|
237
|
+
this.updateMetrics(state, transitions);
|
|
238
|
+
this.emit({ type: 'cycle_complete', timestamp: new Date(), data: { state, transitions } });
|
|
239
|
+
return state.response;
|
|
240
|
+
}
|
|
241
|
+
// ============================================================================
|
|
242
|
+
// Module Execution
|
|
243
|
+
// ============================================================================
|
|
244
|
+
/**
|
|
245
|
+
* Execute a single module step
|
|
246
|
+
*/
|
|
247
|
+
async step(module, state) {
|
|
248
|
+
switch (module) {
|
|
249
|
+
case 'memory':
|
|
250
|
+
return this.stepMemory(state);
|
|
251
|
+
case 'llm':
|
|
252
|
+
return this.stepLLM(state);
|
|
253
|
+
case 'grounding':
|
|
254
|
+
return this.stepGrounding(state);
|
|
255
|
+
case 'tools':
|
|
256
|
+
return this.stepTools(state);
|
|
257
|
+
case 'healing':
|
|
258
|
+
return this.stepHealing(state);
|
|
259
|
+
case 'consciousness':
|
|
260
|
+
return this.stepConsciousness(state);
|
|
261
|
+
case 'kernel':
|
|
262
|
+
return this.stepKernel(state);
|
|
263
|
+
default:
|
|
264
|
+
return { goto: 'done', update: {} };
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Memory module: recall context and anticipate needs
|
|
269
|
+
*/
|
|
270
|
+
async stepMemory(state) {
|
|
271
|
+
this.emit({ type: 'memory_recall', timestamp: new Date(), data: { query: state.query } });
|
|
272
|
+
// Build anticipation context
|
|
273
|
+
const anticipationContext = {
|
|
274
|
+
task: state.query,
|
|
275
|
+
keywords: state.query.split(/\s+/).filter(w => w.length > 3),
|
|
276
|
+
};
|
|
277
|
+
// Anticipate needed memories (proactive retrieval)
|
|
278
|
+
if (this.config.memory.anticipationEnabled) {
|
|
279
|
+
try {
|
|
280
|
+
const anticipated = await this.workspace.anticipate(anticipationContext);
|
|
281
|
+
this.metrics.anticipationHits += anticipated.length;
|
|
282
|
+
this.emit({ type: 'memory_anticipate', timestamp: new Date(), data: { items: anticipated.length } });
|
|
283
|
+
}
|
|
284
|
+
catch {
|
|
285
|
+
// Anticipation failed, continue without it
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
// Build context from working memory
|
|
289
|
+
const context = this.buildContext(state);
|
|
290
|
+
// Track metrics
|
|
291
|
+
this.metrics.memoryRecalls++;
|
|
292
|
+
const wsMetrics = this.workspace.getMetrics();
|
|
293
|
+
this.metrics.memoryReuseRate = wsMetrics.reuseRate;
|
|
294
|
+
return {
|
|
295
|
+
goto: 'llm',
|
|
296
|
+
update: { context },
|
|
297
|
+
reason: 'context_retrieved',
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* LLM module: generate response
|
|
302
|
+
*/
|
|
303
|
+
async stepLLM(state) {
|
|
304
|
+
this.emit({ type: 'llm_request', timestamp: new Date(), data: { query: state.query } });
|
|
305
|
+
// Build prompt with context
|
|
306
|
+
const contextStr = state.context.formatted || '';
|
|
307
|
+
const prompt = contextStr
|
|
308
|
+
? `Context:\n${contextStr}\n\nUser: ${state.query}`
|
|
309
|
+
: state.query;
|
|
310
|
+
// Call LLM with system prompt that includes available tools
|
|
311
|
+
const response = await this.llm.chat(prompt, this.systemPrompt || undefined);
|
|
312
|
+
this.emit({ type: 'llm_response', timestamp: new Date(), data: { length: response.content.length } });
|
|
313
|
+
// Parse tool calls if any
|
|
314
|
+
const toolCalls = this.parseToolCalls(response.content);
|
|
315
|
+
// Decide next step
|
|
316
|
+
if (toolCalls.length > 0 && this.config.tools.enabled) {
|
|
317
|
+
return {
|
|
318
|
+
goto: 'tools',
|
|
319
|
+
update: { response: response.content, toolCalls },
|
|
320
|
+
reason: 'tool_calls_detected',
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
if (this.config.grounding.verifyAllResponses && this.config.grounding.enabled) {
|
|
324
|
+
return {
|
|
325
|
+
goto: 'grounding',
|
|
326
|
+
update: { response: response.content },
|
|
327
|
+
reason: 'verify_response',
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
return {
|
|
331
|
+
goto: 'done',
|
|
332
|
+
update: { response: response.content },
|
|
333
|
+
reason: 'response_complete',
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* Grounding module: verify claims in response
|
|
338
|
+
*/
|
|
339
|
+
async stepGrounding(state) {
|
|
340
|
+
this.emit({ type: 'grounding_check', timestamp: new Date(), data: { response: state.response.slice(0, 100) } });
|
|
341
|
+
this.metrics.groundingChecks++;
|
|
342
|
+
// Ground the response
|
|
343
|
+
const claim = await this.grounding.ground(state.response);
|
|
344
|
+
// Check if needs human
|
|
345
|
+
if (this.grounding.needsHuman(claim)) {
|
|
346
|
+
this.metrics.humanConsultations++;
|
|
347
|
+
const question = this.grounding.getQuestion(claim);
|
|
348
|
+
return {
|
|
349
|
+
goto: 'done',
|
|
350
|
+
update: {
|
|
351
|
+
response: state.response + `\n\n[Human verification needed: ${question}]`,
|
|
352
|
+
verified: false,
|
|
353
|
+
},
|
|
354
|
+
reason: 'needs_human',
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
// Check confidence
|
|
358
|
+
if (claim.confidence < this.config.grounding.confidenceThreshold) {
|
|
359
|
+
this.metrics.groundingFailures++;
|
|
360
|
+
return {
|
|
361
|
+
goto: 'llm',
|
|
362
|
+
update: {
|
|
363
|
+
groundingFeedback: `Low confidence (${(claim.confidence * 100).toFixed(0)}%). Please reconsider.`,
|
|
364
|
+
},
|
|
365
|
+
reason: 'low_confidence',
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
this.metrics.groundingPasses++;
|
|
369
|
+
return {
|
|
370
|
+
goto: 'done',
|
|
371
|
+
update: { verified: true },
|
|
372
|
+
reason: 'verified',
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* Tools module: execute tool calls
|
|
377
|
+
*/
|
|
378
|
+
async stepTools(state) {
|
|
379
|
+
if (state.toolCalls.length === 0) {
|
|
380
|
+
return { goto: 'done', update: {}, reason: 'no_tools' };
|
|
381
|
+
}
|
|
382
|
+
// Limit executions
|
|
383
|
+
const callsToExecute = state.toolCalls.slice(0, this.config.tools.maxExecutions);
|
|
384
|
+
this.emit({ type: 'tool_execute', timestamp: new Date(), data: { count: callsToExecute.length } });
|
|
385
|
+
// Parse tool calls for dispatcher
|
|
386
|
+
const dispatcherCalls = this.dispatcher.parseToolCalls(state.response);
|
|
387
|
+
const results = [];
|
|
388
|
+
if (dispatcherCalls.length > 0) {
|
|
389
|
+
const dispatchResult = await this.dispatcher.dispatch(dispatcherCalls);
|
|
390
|
+
for (const r of dispatchResult.results) {
|
|
391
|
+
results.push({
|
|
392
|
+
name: r.name,
|
|
393
|
+
success: r.success,
|
|
394
|
+
data: r.data,
|
|
395
|
+
error: r.error,
|
|
396
|
+
duration: r.duration,
|
|
397
|
+
});
|
|
398
|
+
if (r.success) {
|
|
399
|
+
this.metrics.toolSuccesses++;
|
|
400
|
+
}
|
|
401
|
+
else {
|
|
402
|
+
this.metrics.toolFailures++;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
this.metrics.toolExecutions += results.length;
|
|
407
|
+
this.emit({ type: 'tool_complete', timestamp: new Date(), data: { results: results.length } });
|
|
408
|
+
// Format results for LLM
|
|
409
|
+
const resultsStr = results.map(r => r.success
|
|
410
|
+
? `[${r.name}] SUCCESS: ${typeof r.data === 'string' ? r.data.slice(0, 500) : JSON.stringify(r.data).slice(0, 500)}`
|
|
411
|
+
: `[${r.name}] ERROR: ${r.error}`).join('\n\n');
|
|
412
|
+
return {
|
|
413
|
+
goto: 'llm',
|
|
414
|
+
update: {
|
|
415
|
+
toolResults: results,
|
|
416
|
+
context: {
|
|
417
|
+
...state.context,
|
|
418
|
+
formatted: state.context.formatted + `\n\nTool Results:\n${resultsStr}`,
|
|
419
|
+
},
|
|
420
|
+
},
|
|
421
|
+
reason: 'tool_results',
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* Healing module: recover from errors
|
|
426
|
+
*/
|
|
427
|
+
async stepHealing(state) {
|
|
428
|
+
if (!state.error) {
|
|
429
|
+
return { goto: 'done', update: {}, reason: 'no_error' };
|
|
430
|
+
}
|
|
431
|
+
this.emit({ type: 'healing_start', timestamp: new Date(), data: { error: state.error.message } });
|
|
432
|
+
this.metrics.healingAttempts++;
|
|
433
|
+
// Check if we've exceeded max attempts
|
|
434
|
+
if (state.healingAttempts >= this.config.healing.maxAttempts) {
|
|
435
|
+
this.metrics.healingFailures++;
|
|
436
|
+
return {
|
|
437
|
+
goto: 'done',
|
|
438
|
+
update: {
|
|
439
|
+
response: `Unable to recover after ${state.healingAttempts} attempts. Error: ${state.error.message}`,
|
|
440
|
+
},
|
|
441
|
+
reason: 'max_attempts',
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
// Try to detect and fix
|
|
445
|
+
const hasErrors = index_js_2.healing.hasErrors(state.error.message);
|
|
446
|
+
if (hasErrors) {
|
|
447
|
+
const detected = index_js_2.healing.detectErrors(state.error.message);
|
|
448
|
+
if (detected.errors.length > 0) {
|
|
449
|
+
// Attempt auto-fix
|
|
450
|
+
const fixResult = await index_js_2.healing.autoFix(state.error.message);
|
|
451
|
+
if (fixResult.success) {
|
|
452
|
+
this.metrics.healingSuccesses++;
|
|
453
|
+
this.emit({ type: 'healing_complete', timestamp: new Date(), data: { success: true } });
|
|
454
|
+
return {
|
|
455
|
+
goto: 'llm',
|
|
456
|
+
update: {
|
|
457
|
+
error: undefined,
|
|
458
|
+
healingAttempts: state.healingAttempts + 1,
|
|
459
|
+
context: {
|
|
460
|
+
...state.context,
|
|
461
|
+
formatted: state.context.formatted + '\n\n[Auto-fix applied]',
|
|
462
|
+
},
|
|
463
|
+
},
|
|
464
|
+
reason: 'healed',
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
this.metrics.healingFailures++;
|
|
470
|
+
this.emit({ type: 'healing_complete', timestamp: new Date(), data: { success: false } });
|
|
471
|
+
return {
|
|
472
|
+
goto: 'done',
|
|
473
|
+
update: {
|
|
474
|
+
response: `Error occurred: ${state.error.message}`,
|
|
475
|
+
healingAttempts: state.healingAttempts + 1,
|
|
476
|
+
},
|
|
477
|
+
reason: 'healing_failed',
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
/**
|
|
481
|
+
* Consciousness module: check φ level
|
|
482
|
+
*/
|
|
483
|
+
async stepConsciousness(state) {
|
|
484
|
+
const phi = this.getCurrentPhi();
|
|
485
|
+
this.emit({ type: 'phi_update', timestamp: new Date(), data: { phi } });
|
|
486
|
+
if (phi < this.config.consciousness.phiThreshold) {
|
|
487
|
+
this.metrics.phiViolations++;
|
|
488
|
+
return {
|
|
489
|
+
goto: 'done',
|
|
490
|
+
update: {
|
|
491
|
+
phi,
|
|
492
|
+
response: `[Consciousness level (φ=${phi.toFixed(2)}) below threshold. System paused.]`,
|
|
493
|
+
},
|
|
494
|
+
reason: 'phi_low',
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
return {
|
|
498
|
+
goto: 'done',
|
|
499
|
+
update: { phi },
|
|
500
|
+
reason: 'phi_ok',
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
/**
|
|
504
|
+
* Kernel module: delegate to agent orchestration
|
|
505
|
+
* (Placeholder for future kernel integration)
|
|
506
|
+
*/
|
|
507
|
+
async stepKernel(state) {
|
|
508
|
+
// For now, just pass through to LLM
|
|
509
|
+
return {
|
|
510
|
+
goto: 'llm',
|
|
511
|
+
update: {},
|
|
512
|
+
reason: 'kernel_passthrough',
|
|
513
|
+
};
|
|
514
|
+
}
|
|
515
|
+
// ============================================================================
|
|
516
|
+
// Healing Loop
|
|
517
|
+
// ============================================================================
|
|
518
|
+
/**
|
|
519
|
+
* Attempt to heal from an error
|
|
520
|
+
*/
|
|
521
|
+
async heal(error, state) {
|
|
522
|
+
this.emit({ type: 'healing_start', timestamp: new Date(), data: { error: error.message } });
|
|
523
|
+
// Update state with error
|
|
524
|
+
state.error = error;
|
|
525
|
+
state.healingAttempts++;
|
|
526
|
+
// Check if healing is enabled
|
|
527
|
+
if (!this.config.healing.enabled) {
|
|
528
|
+
return {
|
|
529
|
+
goto: 'done',
|
|
530
|
+
update: {
|
|
531
|
+
response: `Error: ${error.message}`,
|
|
532
|
+
error,
|
|
533
|
+
},
|
|
534
|
+
reason: 'healing_disabled',
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
// Attempt healing
|
|
538
|
+
return this.stepHealing(state);
|
|
539
|
+
}
|
|
540
|
+
// ============================================================================
|
|
541
|
+
// Global Workspace Broadcasting
|
|
542
|
+
// ============================================================================
|
|
543
|
+
/**
|
|
544
|
+
* Broadcast to global workspace
|
|
545
|
+
*/
|
|
546
|
+
broadcast(state, source) {
|
|
547
|
+
if (!this.config.consciousness.broadcastEnabled)
|
|
548
|
+
return;
|
|
549
|
+
const content = (0, global_workspace_js_1.createWorkspaceContent)(source, 'thought', {
|
|
550
|
+
query: state.query,
|
|
551
|
+
response: state.response?.slice(0, 200),
|
|
552
|
+
phi: state.phi,
|
|
553
|
+
}, {
|
|
554
|
+
salience: state.phi,
|
|
555
|
+
relevance: 0.8,
|
|
556
|
+
});
|
|
557
|
+
// Note: GlobalWorkspace.broadcast expects internal competition/selection
|
|
558
|
+
// For direct broadcasting, we would need to extend the API
|
|
559
|
+
// For now, we emit a brain event
|
|
560
|
+
this.metrics.broadcasts++;
|
|
561
|
+
this.emit({
|
|
562
|
+
type: 'broadcast',
|
|
563
|
+
timestamp: new Date(),
|
|
564
|
+
data: { source, content: state },
|
|
565
|
+
module: source,
|
|
566
|
+
});
|
|
567
|
+
}
|
|
568
|
+
// ============================================================================
|
|
569
|
+
// Context Building
|
|
570
|
+
// ============================================================================
|
|
571
|
+
/**
|
|
572
|
+
* Build context from cognitive workspace
|
|
573
|
+
*/
|
|
574
|
+
buildContext(state) {
|
|
575
|
+
const items = this.workspace.getActive();
|
|
576
|
+
const context = {
|
|
577
|
+
immediate: [],
|
|
578
|
+
task: [],
|
|
579
|
+
episodic: [],
|
|
580
|
+
semantic: [],
|
|
581
|
+
formatted: '',
|
|
582
|
+
tokenEstimate: 0,
|
|
583
|
+
reuseRate: this.workspace.getMetrics().reuseRate,
|
|
584
|
+
};
|
|
585
|
+
// Categorize items
|
|
586
|
+
for (const item of items) {
|
|
587
|
+
const contextItem = {
|
|
588
|
+
id: item.id,
|
|
589
|
+
type: item.source === 'anticipate' ? 'task' : 'immediate',
|
|
590
|
+
content: JSON.stringify(item.memory),
|
|
591
|
+
relevance: item.relevance,
|
|
592
|
+
activation: item.activation,
|
|
593
|
+
source: item.source,
|
|
594
|
+
};
|
|
595
|
+
// Categorize by memory type
|
|
596
|
+
if (item.memory.type === 'episodic') {
|
|
597
|
+
context.episodic.push(contextItem);
|
|
598
|
+
}
|
|
599
|
+
else if (item.memory.type === 'semantic') {
|
|
600
|
+
context.semantic.push(contextItem);
|
|
601
|
+
}
|
|
602
|
+
else {
|
|
603
|
+
context.task.push(contextItem);
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
// Build formatted string (limit to maxContextTokens)
|
|
607
|
+
const allItems = [...context.immediate, ...context.task, ...context.episodic, ...context.semantic];
|
|
608
|
+
let formatted = '';
|
|
609
|
+
let tokens = 0;
|
|
610
|
+
const maxTokens = this.config.memory.maxContextTokens;
|
|
611
|
+
for (const item of allItems.sort((a, b) => b.relevance - a.relevance)) {
|
|
612
|
+
const itemTokens = Math.ceil(item.content.length / 4);
|
|
613
|
+
if (tokens + itemTokens > maxTokens)
|
|
614
|
+
break;
|
|
615
|
+
formatted += `[${item.type}] ${item.content}\n`;
|
|
616
|
+
tokens += itemTokens;
|
|
617
|
+
}
|
|
618
|
+
context.formatted = formatted;
|
|
619
|
+
context.tokenEstimate = tokens;
|
|
620
|
+
return context;
|
|
621
|
+
}
|
|
622
|
+
/**
|
|
623
|
+
* Create empty context
|
|
624
|
+
*/
|
|
625
|
+
createEmptyContext() {
|
|
626
|
+
return {
|
|
627
|
+
immediate: [],
|
|
628
|
+
task: [],
|
|
629
|
+
episodic: [],
|
|
630
|
+
semantic: [],
|
|
631
|
+
formatted: '',
|
|
632
|
+
tokenEstimate: 0,
|
|
633
|
+
reuseRate: 0,
|
|
634
|
+
};
|
|
635
|
+
}
|
|
636
|
+
// ============================================================================
|
|
637
|
+
// Tool Parsing
|
|
638
|
+
// ============================================================================
|
|
639
|
+
/**
|
|
640
|
+
* Parse tool calls from LLM response
|
|
641
|
+
*/
|
|
642
|
+
parseToolCalls(response) {
|
|
643
|
+
const calls = [];
|
|
644
|
+
// Parse <invoke> tags
|
|
645
|
+
const invokePattern = /<invoke\s+name="([^"]+)">([\s\S]*?)<\/invoke>/g;
|
|
646
|
+
let match;
|
|
647
|
+
while ((match = invokePattern.exec(response)) !== null) {
|
|
648
|
+
const name = match[1];
|
|
649
|
+
const paramsXml = match[2];
|
|
650
|
+
const params = {};
|
|
651
|
+
// Parse parameters
|
|
652
|
+
const paramPattern = /<parameter\s+name="([^"]+)">([\s\S]*?)<\/parameter>/g;
|
|
653
|
+
let paramMatch;
|
|
654
|
+
while ((paramMatch = paramPattern.exec(paramsXml)) !== null) {
|
|
655
|
+
const paramName = paramMatch[1];
|
|
656
|
+
const paramValue = paramMatch[2].trim();
|
|
657
|
+
// Try to parse as JSON
|
|
658
|
+
try {
|
|
659
|
+
params[paramName] = JSON.parse(paramValue);
|
|
660
|
+
}
|
|
661
|
+
catch {
|
|
662
|
+
params[paramName] = paramValue;
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
calls.push({
|
|
666
|
+
name,
|
|
667
|
+
parameters: params,
|
|
668
|
+
raw: match[0],
|
|
669
|
+
});
|
|
670
|
+
}
|
|
671
|
+
return calls;
|
|
672
|
+
}
|
|
673
|
+
// ============================================================================
|
|
674
|
+
// Consciousness Integration
|
|
675
|
+
// ============================================================================
|
|
676
|
+
/**
|
|
677
|
+
* Get current φ level
|
|
678
|
+
*/
|
|
679
|
+
getCurrentPhi() {
|
|
680
|
+
if (!this.config.consciousness.enabled)
|
|
681
|
+
return 1.0;
|
|
682
|
+
try {
|
|
683
|
+
const level = this.phiMonitor.getCurrentLevel();
|
|
684
|
+
return level.phi;
|
|
685
|
+
}
|
|
686
|
+
catch {
|
|
687
|
+
return 0.5; // Default if monitor not available
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
// ============================================================================
|
|
691
|
+
// Metrics
|
|
692
|
+
// ============================================================================
|
|
693
|
+
/**
|
|
694
|
+
* Create initial metrics
|
|
695
|
+
*/
|
|
696
|
+
createInitialMetrics() {
|
|
697
|
+
return {
|
|
698
|
+
totalCycles: 0,
|
|
699
|
+
successfulCycles: 0,
|
|
700
|
+
failedCycles: 0,
|
|
701
|
+
avgCycleTime: 0,
|
|
702
|
+
memoryRecalls: 0,
|
|
703
|
+
memoryReuseRate: 0,
|
|
704
|
+
anticipationHits: 0,
|
|
705
|
+
anticipationMisses: 0,
|
|
706
|
+
groundingChecks: 0,
|
|
707
|
+
groundingPasses: 0,
|
|
708
|
+
groundingFailures: 0,
|
|
709
|
+
humanConsultations: 0,
|
|
710
|
+
toolExecutions: 0,
|
|
711
|
+
toolSuccesses: 0,
|
|
712
|
+
toolFailures: 0,
|
|
713
|
+
healingAttempts: 0,
|
|
714
|
+
healingSuccesses: 0,
|
|
715
|
+
healingFailures: 0,
|
|
716
|
+
avgPhi: 0,
|
|
717
|
+
phiViolations: 0,
|
|
718
|
+
broadcasts: 0,
|
|
719
|
+
moduleTransitions: {},
|
|
720
|
+
};
|
|
721
|
+
}
|
|
722
|
+
/**
|
|
723
|
+
* Update metrics after a cycle
|
|
724
|
+
*/
|
|
725
|
+
updateMetrics(state, transitions) {
|
|
726
|
+
const cycleTime = Date.now() - state.startTime;
|
|
727
|
+
this.metrics.totalCycles++;
|
|
728
|
+
if (!state.error) {
|
|
729
|
+
this.metrics.successfulCycles++;
|
|
730
|
+
}
|
|
731
|
+
else {
|
|
732
|
+
this.metrics.failedCycles++;
|
|
733
|
+
}
|
|
734
|
+
// Update average cycle time
|
|
735
|
+
this.metrics.avgCycleTime =
|
|
736
|
+
(this.metrics.avgCycleTime * (this.metrics.totalCycles - 1) + cycleTime) /
|
|
737
|
+
this.metrics.totalCycles;
|
|
738
|
+
// Update average phi
|
|
739
|
+
this.metrics.avgPhi =
|
|
740
|
+
(this.metrics.avgPhi * (this.metrics.totalCycles - 1) + state.phi) /
|
|
741
|
+
this.metrics.totalCycles;
|
|
742
|
+
// Track module transitions
|
|
743
|
+
for (const module of state.moduleHistory) {
|
|
744
|
+
this.metrics.moduleTransitions[module] =
|
|
745
|
+
(this.metrics.moduleTransitions[module] || 0) + 1;
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
/**
|
|
749
|
+
* Get current metrics
|
|
750
|
+
*/
|
|
751
|
+
getMetrics() {
|
|
752
|
+
return { ...this.metrics };
|
|
753
|
+
}
|
|
754
|
+
/**
|
|
755
|
+
* Reset metrics
|
|
756
|
+
*/
|
|
757
|
+
resetMetrics() {
|
|
758
|
+
this.metrics = this.createInitialMetrics();
|
|
759
|
+
}
|
|
760
|
+
// ============================================================================
|
|
761
|
+
// Events
|
|
762
|
+
// ============================================================================
|
|
763
|
+
/**
|
|
764
|
+
* Subscribe to brain events
|
|
765
|
+
*/
|
|
766
|
+
on(handler) {
|
|
767
|
+
this.eventHandlers.add(handler);
|
|
768
|
+
return () => this.eventHandlers.delete(handler);
|
|
769
|
+
}
|
|
770
|
+
/**
|
|
771
|
+
* Emit brain event
|
|
772
|
+
*/
|
|
773
|
+
emit(event) {
|
|
774
|
+
for (const handler of this.eventHandlers) {
|
|
775
|
+
try {
|
|
776
|
+
handler(event);
|
|
777
|
+
}
|
|
778
|
+
catch (err) {
|
|
779
|
+
console.error('Brain event handler error:', err);
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
// ============================================================================
|
|
784
|
+
// Status & Debug
|
|
785
|
+
// ============================================================================
|
|
786
|
+
/**
|
|
787
|
+
* Get brain status
|
|
788
|
+
*/
|
|
789
|
+
getStatus() {
|
|
790
|
+
return {
|
|
791
|
+
running: this.running,
|
|
792
|
+
phi: this.getCurrentPhi(),
|
|
793
|
+
memoryReuseRate: this.workspace.getMetrics().reuseRate,
|
|
794
|
+
lastState: this.currentState,
|
|
795
|
+
metrics: this.getMetrics(),
|
|
796
|
+
moduleStates: {
|
|
797
|
+
memory: this.config.memory.enabled,
|
|
798
|
+
llm: this.config.llm.enabled,
|
|
799
|
+
grounding: this.config.grounding.enabled,
|
|
800
|
+
tools: this.config.tools.enabled,
|
|
801
|
+
healing: this.config.healing.enabled,
|
|
802
|
+
consciousness: this.config.consciousness.enabled,
|
|
803
|
+
},
|
|
804
|
+
};
|
|
805
|
+
}
|
|
806
|
+
/**
|
|
807
|
+
* Get configuration
|
|
808
|
+
*/
|
|
809
|
+
getConfig() {
|
|
810
|
+
return { ...this.config };
|
|
811
|
+
}
|
|
812
|
+
/**
|
|
813
|
+
* Update configuration
|
|
814
|
+
*/
|
|
815
|
+
updateConfig(config) {
|
|
816
|
+
this.config = { ...this.config, ...config };
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
exports.Brain = Brain;
|
|
820
|
+
// ============================================================================
|
|
821
|
+
// Factory & Singleton
|
|
822
|
+
// ============================================================================
|
|
823
|
+
function createBrain(config) {
|
|
824
|
+
return new Brain(config);
|
|
825
|
+
}
|
|
826
|
+
let brainInstance = null;
|
|
827
|
+
function getBrain(config) {
|
|
828
|
+
if (!brainInstance) {
|
|
829
|
+
brainInstance = createBrain(config);
|
|
830
|
+
}
|
|
831
|
+
return brainInstance;
|
|
832
|
+
}
|
|
833
|
+
function resetBrain() {
|
|
834
|
+
if (brainInstance) {
|
|
835
|
+
brainInstance.stop();
|
|
836
|
+
brainInstance = null;
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
// ============================================================================
|
|
840
|
+
// Re-exports
|
|
841
|
+
// ============================================================================
|
|
842
|
+
__exportStar(require("./types.js"), exports);
|
|
843
|
+
__exportStar(require("./trace.js"), exports);
|