genesis-ai-cli 13.0.0 → 13.1.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/.genesis/code-index/code-index.json +12 -0
- package/dist/.genesis/code-index/embeddings-nomic-embed-text.json +1 -0
- package/dist/.genesis/code-index/metadata.json +1 -0
- package/dist/.genesis/code-index/vectors.json +1 -0
- package/dist/src/brain/index.d.ts +7 -0
- package/dist/src/brain/index.js +27 -1
- package/dist/src/brain/self-knowledge.d.ts +84 -0
- package/dist/src/brain/self-knowledge.js +238 -0
- package/dist/src/cli/chat.js +47 -0
- package/dist/src/genesis.d.ts +177 -0
- package/dist/src/genesis.js +452 -0
- package/dist/src/index.js +21 -0
- package/package.json +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":"9.0.0","model":"nomic-embed-text","dimensions":768,"count":0,"vectors":{}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":"9.0.0","count":0,"items":{}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":"9.0.0","model":"nomic-embed-text","count":0,"vectors":{}}
|
|
@@ -38,6 +38,7 @@
|
|
|
38
38
|
* ```
|
|
39
39
|
*/
|
|
40
40
|
import { BrainState, BrainConfig, BrainMetrics, BrainEventHandler } from './types.js';
|
|
41
|
+
import { SelfKnowledge } from './self-knowledge.js';
|
|
41
42
|
import { UnifiedMemoryQuery } from '../memory/unified-query.js';
|
|
42
43
|
export declare class Brain {
|
|
43
44
|
private config;
|
|
@@ -56,6 +57,7 @@ export declare class Brain {
|
|
|
56
57
|
private darwinGodel;
|
|
57
58
|
private metacognition;
|
|
58
59
|
private fek;
|
|
60
|
+
private selfKnowledge;
|
|
59
61
|
private persistence;
|
|
60
62
|
private unifiedQuery;
|
|
61
63
|
private toolCache;
|
|
@@ -335,6 +337,10 @@ export declare class Brain {
|
|
|
335
337
|
* Reset metrics
|
|
336
338
|
*/
|
|
337
339
|
resetMetrics(): void;
|
|
340
|
+
/**
|
|
341
|
+
* v13.1: Get self-knowledge module for code queries
|
|
342
|
+
*/
|
|
343
|
+
getSelfKnowledge(): SelfKnowledge;
|
|
338
344
|
/**
|
|
339
345
|
* v10.4.2: Get unified memory query for cross-store searches
|
|
340
346
|
*/
|
|
@@ -409,3 +415,4 @@ export declare function resetBrain(): void;
|
|
|
409
415
|
export declare function getBrainInstance(): Brain | null;
|
|
410
416
|
export * from './types.js';
|
|
411
417
|
export * from './trace.js';
|
|
418
|
+
export { SelfKnowledge, getSelfKnowledge, isCodeQuery } from './self-knowledge.js';
|
package/dist/src/brain/index.js
CHANGED
|
@@ -53,7 +53,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
53
53
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
54
54
|
};
|
|
55
55
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
56
|
-
exports.Brain = void 0;
|
|
56
|
+
exports.isCodeQuery = exports.getSelfKnowledge = exports.SelfKnowledge = exports.Brain = void 0;
|
|
57
57
|
exports.createBrain = createBrain;
|
|
58
58
|
exports.getBrain = getBrain;
|
|
59
59
|
exports.resetBrain = resetBrain;
|
|
@@ -83,6 +83,8 @@ const strategy_executor_js_1 = require("../reasoning/strategy-executor.js");
|
|
|
83
83
|
const free_energy_kernel_js_1 = require("../kernel/free-energy-kernel.js");
|
|
84
84
|
// v8.1: Brain State Persistence
|
|
85
85
|
const persistence_js_1 = require("./persistence.js");
|
|
86
|
+
// v13.1: Self-Knowledge — code-aware context
|
|
87
|
+
const self_knowledge_js_1 = require("./self-knowledge.js");
|
|
86
88
|
// v10.4.2: Unified Memory Query
|
|
87
89
|
const unified_query_js_1 = require("../memory/unified-query.js");
|
|
88
90
|
const index_js_10 = require("../memory/index.js");
|
|
@@ -110,6 +112,8 @@ class Brain {
|
|
|
110
112
|
metacognition = null;
|
|
111
113
|
// v12.0: Free Energy Kernel
|
|
112
114
|
fek = null;
|
|
115
|
+
// v13.1: Self-Knowledge (code awareness)
|
|
116
|
+
selfKnowledge;
|
|
113
117
|
// v8.1: State Persistence
|
|
114
118
|
persistence;
|
|
115
119
|
// v10.4.2: Unified Memory Query
|
|
@@ -165,6 +169,8 @@ class Brain {
|
|
|
165
169
|
// v8.1: Initialize state persistence and load persisted metrics
|
|
166
170
|
this.persistence = (0, persistence_js_1.getBrainStatePersistence)();
|
|
167
171
|
this.metrics = { ...this.metrics, ...this.persistence.getMetrics() };
|
|
172
|
+
// v13.1: Self-Knowledge — code awareness (keyword search, no API)
|
|
173
|
+
this.selfKnowledge = (0, self_knowledge_js_1.getSelfKnowledge)();
|
|
168
174
|
// v7.13: Initialize full module integration (lazy - on first use)
|
|
169
175
|
this.initializeV713Modules();
|
|
170
176
|
}
|
|
@@ -737,6 +743,8 @@ class Brain {
|
|
|
737
743
|
this.running = true;
|
|
738
744
|
// v7.2: Build system prompt with available tools
|
|
739
745
|
await this.initializeSystemPrompt();
|
|
746
|
+
// v13.1: Boot self-knowledge (index own source code)
|
|
747
|
+
this.selfKnowledge.boot().catch(() => { });
|
|
740
748
|
// Start consciousness monitoring
|
|
741
749
|
if (this.config.consciousness.enabled) {
|
|
742
750
|
this.phiMonitor.start();
|
|
@@ -1123,6 +1131,14 @@ class Brain {
|
|
|
1123
1131
|
}
|
|
1124
1132
|
// Build context from working memory
|
|
1125
1133
|
const context = this.buildContext(state);
|
|
1134
|
+
// v13.1: Inject self-knowledge if query is about own code/architecture
|
|
1135
|
+
if (this.selfKnowledge.isReady() && (0, self_knowledge_js_1.isCodeQuery)(state.query)) {
|
|
1136
|
+
const codeContext = this.selfKnowledge.getContext(state.query);
|
|
1137
|
+
if (codeContext) {
|
|
1138
|
+
context.formatted = codeContext + '\n' + context.formatted;
|
|
1139
|
+
context.tokenEstimate += Math.ceil(codeContext.length / 4);
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1126
1142
|
// Track metrics
|
|
1127
1143
|
this.metrics.memoryRecalls++;
|
|
1128
1144
|
const wsMetrics = this.workspace.getMetrics();
|
|
@@ -2307,6 +2323,12 @@ class Brain {
|
|
|
2307
2323
|
resetMetrics() {
|
|
2308
2324
|
this.metrics = this.createInitialMetrics();
|
|
2309
2325
|
}
|
|
2326
|
+
/**
|
|
2327
|
+
* v13.1: Get self-knowledge module for code queries
|
|
2328
|
+
*/
|
|
2329
|
+
getSelfKnowledge() {
|
|
2330
|
+
return this.selfKnowledge;
|
|
2331
|
+
}
|
|
2310
2332
|
/**
|
|
2311
2333
|
* v10.4.2: Get unified memory query for cross-store searches
|
|
2312
2334
|
*/
|
|
@@ -2465,3 +2487,7 @@ function getBrainInstance() {
|
|
|
2465
2487
|
// ============================================================================
|
|
2466
2488
|
__exportStar(require("./types.js"), exports);
|
|
2467
2489
|
__exportStar(require("./trace.js"), exports);
|
|
2490
|
+
var self_knowledge_js_2 = require("./self-knowledge.js");
|
|
2491
|
+
Object.defineProperty(exports, "SelfKnowledge", { enumerable: true, get: function () { return self_knowledge_js_2.SelfKnowledge; } });
|
|
2492
|
+
Object.defineProperty(exports, "getSelfKnowledge", { enumerable: true, get: function () { return self_knowledge_js_2.getSelfKnowledge; } });
|
|
2493
|
+
Object.defineProperty(exports, "isCodeQuery", { enumerable: true, get: function () { return self_knowledge_js_2.isCodeQuery; } });
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Genesis v13.1 - Self-Knowledge Module
|
|
3
|
+
*
|
|
4
|
+
* Gives the Brain awareness of its own source code.
|
|
5
|
+
* Uses CodeRAG for keyword-based retrieval (no API keys needed).
|
|
6
|
+
*
|
|
7
|
+
* Architecture:
|
|
8
|
+
* boot() → index src/ → cache to .genesis/code-index.json
|
|
9
|
+
* query(text) → keyword search → relevant CodeChunks
|
|
10
|
+
* getContext(query) → formatted string for Brain context injection
|
|
11
|
+
*
|
|
12
|
+
* The Brain's stepMemory() calls this when the query relates to
|
|
13
|
+
* Genesis's own architecture, code, or capabilities.
|
|
14
|
+
*/
|
|
15
|
+
import { QueryResult } from '../self-modification/code-rag.js';
|
|
16
|
+
import { SelfModel } from '../self-modification/self-model.js';
|
|
17
|
+
export interface SelfKnowledgeConfig {
|
|
18
|
+
rootPath: string;
|
|
19
|
+
maxContextChunks: number;
|
|
20
|
+
maxContextChars: number;
|
|
21
|
+
autoIndex: boolean;
|
|
22
|
+
cacheDir: string;
|
|
23
|
+
}
|
|
24
|
+
export interface CodeContext {
|
|
25
|
+
chunks: QueryResult[];
|
|
26
|
+
summary: string;
|
|
27
|
+
formatted: string;
|
|
28
|
+
selfModel?: SelfModel;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Detect if a query is about Genesis's own code/architecture
|
|
32
|
+
*/
|
|
33
|
+
export declare function isCodeQuery(query: string): boolean;
|
|
34
|
+
export declare class SelfKnowledge {
|
|
35
|
+
private config;
|
|
36
|
+
private codeRAG;
|
|
37
|
+
private selfModelGen;
|
|
38
|
+
private indexed;
|
|
39
|
+
private selfModel;
|
|
40
|
+
private bootPromise;
|
|
41
|
+
constructor(config?: Partial<SelfKnowledgeConfig>);
|
|
42
|
+
/**
|
|
43
|
+
* Boot: index the codebase (or load from cache)
|
|
44
|
+
* Called once when brain starts. Non-blocking if already cached.
|
|
45
|
+
*/
|
|
46
|
+
boot(): Promise<void>;
|
|
47
|
+
private _doBoot;
|
|
48
|
+
/**
|
|
49
|
+
* Query the codebase for relevant chunks
|
|
50
|
+
*/
|
|
51
|
+
query(queryText: string, topK?: number): QueryResult[];
|
|
52
|
+
/**
|
|
53
|
+
* Get formatted context string for brain injection
|
|
54
|
+
* Returns empty string if query isn't code-related or index unavailable
|
|
55
|
+
*/
|
|
56
|
+
getContext(query: string): string;
|
|
57
|
+
/**
|
|
58
|
+
* Get full code context with self-model
|
|
59
|
+
*/
|
|
60
|
+
getFullContext(query: string): Promise<CodeContext>;
|
|
61
|
+
/**
|
|
62
|
+
* Get the self-model (architecture overview)
|
|
63
|
+
*/
|
|
64
|
+
getSelfModel(): Promise<SelfModel>;
|
|
65
|
+
/**
|
|
66
|
+
* Get index statistics
|
|
67
|
+
*/
|
|
68
|
+
getStats(): {
|
|
69
|
+
totalFiles: number;
|
|
70
|
+
totalChunks: number;
|
|
71
|
+
totalLines: number;
|
|
72
|
+
byType: Record<string, number>;
|
|
73
|
+
} | null;
|
|
74
|
+
/**
|
|
75
|
+
* Check if indexed
|
|
76
|
+
*/
|
|
77
|
+
isReady(): boolean;
|
|
78
|
+
/**
|
|
79
|
+
* Force re-index
|
|
80
|
+
*/
|
|
81
|
+
reindex(): Promise<void>;
|
|
82
|
+
}
|
|
83
|
+
export declare function getSelfKnowledge(config?: Partial<SelfKnowledgeConfig>): SelfKnowledge;
|
|
84
|
+
export declare function resetSelfKnowledge(): void;
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Genesis v13.1 - Self-Knowledge Module
|
|
4
|
+
*
|
|
5
|
+
* Gives the Brain awareness of its own source code.
|
|
6
|
+
* Uses CodeRAG for keyword-based retrieval (no API keys needed).
|
|
7
|
+
*
|
|
8
|
+
* Architecture:
|
|
9
|
+
* boot() → index src/ → cache to .genesis/code-index.json
|
|
10
|
+
* query(text) → keyword search → relevant CodeChunks
|
|
11
|
+
* getContext(query) → formatted string for Brain context injection
|
|
12
|
+
*
|
|
13
|
+
* The Brain's stepMemory() calls this when the query relates to
|
|
14
|
+
* Genesis's own architecture, code, or capabilities.
|
|
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.SelfKnowledge = void 0;
|
|
51
|
+
exports.isCodeQuery = isCodeQuery;
|
|
52
|
+
exports.getSelfKnowledge = getSelfKnowledge;
|
|
53
|
+
exports.resetSelfKnowledge = resetSelfKnowledge;
|
|
54
|
+
const code_rag_js_1 = require("../self-modification/code-rag.js");
|
|
55
|
+
const self_model_js_1 = require("../self-modification/self-model.js");
|
|
56
|
+
const path = __importStar(require("path"));
|
|
57
|
+
// __dirname at runtime: <project>/dist/src/brain
|
|
58
|
+
// We need: <project>/ (where src/ lives)
|
|
59
|
+
const PROJECT_ROOT = path.resolve(__dirname, '../../../');
|
|
60
|
+
const DEFAULT_CONFIG = {
|
|
61
|
+
rootPath: PROJECT_ROOT,
|
|
62
|
+
maxContextChunks: 8,
|
|
63
|
+
maxContextChars: 3000,
|
|
64
|
+
autoIndex: true,
|
|
65
|
+
cacheDir: '.genesis/code-index',
|
|
66
|
+
};
|
|
67
|
+
// ============================================================================
|
|
68
|
+
// Code-awareness heuristics
|
|
69
|
+
// ============================================================================
|
|
70
|
+
const CODE_QUERY_PATTERNS = [
|
|
71
|
+
// Direct self-reference
|
|
72
|
+
/\b(tuo|tua|tuoi|tue)\s+(codice|sorgente|architettura|kernel|modulo|classe|funzione)/i,
|
|
73
|
+
/\b(your|its)\s+(code|source|architecture|kernel|module|class|function)/i,
|
|
74
|
+
/\b(come|how)\s+(funzion|work|implement)/i,
|
|
75
|
+
/\b(genesis|brain|kernel|fek|fiber|ness|contraction|leapfrog|fisher)\b/i,
|
|
76
|
+
// Architecture questions
|
|
77
|
+
/\b(architettura|architecture|struttura|structure|design)\b/i,
|
|
78
|
+
/\b(moduli|modules|subsystem|layer|componenti|components)\b/i,
|
|
79
|
+
// Self-awareness
|
|
80
|
+
/\b(te\s+stess|yourself|self-knowledge|self-aware|autopoie)/i,
|
|
81
|
+
/\b(cosa\s+(sei|fai|puoi)|what\s+(are you|can you|do you))\b/i,
|
|
82
|
+
// Code inspection
|
|
83
|
+
/\b(src\/|\.ts\b|import|export|class\s+\w|interface\s+\w|function\s+\w)/i,
|
|
84
|
+
/\b(implementa|implement|codice|code|sorgente|source)\b/i,
|
|
85
|
+
];
|
|
86
|
+
/**
|
|
87
|
+
* Detect if a query is about Genesis's own code/architecture
|
|
88
|
+
*/
|
|
89
|
+
function isCodeQuery(query) {
|
|
90
|
+
return CODE_QUERY_PATTERNS.some(p => p.test(query));
|
|
91
|
+
}
|
|
92
|
+
// ============================================================================
|
|
93
|
+
// SelfKnowledge class
|
|
94
|
+
// ============================================================================
|
|
95
|
+
class SelfKnowledge {
|
|
96
|
+
config;
|
|
97
|
+
codeRAG;
|
|
98
|
+
selfModelGen;
|
|
99
|
+
indexed = false;
|
|
100
|
+
selfModel = null;
|
|
101
|
+
bootPromise = null;
|
|
102
|
+
constructor(config) {
|
|
103
|
+
this.config = { ...DEFAULT_CONFIG, ...config };
|
|
104
|
+
const rootPath = this.config.rootPath;
|
|
105
|
+
const srcPath = path.join(rootPath, 'src');
|
|
106
|
+
this.codeRAG = (0, code_rag_js_1.getCodeRAG)({
|
|
107
|
+
rootPath: srcPath,
|
|
108
|
+
useEmbeddings: false, // Keyword-only, no API needed
|
|
109
|
+
cacheEmbeddings: false,
|
|
110
|
+
cachePath: path.join(rootPath, this.config.cacheDir),
|
|
111
|
+
includePatterns: ['**/*.ts'],
|
|
112
|
+
excludePatterns: ['**/node_modules/**', '**/dist/**', '**/*.test.ts', '**/*.d.ts'],
|
|
113
|
+
});
|
|
114
|
+
this.selfModelGen = (0, self_model_js_1.getSelfModelGenerator)();
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Boot: index the codebase (or load from cache)
|
|
118
|
+
* Called once when brain starts. Non-blocking if already cached.
|
|
119
|
+
*/
|
|
120
|
+
async boot() {
|
|
121
|
+
if (this.indexed)
|
|
122
|
+
return;
|
|
123
|
+
if (this.bootPromise)
|
|
124
|
+
return this.bootPromise;
|
|
125
|
+
this.bootPromise = this._doBoot();
|
|
126
|
+
return this.bootPromise;
|
|
127
|
+
}
|
|
128
|
+
async _doBoot() {
|
|
129
|
+
try {
|
|
130
|
+
// Try loading cached index first
|
|
131
|
+
const loaded = await this.codeRAG.loadIndex();
|
|
132
|
+
if (loaded) {
|
|
133
|
+
this.indexed = true;
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
// Build fresh index (keyword-only, fast)
|
|
137
|
+
if (this.config.autoIndex) {
|
|
138
|
+
await this.codeRAG.buildIndex();
|
|
139
|
+
await this.codeRAG.saveIndex();
|
|
140
|
+
this.indexed = true;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
catch (error) {
|
|
144
|
+
// Non-fatal — brain works without self-knowledge
|
|
145
|
+
console.warn(`[SelfKnowledge] Boot failed: ${error instanceof Error ? error.message : error}`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Query the codebase for relevant chunks
|
|
150
|
+
*/
|
|
151
|
+
query(queryText, topK) {
|
|
152
|
+
if (!this.indexed)
|
|
153
|
+
return [];
|
|
154
|
+
return this.codeRAG.query(queryText, topK || this.config.maxContextChunks);
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Get formatted context string for brain injection
|
|
158
|
+
* Returns empty string if query isn't code-related or index unavailable
|
|
159
|
+
*/
|
|
160
|
+
getContext(query) {
|
|
161
|
+
if (!this.indexed)
|
|
162
|
+
return '';
|
|
163
|
+
if (!isCodeQuery(query))
|
|
164
|
+
return '';
|
|
165
|
+
const results = this.query(query);
|
|
166
|
+
if (results.length === 0)
|
|
167
|
+
return '';
|
|
168
|
+
// Format results for context
|
|
169
|
+
let context = '[self-knowledge] Genesis source code relevant to query:\n';
|
|
170
|
+
let chars = context.length;
|
|
171
|
+
for (const result of results) {
|
|
172
|
+
const chunk = result.chunk;
|
|
173
|
+
const entry = ` ${chunk.type} ${chunk.name} (${chunk.relativePath}:${chunk.startLine}):\n` +
|
|
174
|
+
` ${chunk.content.slice(0, 200).replace(/\n/g, '\n ')}\n`;
|
|
175
|
+
if (chars + entry.length > this.config.maxContextChars)
|
|
176
|
+
break;
|
|
177
|
+
context += entry;
|
|
178
|
+
chars += entry.length;
|
|
179
|
+
}
|
|
180
|
+
return context;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Get full code context with self-model
|
|
184
|
+
*/
|
|
185
|
+
async getFullContext(query) {
|
|
186
|
+
if (!this.indexed) {
|
|
187
|
+
await this.boot();
|
|
188
|
+
}
|
|
189
|
+
const chunks = this.query(query);
|
|
190
|
+
const summary = this.codeRAG.getSummary();
|
|
191
|
+
const formatted = this.getContext(query);
|
|
192
|
+
return { chunks, summary, formatted };
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Get the self-model (architecture overview)
|
|
196
|
+
*/
|
|
197
|
+
async getSelfModel() {
|
|
198
|
+
if (!this.selfModel) {
|
|
199
|
+
this.selfModel = await this.selfModelGen.generate();
|
|
200
|
+
}
|
|
201
|
+
return this.selfModel;
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Get index statistics
|
|
205
|
+
*/
|
|
206
|
+
getStats() {
|
|
207
|
+
return this.codeRAG.getStats();
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Check if indexed
|
|
211
|
+
*/
|
|
212
|
+
isReady() {
|
|
213
|
+
return this.indexed;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Force re-index
|
|
217
|
+
*/
|
|
218
|
+
async reindex() {
|
|
219
|
+
this.indexed = false;
|
|
220
|
+
await this.codeRAG.buildIndex();
|
|
221
|
+
await this.codeRAG.saveIndex();
|
|
222
|
+
this.indexed = true;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
exports.SelfKnowledge = SelfKnowledge;
|
|
226
|
+
// ============================================================================
|
|
227
|
+
// Singleton
|
|
228
|
+
// ============================================================================
|
|
229
|
+
let instance = null;
|
|
230
|
+
function getSelfKnowledge(config) {
|
|
231
|
+
if (!instance) {
|
|
232
|
+
instance = new SelfKnowledge(config);
|
|
233
|
+
}
|
|
234
|
+
return instance;
|
|
235
|
+
}
|
|
236
|
+
function resetSelfKnowledge() {
|
|
237
|
+
instance = null;
|
|
238
|
+
}
|
package/dist/src/cli/chat.js
CHANGED
|
@@ -954,6 +954,52 @@ INSTRUCTION: You MUST report this error to the user. Do NOT fabricate or guess w
|
|
|
954
954
|
console.log((0, ui_js_1.error)(`Consolidation error: ${err instanceof Error ? err.message : err}`));
|
|
955
955
|
});
|
|
956
956
|
break;
|
|
957
|
+
// v13.1: Self-knowledge (code awareness)
|
|
958
|
+
case 'code':
|
|
959
|
+
case 'codice': // Italian
|
|
960
|
+
if (args.length > 0) {
|
|
961
|
+
const codeQuery = args.join(' ');
|
|
962
|
+
const sk = this.brain.getSelfKnowledge();
|
|
963
|
+
if (!sk.isReady()) {
|
|
964
|
+
console.log((0, ui_js_1.info)('Indexing source code...'));
|
|
965
|
+
await sk.boot();
|
|
966
|
+
}
|
|
967
|
+
const results = sk.query(codeQuery, 5);
|
|
968
|
+
if (results.length === 0) {
|
|
969
|
+
console.log((0, ui_js_1.warning)(`No code found for: "${codeQuery}"`));
|
|
970
|
+
}
|
|
971
|
+
else {
|
|
972
|
+
console.log((0, ui_js_1.c)(`Code results for "${codeQuery}":`, 'bold'));
|
|
973
|
+
for (const r of results) {
|
|
974
|
+
const chunk = r.chunk;
|
|
975
|
+
console.log(` ${(0, ui_js_1.c)(chunk.type, 'cyan')} ${(0, ui_js_1.c)(chunk.name, 'green')} (${(0, ui_js_1.muted)(chunk.relativePath + ':' + chunk.startLine)})`);
|
|
976
|
+
const preview = chunk.content.split('\n').slice(0, 3).join('\n ');
|
|
977
|
+
console.log(` ${(0, ui_js_1.muted)(preview)}`);
|
|
978
|
+
console.log();
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
else {
|
|
983
|
+
const sk = this.brain.getSelfKnowledge();
|
|
984
|
+
if (!sk.isReady()) {
|
|
985
|
+
console.log((0, ui_js_1.info)('Indexing source code...'));
|
|
986
|
+
await sk.boot();
|
|
987
|
+
}
|
|
988
|
+
const stats = sk.getStats();
|
|
989
|
+
if (stats) {
|
|
990
|
+
console.log((0, ui_js_1.c)('Self-Knowledge Status:', 'bold'));
|
|
991
|
+
console.log(` Files indexed: ${stats.totalFiles}`);
|
|
992
|
+
console.log(` Code chunks: ${stats.totalChunks}`);
|
|
993
|
+
console.log(` Total lines: ${stats.totalLines}`);
|
|
994
|
+
console.log(` Types: ${Object.entries(stats.byType).map(([t, n]) => `${t}:${n}`).join(', ')}`);
|
|
995
|
+
console.log((0, ui_js_1.muted)('\n Usage: /code <query> — search own source code'));
|
|
996
|
+
}
|
|
997
|
+
else {
|
|
998
|
+
console.log((0, ui_js_1.warning)('Self-knowledge not indexed yet.'));
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
console.log();
|
|
1002
|
+
break;
|
|
957
1003
|
// v7.0: Darwin-Gödel self-improvement commands
|
|
958
1004
|
case 'heal':
|
|
959
1005
|
case 'guarisci': // Italian
|
|
@@ -1554,6 +1600,7 @@ INSTRUCTION: You MUST report this error to the user. Do NOT fabricate or guess w
|
|
|
1554
1600
|
console.log();
|
|
1555
1601
|
console.log(` ${(0, ui_js_1.style)('/brain', 'yellow')} Brain integration on/off`);
|
|
1556
1602
|
console.log(` ${(0, ui_js_1.style)('/memory', 'yellow')} Stato memoria`);
|
|
1603
|
+
console.log(` ${(0, ui_js_1.style)('/code', 'yellow')} Cerca nel proprio codice sorgente`);
|
|
1557
1604
|
console.log(` ${(0, ui_js_1.style)('/phi', 'yellow')} Livello coscienza (φ)`);
|
|
1558
1605
|
console.log(` ${(0, ui_js_1.style)('/improve', 'yellow')} Auto-miglioramento`);
|
|
1559
1606
|
console.log(` ${(0, ui_js_1.style)('/task', 'yellow')} Esegui subagent`);
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Genesis v13.0 — Unified Bootstrap Layer
|
|
3
|
+
*
|
|
4
|
+
* Hierarchical boot (L1→L4), inter-module wiring, and unified process/query interface.
|
|
5
|
+
* Connects all 49 modules into a coherent organism:
|
|
6
|
+
*
|
|
7
|
+
* L1: Persistence, FEK (autonomic substrate)
|
|
8
|
+
* L2: Memory, Active Inference, Kernel, Economic Fiber
|
|
9
|
+
* L3: Brain, Causal Reasoning, Perception
|
|
10
|
+
* L4: Metacognition (MUSE), NESS Monitor, Darwin-Gödel
|
|
11
|
+
*
|
|
12
|
+
* Each level boots only after its predecessor is healthy.
|
|
13
|
+
*/
|
|
14
|
+
import { type FEKState, type FEKStatus } from './kernel/free-energy-kernel.js';
|
|
15
|
+
import { type Effect, type CounterfactualResult, type Intervention, type CausalExplanation } from './causal/index.js';
|
|
16
|
+
import { type ConfidenceEstimate, type ThoughtAudit } from './metacognition/index.js';
|
|
17
|
+
import { type EconomicFiber } from './economy/fiber.js';
|
|
18
|
+
import { type NESSState } from './economy/ness.js';
|
|
19
|
+
import { type ModalityInput, type PerceptionOutput } from './perception/multi-modal.js';
|
|
20
|
+
import { type CurriculumState } from './learning/meta-rl.js';
|
|
21
|
+
import { type CodeRuntime } from './execution/index.js';
|
|
22
|
+
export interface GenesisConfig {
|
|
23
|
+
/** Budget per FEK level (total = sum) */
|
|
24
|
+
totalBudget: number;
|
|
25
|
+
/** Enable causal reasoning */
|
|
26
|
+
causal: boolean;
|
|
27
|
+
/** Enable metacognition (MUSE) */
|
|
28
|
+
metacognition: boolean;
|
|
29
|
+
/** Enable NESS economic monitoring */
|
|
30
|
+
ness: boolean;
|
|
31
|
+
/** Enable multi-modal perception */
|
|
32
|
+
perception: boolean;
|
|
33
|
+
/** Enable meta-RL learning */
|
|
34
|
+
metaRL: boolean;
|
|
35
|
+
/** Enable code execution runtime */
|
|
36
|
+
execution: boolean;
|
|
37
|
+
/** Confidence threshold below which Brain defers to metacognition */
|
|
38
|
+
deferThreshold: number;
|
|
39
|
+
/** Audit all responses for hallucinations */
|
|
40
|
+
auditResponses: boolean;
|
|
41
|
+
}
|
|
42
|
+
export interface GenesisStatus {
|
|
43
|
+
booted: boolean;
|
|
44
|
+
levels: {
|
|
45
|
+
L1: boolean;
|
|
46
|
+
L2: boolean;
|
|
47
|
+
L3: boolean;
|
|
48
|
+
L4: boolean;
|
|
49
|
+
};
|
|
50
|
+
fek: FEKStatus | null;
|
|
51
|
+
brain: {
|
|
52
|
+
running: boolean;
|
|
53
|
+
phi: number;
|
|
54
|
+
} | null;
|
|
55
|
+
causal: {
|
|
56
|
+
graphSize: number;
|
|
57
|
+
} | null;
|
|
58
|
+
metacognition: {
|
|
59
|
+
confidence: number;
|
|
60
|
+
calibrationError: number;
|
|
61
|
+
} | null;
|
|
62
|
+
perception: boolean;
|
|
63
|
+
metaRL: {
|
|
64
|
+
curriculumSize: number;
|
|
65
|
+
} | null;
|
|
66
|
+
execution: boolean;
|
|
67
|
+
ness: NESSState | null;
|
|
68
|
+
fiber: {
|
|
69
|
+
netFlow: number;
|
|
70
|
+
sustainable: boolean;
|
|
71
|
+
} | null;
|
|
72
|
+
uptime: number;
|
|
73
|
+
cycleCount: number;
|
|
74
|
+
}
|
|
75
|
+
export interface ProcessResult {
|
|
76
|
+
response: string;
|
|
77
|
+
confidence: ConfidenceEstimate | null;
|
|
78
|
+
audit: ThoughtAudit | null;
|
|
79
|
+
cost: number;
|
|
80
|
+
fekState: FEKState | null;
|
|
81
|
+
}
|
|
82
|
+
export declare class Genesis {
|
|
83
|
+
private config;
|
|
84
|
+
private fek;
|
|
85
|
+
private brain;
|
|
86
|
+
private economy;
|
|
87
|
+
private fiber;
|
|
88
|
+
private causal;
|
|
89
|
+
private perception;
|
|
90
|
+
private codeRuntime;
|
|
91
|
+
private metacognition;
|
|
92
|
+
private nessMonitor;
|
|
93
|
+
private lastNESSState;
|
|
94
|
+
private metaRL;
|
|
95
|
+
private booted;
|
|
96
|
+
private bootTime;
|
|
97
|
+
private levels;
|
|
98
|
+
private cycleCount;
|
|
99
|
+
private performanceHistory;
|
|
100
|
+
constructor(config?: Partial<GenesisConfig>);
|
|
101
|
+
boot(): Promise<GenesisStatus>;
|
|
102
|
+
private bootL1;
|
|
103
|
+
private bootL2;
|
|
104
|
+
private bootL3;
|
|
105
|
+
private bootL4;
|
|
106
|
+
/**
|
|
107
|
+
* Process an input through the full Genesis stack:
|
|
108
|
+
* 1. Metacognition pre-check (should we defer?)
|
|
109
|
+
* 2. Brain processes query
|
|
110
|
+
* 3. Metacognition audits response
|
|
111
|
+
* 4. Causal reasoning (if errors detected)
|
|
112
|
+
* 5. FEK cycle with observations
|
|
113
|
+
* 6. NESS + Fiber economic tracking
|
|
114
|
+
*/
|
|
115
|
+
process(input: string): Promise<ProcessResult>;
|
|
116
|
+
/**
|
|
117
|
+
* Estimate causal effect: P(outcome | do(treatment = value))
|
|
118
|
+
*/
|
|
119
|
+
causalEffect(treatment: string, treatmentValue: unknown, outcome: string): Effect | null;
|
|
120
|
+
/**
|
|
121
|
+
* Counterfactual: "What would outcome have been if intervention had occurred?"
|
|
122
|
+
*/
|
|
123
|
+
whatIf(factual: Record<string, unknown>, intervention: Intervention, outcome: string): CounterfactualResult | null;
|
|
124
|
+
/**
|
|
125
|
+
* Diagnose a failure using causal reasoning
|
|
126
|
+
*/
|
|
127
|
+
diagnoseFailure(failure: Error, observedState: Record<string, unknown>): CausalExplanation | null;
|
|
128
|
+
/**
|
|
129
|
+
* Evaluate reasoning quality
|
|
130
|
+
*/
|
|
131
|
+
evaluateReasoning(reasoning: string, context?: string[]): number | null;
|
|
132
|
+
/**
|
|
133
|
+
* Provide outcome feedback for calibration
|
|
134
|
+
*/
|
|
135
|
+
feedback(success: boolean): void;
|
|
136
|
+
/**
|
|
137
|
+
* Get Expected Calibration Error (ECE)
|
|
138
|
+
*/
|
|
139
|
+
getCalibrationError(): number;
|
|
140
|
+
/**
|
|
141
|
+
* Process multi-modal inputs (visual, audio, proprioceptive)
|
|
142
|
+
*/
|
|
143
|
+
perceive(inputs: ModalityInput[], timestamp?: number): PerceptionOutput | null;
|
|
144
|
+
/**
|
|
145
|
+
* Get current curriculum state
|
|
146
|
+
*/
|
|
147
|
+
getCurriculum(): CurriculumState | null;
|
|
148
|
+
/**
|
|
149
|
+
* Report task outcome to meta-RL for curriculum learning
|
|
150
|
+
*/
|
|
151
|
+
reportTaskOutcome(taskId: string, success: boolean, stepsUsed: number): void;
|
|
152
|
+
/**
|
|
153
|
+
* Get the code execution runtime
|
|
154
|
+
*/
|
|
155
|
+
getCodeRuntime(): CodeRuntime | null;
|
|
156
|
+
/**
|
|
157
|
+
* Record revenue from an external source
|
|
158
|
+
*/
|
|
159
|
+
recordRevenue(moduleId: string, amount: number, source: string): void;
|
|
160
|
+
/**
|
|
161
|
+
* Get economic health
|
|
162
|
+
*/
|
|
163
|
+
getEconomicHealth(): {
|
|
164
|
+
fiber: ReturnType<EconomicFiber['getGlobalSection']> | null;
|
|
165
|
+
ness: NESSState | null;
|
|
166
|
+
};
|
|
167
|
+
getStatus(): GenesisStatus;
|
|
168
|
+
/**
|
|
169
|
+
* Graceful shutdown: L4→L1
|
|
170
|
+
*/
|
|
171
|
+
shutdown(): Promise<void>;
|
|
172
|
+
private inferDomain;
|
|
173
|
+
}
|
|
174
|
+
export declare function createGenesis(config?: Partial<GenesisConfig>): Genesis;
|
|
175
|
+
export declare function getGenesis(config?: Partial<GenesisConfig>): Genesis;
|
|
176
|
+
export declare function resetGenesis(): void;
|
|
177
|
+
export default Genesis;
|
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Genesis v13.0 — Unified Bootstrap Layer
|
|
4
|
+
*
|
|
5
|
+
* Hierarchical boot (L1→L4), inter-module wiring, and unified process/query interface.
|
|
6
|
+
* Connects all 49 modules into a coherent organism:
|
|
7
|
+
*
|
|
8
|
+
* L1: Persistence, FEK (autonomic substrate)
|
|
9
|
+
* L2: Memory, Active Inference, Kernel, Economic Fiber
|
|
10
|
+
* L3: Brain, Causal Reasoning, Perception
|
|
11
|
+
* L4: Metacognition (MUSE), NESS Monitor, Darwin-Gödel
|
|
12
|
+
*
|
|
13
|
+
* Each level boots only after its predecessor is healthy.
|
|
14
|
+
*/
|
|
15
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
16
|
+
exports.Genesis = void 0;
|
|
17
|
+
exports.createGenesis = createGenesis;
|
|
18
|
+
exports.getGenesis = getGenesis;
|
|
19
|
+
exports.resetGenesis = resetGenesis;
|
|
20
|
+
const free_energy_kernel_js_1 = require("./kernel/free-energy-kernel.js");
|
|
21
|
+
const index_js_1 = require("./brain/index.js");
|
|
22
|
+
const index_js_2 = require("./causal/index.js");
|
|
23
|
+
const index_js_3 = require("./metacognition/index.js");
|
|
24
|
+
const index_js_4 = require("./economy/index.js");
|
|
25
|
+
const fiber_js_1 = require("./economy/fiber.js");
|
|
26
|
+
const ness_js_1 = require("./economy/ness.js");
|
|
27
|
+
const multi_modal_js_1 = require("./perception/multi-modal.js");
|
|
28
|
+
const meta_rl_js_1 = require("./learning/meta-rl.js");
|
|
29
|
+
const index_js_5 = require("./execution/index.js");
|
|
30
|
+
// ============================================================================
|
|
31
|
+
// Genesis Core
|
|
32
|
+
// ============================================================================
|
|
33
|
+
class Genesis {
|
|
34
|
+
config;
|
|
35
|
+
// L1: Substrate
|
|
36
|
+
fek = null;
|
|
37
|
+
// L2: Reactive
|
|
38
|
+
brain = null;
|
|
39
|
+
economy = null;
|
|
40
|
+
fiber = null;
|
|
41
|
+
// L3: Cognitive
|
|
42
|
+
causal = null;
|
|
43
|
+
perception = null;
|
|
44
|
+
codeRuntime = null;
|
|
45
|
+
// L4: Executive
|
|
46
|
+
metacognition = null;
|
|
47
|
+
nessMonitor = null;
|
|
48
|
+
lastNESSState = null;
|
|
49
|
+
metaRL = null;
|
|
50
|
+
// State
|
|
51
|
+
booted = false;
|
|
52
|
+
bootTime = 0;
|
|
53
|
+
levels = { L1: false, L2: false, L3: false, L4: false };
|
|
54
|
+
cycleCount = 0;
|
|
55
|
+
performanceHistory = [];
|
|
56
|
+
constructor(config) {
|
|
57
|
+
this.config = {
|
|
58
|
+
totalBudget: 100,
|
|
59
|
+
causal: true,
|
|
60
|
+
metacognition: true,
|
|
61
|
+
ness: true,
|
|
62
|
+
perception: true,
|
|
63
|
+
metaRL: true,
|
|
64
|
+
execution: true,
|
|
65
|
+
deferThreshold: 0.3,
|
|
66
|
+
auditResponses: true,
|
|
67
|
+
...config,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
// ==========================================================================
|
|
71
|
+
// Boot Sequence
|
|
72
|
+
// ==========================================================================
|
|
73
|
+
async boot() {
|
|
74
|
+
this.bootTime = Date.now();
|
|
75
|
+
// L1: Autonomic substrate
|
|
76
|
+
await this.bootL1();
|
|
77
|
+
// L2: Reactive layer
|
|
78
|
+
await this.bootL2();
|
|
79
|
+
// L3: Cognitive layer
|
|
80
|
+
await this.bootL3();
|
|
81
|
+
// L4: Executive layer
|
|
82
|
+
await this.bootL4();
|
|
83
|
+
this.booted = true;
|
|
84
|
+
return this.getStatus();
|
|
85
|
+
}
|
|
86
|
+
async bootL1() {
|
|
87
|
+
// Free Energy Kernel — the core autonomic loop
|
|
88
|
+
this.fek = (0, free_energy_kernel_js_1.getFreeEnergyKernel)();
|
|
89
|
+
this.fek.start();
|
|
90
|
+
this.levels.L1 = true;
|
|
91
|
+
}
|
|
92
|
+
async bootL2() {
|
|
93
|
+
if (!this.levels.L1)
|
|
94
|
+
throw new Error('L1 must boot before L2');
|
|
95
|
+
// Brain — the main cognitive processor
|
|
96
|
+
this.brain = (0, index_js_1.getBrain)();
|
|
97
|
+
// Economic systems
|
|
98
|
+
this.economy = (0, index_js_4.getEconomicSystem)({
|
|
99
|
+
dailyLimit: this.config.totalBudget,
|
|
100
|
+
monthlyLimit: this.config.totalBudget * 30,
|
|
101
|
+
perTransactionLimit: this.config.totalBudget * 0.5,
|
|
102
|
+
requireApprovalAbove: this.config.totalBudget * 0.5,
|
|
103
|
+
});
|
|
104
|
+
await this.economy.initialize();
|
|
105
|
+
this.fiber = (0, fiber_js_1.getEconomicFiber)(this.config.totalBudget);
|
|
106
|
+
this.fiber.registerModule('genesis');
|
|
107
|
+
this.fiber.registerModule('brain');
|
|
108
|
+
this.fiber.registerModule('causal');
|
|
109
|
+
this.fiber.registerModule('metacognition');
|
|
110
|
+
this.fiber.registerModule('perception');
|
|
111
|
+
this.fiber.registerModule('metarl');
|
|
112
|
+
this.fiber.registerModule('execution');
|
|
113
|
+
this.levels.L2 = true;
|
|
114
|
+
}
|
|
115
|
+
async bootL3() {
|
|
116
|
+
if (!this.levels.L2)
|
|
117
|
+
throw new Error('L2 must boot before L3');
|
|
118
|
+
if (this.config.causal) {
|
|
119
|
+
// Causal reasoning with standard agent model
|
|
120
|
+
this.causal = (0, index_js_2.createAgentCausalModel)();
|
|
121
|
+
// Wire FEK prediction errors to causal diagnosis
|
|
122
|
+
if (this.fek) {
|
|
123
|
+
this.fek.onPredictionError((error) => {
|
|
124
|
+
if (this.causal) {
|
|
125
|
+
this.causal.diagnoseFailure(new Error(error.content), { source: error.source, target: error.target, magnitude: error.magnitude });
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
if (this.config.perception) {
|
|
131
|
+
this.perception = (0, multi_modal_js_1.createMultiModalPerception)();
|
|
132
|
+
}
|
|
133
|
+
if (this.config.execution) {
|
|
134
|
+
this.codeRuntime = (0, index_js_5.getCodeRuntime)();
|
|
135
|
+
}
|
|
136
|
+
this.levels.L3 = true;
|
|
137
|
+
}
|
|
138
|
+
async bootL4() {
|
|
139
|
+
if (!this.levels.L3)
|
|
140
|
+
throw new Error('L3 must boot before L4');
|
|
141
|
+
if (this.config.metacognition) {
|
|
142
|
+
this.metacognition = (0, index_js_3.createMetacognitionSystem)();
|
|
143
|
+
}
|
|
144
|
+
if (this.config.ness) {
|
|
145
|
+
this.nessMonitor = (0, ness_js_1.getNESSMonitor)();
|
|
146
|
+
}
|
|
147
|
+
if (this.config.metaRL) {
|
|
148
|
+
this.metaRL = (0, meta_rl_js_1.createMetaRLLearner)({
|
|
149
|
+
innerLearningRate: 0.01,
|
|
150
|
+
outerLearningRate: 0.001,
|
|
151
|
+
adaptationWindow: 50,
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
this.levels.L4 = true;
|
|
155
|
+
}
|
|
156
|
+
// ==========================================================================
|
|
157
|
+
// Main Processing Pipeline
|
|
158
|
+
// ==========================================================================
|
|
159
|
+
/**
|
|
160
|
+
* Process an input through the full Genesis stack:
|
|
161
|
+
* 1. Metacognition pre-check (should we defer?)
|
|
162
|
+
* 2. Brain processes query
|
|
163
|
+
* 3. Metacognition audits response
|
|
164
|
+
* 4. Causal reasoning (if errors detected)
|
|
165
|
+
* 5. FEK cycle with observations
|
|
166
|
+
* 6. NESS + Fiber economic tracking
|
|
167
|
+
*/
|
|
168
|
+
async process(input) {
|
|
169
|
+
if (!this.booted)
|
|
170
|
+
await this.boot();
|
|
171
|
+
this.cycleCount++;
|
|
172
|
+
const startTime = Date.now();
|
|
173
|
+
let confidence = null;
|
|
174
|
+
let audit = null;
|
|
175
|
+
// Step 1: Metacognitive pre-check
|
|
176
|
+
if (this.metacognition) {
|
|
177
|
+
const domain = this.inferDomain(input);
|
|
178
|
+
if (this.metacognition.shouldDefer(domain)) {
|
|
179
|
+
// Low competence — still process but flag it
|
|
180
|
+
confidence = this.metacognition.getConfidence(0.3, domain);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
// Step 2: Brain processes
|
|
184
|
+
let response = '';
|
|
185
|
+
if (this.brain) {
|
|
186
|
+
response = await this.brain.process(input);
|
|
187
|
+
}
|
|
188
|
+
// Step 3: Metacognitive audit
|
|
189
|
+
if (this.metacognition && this.config.auditResponses && response) {
|
|
190
|
+
audit = this.metacognition.auditThought(response);
|
|
191
|
+
// Get calibrated confidence
|
|
192
|
+
const domain = this.inferDomain(input);
|
|
193
|
+
const rawConfidence = audit.coherence * 0.5 + audit.groundedness * 0.5;
|
|
194
|
+
confidence = this.metacognition.getConfidence(rawConfidence, domain);
|
|
195
|
+
}
|
|
196
|
+
// Step 4: FEK cycle
|
|
197
|
+
let fekState = null;
|
|
198
|
+
if (this.fek) {
|
|
199
|
+
fekState = this.fek.cycle({
|
|
200
|
+
energy: 1.0,
|
|
201
|
+
agentResponsive: true,
|
|
202
|
+
merkleValid: true,
|
|
203
|
+
systemLoad: this.cycleCount / 100,
|
|
204
|
+
phi: confidence?.value,
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
// Step 5: Economic tracking
|
|
208
|
+
const elapsed = Date.now() - startTime;
|
|
209
|
+
const cost = elapsed * 0.001; // Rough cost proxy: $0.001 per ms
|
|
210
|
+
if (this.fiber) {
|
|
211
|
+
this.fiber.recordCost('brain', cost, 'process');
|
|
212
|
+
}
|
|
213
|
+
if (this.nessMonitor && this.fiber) {
|
|
214
|
+
const section = this.fiber.getGlobalSection();
|
|
215
|
+
this.lastNESSState = this.nessMonitor.observe({
|
|
216
|
+
revenue: section.totalRevenue,
|
|
217
|
+
costs: section.totalCosts,
|
|
218
|
+
customers: 1,
|
|
219
|
+
quality: confidence?.value ?? 0.8,
|
|
220
|
+
balance: section.netFlow,
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
// Track for calibration
|
|
224
|
+
if (confidence) {
|
|
225
|
+
this.performanceHistory.push({
|
|
226
|
+
predicted: confidence.value,
|
|
227
|
+
actual: true, // Updated externally via feedback()
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
return { response, confidence, audit, cost, fekState };
|
|
231
|
+
}
|
|
232
|
+
// ==========================================================================
|
|
233
|
+
// Causal Reasoning Interface
|
|
234
|
+
// ==========================================================================
|
|
235
|
+
/**
|
|
236
|
+
* Estimate causal effect: P(outcome | do(treatment = value))
|
|
237
|
+
*/
|
|
238
|
+
causalEffect(treatment, treatmentValue, outcome) {
|
|
239
|
+
if (!this.causal)
|
|
240
|
+
return null;
|
|
241
|
+
return this.causal.estimateEffect(treatment, treatmentValue, outcome);
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Counterfactual: "What would outcome have been if intervention had occurred?"
|
|
245
|
+
*/
|
|
246
|
+
whatIf(factual, intervention, outcome) {
|
|
247
|
+
if (!this.causal)
|
|
248
|
+
return null;
|
|
249
|
+
return this.causal.whatIf(factual, intervention, outcome);
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Diagnose a failure using causal reasoning
|
|
253
|
+
*/
|
|
254
|
+
diagnoseFailure(failure, observedState) {
|
|
255
|
+
if (!this.causal)
|
|
256
|
+
return null;
|
|
257
|
+
return this.causal.diagnoseFailure(failure, observedState);
|
|
258
|
+
}
|
|
259
|
+
// ==========================================================================
|
|
260
|
+
// Metacognitive Interface
|
|
261
|
+
// ==========================================================================
|
|
262
|
+
/**
|
|
263
|
+
* Evaluate reasoning quality
|
|
264
|
+
*/
|
|
265
|
+
evaluateReasoning(reasoning, context) {
|
|
266
|
+
if (!this.metacognition)
|
|
267
|
+
return null;
|
|
268
|
+
return this.metacognition.evaluateReasoning(reasoning, context);
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Provide outcome feedback for calibration
|
|
272
|
+
*/
|
|
273
|
+
feedback(success) {
|
|
274
|
+
if (this.performanceHistory.length > 0) {
|
|
275
|
+
this.performanceHistory[this.performanceHistory.length - 1].actual = success;
|
|
276
|
+
}
|
|
277
|
+
if (this.metacognition) {
|
|
278
|
+
const domain = 'general';
|
|
279
|
+
const predicted = this.performanceHistory.length > 0
|
|
280
|
+
? this.performanceHistory[this.performanceHistory.length - 1].predicted
|
|
281
|
+
: 0.5;
|
|
282
|
+
this.metacognition.updateFromOutcome(domain, success, predicted);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Get Expected Calibration Error (ECE)
|
|
287
|
+
*/
|
|
288
|
+
getCalibrationError() {
|
|
289
|
+
if (this.performanceHistory.length < 10)
|
|
290
|
+
return 0;
|
|
291
|
+
// Bin predictions into 10 buckets, compute |avg_predicted - avg_actual| per bin
|
|
292
|
+
const bins = Array.from({ length: 10 }, () => ({ predicted: 0, actual: 0, count: 0 }));
|
|
293
|
+
for (const entry of this.performanceHistory) {
|
|
294
|
+
const binIdx = Math.min(9, Math.floor(entry.predicted * 10));
|
|
295
|
+
bins[binIdx].predicted += entry.predicted;
|
|
296
|
+
bins[binIdx].actual += entry.actual ? 1 : 0;
|
|
297
|
+
bins[binIdx].count++;
|
|
298
|
+
}
|
|
299
|
+
let ece = 0;
|
|
300
|
+
const total = this.performanceHistory.length;
|
|
301
|
+
for (const bin of bins) {
|
|
302
|
+
if (bin.count === 0)
|
|
303
|
+
continue;
|
|
304
|
+
const avgPredicted = bin.predicted / bin.count;
|
|
305
|
+
const avgActual = bin.actual / bin.count;
|
|
306
|
+
ece += (bin.count / total) * Math.abs(avgPredicted - avgActual);
|
|
307
|
+
}
|
|
308
|
+
return ece;
|
|
309
|
+
}
|
|
310
|
+
// ==========================================================================
|
|
311
|
+
// Perception Interface
|
|
312
|
+
// ==========================================================================
|
|
313
|
+
/**
|
|
314
|
+
* Process multi-modal inputs (visual, audio, proprioceptive)
|
|
315
|
+
*/
|
|
316
|
+
perceive(inputs, timestamp) {
|
|
317
|
+
if (!this.perception)
|
|
318
|
+
return null;
|
|
319
|
+
const output = this.perception.perceive(inputs, timestamp);
|
|
320
|
+
if (this.fiber) {
|
|
321
|
+
this.fiber.recordCost('perception', 0.01 * inputs.length, 'perceive');
|
|
322
|
+
}
|
|
323
|
+
return output;
|
|
324
|
+
}
|
|
325
|
+
// ==========================================================================
|
|
326
|
+
// Meta-RL Interface
|
|
327
|
+
// ==========================================================================
|
|
328
|
+
/**
|
|
329
|
+
* Get current curriculum state
|
|
330
|
+
*/
|
|
331
|
+
getCurriculum() {
|
|
332
|
+
if (!this.metaRL)
|
|
333
|
+
return null;
|
|
334
|
+
return this.metaRL.getCurriculum();
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* Report task outcome to meta-RL for curriculum learning
|
|
338
|
+
*/
|
|
339
|
+
reportTaskOutcome(taskId, success, stepsUsed) {
|
|
340
|
+
if (this.metaRL) {
|
|
341
|
+
this.metaRL.updateCurriculum(taskId, success, stepsUsed);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
// ==========================================================================
|
|
345
|
+
// Code Execution Interface
|
|
346
|
+
// ==========================================================================
|
|
347
|
+
/**
|
|
348
|
+
* Get the code execution runtime
|
|
349
|
+
*/
|
|
350
|
+
getCodeRuntime() {
|
|
351
|
+
return this.codeRuntime;
|
|
352
|
+
}
|
|
353
|
+
// ==========================================================================
|
|
354
|
+
// Economic Interface
|
|
355
|
+
// ==========================================================================
|
|
356
|
+
/**
|
|
357
|
+
* Record revenue from an external source
|
|
358
|
+
*/
|
|
359
|
+
recordRevenue(moduleId, amount, source) {
|
|
360
|
+
if (this.fiber) {
|
|
361
|
+
this.fiber.recordRevenue(moduleId, amount, source);
|
|
362
|
+
}
|
|
363
|
+
if (this.fek) {
|
|
364
|
+
this.fek.recordRevenue(moduleId, amount, source);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* Get economic health
|
|
369
|
+
*/
|
|
370
|
+
getEconomicHealth() {
|
|
371
|
+
return {
|
|
372
|
+
fiber: this.fiber?.getGlobalSection() ?? null,
|
|
373
|
+
ness: this.lastNESSState,
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
// ==========================================================================
|
|
377
|
+
// Status & Introspection
|
|
378
|
+
// ==========================================================================
|
|
379
|
+
getStatus() {
|
|
380
|
+
const fekStatus = this.fek?.getStatus() ?? null;
|
|
381
|
+
const brainStatus = this.brain?.getStatus();
|
|
382
|
+
const metacogState = this.metacognition?.getState();
|
|
383
|
+
const fiberSection = this.fiber?.getGlobalSection();
|
|
384
|
+
const nessState = this.lastNESSState;
|
|
385
|
+
const causalGraph = this.causal?.getGraph();
|
|
386
|
+
const curriculum = this.metaRL?.getCurriculum();
|
|
387
|
+
return {
|
|
388
|
+
booted: this.booted,
|
|
389
|
+
levels: { ...this.levels },
|
|
390
|
+
fek: fekStatus,
|
|
391
|
+
brain: brainStatus ? { running: brainStatus.running, phi: brainStatus.phi } : null,
|
|
392
|
+
causal: causalGraph ? { graphSize: causalGraph.variables?.size ?? 0 } : null,
|
|
393
|
+
metacognition: metacogState ? {
|
|
394
|
+
confidence: metacogState.currentConfidence.value,
|
|
395
|
+
calibrationError: metacogState.currentConfidence.calibrationError,
|
|
396
|
+
} : null,
|
|
397
|
+
perception: this.perception !== null,
|
|
398
|
+
metaRL: curriculum ? { curriculumSize: curriculum.taskHistory.length } : null,
|
|
399
|
+
execution: this.codeRuntime !== null,
|
|
400
|
+
ness: nessState,
|
|
401
|
+
fiber: fiberSection ? { netFlow: fiberSection.netFlow, sustainable: fiberSection.sustainable } : null,
|
|
402
|
+
uptime: this.bootTime > 0 ? Date.now() - this.bootTime : 0,
|
|
403
|
+
cycleCount: this.cycleCount,
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* Graceful shutdown: L4→L1
|
|
408
|
+
*/
|
|
409
|
+
async shutdown() {
|
|
410
|
+
if (this.fek) {
|
|
411
|
+
this.fek.stop();
|
|
412
|
+
}
|
|
413
|
+
this.booted = false;
|
|
414
|
+
this.levels = { L1: false, L2: false, L3: false, L4: false };
|
|
415
|
+
}
|
|
416
|
+
// ==========================================================================
|
|
417
|
+
// Helpers
|
|
418
|
+
// ==========================================================================
|
|
419
|
+
inferDomain(input) {
|
|
420
|
+
const lower = input.toLowerCase();
|
|
421
|
+
if (lower.includes('code') || lower.includes('function') || lower.includes('bug'))
|
|
422
|
+
return 'coding';
|
|
423
|
+
if (lower.includes('math') || lower.includes('calcul') || lower.includes('equat'))
|
|
424
|
+
return 'math';
|
|
425
|
+
if (lower.includes('deploy') || lower.includes('server') || lower.includes('infra'))
|
|
426
|
+
return 'infrastructure';
|
|
427
|
+
if (lower.includes('money') || lower.includes('pay') || lower.includes('budget'))
|
|
428
|
+
return 'economics';
|
|
429
|
+
return 'general';
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
exports.Genesis = Genesis;
|
|
433
|
+
// ============================================================================
|
|
434
|
+
// Factory & Singleton
|
|
435
|
+
// ============================================================================
|
|
436
|
+
let genesisInstance = null;
|
|
437
|
+
function createGenesis(config) {
|
|
438
|
+
return new Genesis(config);
|
|
439
|
+
}
|
|
440
|
+
function getGenesis(config) {
|
|
441
|
+
if (!genesisInstance) {
|
|
442
|
+
genesisInstance = new Genesis(config);
|
|
443
|
+
}
|
|
444
|
+
return genesisInstance;
|
|
445
|
+
}
|
|
446
|
+
function resetGenesis() {
|
|
447
|
+
if (genesisInstance) {
|
|
448
|
+
genesisInstance.shutdown();
|
|
449
|
+
}
|
|
450
|
+
genesisInstance = null;
|
|
451
|
+
}
|
|
452
|
+
exports.default = Genesis;
|
package/dist/src/index.js
CHANGED
|
@@ -81,6 +81,7 @@ const index_js_5 = require("./brain/index.js");
|
|
|
81
81
|
const index_js_6 = require("./autonomous/index.js");
|
|
82
82
|
const code_quality_analyzer_js_1 = require("./self-modification/code-quality-analyzer.js");
|
|
83
83
|
const index_js_7 = require("./integration/index.js");
|
|
84
|
+
const genesis_js_1 = require("./genesis.js");
|
|
84
85
|
// ============================================================================
|
|
85
86
|
// CLI Colors
|
|
86
87
|
// ============================================================================
|
|
@@ -159,6 +160,26 @@ async function cmdStatus() {
|
|
|
159
160
|
console.log(` Checks performed: ${state.governanceChecks}`);
|
|
160
161
|
console.log(c('\n[A2A]', 'green'));
|
|
161
162
|
console.log(` Delegations: ${state.a2aDelegations}`);
|
|
163
|
+
// v13.0: Genesis unified system status
|
|
164
|
+
console.log(c('\n=== GENESIS CORE ===\n', 'bold'));
|
|
165
|
+
const genesis = (0, genesis_js_1.getGenesis)();
|
|
166
|
+
const gStatus = genesis.getStatus();
|
|
167
|
+
const lvl = (b) => b ? c('●', 'green') : c('○', 'red');
|
|
168
|
+
console.log(c('[LEVELS]', 'cyan'));
|
|
169
|
+
console.log(` ${lvl(gStatus.levels.L1)} L1 Autonomic ${lvl(gStatus.levels.L2)} L2 Reactive ${lvl(gStatus.levels.L3)} L3 Cognitive ${lvl(gStatus.levels.L4)} L4 Executive`);
|
|
170
|
+
console.log(c('\n[MODULES]', 'magenta'));
|
|
171
|
+
console.log(` FEK: ${gStatus.fek ? `running, ${gStatus.fek.cycleCount} cycles, FE=${gStatus.fek.totalFE.toFixed(3)}` : 'offline'}`);
|
|
172
|
+
console.log(` Brain: ${gStatus.brain ? `phi=${gStatus.brain.phi.toFixed(3)}` : 'offline'}`);
|
|
173
|
+
console.log(` Causal: ${gStatus.causal ? `${gStatus.causal.graphSize} variables` : 'disabled'}`);
|
|
174
|
+
console.log(` Metacognition: ${gStatus.metacognition ? `conf=${gStatus.metacognition.confidence.toFixed(2)}, ECE=${gStatus.metacognition.calibrationError.toFixed(3)}` : 'disabled'}`);
|
|
175
|
+
console.log(` Perception: ${gStatus.perception ? 'active' : 'disabled'}`);
|
|
176
|
+
console.log(` Meta-RL: ${gStatus.metaRL ? `${gStatus.metaRL.curriculumSize} tasks learned` : 'disabled'}`);
|
|
177
|
+
console.log(` Execution: ${gStatus.execution ? 'active' : 'disabled'}`);
|
|
178
|
+
if (gStatus.fiber) {
|
|
179
|
+
console.log(c('\n[ECONOMICS]', 'yellow'));
|
|
180
|
+
console.log(` Net flow: $${gStatus.fiber.netFlow.toFixed(4)}/cycle`);
|
|
181
|
+
console.log(` Sustainable: ${gStatus.fiber.sustainable ? c('yes', 'green') : c('no', 'red')}`);
|
|
182
|
+
}
|
|
162
183
|
console.log();
|
|
163
184
|
}
|
|
164
185
|
async function cmdCreate(name, options) {
|
package/package.json
CHANGED