genesis-ai-cli 13.0.0 → 13.2.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.
Files changed (38) hide show
  1. package/dist/.genesis/code-index/code-index.json +12 -0
  2. package/dist/.genesis/code-index/embeddings-nomic-embed-text.json +1 -0
  3. package/dist/.genesis/code-index/metadata.json +1 -0
  4. package/dist/.genesis/code-index/vectors.json +1 -0
  5. package/dist/src/active-inference/actions.js +60 -9
  6. package/dist/src/active-inference/autonomous-loop.js +16 -0
  7. package/dist/src/active-inference/economic-integration.d.ts +1 -0
  8. package/dist/src/active-inference/economic-integration.js +25 -1
  9. package/dist/src/active-inference/observations.js +17 -3
  10. package/dist/src/brain/index.d.ts +7 -0
  11. package/dist/src/brain/index.js +48 -1
  12. package/dist/src/brain/self-knowledge.d.ts +84 -0
  13. package/dist/src/brain/self-knowledge.js +238 -0
  14. package/dist/src/cli/chat.js +47 -0
  15. package/dist/src/economy/autonomous.d.ts +144 -0
  16. package/dist/src/economy/autonomous.js +619 -0
  17. package/dist/src/economy/capital-allocator.d.ts +107 -0
  18. package/dist/src/economy/capital-allocator.js +275 -0
  19. package/dist/src/economy/generators/bounty-hunter.d.ts +116 -0
  20. package/dist/src/economy/generators/bounty-hunter.js +301 -0
  21. package/dist/src/economy/generators/index.d.ts +5 -0
  22. package/dist/src/economy/generators/index.js +14 -0
  23. package/dist/src/economy/generators/keeper.d.ts +107 -0
  24. package/dist/src/economy/generators/keeper.js +299 -0
  25. package/dist/src/economy/index.d.ts +4 -0
  26. package/dist/src/economy/index.js +28 -1
  27. package/dist/src/economy/infrastructure/index.d.ts +5 -0
  28. package/dist/src/economy/infrastructure/index.js +14 -0
  29. package/dist/src/economy/infrastructure/mcp-marketplace.d.ts +129 -0
  30. package/dist/src/economy/infrastructure/mcp-marketplace.js +441 -0
  31. package/dist/src/economy/infrastructure/x402-facilitator.d.ts +126 -0
  32. package/dist/src/economy/infrastructure/x402-facilitator.js +249 -0
  33. package/dist/src/genesis.d.ts +186 -0
  34. package/dist/src/genesis.js +481 -0
  35. package/dist/src/index.js +21 -0
  36. package/dist/src/kernel/free-energy-kernel.d.ts +5 -0
  37. package/dist/src/kernel/free-energy-kernel.js +65 -7
  38. package/package.json +1 -1
@@ -0,0 +1,12 @@
1
+ {
2
+ "version": "8.5.0",
3
+ "indexedAt": "2026-01-24T18:24:32.643Z",
4
+ "rootPath": "/Users/lucarossignoli/genesis/dist/src",
5
+ "chunks": [],
6
+ "stats": {
7
+ "totalFiles": 0,
8
+ "totalChunks": 0,
9
+ "totalLines": 0,
10
+ "byType": {}
11
+ }
12
+ }
@@ -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":{}}
@@ -290,17 +290,68 @@ registerAction('verify.ethics', async (context) => {
290
290
  });
291
291
  /**
292
292
  * execute.task: Execute the planned task
293
+ * v13.1: Closes the autopoietic execution loop by routing through Brain.process()
293
294
  */
295
+ let _executeTaskDepth = 0;
296
+ const MAX_EXECUTE_DEPTH = 2; // Prevent infinite recursion (AIF → brain → AIF → brain)
294
297
  registerAction('execute.task', async (context) => {
295
- return {
296
- success: true,
297
- action: 'execute.task',
298
- data: {
299
- taskId: context.taskId,
300
- result: null,
301
- },
302
- duration: 0,
303
- };
298
+ const start = Date.now();
299
+ // Re-entrancy guard: prevent recursive brain.process() calls
300
+ if (_executeTaskDepth >= MAX_EXECUTE_DEPTH) {
301
+ return {
302
+ success: false,
303
+ action: 'execute.task',
304
+ error: `Execution depth limit (${MAX_EXECUTE_DEPTH}) reached — preventing recursion`,
305
+ duration: Date.now() - start,
306
+ };
307
+ }
308
+ _executeTaskDepth++;
309
+ try {
310
+ // Dynamic import to avoid circular dependency (brain → actions → brain)
311
+ const { getBrainInstance } = await import('../brain/index.js');
312
+ const brain = getBrainInstance();
313
+ if (!brain) {
314
+ return {
315
+ success: false,
316
+ action: 'execute.task',
317
+ error: 'Brain not initialized — cannot execute task',
318
+ duration: Date.now() - start,
319
+ };
320
+ }
321
+ const goal = context.goal || context.parameters?.goal || '';
322
+ if (!goal) {
323
+ return {
324
+ success: false,
325
+ action: 'execute.task',
326
+ error: 'No goal specified for task execution',
327
+ duration: Date.now() - start,
328
+ };
329
+ }
330
+ // Route through Brain's full processing pipeline (memory → LLM → tools → response)
331
+ const result = await brain.process(goal);
332
+ return {
333
+ success: true,
334
+ action: 'execute.task',
335
+ data: {
336
+ taskId: context.taskId,
337
+ goal,
338
+ result,
339
+ truncated: result.length > 500,
340
+ },
341
+ duration: Date.now() - start,
342
+ };
343
+ }
344
+ catch (error) {
345
+ return {
346
+ success: false,
347
+ action: 'execute.task',
348
+ error: error instanceof Error ? error.message : String(error),
349
+ duration: Date.now() - start,
350
+ };
351
+ }
352
+ finally {
353
+ _executeTaskDepth--;
354
+ }
304
355
  });
305
356
  /**
306
357
  * execute.cycle: Run a processing cycle
@@ -575,12 +575,28 @@ class AutonomousLoop {
575
575
  const avgS = highSurprise.reduce((s, e) => s + e.surprise, 0) / highSurprise.length;
576
576
  console.log(`[AI Loop] Dream: ${highSurprise.length} experiences, avg surprise ${avgS.toFixed(2)}`);
577
577
  }
578
+ // v13.1: Notify FEK to enter dreaming mode (suppresses L2-L4 during consolidation)
579
+ try {
580
+ const { getFreeEnergyKernel } = require('../kernel/free-energy-kernel.js');
581
+ const fek = getFreeEnergyKernel();
582
+ if (fek?.setMode)
583
+ fek.setMode('dreaming');
584
+ }
585
+ catch { /* FEK may not be available */ }
578
586
  // v11.4: Delegate to DreamService for NREM/SWS/REM phases
579
587
  // DreamService handles: episodic consolidation, pattern extraction, creative synthesis
580
588
  this.dreamService.startDream({ duration: 3000 }).then(session => {
581
589
  if (this.config.verbose && session?.results) {
582
590
  console.log(`[AI Loop] Dream complete: ${session.results.memoriesConsolidated} consolidated, ${session.results.patternsExtracted} patterns`);
583
591
  }
592
+ // v13.1: Restore FEK to awake mode after dream
593
+ try {
594
+ const { getFreeEnergyKernel } = require('../kernel/free-energy-kernel.js');
595
+ const fek = getFreeEnergyKernel();
596
+ if (fek?.setMode)
597
+ fek.setMode('awake');
598
+ }
599
+ catch { /* non-fatal */ }
584
600
  }).catch(() => {
585
601
  // Fallback: direct 3× replay if DreamService fails
586
602
  for (let iter = 0; iter < 3; iter++) {
@@ -190,6 +190,7 @@ export declare class EconomicIntegration {
190
190
  export declare function getEconomicIntegration(): EconomicIntegration;
191
191
  /**
192
192
  * Hook to record LLM costs (call this after each LLM request)
193
+ * v13.1: Also feeds real costs into EconomicFiber for FEK's leapfrog budget allocation
193
194
  */
194
195
  export declare function recordLLMCost(provider: string, inputTokens: number, outputTokens: number, model: string): void;
195
196
  /**
@@ -17,6 +17,7 @@ exports.getEconomicIntegration = getEconomicIntegration;
17
17
  exports.recordLLMCost = recordLLMCost;
18
18
  exports.recordRevenue = recordRevenue;
19
19
  const index_js_1 = require("../economy/index.js");
20
+ const fiber_js_1 = require("../economy/fiber.js");
20
21
  // ============================================================================
21
22
  // Cost Tracker
22
23
  // ============================================================================
@@ -511,9 +512,32 @@ function getEconomicIntegration() {
511
512
  }
512
513
  /**
513
514
  * Hook to record LLM costs (call this after each LLM request)
515
+ * v13.1: Also feeds real costs into EconomicFiber for FEK's leapfrog budget allocation
514
516
  */
515
517
  function recordLLMCost(provider, inputTokens, outputTokens, model) {
516
- getEconomicIntegration().getCostTracker().recordLLMCost(provider, inputTokens, outputTokens, model);
518
+ const tracker = getEconomicIntegration().getCostTracker();
519
+ tracker.recordLLMCost(provider, inputTokens, outputTokens, model);
520
+ // v13.1: Feed real cost into FEK's EconomicFiber (replaces synthetic $0.001/cycle)
521
+ // Recompute cost using same pricing as CostTracker
522
+ const pricing = {
523
+ 'claude-3-opus': { input: 15, output: 75 },
524
+ 'claude-3-sonnet': { input: 3, output: 15 },
525
+ 'claude-3-haiku': { input: 0.25, output: 1.25 },
526
+ 'claude-opus-4': { input: 15, output: 75 },
527
+ 'claude-sonnet-4': { input: 3, output: 15 },
528
+ 'gpt-4o': { input: 2.5, output: 10 },
529
+ 'gpt-4o-mini': { input: 0.15, output: 0.6 },
530
+ 'default': { input: 1, output: 4 },
531
+ };
532
+ const rates = pricing[model] || pricing['default'];
533
+ const realCost = (inputTokens / 1_000_000) * rates.input + (outputTokens / 1_000_000) * rates.output;
534
+ try {
535
+ const fiber = (0, fiber_js_1.getEconomicFiber)();
536
+ fiber.recordCost('llm', realCost, `${provider}:${model}`);
537
+ }
538
+ catch {
539
+ // Fiber may not be initialized yet during startup
540
+ }
517
541
  }
518
542
  /**
519
543
  * Hook to record revenue (call this when receiving payment)
@@ -55,12 +55,26 @@ class ObservationGatherer {
55
55
  if (this.realSourcesInitialized)
56
56
  return;
57
57
  this.realSourcesInitialized = true;
58
- // Wire kernel state to process metrics
58
+ // Wire kernel state to process metrics + FEK total free energy
59
+ // v13.1: Incorporates FEK's hierarchical free energy as the primary energy signal
59
60
  this.getKernelState = () => {
60
61
  const mem = process.memoryUsage();
61
62
  const heapUsedRatio = mem.heapUsed / mem.heapTotal;
62
- // Energy = inverse of resource pressure (more heap used = less energy)
63
- const energy = Math.max(0, Math.min(1, 1 - heapUsedRatio));
63
+ const heapEnergy = Math.max(0, Math.min(1, 1 - heapUsedRatio));
64
+ // v13.1: Blend with FEK's total free energy (low FE = high energy/viability)
65
+ let fekEnergy = heapEnergy;
66
+ try {
67
+ const { getFreeEnergyKernel } = require('../kernel/free-energy-kernel.js');
68
+ const fek = getFreeEnergyKernel();
69
+ if (fek) {
70
+ const totalFE = fek.getTotalFE?.() ?? 0;
71
+ // Map FE to energy: FE=0 → energy=1.0, FE≥5 → energy=0.0
72
+ fekEnergy = Math.max(0, Math.min(1, 1 - totalFE / 5));
73
+ }
74
+ }
75
+ catch { /* FEK may not be initialized */ }
76
+ // Blend: 30% heap pressure, 70% FEK free energy
77
+ const energy = 0.3 * heapEnergy + 0.7 * fekEnergy;
64
78
  return {
65
79
  energy,
66
80
  state: 'running',
@@ -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';
@@ -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
  }
@@ -275,6 +281,27 @@ class Brain {
275
281
  data: { mode, prev, kernel: 'fek' },
276
282
  module: 'consciousness',
277
283
  });
284
+ // v13.1: Close the self-modification loop — when FEK L4 requests
285
+ // self_improving mode, trigger the DarwinGodel improvement engine
286
+ if (mode === 'self_improving' && prev !== 'self_improving' && this.darwinGodel) {
287
+ import('../active-inference/actions.js').then(({ executeAction }) => {
288
+ executeAction('improve.self', {
289
+ parameters: { autoApply: false },
290
+ beliefs: { viability: 0.5, worldState: 0.5, coupling: 0.5, goalProgress: 0.5 },
291
+ }).then((result) => {
292
+ this.emit({
293
+ type: 'module_exit',
294
+ timestamp: new Date(),
295
+ data: {
296
+ type: 'fek_self_improvement',
297
+ success: result.success,
298
+ opportunities: result.data?.opportunities?.length || 0,
299
+ },
300
+ module: 'consciousness',
301
+ });
302
+ }).catch(() => { });
303
+ }).catch(() => { });
304
+ }
278
305
  });
279
306
  }
280
307
  catch {
@@ -737,6 +764,8 @@ class Brain {
737
764
  this.running = true;
738
765
  // v7.2: Build system prompt with available tools
739
766
  await this.initializeSystemPrompt();
767
+ // v13.1: Boot self-knowledge (index own source code)
768
+ this.selfKnowledge.boot().catch(() => { });
740
769
  // Start consciousness monitoring
741
770
  if (this.config.consciousness.enabled) {
742
771
  this.phiMonitor.start();
@@ -1123,6 +1152,14 @@ class Brain {
1123
1152
  }
1124
1153
  // Build context from working memory
1125
1154
  const context = this.buildContext(state);
1155
+ // v13.1: Inject self-knowledge if query is about own code/architecture
1156
+ if (this.selfKnowledge.isReady() && (0, self_knowledge_js_1.isCodeQuery)(state.query)) {
1157
+ const codeContext = this.selfKnowledge.getContext(state.query);
1158
+ if (codeContext) {
1159
+ context.formatted = codeContext + '\n' + context.formatted;
1160
+ context.tokenEstimate += Math.ceil(codeContext.length / 4);
1161
+ }
1162
+ }
1126
1163
  // Track metrics
1127
1164
  this.metrics.memoryRecalls++;
1128
1165
  const wsMetrics = this.workspace.getMetrics();
@@ -2307,6 +2344,12 @@ class Brain {
2307
2344
  resetMetrics() {
2308
2345
  this.metrics = this.createInitialMetrics();
2309
2346
  }
2347
+ /**
2348
+ * v13.1: Get self-knowledge module for code queries
2349
+ */
2350
+ getSelfKnowledge() {
2351
+ return this.selfKnowledge;
2352
+ }
2310
2353
  /**
2311
2354
  * v10.4.2: Get unified memory query for cross-store searches
2312
2355
  */
@@ -2465,3 +2508,7 @@ function getBrainInstance() {
2465
2508
  // ============================================================================
2466
2509
  __exportStar(require("./types.js"), exports);
2467
2510
  __exportStar(require("./trace.js"), exports);
2511
+ var self_knowledge_js_2 = require("./self-knowledge.js");
2512
+ Object.defineProperty(exports, "SelfKnowledge", { enumerable: true, get: function () { return self_knowledge_js_2.SelfKnowledge; } });
2513
+ Object.defineProperty(exports, "getSelfKnowledge", { enumerable: true, get: function () { return self_knowledge_js_2.getSelfKnowledge; } });
2514
+ 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
+ }