genesis-ai-cli 8.2.0 → 8.4.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.
@@ -61,6 +61,9 @@ const child_process_1 = require("child_process");
61
61
  const util_1 = require("util");
62
62
  const fs = __importStar(require("fs"));
63
63
  const path = __importStar(require("path"));
64
+ // v8.3: Self-modification imports
65
+ const darwin_godel_js_1 = require("../self-modification/darwin-godel.js");
66
+ const self_improvement_js_1 = require("../self-modification/self-improvement.js");
64
67
  const execAsync = (0, util_1.promisify)(child_process_1.exec);
65
68
  // ============================================================================
66
69
  // Lazy Singleton Instances
@@ -1410,6 +1413,215 @@ registerAction('code.diff', async (context) => {
1410
1413
  }
1411
1414
  });
1412
1415
  // ============================================================================
1416
+ // SELF-MODIFICATION EXECUTOR (v8.3)
1417
+ // ============================================================================
1418
+ /**
1419
+ * self.modify: Radical self-modification via Darwin-Gödel Engine
1420
+ *
1421
+ * This is the core action that allows Genesis to modify its own code.
1422
+ * Requires:
1423
+ * - φ ≥ 0.3 (consciousness threshold)
1424
+ * - Valid modification plan
1425
+ * - All invariants must pass after modification
1426
+ *
1427
+ * Flow:
1428
+ * 1. Check consciousness level
1429
+ * 2. Generate or use provided modification plan
1430
+ * 3. Validate plan (syntax, safety)
1431
+ * 4. Apply in sandbox
1432
+ * 5. Verify (build, test, invariants)
1433
+ * 6. Atomic apply on success
1434
+ * 7. Store outcome in memory
1435
+ */
1436
+ registerAction('self.modify', async (context) => {
1437
+ const start = Date.now();
1438
+ try {
1439
+ // 1. Check consciousness level
1440
+ const phiMonitor = getPhiMonitor();
1441
+ const level = phiMonitor.getCurrentLevel();
1442
+ const phi = level.phi;
1443
+ if (phi < 0.3) {
1444
+ return {
1445
+ success: false,
1446
+ action: 'self.modify',
1447
+ error: `Insufficient consciousness level: φ=${phi.toFixed(3)} (need ≥0.3)`,
1448
+ data: { phi, threshold: 0.3 },
1449
+ duration: Date.now() - start,
1450
+ };
1451
+ }
1452
+ // 2. Get or create modification plan
1453
+ let plan;
1454
+ if (context.parameters?.plan) {
1455
+ // Use provided plan
1456
+ plan = context.parameters.plan;
1457
+ }
1458
+ else if (context.parameters?.targetMetric) {
1459
+ // Use SelfImprovementEngine to find opportunity
1460
+ const engine = (0, self_improvement_js_1.getSelfImprovementEngine)();
1461
+ const cycleResult = await engine.runCycle();
1462
+ // Find opportunity matching target metric
1463
+ const targetMetric = context.parameters.targetMetric;
1464
+ const opportunity = cycleResult.opportunities.find((o) => o.metric === targetMetric);
1465
+ if (!opportunity || !opportunity.suggestedFix) {
1466
+ return {
1467
+ success: false,
1468
+ action: 'self.modify',
1469
+ error: `No improvement opportunity found for metric: ${targetMetric}`,
1470
+ data: {
1471
+ metrics: cycleResult.metrics,
1472
+ availableOpportunities: cycleResult.opportunities.map((o) => o.metric),
1473
+ },
1474
+ duration: Date.now() - start,
1475
+ };
1476
+ }
1477
+ plan = opportunity.suggestedFix;
1478
+ }
1479
+ else {
1480
+ // Auto-detect: run full improvement cycle
1481
+ const engine = (0, self_improvement_js_1.getSelfImprovementEngine)();
1482
+ const result = await engine.runCycle();
1483
+ if (result.results.length === 0) {
1484
+ return {
1485
+ success: true,
1486
+ action: 'self.modify',
1487
+ data: {
1488
+ message: 'No improvements needed - all metrics within targets',
1489
+ metrics: result.metrics,
1490
+ opportunities: result.opportunities.length,
1491
+ },
1492
+ duration: Date.now() - start,
1493
+ };
1494
+ }
1495
+ // Return first improvement result
1496
+ const improvement = result.results[0];
1497
+ return {
1498
+ success: improvement.success,
1499
+ action: 'self.modify',
1500
+ data: {
1501
+ opportunityId: improvement.opportunityId,
1502
+ applied: improvement.applied,
1503
+ beforeMetrics: improvement.beforeMetrics,
1504
+ afterMetrics: improvement.afterMetrics,
1505
+ commitHash: improvement.commitHash,
1506
+ },
1507
+ duration: Date.now() - start,
1508
+ };
1509
+ }
1510
+ // 3. Apply via Darwin-Gödel Engine
1511
+ const darwinGodel = (0, darwin_godel_js_1.getDarwinGodelEngine)();
1512
+ const applyResult = await darwinGodel.apply(plan);
1513
+ // 4. Log outcome (memory storage removed - use event system instead)
1514
+ console.log(`[self.modify] ${applyResult.success ? 'SUCCESS' : 'FAILED'}: ${plan.name}`);
1515
+ return {
1516
+ success: applyResult.success,
1517
+ action: 'self.modify',
1518
+ data: {
1519
+ planId: plan.id,
1520
+ planName: plan.name,
1521
+ modificationsCount: plan.modifications.length,
1522
+ verification: {
1523
+ buildSuccess: applyResult.verificaton.buildSuccess,
1524
+ testsSuccess: applyResult.verificaton.testsSuccess,
1525
+ invariantsPass: applyResult.verificaton.invariantsPass,
1526
+ },
1527
+ commitHash: applyResult.commitHash,
1528
+ rollbackHash: applyResult.rollbackHash,
1529
+ canRollback: !!applyResult.rollbackHash,
1530
+ },
1531
+ duration: Date.now() - start,
1532
+ };
1533
+ }
1534
+ catch (error) {
1535
+ return {
1536
+ success: false,
1537
+ action: 'self.modify',
1538
+ error: error instanceof Error ? error.message : String(error),
1539
+ duration: Date.now() - start,
1540
+ };
1541
+ }
1542
+ });
1543
+ /**
1544
+ * improve.self: High-level self-improvement action
1545
+ *
1546
+ * Observes metrics, identifies bottlenecks, and triggers self.modify.
1547
+ * This is the "autonomous improvement" entry point.
1548
+ */
1549
+ registerAction('improve.self', async (context) => {
1550
+ const start = Date.now();
1551
+ try {
1552
+ const engine = (0, self_improvement_js_1.getSelfImprovementEngine)();
1553
+ // 1. Run improvement cycle (observe + reflect + optionally apply)
1554
+ const cycleResult = await engine.runCycle();
1555
+ const { metrics, opportunities, results } = cycleResult;
1556
+ if (opportunities.length === 0) {
1557
+ return {
1558
+ success: true,
1559
+ action: 'improve.self',
1560
+ data: {
1561
+ message: 'System is operating within optimal parameters',
1562
+ metrics: {
1563
+ phi: metrics.phi,
1564
+ memoryReuse: metrics.memoryReuse,
1565
+ errorRate: metrics.errorRate,
1566
+ taskSuccessRate: metrics.taskSuccessRate,
1567
+ },
1568
+ },
1569
+ duration: Date.now() - start,
1570
+ };
1571
+ }
1572
+ // 2. Sort by priority and pick top
1573
+ const sorted = [...opportunities].sort((a, b) => b.priority - a.priority);
1574
+ const topOpportunity = sorted[0];
1575
+ // 3. If autoApply and we have results, report them
1576
+ if (context.parameters?.autoApply && results.length > 0) {
1577
+ return {
1578
+ success: true,
1579
+ action: 'improve.self',
1580
+ data: {
1581
+ applied: results.length > 0,
1582
+ improvements: results.map((i) => ({
1583
+ id: i.opportunityId,
1584
+ success: i.success,
1585
+ })),
1586
+ metrics: metrics,
1587
+ },
1588
+ duration: Date.now() - start,
1589
+ };
1590
+ }
1591
+ // 4. Otherwise, just report opportunities
1592
+ return {
1593
+ success: true,
1594
+ action: 'improve.self',
1595
+ data: {
1596
+ opportunities: sorted.map((o) => ({
1597
+ id: o.id,
1598
+ category: o.category,
1599
+ metric: o.metric,
1600
+ current: o.currentValue,
1601
+ target: o.targetValue,
1602
+ priority: o.priority,
1603
+ description: o.description,
1604
+ })),
1605
+ topRecommendation: {
1606
+ metric: topOpportunity.metric,
1607
+ description: topOpportunity.description,
1608
+ priority: topOpportunity.priority,
1609
+ },
1610
+ hint: 'Use self.modify with targetMetric parameter to apply improvement',
1611
+ },
1612
+ duration: Date.now() - start,
1613
+ };
1614
+ }
1615
+ catch (error) {
1616
+ return {
1617
+ success: false,
1618
+ action: 'improve.self',
1619
+ error: error instanceof Error ? error.message : String(error),
1620
+ duration: Date.now() - start,
1621
+ };
1622
+ }
1623
+ });
1624
+ // ============================================================================
1413
1625
  // Action Executor Manager
1414
1626
  // ============================================================================
1415
1627
  class ActionExecutorManager {
@@ -84,6 +84,34 @@ export declare class Brain {
84
84
  * Check if brain is running
85
85
  */
86
86
  isRunning(): boolean;
87
+ /**
88
+ * v8.4: Check for self-improvement opportunities
89
+ *
90
+ * This method can be called periodically (e.g., by daemon during idle periods)
91
+ * to discover and optionally apply improvements.
92
+ *
93
+ * @param autoApply - If true, automatically apply discovered improvements
94
+ * @returns Improvement results or opportunities
95
+ */
96
+ checkForImprovements(autoApply?: boolean): Promise<{
97
+ success: boolean;
98
+ opportunities?: Array<{
99
+ metric: string;
100
+ description: string;
101
+ priority: number;
102
+ }>;
103
+ applied?: Array<{
104
+ id: string;
105
+ success: boolean;
106
+ }>;
107
+ error?: string;
108
+ }>;
109
+ /**
110
+ * v8.4: Get the current self-model
111
+ *
112
+ * Returns Genesis's understanding of its own architecture
113
+ */
114
+ getSelfModel(): Promise<any>;
87
115
  /**
88
116
  * Process an input through the brain
89
117
  *
@@ -274,6 +274,73 @@ class Brain {
274
274
  isRunning() {
275
275
  return this.running;
276
276
  }
277
+ /**
278
+ * v8.4: Check for self-improvement opportunities
279
+ *
280
+ * This method can be called periodically (e.g., by daemon during idle periods)
281
+ * to discover and optionally apply improvements.
282
+ *
283
+ * @param autoApply - If true, automatically apply discovered improvements
284
+ * @returns Improvement results or opportunities
285
+ */
286
+ async checkForImprovements(autoApply = false) {
287
+ try {
288
+ // Check consciousness level
289
+ const phi = this.getCurrentPhi();
290
+ if (phi < 0.3) {
291
+ return {
292
+ success: false,
293
+ error: `Consciousness level too low: φ=${phi.toFixed(3)} (need ≥0.3)`,
294
+ };
295
+ }
296
+ // Import action executor
297
+ const { executeAction } = await import('../active-inference/actions.js');
298
+ // Run improve.self action
299
+ const result = await executeAction('improve.self', {
300
+ parameters: { autoApply },
301
+ beliefs: { viability: 0.5, worldState: 0.5, coupling: 0.5, goalProgress: 0.5 },
302
+ });
303
+ if (result.success) {
304
+ if (result.data?.opportunities) {
305
+ return {
306
+ success: true,
307
+ opportunities: result.data.opportunities,
308
+ };
309
+ }
310
+ if (result.data?.applied) {
311
+ return {
312
+ success: true,
313
+ applied: result.data.improvements,
314
+ };
315
+ }
316
+ return { success: true };
317
+ }
318
+ return {
319
+ success: false,
320
+ error: result.error || 'Unknown error',
321
+ };
322
+ }
323
+ catch (error) {
324
+ return {
325
+ success: false,
326
+ error: error instanceof Error ? error.message : String(error),
327
+ };
328
+ }
329
+ }
330
+ /**
331
+ * v8.4: Get the current self-model
332
+ *
333
+ * Returns Genesis's understanding of its own architecture
334
+ */
335
+ async getSelfModel() {
336
+ try {
337
+ const { generateSelfModel } = await import('../self-modification/self-model.js');
338
+ return await generateSelfModel();
339
+ }
340
+ catch (error) {
341
+ return { error: error instanceof Error ? error.message : String(error) };
342
+ }
343
+ }
277
344
  // ============================================================================
278
345
  // Main Processing Loop
279
346
  // ============================================================================
@@ -1046,14 +1113,16 @@ class Brain {
1046
1113
  };
1047
1114
  }
1048
1115
  try {
1049
- // Self-modification should only occur with explicit request
1050
- // Check if query indicates a self-improvement request
1116
+ // v8.4: Use Active Inference action executors for self-modification
1051
1117
  const queryLower = state.query.toLowerCase();
1052
- const isImprovementRequest = queryLower.includes('improve') ||
1118
+ // Determine which action to invoke based on query
1119
+ const isExplicitModify = queryLower.includes('self-modify') ||
1120
+ queryLower.includes('self modify') ||
1121
+ queryLower.includes('modifica te stesso');
1122
+ const isImproveRequest = queryLower.includes('improve') ||
1053
1123
  queryLower.includes('optimize') ||
1054
- queryLower.includes('self-modify') ||
1055
- queryLower.includes('self modify');
1056
- if (!isImprovementRequest) {
1124
+ queryLower.includes('miglior');
1125
+ if (!isExplicitModify && !isImproveRequest) {
1057
1126
  // Not a self-modification request, skip
1058
1127
  return {
1059
1128
  goto: 'done',
@@ -1061,29 +1130,67 @@ class Brain {
1061
1130
  reason: 'self_modify_not_requested',
1062
1131
  };
1063
1132
  }
1064
- // Create a simple diagnostic checkpoint before any potential changes
1065
- const checkpointHash = await this.darwinGodel.createCheckpoint('brain-self-modify-checkpoint');
1066
- // Report current system status (no actual modification without explicit plan)
1067
- const failureRate = this.metrics.failedCycles / Math.max(this.metrics.totalCycles, 1);
1068
- const healingRate = this.metrics.healingSuccesses / Math.max(this.metrics.healingAttempts, 1);
1069
- const statusReport = [
1070
- `System Status:`,
1071
- `- Total cycles: ${this.metrics.totalCycles}`,
1072
- `- Failure rate: ${(failureRate * 100).toFixed(1)}%`,
1073
- `- Healing success rate: ${(healingRate * 100).toFixed(1)}%`,
1074
- `- Avg cycle time: ${this.metrics.avgCycleTime.toFixed(0)}ms`,
1075
- `- Memory reuse: ${(this.metrics.memoryReuseRate * 100).toFixed(1)}%`,
1076
- `- Checkpoint: ${checkpointHash || 'none'}`,
1077
- ``,
1078
- `Note: Automatic self-modification requires explicit ModificationPlan.`,
1079
- `Use DarwinGodelEngine.validatePlan() and apply() for safe modifications.`,
1080
- ].join('\n');
1133
+ // Import action executor dynamically to avoid circular deps
1134
+ const { executeAction } = await import('../active-inference/actions.js');
1135
+ // Check consciousness level first
1136
+ const phi = this.phiMonitor?.getCurrentLevel().phi ?? 0;
1137
+ if (phi < 0.3) {
1138
+ return {
1139
+ goto: 'done',
1140
+ update: {
1141
+ response: `[Self-modification blocked: consciousness level φ=${phi.toFixed(3)} < 0.3 required]`,
1142
+ },
1143
+ reason: 'self_modify_phi_too_low',
1144
+ };
1145
+ }
1146
+ // Default beliefs for Active Inference context
1147
+ const defaultBeliefs = { viability: 0.5, worldState: 0.5, coupling: 0.5, goalProgress: 0.5 };
1148
+ // Execute the appropriate action
1149
+ let result;
1150
+ if (isExplicitModify) {
1151
+ // Direct modification - extract target metric if specified
1152
+ const metricMatch = queryLower.match(/(?:metric|metrica)[:\s]+(\w+)/);
1153
+ const targetMetric = metricMatch ? metricMatch[1] : undefined;
1154
+ result = await executeAction('self.modify', {
1155
+ parameters: targetMetric ? { targetMetric } : {},
1156
+ beliefs: defaultBeliefs,
1157
+ });
1158
+ }
1159
+ else {
1160
+ // Improvement discovery
1161
+ const autoApply = queryLower.includes('auto') || queryLower.includes('applica');
1162
+ result = await executeAction('improve.self', {
1163
+ parameters: { autoApply },
1164
+ beliefs: defaultBeliefs,
1165
+ });
1166
+ }
1167
+ // Format response based on result
1168
+ let response;
1169
+ if (result.success) {
1170
+ if (result.data?.message) {
1171
+ response = result.data.message;
1172
+ }
1173
+ else if (result.data?.opportunities) {
1174
+ response = [
1175
+ `Found ${result.data.opportunities.length} improvement opportunities:`,
1176
+ ...result.data.opportunities.slice(0, 5).map((o, i) => `${i + 1}. [${o.category}] ${o.metric}: ${o.description} (priority: ${o.priority})`),
1177
+ result.data.hint || '',
1178
+ ].join('\n');
1179
+ }
1180
+ else if (result.data?.applied) {
1181
+ response = `Applied ${result.data.improvements?.length || 0} improvements.`;
1182
+ }
1183
+ else {
1184
+ response = `Self-modification completed: ${JSON.stringify(result.data)}`;
1185
+ }
1186
+ }
1187
+ else {
1188
+ response = `Self-modification failed: ${result.error}`;
1189
+ }
1081
1190
  return {
1082
1191
  goto: 'done',
1083
- update: {
1084
- response: statusReport,
1085
- },
1086
- reason: 'self_modify_status_report',
1192
+ update: { response },
1193
+ reason: result.success ? 'self_modify_success' : 'self_modify_failed',
1087
1194
  };
1088
1195
  }
1089
1196
  catch (error) {
@@ -11,4 +11,5 @@
11
11
  */
12
12
  export { DarwinGodelEngine, getDarwinGodelEngine, resetDarwinGodelEngine, Modification, ModificationPlan, VerificationResult, ApplyResult, DarwinGodelConfig, } from './darwin-godel.js';
13
13
  export { SelfImprovementEngine, getSelfImprovementEngine, resetSelfImprovementEngine, createSelfImprovementEngine, SystemMetrics, ImprovementOpportunity, ImprovementResult, SelfImprovementConfig, DEFAULT_IMPROVEMENT_CONFIG, } from './self-improvement.js';
14
+ export { SelfModelGenerator, getSelfModelGenerator, generateSelfModel, saveSelfModel, SelfModel, ModuleInfo, MetricInfo, PatternInfo, } from './self-model.js';
14
15
  export { invariantRegistry, InvariantRegistry, InvariantContext, InvariantResult, InvariantDefinition, InvariantChecker, } from '../kernel/invariants.js';
@@ -11,7 +11,7 @@
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.DEFAULT_IMPROVEMENT_CONFIG = exports.createSelfImprovementEngine = exports.resetSelfImprovementEngine = exports.getSelfImprovementEngine = exports.SelfImprovementEngine = exports.resetDarwinGodelEngine = exports.getDarwinGodelEngine = exports.DarwinGodelEngine = void 0;
14
+ exports.InvariantRegistry = exports.invariantRegistry = exports.saveSelfModel = exports.generateSelfModel = exports.getSelfModelGenerator = exports.SelfModelGenerator = 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; } });
@@ -23,6 +23,12 @@ Object.defineProperty(exports, "getSelfImprovementEngine", { enumerable: true, g
23
23
  Object.defineProperty(exports, "resetSelfImprovementEngine", { enumerable: true, get: function () { return self_improvement_js_1.resetSelfImprovementEngine; } });
24
24
  Object.defineProperty(exports, "createSelfImprovementEngine", { enumerable: true, get: function () { return self_improvement_js_1.createSelfImprovementEngine; } });
25
25
  Object.defineProperty(exports, "DEFAULT_IMPROVEMENT_CONFIG", { enumerable: true, get: function () { return self_improvement_js_1.DEFAULT_IMPROVEMENT_CONFIG; } });
26
+ // v8.4: Self-Model Generator
27
+ var self_model_js_1 = require("./self-model.js");
28
+ Object.defineProperty(exports, "SelfModelGenerator", { enumerable: true, get: function () { return self_model_js_1.SelfModelGenerator; } });
29
+ Object.defineProperty(exports, "getSelfModelGenerator", { enumerable: true, get: function () { return self_model_js_1.getSelfModelGenerator; } });
30
+ Object.defineProperty(exports, "generateSelfModel", { enumerable: true, get: function () { return self_model_js_1.generateSelfModel; } });
31
+ Object.defineProperty(exports, "saveSelfModel", { enumerable: true, get: function () { return self_model_js_1.saveSelfModel; } });
26
32
  // Re-export invariant types for convenience
27
33
  var invariants_js_1 = require("../kernel/invariants.js");
28
34
  Object.defineProperty(exports, "invariantRegistry", { enumerable: true, get: function () { return invariants_js_1.invariantRegistry; } });
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Self-Model Generator
3
+ *
4
+ * Generates a machine-readable representation of Genesis's own architecture.
5
+ * This enables the system to understand, reason about, and modify itself.
6
+ *
7
+ * Key capabilities:
8
+ * - Introspects module structure
9
+ * - Maps dependencies and interfaces
10
+ * - Tracks metrics and state
11
+ * - Identifies modification points
12
+ *
13
+ * @module self-modification/self-model
14
+ */
15
+ export interface ModuleInfo {
16
+ name: string;
17
+ path: string;
18
+ exports: string[];
19
+ dependencies: string[];
20
+ description: string;
21
+ modifiable: boolean;
22
+ tcbProtected: boolean;
23
+ }
24
+ export interface MetricInfo {
25
+ name: string;
26
+ current: number;
27
+ target?: number;
28
+ trend: 'improving' | 'stable' | 'degrading' | 'unknown';
29
+ }
30
+ export interface PatternInfo {
31
+ name: string;
32
+ description: string;
33
+ files: string[];
34
+ purpose: string;
35
+ }
36
+ export interface SelfModel {
37
+ version: string;
38
+ generatedAt: string;
39
+ architecture: {
40
+ layers: string[];
41
+ modules: ModuleInfo[];
42
+ patterns: PatternInfo[];
43
+ };
44
+ metrics: MetricInfo[];
45
+ modificationPoints: {
46
+ safe: string[];
47
+ restricted: string[];
48
+ forbidden: string[];
49
+ };
50
+ capabilities: string[];
51
+ limitations: string[];
52
+ }
53
+ export declare class SelfModelGenerator {
54
+ private basePath;
55
+ constructor(basePath?: string);
56
+ /**
57
+ * Generate the complete self-model
58
+ */
59
+ generate(): Promise<SelfModel>;
60
+ /**
61
+ * Introspect modules and their exports
62
+ */
63
+ private introspectModules;
64
+ /**
65
+ * Get exports from a module
66
+ */
67
+ private getModuleExports;
68
+ /**
69
+ * Gather current system metrics
70
+ */
71
+ private gatherMetrics;
72
+ /**
73
+ * Classify modification points by safety level
74
+ */
75
+ private classifyModificationPoints;
76
+ /**
77
+ * List system capabilities
78
+ */
79
+ private listCapabilities;
80
+ /**
81
+ * List known limitations
82
+ */
83
+ private listLimitations;
84
+ /**
85
+ * Get current version from package.json
86
+ */
87
+ private getVersion;
88
+ /**
89
+ * Generate markdown representation
90
+ */
91
+ generateMarkdown(): Promise<string>;
92
+ /**
93
+ * Save self-model to file
94
+ */
95
+ save(outputPath?: string): Promise<void>;
96
+ }
97
+ export declare function getSelfModelGenerator(): SelfModelGenerator;
98
+ export declare function generateSelfModel(): Promise<SelfModel>;
99
+ export declare function saveSelfModel(outputPath?: string): Promise<void>;
@@ -0,0 +1,513 @@
1
+ "use strict";
2
+ /**
3
+ * Self-Model Generator
4
+ *
5
+ * Generates a machine-readable representation of Genesis's own architecture.
6
+ * This enables the system to understand, reason about, and modify itself.
7
+ *
8
+ * Key capabilities:
9
+ * - Introspects module structure
10
+ * - Maps dependencies and interfaces
11
+ * - Tracks metrics and state
12
+ * - Identifies modification points
13
+ *
14
+ * @module self-modification/self-model
15
+ */
16
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
17
+ if (k2 === undefined) k2 = k;
18
+ var desc = Object.getOwnPropertyDescriptor(m, k);
19
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
20
+ desc = { enumerable: true, get: function() { return m[k]; } };
21
+ }
22
+ Object.defineProperty(o, k2, desc);
23
+ }) : (function(o, m, k, k2) {
24
+ if (k2 === undefined) k2 = k;
25
+ o[k2] = m[k];
26
+ }));
27
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
28
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
29
+ }) : function(o, v) {
30
+ o["default"] = v;
31
+ });
32
+ var __importStar = (this && this.__importStar) || (function () {
33
+ var ownKeys = function(o) {
34
+ ownKeys = Object.getOwnPropertyNames || function (o) {
35
+ var ar = [];
36
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
37
+ return ar;
38
+ };
39
+ return ownKeys(o);
40
+ };
41
+ return function (mod) {
42
+ if (mod && mod.__esModule) return mod;
43
+ var result = {};
44
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
45
+ __setModuleDefault(result, mod);
46
+ return result;
47
+ };
48
+ })();
49
+ Object.defineProperty(exports, "__esModule", { value: true });
50
+ exports.SelfModelGenerator = void 0;
51
+ exports.getSelfModelGenerator = getSelfModelGenerator;
52
+ exports.generateSelfModel = generateSelfModel;
53
+ exports.saveSelfModel = saveSelfModel;
54
+ const fs = __importStar(require("fs"));
55
+ const path = __importStar(require("path"));
56
+ // ============================================================================
57
+ // Module Registry (Static Knowledge)
58
+ // ============================================================================
59
+ const MODULE_REGISTRY = [
60
+ // Core Layer (TCB Protected)
61
+ {
62
+ name: 'kernel',
63
+ path: 'src/kernel',
64
+ dependencies: [],
65
+ description: 'Immutable safety kernel - validates all modifications',
66
+ modifiable: false,
67
+ tcbProtected: true,
68
+ },
69
+ {
70
+ name: 'governance',
71
+ path: 'src/governance',
72
+ dependencies: ['kernel'],
73
+ description: 'Constitutional constraints and ethical boundaries',
74
+ modifiable: false,
75
+ tcbProtected: true,
76
+ },
77
+ // Consciousness Layer
78
+ {
79
+ name: 'consciousness',
80
+ path: 'src/consciousness',
81
+ dependencies: ['kernel'],
82
+ description: 'Phi calculation, global workspace, attention schema',
83
+ modifiable: true,
84
+ tcbProtected: false,
85
+ },
86
+ {
87
+ name: 'phi-monitor',
88
+ path: 'src/consciousness/phi-monitor.ts',
89
+ dependencies: ['consciousness'],
90
+ description: 'Real-time consciousness level monitoring',
91
+ modifiable: true,
92
+ tcbProtected: false,
93
+ },
94
+ // Memory Layer
95
+ {
96
+ name: 'memory',
97
+ path: 'src/memory',
98
+ dependencies: ['kernel'],
99
+ description: 'Episodic, semantic, procedural memory systems',
100
+ modifiable: true,
101
+ tcbProtected: false,
102
+ },
103
+ {
104
+ name: 'cognitive-workspace',
105
+ path: 'src/memory/cognitive-workspace.ts',
106
+ dependencies: ['memory', 'consciousness'],
107
+ description: 'Working memory for active reasoning',
108
+ modifiable: true,
109
+ tcbProtected: false,
110
+ },
111
+ // World Model Layer
112
+ {
113
+ name: 'world-model',
114
+ path: 'src/world-model',
115
+ dependencies: ['memory'],
116
+ description: 'Latent state encoding, prediction, digital twins',
117
+ modifiable: true,
118
+ tcbProtected: false,
119
+ },
120
+ // Active Inference Layer
121
+ {
122
+ name: 'active-inference',
123
+ path: 'src/active-inference',
124
+ dependencies: ['world-model', 'consciousness'],
125
+ description: 'Free energy minimization, action selection',
126
+ modifiable: true,
127
+ tcbProtected: false,
128
+ },
129
+ // Self-Modification Layer
130
+ {
131
+ name: 'darwin-godel',
132
+ path: 'src/self-modification/darwin-godel.ts',
133
+ dependencies: ['kernel', 'governance'],
134
+ description: 'Safe self-modification via TCB pattern',
135
+ modifiable: false,
136
+ tcbProtected: true,
137
+ },
138
+ {
139
+ name: 'self-improvement',
140
+ path: 'src/self-modification/self-improvement.ts',
141
+ dependencies: ['darwin-godel', 'active-inference'],
142
+ description: 'Autonomous improvement discovery and application',
143
+ modifiable: true,
144
+ tcbProtected: false,
145
+ },
146
+ // Integration Layer
147
+ {
148
+ name: 'brain',
149
+ path: 'src/brain',
150
+ dependencies: ['consciousness', 'memory', 'active-inference', 'world-model'],
151
+ description: 'Cognitive integration and command routing',
152
+ modifiable: true,
153
+ tcbProtected: false,
154
+ },
155
+ // Grounding Layer
156
+ {
157
+ name: 'grounding',
158
+ path: 'src/grounding',
159
+ dependencies: ['kernel'],
160
+ description: 'Truth verification via science, wisdom, tradition',
161
+ modifiable: true,
162
+ tcbProtected: false,
163
+ },
164
+ // Execution Layer
165
+ {
166
+ name: 'execution',
167
+ path: 'src/execution',
168
+ dependencies: ['brain', 'grounding'],
169
+ description: 'Tool execution, shell integration',
170
+ modifiable: true,
171
+ tcbProtected: false,
172
+ },
173
+ // LLM Layer
174
+ {
175
+ name: 'llm',
176
+ path: 'src/llm',
177
+ dependencies: [],
178
+ description: 'Multi-provider LLM routing and cost optimization',
179
+ modifiable: true,
180
+ tcbProtected: false,
181
+ },
182
+ // MCP Layer
183
+ {
184
+ name: 'mcp',
185
+ path: 'src/mcp',
186
+ dependencies: ['llm'],
187
+ description: 'Model Context Protocol client and tool integration',
188
+ modifiable: true,
189
+ tcbProtected: false,
190
+ },
191
+ ];
192
+ const ARCHITECTURAL_PATTERNS = [
193
+ {
194
+ name: 'TCB (Trusted Computing Base)',
195
+ description: 'Immutable safety kernel that cannot modify itself',
196
+ files: ['src/kernel/index.ts', 'src/kernel/invariants.ts'],
197
+ purpose: 'Ensures safety constraints survive self-modification',
198
+ },
199
+ {
200
+ name: 'Phi-Gated Operations',
201
+ description: 'Critical operations require sufficient consciousness level (φ ≥ 0.3)',
202
+ files: ['src/consciousness/phi-monitor.ts', 'src/active-inference/actions.ts'],
203
+ purpose: 'Prevents modifications during low-awareness states',
204
+ },
205
+ {
206
+ name: 'Free Energy Minimization',
207
+ description: 'Action selection via Active Inference and expected free energy',
208
+ files: ['src/active-inference/core.ts', 'src/active-inference/deep-aif.ts'],
209
+ purpose: 'Principled decision-making under uncertainty',
210
+ },
211
+ {
212
+ name: 'Global Workspace',
213
+ description: 'Consciousness broadcast for information integration',
214
+ files: ['src/consciousness/global-workspace.ts'],
215
+ purpose: 'Unified access to distributed cognitive processes',
216
+ },
217
+ {
218
+ name: 'Episodic-Semantic-Procedural Memory',
219
+ description: 'Three-tier memory architecture',
220
+ files: ['src/memory/episodic.ts', 'src/memory/semantic.ts', 'src/memory/procedural.ts'],
221
+ purpose: 'Rich temporal and conceptual memory',
222
+ },
223
+ {
224
+ name: 'Darwin-Gödel Engine',
225
+ description: 'Sandbox → Verify → Apply → Rollback pipeline',
226
+ files: ['src/self-modification/darwin-godel.ts'],
227
+ purpose: 'Safe self-modification with automatic rollback',
228
+ },
229
+ ];
230
+ // ============================================================================
231
+ // Self-Model Generator
232
+ // ============================================================================
233
+ class SelfModelGenerator {
234
+ basePath;
235
+ constructor(basePath = process.cwd()) {
236
+ this.basePath = basePath;
237
+ }
238
+ /**
239
+ * Generate the complete self-model
240
+ */
241
+ async generate() {
242
+ const modules = await this.introspectModules();
243
+ const metrics = await this.gatherMetrics();
244
+ return {
245
+ version: await this.getVersion(),
246
+ generatedAt: new Date().toISOString(),
247
+ architecture: {
248
+ layers: [
249
+ 'Core (TCB Protected)',
250
+ 'Consciousness',
251
+ 'Memory',
252
+ 'World Model',
253
+ 'Active Inference',
254
+ 'Self-Modification',
255
+ 'Integration',
256
+ 'Grounding',
257
+ 'Execution',
258
+ 'LLM',
259
+ 'MCP',
260
+ ],
261
+ modules,
262
+ patterns: ARCHITECTURAL_PATTERNS,
263
+ },
264
+ metrics,
265
+ modificationPoints: this.classifyModificationPoints(modules),
266
+ capabilities: this.listCapabilities(),
267
+ limitations: this.listLimitations(),
268
+ };
269
+ }
270
+ /**
271
+ * Introspect modules and their exports
272
+ */
273
+ async introspectModules() {
274
+ const modules = [];
275
+ for (const reg of MODULE_REGISTRY) {
276
+ const exports = await this.getModuleExports(reg.path);
277
+ modules.push({
278
+ ...reg,
279
+ exports,
280
+ });
281
+ }
282
+ return modules;
283
+ }
284
+ /**
285
+ * Get exports from a module
286
+ */
287
+ async getModuleExports(modulePath) {
288
+ const fullPath = path.join(this.basePath, modulePath);
289
+ const exports = [];
290
+ try {
291
+ // Check if it's a directory or file
292
+ const stat = fs.statSync(fullPath);
293
+ const targetFile = stat.isDirectory()
294
+ ? path.join(fullPath, 'index.ts')
295
+ : fullPath;
296
+ if (fs.existsSync(targetFile)) {
297
+ const content = fs.readFileSync(targetFile, 'utf-8');
298
+ // Extract export declarations
299
+ const exportMatches = content.matchAll(/export\s+(?:async\s+)?(?:function|class|const|let|type|interface|enum)\s+(\w+)/g);
300
+ for (const match of exportMatches) {
301
+ exports.push(match[1]);
302
+ }
303
+ // Extract re-exports
304
+ const reExportMatches = content.matchAll(/export\s+\{\s*([^}]+)\s*\}/g);
305
+ for (const match of reExportMatches) {
306
+ const items = match[1].split(',').map(s => s.trim().split(/\s+as\s+/)[0].trim());
307
+ exports.push(...items.filter(i => i && !i.startsWith('type')));
308
+ }
309
+ }
310
+ }
311
+ catch {
312
+ // Module not found or error reading
313
+ }
314
+ return [...new Set(exports)]; // Deduplicate
315
+ }
316
+ /**
317
+ * Gather current system metrics
318
+ */
319
+ async gatherMetrics() {
320
+ // Try to get real metrics from running system
321
+ try {
322
+ const { getBrain } = await import('../brain/index.js');
323
+ const brain = getBrain();
324
+ const brainMetrics = brain.getMetrics();
325
+ return [
326
+ {
327
+ name: 'avgPhi',
328
+ current: brainMetrics.avgPhi,
329
+ target: 0.5,
330
+ trend: brainMetrics.avgPhi > 0.3 ? 'stable' : 'degrading',
331
+ },
332
+ {
333
+ name: 'memoryReuseRate',
334
+ current: brainMetrics.memoryReuseRate,
335
+ target: 0.7,
336
+ trend: 'unknown',
337
+ },
338
+ {
339
+ name: 'totalCycles',
340
+ current: brainMetrics.totalCycles,
341
+ trend: 'improving',
342
+ },
343
+ {
344
+ name: 'successRate',
345
+ current: brainMetrics.totalCycles > 0
346
+ ? brainMetrics.successfulCycles / brainMetrics.totalCycles
347
+ : 1.0,
348
+ target: 0.95,
349
+ trend: 'stable',
350
+ },
351
+ ];
352
+ }
353
+ catch {
354
+ // Brain not available, return defaults
355
+ return [
356
+ { name: 'avgPhi', current: 0, trend: 'unknown' },
357
+ { name: 'memoryReuseRate', current: 0, trend: 'unknown' },
358
+ { name: 'totalCycles', current: 0, trend: 'unknown' },
359
+ { name: 'successRate', current: 0, trend: 'unknown' },
360
+ ];
361
+ }
362
+ }
363
+ /**
364
+ * Classify modification points by safety level
365
+ */
366
+ classifyModificationPoints(modules) {
367
+ const safe = [];
368
+ const restricted = [];
369
+ const forbidden = [];
370
+ for (const mod of modules) {
371
+ if (mod.tcbProtected) {
372
+ forbidden.push(mod.path);
373
+ }
374
+ else if (!mod.modifiable) {
375
+ restricted.push(mod.path);
376
+ }
377
+ else {
378
+ safe.push(mod.path);
379
+ }
380
+ }
381
+ return { safe, restricted, forbidden };
382
+ }
383
+ /**
384
+ * List system capabilities
385
+ */
386
+ listCapabilities() {
387
+ return [
388
+ 'Multi-provider LLM routing (Anthropic, OpenAI, Google, Ollama, X.AI)',
389
+ 'MCP tool integration',
390
+ 'Episodic/semantic/procedural memory',
391
+ 'Active Inference action selection',
392
+ 'Phi-gated self-modification',
393
+ 'Darwin-Gödel safe modification pipeline',
394
+ 'Global workspace consciousness integration',
395
+ 'Epistemic grounding (science, wisdom, tradition)',
396
+ 'Autonomous improvement discovery',
397
+ 'Digital twin simulation',
398
+ ];
399
+ }
400
+ /**
401
+ * List known limitations
402
+ */
403
+ listLimitations() {
404
+ return [
405
+ 'Cannot modify TCB (kernel, governance) - by design',
406
+ 'Self-modification requires φ ≥ 0.3',
407
+ 'No direct hardware access',
408
+ 'Dependent on external LLM providers',
409
+ 'Memory limited by embedding model capacity',
410
+ 'Cannot violate constitutional constraints',
411
+ ];
412
+ }
413
+ /**
414
+ * Get current version from package.json
415
+ */
416
+ async getVersion() {
417
+ try {
418
+ const pkgPath = path.join(this.basePath, 'package.json');
419
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
420
+ return pkg.version || 'unknown';
421
+ }
422
+ catch {
423
+ return 'unknown';
424
+ }
425
+ }
426
+ /**
427
+ * Generate markdown representation
428
+ */
429
+ async generateMarkdown() {
430
+ const model = await this.generate();
431
+ let md = `# Genesis Self-Model
432
+
433
+ > Auto-generated: ${model.generatedAt}
434
+ > Version: ${model.version}
435
+
436
+ ## Architecture Layers
437
+
438
+ ${model.architecture.layers.map((l, i) => `${i + 1}. ${l}`).join('\n')}
439
+
440
+ ## Modules
441
+
442
+ | Module | Path | TCB | Modifiable | Exports |
443
+ |--------|------|-----|------------|---------|
444
+ ${model.architecture.modules.map(m => `| ${m.name} | \`${m.path}\` | ${m.tcbProtected ? '✓' : ''} | ${m.modifiable ? '✓' : ''} | ${m.exports.slice(0, 3).join(', ')}${m.exports.length > 3 ? '...' : ''} |`).join('\n')}
445
+
446
+ ## Architectural Patterns
447
+
448
+ ${model.architecture.patterns.map(p => `### ${p.name}
449
+
450
+ ${p.description}
451
+
452
+ **Purpose:** ${p.purpose}
453
+
454
+ **Files:** ${p.files.map(f => `\`${f}\``).join(', ')}
455
+ `).join('\n')}
456
+
457
+ ## Current Metrics
458
+
459
+ | Metric | Current | Target | Trend |
460
+ |--------|---------|--------|-------|
461
+ ${model.metrics.map(m => `| ${m.name} | ${typeof m.current === 'number' ? m.current.toFixed(3) : m.current} | ${m.target?.toFixed(3) || '-'} | ${m.trend} |`).join('\n')}
462
+
463
+ ## Modification Points
464
+
465
+ ### Safe (can modify freely)
466
+ ${model.modificationPoints.safe.map(p => `- \`${p}\``).join('\n')}
467
+
468
+ ### Restricted (requires approval)
469
+ ${model.modificationPoints.restricted.map(p => `- \`${p}\``).join('\n') || '- None'}
470
+
471
+ ### Forbidden (TCB protected)
472
+ ${model.modificationPoints.forbidden.map(p => `- \`${p}\``).join('\n')}
473
+
474
+ ## Capabilities
475
+
476
+ ${model.capabilities.map(c => `- ${c}`).join('\n')}
477
+
478
+ ## Limitations
479
+
480
+ ${model.limitations.map(l => `- ${l}`).join('\n')}
481
+
482
+ ---
483
+ *This file is auto-generated by \`src/self-modification/self-model.ts\`*
484
+ `;
485
+ return md;
486
+ }
487
+ /**
488
+ * Save self-model to file
489
+ */
490
+ async save(outputPath = 'SELF-MODEL.md') {
491
+ const markdown = await this.generateMarkdown();
492
+ const fullPath = path.join(this.basePath, outputPath);
493
+ fs.writeFileSync(fullPath, markdown, 'utf-8');
494
+ console.log(`[self-model] Saved to ${fullPath}`);
495
+ }
496
+ }
497
+ exports.SelfModelGenerator = SelfModelGenerator;
498
+ // ============================================================================
499
+ // Singleton Access
500
+ // ============================================================================
501
+ let generatorInstance = null;
502
+ function getSelfModelGenerator() {
503
+ if (!generatorInstance) {
504
+ generatorInstance = new SelfModelGenerator();
505
+ }
506
+ return generatorInstance;
507
+ }
508
+ async function generateSelfModel() {
509
+ return getSelfModelGenerator().generate();
510
+ }
511
+ async function saveSelfModel(outputPath) {
512
+ return getSelfModelGenerator().save(outputPath);
513
+ }
@@ -123,18 +123,24 @@ const node_assert_1 = __importDefault(require("node:assert"));
123
123
  });
124
124
  });
125
125
  (0, node_test_1.describe)('Brain Metrics', () => {
126
- (0, node_test_1.test)('initial metrics are zeroed', async () => {
126
+ (0, node_test_1.test)('metrics have correct structure and types', async () => {
127
127
  const { createBrain } = await import('../src/brain/index.js');
128
128
  const brain = createBrain();
129
129
  const metrics = brain.getMetrics();
130
- node_assert_1.default.strictEqual(metrics.totalCycles, 0);
131
- node_assert_1.default.strictEqual(metrics.successfulCycles, 0);
132
- node_assert_1.default.strictEqual(metrics.failedCycles, 0);
133
- node_assert_1.default.strictEqual(metrics.memoryRecalls, 0);
134
- node_assert_1.default.strictEqual(metrics.groundingChecks, 0);
135
- node_assert_1.default.strictEqual(metrics.toolExecutions, 0);
136
- node_assert_1.default.strictEqual(metrics.healingAttempts, 0);
137
- node_assert_1.default.strictEqual(metrics.broadcasts, 0);
130
+ // Note: Due to v8.1 state persistence, metrics may carry over from previous runs
131
+ // We verify the metrics structure and types rather than exact values
132
+ node_assert_1.default.ok(typeof metrics.totalCycles === 'number', 'totalCycles should be a number');
133
+ node_assert_1.default.ok(typeof metrics.successfulCycles === 'number', 'successfulCycles should be a number');
134
+ node_assert_1.default.ok(typeof metrics.failedCycles === 'number', 'failedCycles should be a number');
135
+ node_assert_1.default.ok(typeof metrics.memoryRecalls === 'number', 'memoryRecalls should be a number');
136
+ node_assert_1.default.ok(typeof metrics.groundingChecks === 'number', 'groundingChecks should be a number');
137
+ node_assert_1.default.ok(typeof metrics.toolExecutions === 'number', 'toolExecutions should be a number');
138
+ node_assert_1.default.ok(typeof metrics.healingAttempts === 'number', 'healingAttempts should be a number');
139
+ node_assert_1.default.ok(typeof metrics.broadcasts === 'number', 'broadcasts should be a number');
140
+ // Verify metrics are non-negative
141
+ node_assert_1.default.ok(metrics.totalCycles >= 0, 'totalCycles should be >= 0');
142
+ node_assert_1.default.ok(metrics.successfulCycles >= 0, 'successfulCycles should be >= 0');
143
+ node_assert_1.default.ok(metrics.failedCycles >= 0, 'failedCycles should be >= 0');
138
144
  });
139
145
  (0, node_test_1.test)('metrics track avgPhi', async () => {
140
146
  const { createBrain } = await import('../src/brain/index.js');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "genesis-ai-cli",
3
- "version": "8.2.0",
3
+ "version": "8.4.0",
4
4
  "description": "Fully Autonomous AI System - Self-funding, Self-deploying, Production Memory, A2A Protocol & Governance",
5
5
  "main": "dist/src/index.js",
6
6
  "types": "dist/src/index.d.ts",