genesis-ai-cli 7.16.0 → 7.17.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/self-modification/index.d.ts +1 -0
- package/dist/src/self-modification/index.js +8 -1
- package/dist/src/self-modification/self-improvement.d.ts +164 -0
- package/dist/src/self-modification/self-improvement.js +550 -0
- package/dist/src/unified-system.d.ts +154 -0
- package/dist/src/unified-system.js +355 -0
- package/package.json +1 -1
|
@@ -10,4 +10,5 @@
|
|
|
10
10
|
* - Invariant System: Ensures core properties survive modification
|
|
11
11
|
*/
|
|
12
12
|
export { DarwinGodelEngine, getDarwinGodelEngine, resetDarwinGodelEngine, Modification, ModificationPlan, VerificationResult, ApplyResult, DarwinGodelConfig, } from './darwin-godel.js';
|
|
13
|
+
export { SelfImprovementEngine, getSelfImprovementEngine, resetSelfImprovementEngine, createSelfImprovementEngine, SystemMetrics, ImprovementOpportunity, ImprovementResult, SelfImprovementConfig, DEFAULT_IMPROVEMENT_CONFIG, } from './self-improvement.js';
|
|
13
14
|
export { invariantRegistry, InvariantRegistry, InvariantContext, InvariantResult, InvariantDefinition, InvariantChecker, } from '../kernel/invariants.js';
|
|
@@ -11,11 +11,18 @@
|
|
|
11
11
|
* - Invariant System: Ensures core properties survive modification
|
|
12
12
|
*/
|
|
13
13
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
14
|
-
exports.InvariantRegistry = exports.invariantRegistry = exports.resetDarwinGodelEngine = exports.getDarwinGodelEngine = exports.DarwinGodelEngine = void 0;
|
|
14
|
+
exports.InvariantRegistry = exports.invariantRegistry = exports.DEFAULT_IMPROVEMENT_CONFIG = exports.createSelfImprovementEngine = exports.resetSelfImprovementEngine = exports.getSelfImprovementEngine = exports.SelfImprovementEngine = exports.resetDarwinGodelEngine = exports.getDarwinGodelEngine = exports.DarwinGodelEngine = void 0;
|
|
15
15
|
var darwin_godel_js_1 = require("./darwin-godel.js");
|
|
16
16
|
Object.defineProperty(exports, "DarwinGodelEngine", { enumerable: true, get: function () { return darwin_godel_js_1.DarwinGodelEngine; } });
|
|
17
17
|
Object.defineProperty(exports, "getDarwinGodelEngine", { enumerable: true, get: function () { return darwin_godel_js_1.getDarwinGodelEngine; } });
|
|
18
18
|
Object.defineProperty(exports, "resetDarwinGodelEngine", { enumerable: true, get: function () { return darwin_godel_js_1.resetDarwinGodelEngine; } });
|
|
19
|
+
// v7.17: Self-Improvement Cycle
|
|
20
|
+
var self_improvement_js_1 = require("./self-improvement.js");
|
|
21
|
+
Object.defineProperty(exports, "SelfImprovementEngine", { enumerable: true, get: function () { return self_improvement_js_1.SelfImprovementEngine; } });
|
|
22
|
+
Object.defineProperty(exports, "getSelfImprovementEngine", { enumerable: true, get: function () { return self_improvement_js_1.getSelfImprovementEngine; } });
|
|
23
|
+
Object.defineProperty(exports, "resetSelfImprovementEngine", { enumerable: true, get: function () { return self_improvement_js_1.resetSelfImprovementEngine; } });
|
|
24
|
+
Object.defineProperty(exports, "createSelfImprovementEngine", { enumerable: true, get: function () { return self_improvement_js_1.createSelfImprovementEngine; } });
|
|
25
|
+
Object.defineProperty(exports, "DEFAULT_IMPROVEMENT_CONFIG", { enumerable: true, get: function () { return self_improvement_js_1.DEFAULT_IMPROVEMENT_CONFIG; } });
|
|
19
26
|
// Re-export invariant types for convenience
|
|
20
27
|
var invariants_js_1 = require("../kernel/invariants.js");
|
|
21
28
|
Object.defineProperty(exports, "invariantRegistry", { enumerable: true, get: function () { return invariants_js_1.invariantRegistry; } });
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Genesis 7.17 - Self-Improvement Cycle
|
|
3
|
+
*
|
|
4
|
+
* Autonomous self-improvement via observation, reflection, and modification.
|
|
5
|
+
* Uses Darwin-Gödel Engine for safe code modifications.
|
|
6
|
+
*
|
|
7
|
+
* Cycle:
|
|
8
|
+
* 1. OBSERVE - Collect metrics from all systems
|
|
9
|
+
* 2. REFLECT - Identify bottlenecks and improvement opportunities
|
|
10
|
+
* 3. PROPOSE - Generate modification plans
|
|
11
|
+
* 4. APPLY - Use Darwin-Gödel to safely apply changes
|
|
12
|
+
* 5. VERIFY - Check if improvement was achieved
|
|
13
|
+
*/
|
|
14
|
+
import { EventEmitter } from 'events';
|
|
15
|
+
import { ModificationPlan } from './darwin-godel.js';
|
|
16
|
+
import { PhiMonitor } from '../consciousness/phi-monitor.js';
|
|
17
|
+
import { CognitiveWorkspace } from '../memory/cognitive-workspace.js';
|
|
18
|
+
export interface SystemMetrics {
|
|
19
|
+
phi: number;
|
|
20
|
+
consciousnessState: string;
|
|
21
|
+
phiTrend: 'rising' | 'stable' | 'falling';
|
|
22
|
+
memoryReuse: number;
|
|
23
|
+
cacheHitRate: number;
|
|
24
|
+
memorySize: number;
|
|
25
|
+
avgResponseTime: number;
|
|
26
|
+
taskSuccessRate: number;
|
|
27
|
+
errorRate: number;
|
|
28
|
+
avgSurprise: number;
|
|
29
|
+
expectedFreeEnergy: number;
|
|
30
|
+
uptime: number;
|
|
31
|
+
cyclesCompleted: number;
|
|
32
|
+
timestamp: Date;
|
|
33
|
+
}
|
|
34
|
+
export interface ImprovementOpportunity {
|
|
35
|
+
id: string;
|
|
36
|
+
category: 'performance' | 'consciousness' | 'memory' | 'reliability' | 'capability';
|
|
37
|
+
metric: keyof SystemMetrics;
|
|
38
|
+
currentValue: number;
|
|
39
|
+
targetValue: number;
|
|
40
|
+
priority: number;
|
|
41
|
+
description: string;
|
|
42
|
+
suggestedFix?: ModificationPlan;
|
|
43
|
+
}
|
|
44
|
+
export interface ImprovementResult {
|
|
45
|
+
opportunityId: string;
|
|
46
|
+
applied: boolean;
|
|
47
|
+
success: boolean;
|
|
48
|
+
beforeMetrics: SystemMetrics;
|
|
49
|
+
afterMetrics?: SystemMetrics;
|
|
50
|
+
commitHash?: string;
|
|
51
|
+
rollbackHash?: string;
|
|
52
|
+
error?: string;
|
|
53
|
+
duration: number;
|
|
54
|
+
}
|
|
55
|
+
export interface SelfImprovementConfig {
|
|
56
|
+
/** Enable automatic improvements */
|
|
57
|
+
autoImprove: boolean;
|
|
58
|
+
/** Minimum φ required to self-improve */
|
|
59
|
+
minPhiForImprovement: number;
|
|
60
|
+
/** Maximum improvements per cycle */
|
|
61
|
+
maxImprovementsPerCycle: number;
|
|
62
|
+
/** Cooldown between improvement attempts (ms) */
|
|
63
|
+
improvementCooldownMs: number;
|
|
64
|
+
/** Metric thresholds that trigger improvement */
|
|
65
|
+
thresholds: {
|
|
66
|
+
minPhi: number;
|
|
67
|
+
minMemoryReuse: number;
|
|
68
|
+
maxErrorRate: number;
|
|
69
|
+
maxSurprise: number;
|
|
70
|
+
minTaskSuccessRate: number;
|
|
71
|
+
};
|
|
72
|
+
/** Metric targets for improvement */
|
|
73
|
+
targets: {
|
|
74
|
+
phi: number;
|
|
75
|
+
memoryReuse: number;
|
|
76
|
+
errorRate: number;
|
|
77
|
+
surprise: number;
|
|
78
|
+
taskSuccessRate: number;
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
export declare const DEFAULT_IMPROVEMENT_CONFIG: SelfImprovementConfig;
|
|
82
|
+
export type SelfImprovementEventType = 'cycle:started' | 'cycle:completed' | 'metrics:collected' | 'opportunity:found' | 'improvement:started' | 'improvement:success' | 'improvement:failed' | 'improvement:skipped';
|
|
83
|
+
export declare class SelfImprovementEngine extends EventEmitter {
|
|
84
|
+
private config;
|
|
85
|
+
private darwinGodel;
|
|
86
|
+
private phiMonitor?;
|
|
87
|
+
private cognitiveWorkspace?;
|
|
88
|
+
private running;
|
|
89
|
+
private lastImprovement;
|
|
90
|
+
private improvementHistory;
|
|
91
|
+
private currentMetrics;
|
|
92
|
+
private metricsCollectors;
|
|
93
|
+
constructor(config?: Partial<SelfImprovementConfig>);
|
|
94
|
+
/**
|
|
95
|
+
* Set the φ monitor for consciousness metrics
|
|
96
|
+
*/
|
|
97
|
+
setPhiMonitor(monitor: PhiMonitor): void;
|
|
98
|
+
/**
|
|
99
|
+
* Set the cognitive workspace for memory metrics
|
|
100
|
+
*/
|
|
101
|
+
setCognitiveWorkspace(workspace: CognitiveWorkspace): void;
|
|
102
|
+
/**
|
|
103
|
+
* Register a custom metrics collector
|
|
104
|
+
*/
|
|
105
|
+
registerMetricsCollector(name: string, collector: () => Partial<SystemMetrics>): void;
|
|
106
|
+
/**
|
|
107
|
+
* Run a single improvement cycle
|
|
108
|
+
*/
|
|
109
|
+
runCycle(): Promise<{
|
|
110
|
+
metrics: SystemMetrics;
|
|
111
|
+
opportunities: ImprovementOpportunity[];
|
|
112
|
+
results: ImprovementResult[];
|
|
113
|
+
}>;
|
|
114
|
+
/**
|
|
115
|
+
* Collect metrics from all systems
|
|
116
|
+
*/
|
|
117
|
+
collectMetrics(): SystemMetrics;
|
|
118
|
+
/**
|
|
119
|
+
* Find improvement opportunities based on current metrics
|
|
120
|
+
*/
|
|
121
|
+
findOpportunities(metrics: SystemMetrics): ImprovementOpportunity[];
|
|
122
|
+
/**
|
|
123
|
+
* Check if we can attempt an improvement
|
|
124
|
+
*/
|
|
125
|
+
private canAttemptImprovement;
|
|
126
|
+
/**
|
|
127
|
+
* Apply a single improvement
|
|
128
|
+
*/
|
|
129
|
+
private applyImprovement;
|
|
130
|
+
/**
|
|
131
|
+
* Verify that an improvement actually improved the metric
|
|
132
|
+
*/
|
|
133
|
+
private verifyImprovement;
|
|
134
|
+
/**
|
|
135
|
+
* Get improvement statistics
|
|
136
|
+
*/
|
|
137
|
+
stats(): {
|
|
138
|
+
totalAttempts: number;
|
|
139
|
+
successfulImprovements: number;
|
|
140
|
+
failedImprovements: number;
|
|
141
|
+
successRate: number;
|
|
142
|
+
lastImprovement: Date | null;
|
|
143
|
+
currentMetrics: SystemMetrics | null;
|
|
144
|
+
};
|
|
145
|
+
/**
|
|
146
|
+
* Get improvement history
|
|
147
|
+
*/
|
|
148
|
+
getHistory(): ImprovementResult[];
|
|
149
|
+
/**
|
|
150
|
+
* Get current configuration
|
|
151
|
+
*/
|
|
152
|
+
getConfig(): SelfImprovementConfig;
|
|
153
|
+
/**
|
|
154
|
+
* Update configuration
|
|
155
|
+
*/
|
|
156
|
+
updateConfig(partial: Partial<SelfImprovementConfig>): void;
|
|
157
|
+
/**
|
|
158
|
+
* Enable/disable auto-improvement
|
|
159
|
+
*/
|
|
160
|
+
setAutoImprove(enabled: boolean): void;
|
|
161
|
+
}
|
|
162
|
+
export declare function getSelfImprovementEngine(config?: Partial<SelfImprovementConfig>): SelfImprovementEngine;
|
|
163
|
+
export declare function resetSelfImprovementEngine(): void;
|
|
164
|
+
export declare function createSelfImprovementEngine(config?: Partial<SelfImprovementConfig>): SelfImprovementEngine;
|
|
@@ -0,0 +1,550 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Genesis 7.17 - Self-Improvement Cycle
|
|
4
|
+
*
|
|
5
|
+
* Autonomous self-improvement via observation, reflection, and modification.
|
|
6
|
+
* Uses Darwin-Gödel Engine for safe code modifications.
|
|
7
|
+
*
|
|
8
|
+
* Cycle:
|
|
9
|
+
* 1. OBSERVE - Collect metrics from all systems
|
|
10
|
+
* 2. REFLECT - Identify bottlenecks and improvement opportunities
|
|
11
|
+
* 3. PROPOSE - Generate modification plans
|
|
12
|
+
* 4. APPLY - Use Darwin-Gödel to safely apply changes
|
|
13
|
+
* 5. VERIFY - Check if improvement was achieved
|
|
14
|
+
*/
|
|
15
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
16
|
+
exports.SelfImprovementEngine = exports.DEFAULT_IMPROVEMENT_CONFIG = void 0;
|
|
17
|
+
exports.getSelfImprovementEngine = getSelfImprovementEngine;
|
|
18
|
+
exports.resetSelfImprovementEngine = resetSelfImprovementEngine;
|
|
19
|
+
exports.createSelfImprovementEngine = createSelfImprovementEngine;
|
|
20
|
+
const events_1 = require("events");
|
|
21
|
+
const darwin_godel_js_1 = require("./darwin-godel.js");
|
|
22
|
+
const invariants_js_1 = require("../kernel/invariants.js");
|
|
23
|
+
exports.DEFAULT_IMPROVEMENT_CONFIG = {
|
|
24
|
+
autoImprove: false, // Disabled by default for safety
|
|
25
|
+
minPhiForImprovement: 0.3,
|
|
26
|
+
maxImprovementsPerCycle: 3,
|
|
27
|
+
improvementCooldownMs: 60000, // 1 minute
|
|
28
|
+
thresholds: {
|
|
29
|
+
minPhi: 0.2,
|
|
30
|
+
minMemoryReuse: 0.4,
|
|
31
|
+
maxErrorRate: 0.1,
|
|
32
|
+
maxSurprise: 5.0,
|
|
33
|
+
minTaskSuccessRate: 0.8,
|
|
34
|
+
},
|
|
35
|
+
targets: {
|
|
36
|
+
phi: 0.5,
|
|
37
|
+
memoryReuse: 0.6, // 54-60% from research
|
|
38
|
+
errorRate: 0.01,
|
|
39
|
+
surprise: 2.0,
|
|
40
|
+
taskSuccessRate: 0.95,
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
// ============================================================================
|
|
44
|
+
// Improvement Templates
|
|
45
|
+
// ============================================================================
|
|
46
|
+
/**
|
|
47
|
+
* Pre-defined improvement patterns that can be applied
|
|
48
|
+
*/
|
|
49
|
+
const IMPROVEMENT_TEMPLATES = {
|
|
50
|
+
/**
|
|
51
|
+
* Improve φ by adjusting calculation parameters
|
|
52
|
+
*/
|
|
53
|
+
'improve-phi': (metrics) => {
|
|
54
|
+
if (metrics.phi >= 0.3)
|
|
55
|
+
return null;
|
|
56
|
+
return {
|
|
57
|
+
id: `improve-phi-${Date.now()}`,
|
|
58
|
+
name: 'Improve φ calculation efficiency',
|
|
59
|
+
description: 'Switch to faster approximation while maintaining accuracy',
|
|
60
|
+
modifications: [{
|
|
61
|
+
id: 'phi-approx',
|
|
62
|
+
description: 'Use faster φ approximation',
|
|
63
|
+
targetFile: 'consciousness/phi-calculator.ts',
|
|
64
|
+
type: 'replace',
|
|
65
|
+
search: "approximationLevel: 'exact'",
|
|
66
|
+
content: "approximationLevel: 'fast'",
|
|
67
|
+
reason: 'Current φ is below threshold, faster calculation enables more frequent updates',
|
|
68
|
+
expectedImprovement: 'φ update frequency +50%',
|
|
69
|
+
}],
|
|
70
|
+
createdAt: new Date(),
|
|
71
|
+
};
|
|
72
|
+
},
|
|
73
|
+
/**
|
|
74
|
+
* Improve memory reuse by adjusting workspace parameters
|
|
75
|
+
*/
|
|
76
|
+
'improve-memory-reuse': (metrics) => {
|
|
77
|
+
if (metrics.memoryReuse >= 0.5)
|
|
78
|
+
return null;
|
|
79
|
+
return {
|
|
80
|
+
id: `improve-memory-${Date.now()}`,
|
|
81
|
+
name: 'Optimize memory workspace for better reuse',
|
|
82
|
+
description: 'Adjust cognitive workspace capacity to improve reuse rate',
|
|
83
|
+
modifications: [{
|
|
84
|
+
id: 'memory-capacity',
|
|
85
|
+
description: 'Increase immediate memory capacity',
|
|
86
|
+
targetFile: 'memory/cognitive-workspace.ts',
|
|
87
|
+
type: 'replace',
|
|
88
|
+
search: 'immediateCapacity: 8192',
|
|
89
|
+
content: 'immediateCapacity: 16384',
|
|
90
|
+
reason: `Memory reuse at ${(metrics.memoryReuse * 100).toFixed(1)}%, target is 54-60%`,
|
|
91
|
+
expectedImprovement: 'Memory reuse +15%',
|
|
92
|
+
}],
|
|
93
|
+
createdAt: new Date(),
|
|
94
|
+
};
|
|
95
|
+
},
|
|
96
|
+
/**
|
|
97
|
+
* Reduce error rate by adding retry logic
|
|
98
|
+
*/
|
|
99
|
+
'reduce-error-rate': (metrics) => {
|
|
100
|
+
if (metrics.errorRate <= 0.05)
|
|
101
|
+
return null;
|
|
102
|
+
return {
|
|
103
|
+
id: `reduce-errors-${Date.now()}`,
|
|
104
|
+
name: 'Add retry logic for resilience',
|
|
105
|
+
description: 'Implement exponential backoff for failed operations',
|
|
106
|
+
modifications: [{
|
|
107
|
+
id: 'add-retry',
|
|
108
|
+
description: 'Add retry wrapper to MCP calls',
|
|
109
|
+
targetFile: 'mcp/resilient.ts',
|
|
110
|
+
type: 'replace',
|
|
111
|
+
search: 'maxRetries: 3',
|
|
112
|
+
content: 'maxRetries: 5',
|
|
113
|
+
reason: `Error rate at ${(metrics.errorRate * 100).toFixed(1)}%, increasing retries`,
|
|
114
|
+
expectedImprovement: 'Error rate -40%',
|
|
115
|
+
}],
|
|
116
|
+
createdAt: new Date(),
|
|
117
|
+
};
|
|
118
|
+
},
|
|
119
|
+
/**
|
|
120
|
+
* Reduce surprise by improving prediction
|
|
121
|
+
*/
|
|
122
|
+
'reduce-surprise': (metrics) => {
|
|
123
|
+
if (metrics.avgSurprise <= 3.0)
|
|
124
|
+
return null;
|
|
125
|
+
return {
|
|
126
|
+
id: `reduce-surprise-${Date.now()}`,
|
|
127
|
+
name: 'Improve world model predictions',
|
|
128
|
+
description: 'Increase prediction horizon for better anticipation',
|
|
129
|
+
modifications: [{
|
|
130
|
+
id: 'prediction-horizon',
|
|
131
|
+
description: 'Increase prediction steps',
|
|
132
|
+
targetFile: 'world-model/predictor.ts',
|
|
133
|
+
type: 'replace',
|
|
134
|
+
search: 'predictionSteps: 5',
|
|
135
|
+
content: 'predictionSteps: 10',
|
|
136
|
+
reason: `Average surprise at ${metrics.avgSurprise.toFixed(2)}, improving predictions`,
|
|
137
|
+
expectedImprovement: 'Surprise -25%',
|
|
138
|
+
}],
|
|
139
|
+
createdAt: new Date(),
|
|
140
|
+
};
|
|
141
|
+
},
|
|
142
|
+
};
|
|
143
|
+
class SelfImprovementEngine extends events_1.EventEmitter {
|
|
144
|
+
config;
|
|
145
|
+
darwinGodel;
|
|
146
|
+
phiMonitor;
|
|
147
|
+
cognitiveWorkspace;
|
|
148
|
+
// State
|
|
149
|
+
running = false;
|
|
150
|
+
lastImprovement = new Date(0);
|
|
151
|
+
improvementHistory = [];
|
|
152
|
+
currentMetrics = null;
|
|
153
|
+
// Metrics collectors (injected)
|
|
154
|
+
metricsCollectors = new Map();
|
|
155
|
+
constructor(config = {}) {
|
|
156
|
+
super();
|
|
157
|
+
this.config = { ...exports.DEFAULT_IMPROVEMENT_CONFIG, ...config };
|
|
158
|
+
this.darwinGodel = (0, darwin_godel_js_1.getDarwinGodelEngine)();
|
|
159
|
+
}
|
|
160
|
+
// ============================================================================
|
|
161
|
+
// Lifecycle
|
|
162
|
+
// ============================================================================
|
|
163
|
+
/**
|
|
164
|
+
* Set the φ monitor for consciousness metrics
|
|
165
|
+
*/
|
|
166
|
+
setPhiMonitor(monitor) {
|
|
167
|
+
this.phiMonitor = monitor;
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Set the cognitive workspace for memory metrics
|
|
171
|
+
*/
|
|
172
|
+
setCognitiveWorkspace(workspace) {
|
|
173
|
+
this.cognitiveWorkspace = workspace;
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Register a custom metrics collector
|
|
177
|
+
*/
|
|
178
|
+
registerMetricsCollector(name, collector) {
|
|
179
|
+
this.metricsCollectors.set(name, collector);
|
|
180
|
+
}
|
|
181
|
+
// ============================================================================
|
|
182
|
+
// Main Cycle
|
|
183
|
+
// ============================================================================
|
|
184
|
+
/**
|
|
185
|
+
* Run a single improvement cycle
|
|
186
|
+
*/
|
|
187
|
+
async runCycle() {
|
|
188
|
+
const startTime = Date.now();
|
|
189
|
+
this.emit('cycle:started', { timestamp: new Date() });
|
|
190
|
+
// 1. OBSERVE - Collect metrics
|
|
191
|
+
const metrics = this.collectMetrics();
|
|
192
|
+
this.currentMetrics = metrics;
|
|
193
|
+
this.emit('metrics:collected', { metrics });
|
|
194
|
+
// 2. REFLECT - Find improvement opportunities
|
|
195
|
+
const opportunities = this.findOpportunities(metrics);
|
|
196
|
+
for (const opp of opportunities) {
|
|
197
|
+
this.emit('opportunity:found', { opportunity: opp });
|
|
198
|
+
}
|
|
199
|
+
// 3. CHECK - Can we improve?
|
|
200
|
+
const canImprove = this.canAttemptImprovement(metrics);
|
|
201
|
+
const results = [];
|
|
202
|
+
if (!canImprove) {
|
|
203
|
+
this.emit('improvement:skipped', { reason: 'conditions not met', metrics });
|
|
204
|
+
}
|
|
205
|
+
else if (!this.config.autoImprove) {
|
|
206
|
+
this.emit('improvement:skipped', { reason: 'auto-improve disabled' });
|
|
207
|
+
}
|
|
208
|
+
else {
|
|
209
|
+
// 4. APPLY - Try improvements
|
|
210
|
+
const sorted = opportunities.sort((a, b) => b.priority - a.priority);
|
|
211
|
+
const toApply = sorted.slice(0, this.config.maxImprovementsPerCycle);
|
|
212
|
+
for (const opportunity of toApply) {
|
|
213
|
+
if (opportunity.suggestedFix) {
|
|
214
|
+
const result = await this.applyImprovement(opportunity, metrics);
|
|
215
|
+
results.push(result);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
this.emit('cycle:completed', {
|
|
220
|
+
duration: Date.now() - startTime,
|
|
221
|
+
metrics,
|
|
222
|
+
opportunitiesFound: opportunities.length,
|
|
223
|
+
improvementsApplied: results.filter(r => r.success).length,
|
|
224
|
+
});
|
|
225
|
+
return { metrics, opportunities, results };
|
|
226
|
+
}
|
|
227
|
+
// ============================================================================
|
|
228
|
+
// Observe - Metrics Collection
|
|
229
|
+
// ============================================================================
|
|
230
|
+
/**
|
|
231
|
+
* Collect metrics from all systems
|
|
232
|
+
*/
|
|
233
|
+
collectMetrics() {
|
|
234
|
+
const now = new Date();
|
|
235
|
+
// Base metrics
|
|
236
|
+
const metrics = {
|
|
237
|
+
phi: 0.3,
|
|
238
|
+
consciousnessState: 'normal',
|
|
239
|
+
phiTrend: 'stable',
|
|
240
|
+
memoryReuse: 0.5,
|
|
241
|
+
cacheHitRate: 0.7,
|
|
242
|
+
memorySize: 0,
|
|
243
|
+
avgResponseTime: 100,
|
|
244
|
+
taskSuccessRate: 0.9,
|
|
245
|
+
errorRate: 0.05,
|
|
246
|
+
avgSurprise: 3.0,
|
|
247
|
+
expectedFreeEnergy: 10.0,
|
|
248
|
+
uptime: process.uptime() * 1000,
|
|
249
|
+
cyclesCompleted: 0,
|
|
250
|
+
timestamp: now,
|
|
251
|
+
};
|
|
252
|
+
// Get φ from monitor
|
|
253
|
+
if (this.phiMonitor) {
|
|
254
|
+
const level = this.phiMonitor.getCurrentLevel();
|
|
255
|
+
metrics.phi = level.rawPhi;
|
|
256
|
+
metrics.consciousnessState = this.phiMonitor.getState();
|
|
257
|
+
metrics.phiTrend = this.phiMonitor.getTrend();
|
|
258
|
+
}
|
|
259
|
+
// Get memory metrics from workspace
|
|
260
|
+
if (this.cognitiveWorkspace) {
|
|
261
|
+
const wsMetrics = this.cognitiveWorkspace.getMetrics();
|
|
262
|
+
const wsStats = this.cognitiveWorkspace.getStats();
|
|
263
|
+
metrics.memoryReuse = wsMetrics.reuseRate;
|
|
264
|
+
metrics.memorySize = wsStats.estimatedTokens;
|
|
265
|
+
}
|
|
266
|
+
// Collect from registered collectors
|
|
267
|
+
for (const collector of this.metricsCollectors.values()) {
|
|
268
|
+
try {
|
|
269
|
+
const partial = collector();
|
|
270
|
+
Object.assign(metrics, partial);
|
|
271
|
+
}
|
|
272
|
+
catch (e) {
|
|
273
|
+
// Ignore collector errors
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
return metrics;
|
|
277
|
+
}
|
|
278
|
+
// ============================================================================
|
|
279
|
+
// Reflect - Find Opportunities
|
|
280
|
+
// ============================================================================
|
|
281
|
+
/**
|
|
282
|
+
* Find improvement opportunities based on current metrics
|
|
283
|
+
*/
|
|
284
|
+
findOpportunities(metrics) {
|
|
285
|
+
const opportunities = [];
|
|
286
|
+
const { thresholds, targets } = this.config;
|
|
287
|
+
// Check φ
|
|
288
|
+
if (metrics.phi < thresholds.minPhi) {
|
|
289
|
+
const plan = IMPROVEMENT_TEMPLATES['improve-phi'](metrics);
|
|
290
|
+
if (plan) {
|
|
291
|
+
opportunities.push({
|
|
292
|
+
id: 'opp-phi',
|
|
293
|
+
category: 'consciousness',
|
|
294
|
+
metric: 'phi',
|
|
295
|
+
currentValue: metrics.phi,
|
|
296
|
+
targetValue: targets.phi,
|
|
297
|
+
priority: 0.9, // High priority - consciousness is core
|
|
298
|
+
description: `φ is ${metrics.phi.toFixed(3)}, below threshold ${thresholds.minPhi}`,
|
|
299
|
+
suggestedFix: plan,
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
// Check memory reuse
|
|
304
|
+
if (metrics.memoryReuse < thresholds.minMemoryReuse) {
|
|
305
|
+
const plan = IMPROVEMENT_TEMPLATES['improve-memory-reuse'](metrics);
|
|
306
|
+
if (plan) {
|
|
307
|
+
opportunities.push({
|
|
308
|
+
id: 'opp-memory',
|
|
309
|
+
category: 'memory',
|
|
310
|
+
metric: 'memoryReuse',
|
|
311
|
+
currentValue: metrics.memoryReuse,
|
|
312
|
+
targetValue: targets.memoryReuse,
|
|
313
|
+
priority: 0.7,
|
|
314
|
+
description: `Memory reuse at ${(metrics.memoryReuse * 100).toFixed(1)}%, target is ${(targets.memoryReuse * 100).toFixed(0)}%`,
|
|
315
|
+
suggestedFix: plan,
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
// Check error rate
|
|
320
|
+
if (metrics.errorRate > thresholds.maxErrorRate) {
|
|
321
|
+
const plan = IMPROVEMENT_TEMPLATES['reduce-error-rate'](metrics);
|
|
322
|
+
if (plan) {
|
|
323
|
+
opportunities.push({
|
|
324
|
+
id: 'opp-errors',
|
|
325
|
+
category: 'reliability',
|
|
326
|
+
metric: 'errorRate',
|
|
327
|
+
currentValue: metrics.errorRate,
|
|
328
|
+
targetValue: targets.errorRate,
|
|
329
|
+
priority: 0.8,
|
|
330
|
+
description: `Error rate at ${(metrics.errorRate * 100).toFixed(1)}%, above threshold ${(thresholds.maxErrorRate * 100).toFixed(0)}%`,
|
|
331
|
+
suggestedFix: plan,
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
// Check surprise
|
|
336
|
+
if (metrics.avgSurprise > thresholds.maxSurprise) {
|
|
337
|
+
const plan = IMPROVEMENT_TEMPLATES['reduce-surprise'](metrics);
|
|
338
|
+
if (plan) {
|
|
339
|
+
opportunities.push({
|
|
340
|
+
id: 'opp-surprise',
|
|
341
|
+
category: 'performance',
|
|
342
|
+
metric: 'avgSurprise',
|
|
343
|
+
currentValue: metrics.avgSurprise,
|
|
344
|
+
targetValue: targets.surprise,
|
|
345
|
+
priority: 0.6,
|
|
346
|
+
description: `Average surprise at ${metrics.avgSurprise.toFixed(2)}, above threshold ${thresholds.maxSurprise}`,
|
|
347
|
+
suggestedFix: plan,
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
// Check task success rate
|
|
352
|
+
if (metrics.taskSuccessRate < thresholds.minTaskSuccessRate) {
|
|
353
|
+
opportunities.push({
|
|
354
|
+
id: 'opp-success',
|
|
355
|
+
category: 'performance',
|
|
356
|
+
metric: 'taskSuccessRate',
|
|
357
|
+
currentValue: metrics.taskSuccessRate,
|
|
358
|
+
targetValue: targets.taskSuccessRate,
|
|
359
|
+
priority: 0.75,
|
|
360
|
+
description: `Task success at ${(metrics.taskSuccessRate * 100).toFixed(1)}%, below threshold ${(thresholds.minTaskSuccessRate * 100).toFixed(0)}%`,
|
|
361
|
+
// No automatic fix - needs analysis
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
return opportunities;
|
|
365
|
+
}
|
|
366
|
+
// ============================================================================
|
|
367
|
+
// Apply - Implement Improvements
|
|
368
|
+
// ============================================================================
|
|
369
|
+
/**
|
|
370
|
+
* Check if we can attempt an improvement
|
|
371
|
+
*/
|
|
372
|
+
canAttemptImprovement(metrics) {
|
|
373
|
+
// Check φ threshold
|
|
374
|
+
if (metrics.phi < this.config.minPhiForImprovement) {
|
|
375
|
+
return false;
|
|
376
|
+
}
|
|
377
|
+
// Check cooldown
|
|
378
|
+
const timeSinceLastImprovement = Date.now() - this.lastImprovement.getTime();
|
|
379
|
+
if (timeSinceLastImprovement < this.config.improvementCooldownMs) {
|
|
380
|
+
return false;
|
|
381
|
+
}
|
|
382
|
+
// Check invariants
|
|
383
|
+
const invariantContext = {
|
|
384
|
+
energy: 1.0, // Assume full energy for self-improvement
|
|
385
|
+
dormancyThreshold: 0.1,
|
|
386
|
+
isDormant: false,
|
|
387
|
+
responsiveAgentCount: 1,
|
|
388
|
+
totalAgentCount: 1,
|
|
389
|
+
};
|
|
390
|
+
const invariantResults = invariants_js_1.invariantRegistry.checkAll(invariantContext);
|
|
391
|
+
const allPassed = invariantResults.every(r => r.passed);
|
|
392
|
+
return allPassed;
|
|
393
|
+
}
|
|
394
|
+
/**
|
|
395
|
+
* Apply a single improvement
|
|
396
|
+
*/
|
|
397
|
+
async applyImprovement(opportunity, beforeMetrics) {
|
|
398
|
+
const startTime = Date.now();
|
|
399
|
+
if (!opportunity.suggestedFix) {
|
|
400
|
+
return {
|
|
401
|
+
opportunityId: opportunity.id,
|
|
402
|
+
applied: false,
|
|
403
|
+
success: false,
|
|
404
|
+
beforeMetrics,
|
|
405
|
+
error: 'No suggested fix available',
|
|
406
|
+
duration: Date.now() - startTime,
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
this.emit('improvement:started', { opportunity });
|
|
410
|
+
try {
|
|
411
|
+
// Use Darwin-Gödel to apply
|
|
412
|
+
const result = await this.darwinGodel.apply(opportunity.suggestedFix);
|
|
413
|
+
if (!result.success) {
|
|
414
|
+
this.emit('improvement:failed', {
|
|
415
|
+
opportunity,
|
|
416
|
+
errors: result.verificaton.errors,
|
|
417
|
+
});
|
|
418
|
+
return {
|
|
419
|
+
opportunityId: opportunity.id,
|
|
420
|
+
applied: false,
|
|
421
|
+
success: false,
|
|
422
|
+
beforeMetrics,
|
|
423
|
+
error: result.verificaton.errors.join('; '),
|
|
424
|
+
rollbackHash: result.rollbackHash,
|
|
425
|
+
duration: Date.now() - startTime,
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
// Collect after metrics
|
|
429
|
+
const afterMetrics = this.collectMetrics();
|
|
430
|
+
// Verify improvement
|
|
431
|
+
const improved = this.verifyImprovement(opportunity, beforeMetrics, afterMetrics);
|
|
432
|
+
this.lastImprovement = new Date();
|
|
433
|
+
const improvementResult = {
|
|
434
|
+
opportunityId: opportunity.id,
|
|
435
|
+
applied: true,
|
|
436
|
+
success: improved,
|
|
437
|
+
beforeMetrics,
|
|
438
|
+
afterMetrics,
|
|
439
|
+
commitHash: result.commitHash,
|
|
440
|
+
rollbackHash: result.rollbackHash,
|
|
441
|
+
duration: Date.now() - startTime,
|
|
442
|
+
};
|
|
443
|
+
this.improvementHistory.push(improvementResult);
|
|
444
|
+
if (improved) {
|
|
445
|
+
this.emit('improvement:success', { opportunity, result: improvementResult });
|
|
446
|
+
}
|
|
447
|
+
else {
|
|
448
|
+
// Rollback if no improvement
|
|
449
|
+
if (result.rollbackHash) {
|
|
450
|
+
this.darwinGodel.rollback(result.rollbackHash);
|
|
451
|
+
}
|
|
452
|
+
this.emit('improvement:failed', {
|
|
453
|
+
opportunity,
|
|
454
|
+
reason: 'no measurable improvement',
|
|
455
|
+
result: improvementResult,
|
|
456
|
+
});
|
|
457
|
+
}
|
|
458
|
+
return improvementResult;
|
|
459
|
+
}
|
|
460
|
+
catch (error) {
|
|
461
|
+
const errorMsg = error instanceof Error ? error.message : String(error);
|
|
462
|
+
this.emit('improvement:failed', {
|
|
463
|
+
opportunity,
|
|
464
|
+
error: errorMsg,
|
|
465
|
+
});
|
|
466
|
+
return {
|
|
467
|
+
opportunityId: opportunity.id,
|
|
468
|
+
applied: false,
|
|
469
|
+
success: false,
|
|
470
|
+
beforeMetrics,
|
|
471
|
+
error: errorMsg,
|
|
472
|
+
duration: Date.now() - startTime,
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
/**
|
|
477
|
+
* Verify that an improvement actually improved the metric
|
|
478
|
+
*/
|
|
479
|
+
verifyImprovement(opportunity, before, after) {
|
|
480
|
+
const metric = opportunity.metric;
|
|
481
|
+
const beforeValue = before[metric];
|
|
482
|
+
const afterValue = after[metric];
|
|
483
|
+
const target = opportunity.targetValue;
|
|
484
|
+
// For metrics where lower is better
|
|
485
|
+
if (['errorRate', 'avgSurprise', 'expectedFreeEnergy'].includes(metric)) {
|
|
486
|
+
return afterValue < beforeValue;
|
|
487
|
+
}
|
|
488
|
+
// For metrics where higher is better
|
|
489
|
+
return afterValue > beforeValue;
|
|
490
|
+
}
|
|
491
|
+
// ============================================================================
|
|
492
|
+
// Stats
|
|
493
|
+
// ============================================================================
|
|
494
|
+
/**
|
|
495
|
+
* Get improvement statistics
|
|
496
|
+
*/
|
|
497
|
+
stats() {
|
|
498
|
+
const total = this.improvementHistory.length;
|
|
499
|
+
const successful = this.improvementHistory.filter(r => r.success).length;
|
|
500
|
+
return {
|
|
501
|
+
totalAttempts: total,
|
|
502
|
+
successfulImprovements: successful,
|
|
503
|
+
failedImprovements: total - successful,
|
|
504
|
+
successRate: total > 0 ? successful / total : 0,
|
|
505
|
+
lastImprovement: this.lastImprovement.getTime() > 0 ? this.lastImprovement : null,
|
|
506
|
+
currentMetrics: this.currentMetrics,
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
/**
|
|
510
|
+
* Get improvement history
|
|
511
|
+
*/
|
|
512
|
+
getHistory() {
|
|
513
|
+
return [...this.improvementHistory];
|
|
514
|
+
}
|
|
515
|
+
/**
|
|
516
|
+
* Get current configuration
|
|
517
|
+
*/
|
|
518
|
+
getConfig() {
|
|
519
|
+
return { ...this.config };
|
|
520
|
+
}
|
|
521
|
+
/**
|
|
522
|
+
* Update configuration
|
|
523
|
+
*/
|
|
524
|
+
updateConfig(partial) {
|
|
525
|
+
this.config = { ...this.config, ...partial };
|
|
526
|
+
}
|
|
527
|
+
/**
|
|
528
|
+
* Enable/disable auto-improvement
|
|
529
|
+
*/
|
|
530
|
+
setAutoImprove(enabled) {
|
|
531
|
+
this.config.autoImprove = enabled;
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
exports.SelfImprovementEngine = SelfImprovementEngine;
|
|
535
|
+
// ============================================================================
|
|
536
|
+
// Factory
|
|
537
|
+
// ============================================================================
|
|
538
|
+
let improvementInstance = null;
|
|
539
|
+
function getSelfImprovementEngine(config) {
|
|
540
|
+
if (!improvementInstance) {
|
|
541
|
+
improvementInstance = new SelfImprovementEngine(config);
|
|
542
|
+
}
|
|
543
|
+
return improvementInstance;
|
|
544
|
+
}
|
|
545
|
+
function resetSelfImprovementEngine() {
|
|
546
|
+
improvementInstance = null;
|
|
547
|
+
}
|
|
548
|
+
function createSelfImprovementEngine(config) {
|
|
549
|
+
return new SelfImprovementEngine(config);
|
|
550
|
+
}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Genesis 7.17 - Unified Autonomous System
|
|
3
|
+
*
|
|
4
|
+
* Connects all Genesis modules into a single coherent system:
|
|
5
|
+
*
|
|
6
|
+
* ┌─────────────────────────────────────────────────────────────────────────┐
|
|
7
|
+
* │ UNIFIED SYSTEM │
|
|
8
|
+
* ├─────────────────────────────────────────────────────────────────────────┤
|
|
9
|
+
* │ │
|
|
10
|
+
* │ PERCEPTION (MCP) → COGNITION → ACTION (MCP) │
|
|
11
|
+
* │ ↓ ↓ ↑ │
|
|
12
|
+
* │ ┌─────────────────────────────────────────────────────────────────┐ │
|
|
13
|
+
* │ │ CONSCIOUSNESS (φ Monitor + Global Workspace) │ │
|
|
14
|
+
* │ └─────────────────────────────────────────────────────────────────┘ │
|
|
15
|
+
* │ ↓ ↓ ↑ │
|
|
16
|
+
* │ ┌─────────────────────────────────────────────────────────────────┐ │
|
|
17
|
+
* │ │ MEMORY (Episodic + Semantic + Working) │ │
|
|
18
|
+
* │ └─────────────────────────────────────────────────────────────────┘ │
|
|
19
|
+
* │ ↓ ↓ ↑ │
|
|
20
|
+
* │ ┌─────────────────────────────────────────────────────────────────┐ │
|
|
21
|
+
* │ │ SELF-IMPROVEMENT (Darwin-Gödel) │ │
|
|
22
|
+
* │ └─────────────────────────────────────────────────────────────────┘ │
|
|
23
|
+
* │ │
|
|
24
|
+
* └─────────────────────────────────────────────────────────────────────────┘
|
|
25
|
+
*
|
|
26
|
+
* This is Genesis's core loop - a conscious, self-improving autonomous agent.
|
|
27
|
+
*/
|
|
28
|
+
import { EventEmitter } from 'events';
|
|
29
|
+
import { ConsciousnessSystem, ConsciousnessSnapshot, ConsciousnessConfig } from './consciousness/index.js';
|
|
30
|
+
import { ActionResult } from './consciousness/conscious-agent.js';
|
|
31
|
+
import { PerceptionStream, Perception } from './consciousness/perception-stream.js';
|
|
32
|
+
import { CognitiveWorkspace } from './memory/cognitive-workspace.js';
|
|
33
|
+
import { SelfImprovementEngine, SystemMetrics, ImprovementOpportunity, ImprovementResult } from './self-modification/index.js';
|
|
34
|
+
export interface UnifiedSystemConfig {
|
|
35
|
+
/** System name */
|
|
36
|
+
name: string;
|
|
37
|
+
/** Enable consciousness monitoring */
|
|
38
|
+
consciousnessEnabled: boolean;
|
|
39
|
+
/** Enable self-improvement */
|
|
40
|
+
selfImprovementEnabled: boolean;
|
|
41
|
+
/** Enable MCP perception */
|
|
42
|
+
perceptionEnabled: boolean;
|
|
43
|
+
/** Enable active inference loop */
|
|
44
|
+
activeInferenceEnabled: boolean;
|
|
45
|
+
/** Initial goals */
|
|
46
|
+
goals: string[];
|
|
47
|
+
/** Maximum cycles for autonomous mode */
|
|
48
|
+
maxCycles: number;
|
|
49
|
+
/** Cycle interval in ms */
|
|
50
|
+
cycleIntervalMs: number;
|
|
51
|
+
/** Minimum φ to continue operation */
|
|
52
|
+
minPhi: number;
|
|
53
|
+
/** Consciousness config */
|
|
54
|
+
consciousness?: Partial<ConsciousnessConfig>;
|
|
55
|
+
}
|
|
56
|
+
export declare const DEFAULT_UNIFIED_CONFIG: UnifiedSystemConfig;
|
|
57
|
+
export interface UnifiedSystemState {
|
|
58
|
+
status: 'idle' | 'running' | 'paused' | 'stopped' | 'error';
|
|
59
|
+
cyclesCompleted: number;
|
|
60
|
+
currentPhi: number;
|
|
61
|
+
consciousnessLevel: string;
|
|
62
|
+
memoryReuseRate: number;
|
|
63
|
+
lastAction: ActionResult | null;
|
|
64
|
+
lastPerception: Perception | null;
|
|
65
|
+
improvementsApplied: number;
|
|
66
|
+
uptime: number;
|
|
67
|
+
errors: string[];
|
|
68
|
+
}
|
|
69
|
+
export type UnifiedEventType = 'system:started' | 'system:stopped' | 'system:paused' | 'system:resumed' | 'system:error' | 'cycle:started' | 'cycle:completed' | 'perception:received' | 'action:executed' | 'improvement:applied' | 'consciousness:changed' | 'invariant:violated';
|
|
70
|
+
export declare class UnifiedSystem extends EventEmitter {
|
|
71
|
+
private config;
|
|
72
|
+
private consciousness;
|
|
73
|
+
private consciousAgent?;
|
|
74
|
+
private perceptionStream?;
|
|
75
|
+
private cognitiveWorkspace;
|
|
76
|
+
private mcpManager;
|
|
77
|
+
private selfImprovement;
|
|
78
|
+
private state;
|
|
79
|
+
private running;
|
|
80
|
+
private paused;
|
|
81
|
+
private startTime;
|
|
82
|
+
private cycleTimer?;
|
|
83
|
+
constructor(config?: Partial<UnifiedSystemConfig>);
|
|
84
|
+
/**
|
|
85
|
+
* Start the unified system
|
|
86
|
+
*/
|
|
87
|
+
start(): Promise<void>;
|
|
88
|
+
/**
|
|
89
|
+
* Stop the unified system
|
|
90
|
+
*/
|
|
91
|
+
stop(): Promise<void>;
|
|
92
|
+
/**
|
|
93
|
+
* Pause the system
|
|
94
|
+
*/
|
|
95
|
+
pause(): void;
|
|
96
|
+
/**
|
|
97
|
+
* Resume the system
|
|
98
|
+
*/
|
|
99
|
+
resume(): void;
|
|
100
|
+
/**
|
|
101
|
+
* Run a single unified cycle
|
|
102
|
+
*/
|
|
103
|
+
private runCycle;
|
|
104
|
+
private setupEventHandlers;
|
|
105
|
+
/**
|
|
106
|
+
* Get current system state
|
|
107
|
+
*/
|
|
108
|
+
getState(): UnifiedSystemState;
|
|
109
|
+
/**
|
|
110
|
+
* Get consciousness snapshot
|
|
111
|
+
*/
|
|
112
|
+
getConsciousnessSnapshot(): ConsciousnessSnapshot | null;
|
|
113
|
+
/**
|
|
114
|
+
* Get improvement opportunities
|
|
115
|
+
*/
|
|
116
|
+
getImprovementOpportunities(): Promise<ImprovementOpportunity[]>;
|
|
117
|
+
/**
|
|
118
|
+
* Get system metrics
|
|
119
|
+
*/
|
|
120
|
+
getMetrics(): SystemMetrics;
|
|
121
|
+
/**
|
|
122
|
+
* Get comprehensive stats
|
|
123
|
+
*/
|
|
124
|
+
stats(): {
|
|
125
|
+
system: UnifiedSystemState;
|
|
126
|
+
consciousness: ReturnType<ConsciousnessSystem['stats']>;
|
|
127
|
+
memory: ReturnType<CognitiveWorkspace['getMetrics']>;
|
|
128
|
+
improvement: ReturnType<SelfImprovementEngine['stats']>;
|
|
129
|
+
perceptions: ReturnType<PerceptionStream['stats']> | null;
|
|
130
|
+
};
|
|
131
|
+
/**
|
|
132
|
+
* Manually trigger self-improvement cycle
|
|
133
|
+
*/
|
|
134
|
+
triggerSelfImprovement(): Promise<{
|
|
135
|
+
metrics: SystemMetrics;
|
|
136
|
+
opportunities: ImprovementOpportunity[];
|
|
137
|
+
results: ImprovementResult[];
|
|
138
|
+
}>;
|
|
139
|
+
/**
|
|
140
|
+
* Set goals for the system
|
|
141
|
+
*/
|
|
142
|
+
setGoals(goals: string[]): void;
|
|
143
|
+
/**
|
|
144
|
+
* Enable/disable self-improvement
|
|
145
|
+
*/
|
|
146
|
+
setSelfImprovementEnabled(enabled: boolean): void;
|
|
147
|
+
/**
|
|
148
|
+
* Get configuration
|
|
149
|
+
*/
|
|
150
|
+
getConfig(): UnifiedSystemConfig;
|
|
151
|
+
}
|
|
152
|
+
export declare function getUnifiedSystem(config?: Partial<UnifiedSystemConfig>): UnifiedSystem;
|
|
153
|
+
export declare function resetUnifiedSystem(): void;
|
|
154
|
+
export declare function createUnifiedSystem(config?: Partial<UnifiedSystemConfig>): UnifiedSystem;
|
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Genesis 7.17 - Unified Autonomous System
|
|
4
|
+
*
|
|
5
|
+
* Connects all Genesis modules into a single coherent system:
|
|
6
|
+
*
|
|
7
|
+
* ┌─────────────────────────────────────────────────────────────────────────┐
|
|
8
|
+
* │ UNIFIED SYSTEM │
|
|
9
|
+
* ├─────────────────────────────────────────────────────────────────────────┤
|
|
10
|
+
* │ │
|
|
11
|
+
* │ PERCEPTION (MCP) → COGNITION → ACTION (MCP) │
|
|
12
|
+
* │ ↓ ↓ ↑ │
|
|
13
|
+
* │ ┌─────────────────────────────────────────────────────────────────┐ │
|
|
14
|
+
* │ │ CONSCIOUSNESS (φ Monitor + Global Workspace) │ │
|
|
15
|
+
* │ └─────────────────────────────────────────────────────────────────┘ │
|
|
16
|
+
* │ ↓ ↓ ↑ │
|
|
17
|
+
* │ ┌─────────────────────────────────────────────────────────────────┐ │
|
|
18
|
+
* │ │ MEMORY (Episodic + Semantic + Working) │ │
|
|
19
|
+
* │ └─────────────────────────────────────────────────────────────────┘ │
|
|
20
|
+
* │ ↓ ↓ ↑ │
|
|
21
|
+
* │ ┌─────────────────────────────────────────────────────────────────┐ │
|
|
22
|
+
* │ │ SELF-IMPROVEMENT (Darwin-Gödel) │ │
|
|
23
|
+
* │ └─────────────────────────────────────────────────────────────────┘ │
|
|
24
|
+
* │ │
|
|
25
|
+
* └─────────────────────────────────────────────────────────────────────────┘
|
|
26
|
+
*
|
|
27
|
+
* This is Genesis's core loop - a conscious, self-improving autonomous agent.
|
|
28
|
+
*/
|
|
29
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
30
|
+
exports.UnifiedSystem = exports.DEFAULT_UNIFIED_CONFIG = void 0;
|
|
31
|
+
exports.getUnifiedSystem = getUnifiedSystem;
|
|
32
|
+
exports.resetUnifiedSystem = resetUnifiedSystem;
|
|
33
|
+
exports.createUnifiedSystem = createUnifiedSystem;
|
|
34
|
+
const events_1 = require("events");
|
|
35
|
+
// Consciousness
|
|
36
|
+
const index_js_1 = require("./consciousness/index.js");
|
|
37
|
+
const conscious_agent_js_1 = require("./consciousness/conscious-agent.js");
|
|
38
|
+
const perception_stream_js_1 = require("./consciousness/perception-stream.js");
|
|
39
|
+
// Memory
|
|
40
|
+
const cognitive_workspace_js_1 = require("./memory/cognitive-workspace.js");
|
|
41
|
+
// MCP
|
|
42
|
+
const client_manager_js_1 = require("./mcp/client-manager.js");
|
|
43
|
+
// Self-Improvement
|
|
44
|
+
const index_js_2 = require("./self-modification/index.js");
|
|
45
|
+
exports.DEFAULT_UNIFIED_CONFIG = {
|
|
46
|
+
name: 'Genesis',
|
|
47
|
+
consciousnessEnabled: true,
|
|
48
|
+
selfImprovementEnabled: false, // Disabled by default for safety
|
|
49
|
+
perceptionEnabled: true,
|
|
50
|
+
activeInferenceEnabled: true,
|
|
51
|
+
goals: ['understand', 'assist', 'improve'],
|
|
52
|
+
maxCycles: 1000,
|
|
53
|
+
cycleIntervalMs: 100,
|
|
54
|
+
minPhi: 0.2,
|
|
55
|
+
};
|
|
56
|
+
// ============================================================================
|
|
57
|
+
// Unified System
|
|
58
|
+
// ============================================================================
|
|
59
|
+
class UnifiedSystem extends events_1.EventEmitter {
|
|
60
|
+
config;
|
|
61
|
+
// Core components
|
|
62
|
+
consciousness;
|
|
63
|
+
consciousAgent;
|
|
64
|
+
perceptionStream;
|
|
65
|
+
cognitiveWorkspace;
|
|
66
|
+
mcpManager;
|
|
67
|
+
selfImprovement;
|
|
68
|
+
// State
|
|
69
|
+
state;
|
|
70
|
+
running = false;
|
|
71
|
+
paused = false;
|
|
72
|
+
startTime = 0;
|
|
73
|
+
cycleTimer;
|
|
74
|
+
constructor(config = {}) {
|
|
75
|
+
super();
|
|
76
|
+
this.config = { ...exports.DEFAULT_UNIFIED_CONFIG, ...config };
|
|
77
|
+
// Initialize state
|
|
78
|
+
this.state = {
|
|
79
|
+
status: 'idle',
|
|
80
|
+
cyclesCompleted: 0,
|
|
81
|
+
currentPhi: 0.3,
|
|
82
|
+
consciousnessLevel: 'normal',
|
|
83
|
+
memoryReuseRate: 0.5,
|
|
84
|
+
lastAction: null,
|
|
85
|
+
lastPerception: null,
|
|
86
|
+
improvementsApplied: 0,
|
|
87
|
+
uptime: 0,
|
|
88
|
+
errors: [],
|
|
89
|
+
};
|
|
90
|
+
// Initialize components
|
|
91
|
+
this.consciousness = (0, index_js_1.createConsciousnessSystem)(this.config.consciousness);
|
|
92
|
+
this.cognitiveWorkspace = (0, cognitive_workspace_js_1.getCognitiveWorkspace)();
|
|
93
|
+
this.mcpManager = (0, client_manager_js_1.getMCPManager)();
|
|
94
|
+
this.selfImprovement = (0, index_js_2.getSelfImprovementEngine)();
|
|
95
|
+
// Wire up self-improvement to consciousness
|
|
96
|
+
this.selfImprovement.setPhiMonitor(this.consciousness.monitor);
|
|
97
|
+
this.selfImprovement.setCognitiveWorkspace(this.cognitiveWorkspace);
|
|
98
|
+
// Wire up event handlers
|
|
99
|
+
this.setupEventHandlers();
|
|
100
|
+
}
|
|
101
|
+
// ============================================================================
|
|
102
|
+
// Lifecycle
|
|
103
|
+
// ============================================================================
|
|
104
|
+
/**
|
|
105
|
+
* Start the unified system
|
|
106
|
+
*/
|
|
107
|
+
async start() {
|
|
108
|
+
if (this.running)
|
|
109
|
+
return;
|
|
110
|
+
this.running = true;
|
|
111
|
+
this.paused = false;
|
|
112
|
+
this.startTime = Date.now();
|
|
113
|
+
this.state.status = 'running';
|
|
114
|
+
// Start consciousness monitoring
|
|
115
|
+
if (this.config.consciousnessEnabled) {
|
|
116
|
+
this.consciousness.start();
|
|
117
|
+
}
|
|
118
|
+
// Initialize perception if enabled
|
|
119
|
+
if (this.config.perceptionEnabled) {
|
|
120
|
+
this.perceptionStream = (0, perception_stream_js_1.createPerceptionStream)(this.mcpManager);
|
|
121
|
+
this.perceptionStream.connectWorkspace(this.consciousness.workspace);
|
|
122
|
+
this.perceptionStream.start();
|
|
123
|
+
}
|
|
124
|
+
// Initialize conscious agent if active inference enabled
|
|
125
|
+
if (this.config.activeInferenceEnabled) {
|
|
126
|
+
this.consciousAgent = (0, conscious_agent_js_1.createConsciousAgent)(this.mcpManager, {
|
|
127
|
+
minPhiForAction: this.config.minPhi,
|
|
128
|
+
maxActionsPerCycle: 5,
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
// Start the main cycle
|
|
132
|
+
this.cycleTimer = setInterval(() => {
|
|
133
|
+
if (!this.paused) {
|
|
134
|
+
this.runCycle().catch(err => {
|
|
135
|
+
this.state.errors.push(err.message);
|
|
136
|
+
this.emit('system:error', { error: err });
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
}, this.config.cycleIntervalMs);
|
|
140
|
+
this.emit('system:started', { config: this.config });
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Stop the unified system
|
|
144
|
+
*/
|
|
145
|
+
async stop() {
|
|
146
|
+
if (!this.running)
|
|
147
|
+
return;
|
|
148
|
+
this.running = false;
|
|
149
|
+
this.state.status = 'stopped';
|
|
150
|
+
// Stop cycle timer
|
|
151
|
+
if (this.cycleTimer) {
|
|
152
|
+
clearInterval(this.cycleTimer);
|
|
153
|
+
this.cycleTimer = undefined;
|
|
154
|
+
}
|
|
155
|
+
// Stop components
|
|
156
|
+
this.consciousness.stop();
|
|
157
|
+
if (this.perceptionStream) {
|
|
158
|
+
this.perceptionStream.stop();
|
|
159
|
+
}
|
|
160
|
+
this.emit('system:stopped', { state: this.getState() });
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Pause the system
|
|
164
|
+
*/
|
|
165
|
+
pause() {
|
|
166
|
+
this.paused = true;
|
|
167
|
+
this.state.status = 'paused';
|
|
168
|
+
this.emit('system:paused');
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Resume the system
|
|
172
|
+
*/
|
|
173
|
+
resume() {
|
|
174
|
+
this.paused = false;
|
|
175
|
+
this.state.status = 'running';
|
|
176
|
+
this.emit('system:resumed');
|
|
177
|
+
}
|
|
178
|
+
// ============================================================================
|
|
179
|
+
// Main Cycle
|
|
180
|
+
// ============================================================================
|
|
181
|
+
/**
|
|
182
|
+
* Run a single unified cycle
|
|
183
|
+
*/
|
|
184
|
+
async runCycle() {
|
|
185
|
+
const cycleStart = Date.now();
|
|
186
|
+
this.emit('cycle:started', { cycle: this.state.cyclesCompleted + 1 });
|
|
187
|
+
try {
|
|
188
|
+
// 1. Update consciousness snapshot
|
|
189
|
+
const snapshot = this.consciousness.takeSnapshot();
|
|
190
|
+
this.state.currentPhi = snapshot.level.rawPhi;
|
|
191
|
+
this.state.consciousnessLevel = snapshot.state;
|
|
192
|
+
// Check φ threshold
|
|
193
|
+
if (this.state.currentPhi < this.config.minPhi) {
|
|
194
|
+
this.emit('consciousness:changed', {
|
|
195
|
+
warning: `φ dropped below threshold: ${this.state.currentPhi.toFixed(3)} < ${this.config.minPhi}`,
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
// 2. Process perceptions (if agent available)
|
|
199
|
+
if (this.consciousAgent) {
|
|
200
|
+
await this.consciousAgent.runCycle();
|
|
201
|
+
this.emit('action:executed', { cycle: this.state.cyclesCompleted });
|
|
202
|
+
}
|
|
203
|
+
// 3. Update memory metrics
|
|
204
|
+
const wsMetrics = this.cognitiveWorkspace.getMetrics();
|
|
205
|
+
this.state.memoryReuseRate = wsMetrics.reuseRate;
|
|
206
|
+
// 4. Self-improvement (if enabled)
|
|
207
|
+
if (this.config.selfImprovementEnabled) {
|
|
208
|
+
const improvementResult = await this.selfImprovement.runCycle();
|
|
209
|
+
for (const result of improvementResult.results) {
|
|
210
|
+
if (result.success) {
|
|
211
|
+
this.state.improvementsApplied++;
|
|
212
|
+
this.emit('improvement:applied', { result });
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
// 5. Check invariants
|
|
217
|
+
const invariant = this.consciousness.checkInvariant();
|
|
218
|
+
if (!invariant.satisfied) {
|
|
219
|
+
this.emit('invariant:violated', { invariant });
|
|
220
|
+
}
|
|
221
|
+
// Update state
|
|
222
|
+
this.state.cyclesCompleted++;
|
|
223
|
+
this.state.uptime = Date.now() - this.startTime;
|
|
224
|
+
this.emit('cycle:completed', {
|
|
225
|
+
cycle: this.state.cyclesCompleted,
|
|
226
|
+
duration: Date.now() - cycleStart,
|
|
227
|
+
phi: this.state.currentPhi,
|
|
228
|
+
});
|
|
229
|
+
// Check max cycles
|
|
230
|
+
if (this.state.cyclesCompleted >= this.config.maxCycles) {
|
|
231
|
+
await this.stop();
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
catch (error) {
|
|
235
|
+
this.state.errors.push(error instanceof Error ? error.message : String(error));
|
|
236
|
+
this.state.status = 'error';
|
|
237
|
+
throw error;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
// ============================================================================
|
|
241
|
+
// Event Handlers
|
|
242
|
+
// ============================================================================
|
|
243
|
+
setupEventHandlers() {
|
|
244
|
+
// Forward consciousness events
|
|
245
|
+
this.consciousness.on((event) => {
|
|
246
|
+
if (event.type === 'attention_shifted') {
|
|
247
|
+
this.emit('consciousness:changed', event);
|
|
248
|
+
}
|
|
249
|
+
});
|
|
250
|
+
// Forward perception events (if available)
|
|
251
|
+
if (this.perceptionStream) {
|
|
252
|
+
this.perceptionStream.on('perception:received', ({ perception }) => {
|
|
253
|
+
this.state.lastPerception = perception;
|
|
254
|
+
this.emit('perception:received', { perception });
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
// Forward self-improvement events
|
|
258
|
+
this.selfImprovement.on('improvement:success', ({ opportunity, result }) => {
|
|
259
|
+
this.emit('improvement:applied', { opportunity, result });
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
// ============================================================================
|
|
263
|
+
// State & Stats
|
|
264
|
+
// ============================================================================
|
|
265
|
+
/**
|
|
266
|
+
* Get current system state
|
|
267
|
+
*/
|
|
268
|
+
getState() {
|
|
269
|
+
return { ...this.state };
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* Get consciousness snapshot
|
|
273
|
+
*/
|
|
274
|
+
getConsciousnessSnapshot() {
|
|
275
|
+
return this.consciousness.getSnapshot();
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Get improvement opportunities
|
|
279
|
+
*/
|
|
280
|
+
async getImprovementOpportunities() {
|
|
281
|
+
const metrics = this.selfImprovement.collectMetrics();
|
|
282
|
+
return this.selfImprovement.findOpportunities(metrics);
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* Get system metrics
|
|
286
|
+
*/
|
|
287
|
+
getMetrics() {
|
|
288
|
+
return this.selfImprovement.collectMetrics();
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Get comprehensive stats
|
|
292
|
+
*/
|
|
293
|
+
stats() {
|
|
294
|
+
return {
|
|
295
|
+
system: this.getState(),
|
|
296
|
+
consciousness: this.consciousness.stats(),
|
|
297
|
+
memory: this.cognitiveWorkspace.getMetrics(),
|
|
298
|
+
improvement: this.selfImprovement.stats(),
|
|
299
|
+
perceptions: this.perceptionStream?.stats() || null,
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
// ============================================================================
|
|
303
|
+
// Manual Controls
|
|
304
|
+
// ============================================================================
|
|
305
|
+
/**
|
|
306
|
+
* Manually trigger self-improvement cycle
|
|
307
|
+
*/
|
|
308
|
+
async triggerSelfImprovement() {
|
|
309
|
+
return this.selfImprovement.runCycle();
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Set goals for the system
|
|
313
|
+
*/
|
|
314
|
+
setGoals(goals) {
|
|
315
|
+
this.config.goals = goals;
|
|
316
|
+
// Update perception stream goal
|
|
317
|
+
if (this.perceptionStream) {
|
|
318
|
+
this.perceptionStream.setGoal(goals.join(', '));
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Enable/disable self-improvement
|
|
323
|
+
*/
|
|
324
|
+
setSelfImprovementEnabled(enabled) {
|
|
325
|
+
this.config.selfImprovementEnabled = enabled;
|
|
326
|
+
this.selfImprovement.setAutoImprove(enabled);
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* Get configuration
|
|
330
|
+
*/
|
|
331
|
+
getConfig() {
|
|
332
|
+
return { ...this.config };
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
exports.UnifiedSystem = UnifiedSystem;
|
|
336
|
+
// ============================================================================
|
|
337
|
+
// Factory
|
|
338
|
+
// ============================================================================
|
|
339
|
+
let unifiedInstance = null;
|
|
340
|
+
function getUnifiedSystem(config) {
|
|
341
|
+
if (!unifiedInstance) {
|
|
342
|
+
unifiedInstance = new UnifiedSystem(config);
|
|
343
|
+
}
|
|
344
|
+
return unifiedInstance;
|
|
345
|
+
}
|
|
346
|
+
function resetUnifiedSystem() {
|
|
347
|
+
if (unifiedInstance) {
|
|
348
|
+
unifiedInstance.stop();
|
|
349
|
+
}
|
|
350
|
+
unifiedInstance = null;
|
|
351
|
+
(0, cognitive_workspace_js_1.resetCognitiveWorkspace)();
|
|
352
|
+
}
|
|
353
|
+
function createUnifiedSystem(config) {
|
|
354
|
+
return new UnifiedSystem(config);
|
|
355
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "genesis-ai-cli",
|
|
3
|
-
"version": "7.
|
|
3
|
+
"version": "7.17.0",
|
|
4
4
|
"description": "Autonomous AI System Creator - Brain ON by default, Active Inference integrated, Curiosity-driven, Φ monitoring in every response",
|
|
5
5
|
"main": "dist/src/index.js",
|
|
6
6
|
"types": "dist/src/index.d.ts",
|