genesis-ai-cli 10.3.0 → 10.5.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 (57) hide show
  1. package/dist/src/active-inference/core.d.ts +5 -0
  2. package/dist/src/active-inference/core.js +65 -7
  3. package/dist/src/active-inference/types.d.ts +1 -0
  4. package/dist/src/active-inference/types.js +1 -0
  5. package/dist/src/agents/agent-pool.js +17 -6
  6. package/dist/src/agents/memory.d.ts +4 -0
  7. package/dist/src/agents/memory.js +64 -14
  8. package/dist/src/brain/index.d.ts +43 -0
  9. package/dist/src/brain/index.js +293 -0
  10. package/dist/src/cli/block-renderer.d.ts +60 -0
  11. package/dist/src/cli/block-renderer.js +425 -0
  12. package/dist/src/cli/chat-stream-v2.d.ts +75 -0
  13. package/dist/src/cli/chat-stream-v2.js +332 -0
  14. package/dist/src/cli/chat.d.ts +19 -3
  15. package/dist/src/cli/chat.js +387 -151
  16. package/dist/src/cli/reasoning-display.d.ts +64 -0
  17. package/dist/src/cli/reasoning-display.js +345 -0
  18. package/dist/src/cli/sparkline-example.d.ts +41 -0
  19. package/dist/src/cli/sparkline-example.js +128 -0
  20. package/dist/src/cli/sparkline.d.ts +113 -0
  21. package/dist/src/cli/sparkline.js +283 -0
  22. package/dist/src/cli/terminal-detect.d.ts +50 -0
  23. package/dist/src/cli/terminal-detect.js +197 -0
  24. package/dist/src/cli/ui.d.ts +36 -1
  25. package/dist/src/cli/ui.js +96 -13
  26. package/dist/src/index.js +215 -3
  27. package/dist/src/mcp/client-manager.js +3 -0
  28. package/dist/src/mcp/index.js +2 -0
  29. package/dist/src/mcp-server/index.d.ts +1 -0
  30. package/dist/src/mcp-server/index.js +3 -1
  31. package/dist/src/memory/index.d.ts +1 -0
  32. package/dist/src/memory/index.js +11 -1
  33. package/dist/src/memory/unified-query.d.ts +164 -0
  34. package/dist/src/memory/unified-query.js +455 -0
  35. package/dist/src/streaming/context-grounder.d.ts +79 -0
  36. package/dist/src/streaming/context-grounder.js +320 -0
  37. package/dist/src/streaming/hybrid-executor.d.ts +63 -0
  38. package/dist/src/streaming/hybrid-executor.js +529 -0
  39. package/dist/src/streaming/index.d.ts +16 -0
  40. package/dist/src/streaming/index.js +31 -0
  41. package/dist/src/streaming/orchestrator.d.ts +59 -0
  42. package/dist/src/streaming/orchestrator.js +383 -0
  43. package/dist/src/streaming/provider-adapter.d.ts +37 -0
  44. package/dist/src/streaming/provider-adapter.js +540 -0
  45. package/dist/src/streaming/types.d.ts +531 -0
  46. package/dist/src/streaming/types.js +27 -0
  47. package/dist/test/autonomous-loop.test.d.ts +5 -0
  48. package/dist/test/autonomous-loop.test.js +322 -0
  49. package/dist/test/kernel.test.d.ts +5 -0
  50. package/dist/test/kernel.test.js +163 -0
  51. package/dist/test/message-bus.test.d.ts +5 -0
  52. package/dist/test/message-bus.test.js +287 -0
  53. package/dist/test/resilient.test.d.ts +5 -0
  54. package/dist/test/resilient.test.js +233 -0
  55. package/dist/test/thinking.test.d.ts +5 -0
  56. package/dist/test/thinking.test.js +194 -0
  57. package/package.json +1 -1
@@ -59,6 +59,11 @@ export declare class ActiveInferenceEngine {
59
59
  private computeLikelihoods;
60
60
  private updateFactor;
61
61
  private computeEFE;
62
+ /**
63
+ * Compute expected information gain for an action
64
+ * This is the epistemic value - how much the action teaches us about the world
65
+ */
66
+ private computeInformationGain;
62
67
  private predictNextState;
63
68
  private computeSurprise;
64
69
  /**
@@ -54,9 +54,9 @@ function entropy(probs) {
54
54
  }
55
55
  /**
56
56
  * KL divergence: D_KL(P || Q)
57
- * Reserved for future variational free energy computation
57
+ * Used for information gain and variational free energy computation
58
58
  */
59
- function _klDivergence(p, q) {
59
+ function klDivergence(p, q) {
60
60
  return p.reduce((acc, pi, i) => {
61
61
  if (pi > 1e-10 && q[i] > 1e-10) {
62
62
  return acc + pi * Math.log(pi / q[i]);
@@ -442,28 +442,86 @@ class ActiveInferenceEngine {
442
442
  }
443
443
  computeEFE(actionIdx) {
444
444
  // Expected Free Energy for a single action
445
+ // EFE = Ambiguity + Risk - Information Gain (Friston 2017)
446
+ //
447
+ // - Ambiguity: H(o|s,π) - observational uncertainty
448
+ // - Risk: D_KL[Q(s|π) || P(s)] - divergence from preferred outcomes
449
+ // - Information Gain: E[D_KL[Q(s|o,π) || Q(s|π)]] - epistemic value (SUBTRACTED!)
445
450
  // 1. Predicted next state distribution Q(s'|a)
446
451
  const predictedViability = this.predictNextState(this.beliefs.viability, this.B.viability, actionIdx);
447
452
  const predictedWorldState = this.predictNextState(this.beliefs.worldState, this.B.worldState, actionIdx);
448
453
  const predictedCoupling = this.predictNextState(this.beliefs.coupling, this.B.coupling, actionIdx);
449
454
  const predictedGoalProgress = this.predictNextState(this.beliefs.goalProgress, this.B.goalProgress, actionIdx);
450
- // 2. Expected observations under predicted states
455
+ // 2. Expected observations under predicted states P(o|s')
451
456
  const expectedEnergy = matVec(this.A.energy, predictedViability);
452
457
  const expectedPhi = matVec(this.A.phi, predictedWorldState);
453
458
  const expectedTool = matVec(this.A.tool, predictedCoupling);
454
459
  const expectedTask = matVec(this.A.task, predictedGoalProgress);
455
- // 3. Ambiguity: entropy of predicted observations
460
+ // 3. Ambiguity: H(o|s,π) - entropy of predicted observations
461
+ // High ambiguity = uncertain what we'll observe = BAD
456
462
  const ambiguity = entropy(expectedEnergy) +
457
463
  entropy(expectedPhi) +
458
464
  entropy(expectedTool) +
459
465
  entropy(expectedTask);
460
- // 4. Risk: negative expected utility (preferences)
466
+ // 4. Risk: negative expected utility (pragmatic value)
467
+ // High risk = far from preferred outcomes = BAD
461
468
  const risk = -dot(expectedEnergy, this.C.energy) +
462
469
  -dot(expectedPhi, this.C.phi) +
463
470
  -dot(expectedTool, this.C.tool) +
464
471
  -dot(expectedTask, this.C.task);
465
- // EFE = ambiguity + risk
466
- return ambiguity + risk;
472
+ // 5. Information Gain (epistemic value): E[D_KL[Q(s|o,π) || Q(s|π)]]
473
+ // Approximated as mutual information between states and observations
474
+ // High info gain = action will teach us something = GOOD (subtract from EFE)
475
+ const infoGain = this.computeInformationGain(actionIdx, predictedViability, predictedWorldState, predictedCoupling, predictedGoalProgress);
476
+ // EFE = ambiguity + risk - infoGain
477
+ // Lower is better: reduce ambiguity, reduce risk, increase information gain
478
+ return ambiguity + risk - this.config.explorationBonus * infoGain;
479
+ }
480
+ /**
481
+ * Compute expected information gain for an action
482
+ * This is the epistemic value - how much the action teaches us about the world
483
+ */
484
+ computeInformationGain(actionIdx, predViability, predWorld, predCoupling, predGoal) {
485
+ // Information gain ≈ I(S'; O|a) = H(O|a) - H(O|S',a)
486
+ // = entropy of predicted observations - expected conditional entropy
487
+ // Predicted observation distributions
488
+ const predObs = {
489
+ energy: matVec(this.A.energy, predViability),
490
+ phi: matVec(this.A.phi, predWorld),
491
+ tool: matVec(this.A.tool, predCoupling),
492
+ task: matVec(this.A.task, predGoal),
493
+ };
494
+ // Marginal entropy of observations H(O|a)
495
+ const marginalEntropy = entropy(predObs.energy) +
496
+ entropy(predObs.phi) +
497
+ entropy(predObs.tool) +
498
+ entropy(predObs.task);
499
+ // Conditional entropy H(O|S',a) - weighted average of observation entropy per state
500
+ // This is lower when the A matrices are more deterministic (less ambiguous)
501
+ let conditionalEntropy = 0;
502
+ // For each state, compute weighted entropy of observations
503
+ for (let s = 0; s < predViability.length; s++) {
504
+ if (predViability[s] > 1e-10) {
505
+ conditionalEntropy += predViability[s] * entropy(this.A.energy[s] || []);
506
+ }
507
+ }
508
+ for (let s = 0; s < predWorld.length; s++) {
509
+ if (predWorld[s] > 1e-10) {
510
+ conditionalEntropy += predWorld[s] * entropy(this.A.phi[s] || []);
511
+ }
512
+ }
513
+ for (let s = 0; s < predCoupling.length; s++) {
514
+ if (predCoupling[s] > 1e-10) {
515
+ conditionalEntropy += predCoupling[s] * entropy(this.A.tool[s] || []);
516
+ }
517
+ }
518
+ for (let s = 0; s < predGoal.length; s++) {
519
+ if (predGoal[s] > 1e-10) {
520
+ conditionalEntropy += predGoal[s] * entropy(this.A.task[s] || []);
521
+ }
522
+ }
523
+ // Information gain = marginal - conditional (always >= 0 by data processing inequality)
524
+ return Math.max(0, marginalEntropy - conditionalEntropy);
467
525
  }
468
526
  predictNextState(currentBeliefs, transitionMatrix, actionIdx) {
469
527
  // P(s'|a) = sum_s P(s'|s,a) * P(s)
@@ -143,6 +143,7 @@ export interface ActiveInferenceConfig {
143
143
  priorWeight: number;
144
144
  learningRateA: number;
145
145
  learningRateB: number;
146
+ explorationBonus: number;
146
147
  }
147
148
  export declare const DEFAULT_CONFIG: ActiveInferenceConfig;
148
149
  export type AIEventType = 'beliefs_updated' | 'policy_inferred' | 'action_selected' | 'action_executed' | 'observation_received' | 'surprise_high' | 'goal_achieved' | 'energy_critical';
@@ -85,4 +85,5 @@ exports.DEFAULT_CONFIG = {
85
85
  priorWeight: 0.1,
86
86
  learningRateA: 0.01,
87
87
  learningRateB: 0.01,
88
+ explorationBonus: 1.0, // Balance exploration vs exploitation (higher = more exploration)
88
89
  };
@@ -335,29 +335,40 @@ class AgentPool {
335
335
  }
336
336
  async getFromPool(agentType) {
337
337
  const poolEntries = this.pool.get(agentType) || [];
338
- // Find available (not busy) agent
338
+ // Atomically find and claim available agent
339
339
  const available = poolEntries.find(e => !e.busy && e.agent.state === 'idle');
340
340
  if (available) {
341
+ // Mark as busy immediately to prevent race conditions
342
+ available.busy = true;
341
343
  return available;
342
344
  }
343
345
  // Check if we can spawn more
344
346
  if (poolEntries.length >= this.config.maxAgentsPerType) {
345
347
  // Wait for one to become available
346
- await new Promise(resolve => {
348
+ const claimed = await new Promise(resolve => {
349
+ let resolved = false;
347
350
  const check = setInterval(() => {
351
+ if (resolved)
352
+ return;
353
+ // Atomically claim first free agent
348
354
  const free = poolEntries.find(e => !e.busy);
349
355
  if (free) {
356
+ free.busy = true; // Claim it immediately
357
+ resolved = true;
350
358
  clearInterval(check);
351
- resolve();
359
+ resolve(free);
352
360
  }
353
361
  }, 100);
354
362
  // Timeout after 5s
355
363
  setTimeout(() => {
356
- clearInterval(check);
357
- resolve();
364
+ if (!resolved) {
365
+ resolved = true;
366
+ clearInterval(check);
367
+ resolve(null);
368
+ }
358
369
  }, 5000);
359
370
  });
360
- return poolEntries.find(e => !e.busy) || null;
371
+ return claimed;
361
372
  }
362
373
  return null;
363
374
  }
@@ -28,6 +28,10 @@ export declare class MemoryAgent extends BaseAgent {
28
28
  associations?: string[];
29
29
  }): MemoryItem;
30
30
  private addToWorkingMemory;
31
+ private addToShortTermMemory;
32
+ private evictWeakestFromShortTerm;
33
+ private addToLongTermMemory;
34
+ private evictWeakestFromLongTerm;
31
35
  private handleRetrieve;
32
36
  retrieve(query: MemoryQuery): MemoryItem[];
33
37
  private matchesQuery;
@@ -119,8 +119,54 @@ class MemoryAgent extends base_agent_js_1.BaseAgent {
119
119
  // Enforce capacity limit
120
120
  while (this.workingMemory.length > MEMORY_LIMITS.WORKING) {
121
121
  const evicted = this.workingMemory.shift();
122
- // Move to short-term
123
- this.shortTermMemory.set(evicted.id, evicted);
122
+ // Move to short-term (with size limit enforcement)
123
+ this.addToShortTermMemory(evicted);
124
+ }
125
+ }
126
+ addToShortTermMemory(memory) {
127
+ // Enforce short-term capacity - evict weakest if full
128
+ if (this.shortTermMemory.size >= MEMORY_LIMITS.SHORT_TERM) {
129
+ this.evictWeakestFromShortTerm();
130
+ }
131
+ this.shortTermMemory.set(memory.id, memory);
132
+ }
133
+ evictWeakestFromShortTerm() {
134
+ let weakestId = null;
135
+ let weakestScore = Infinity;
136
+ for (const [id, memory] of this.shortTermMemory) {
137
+ const score = this.calculateConsolidationScore(memory);
138
+ if (score < weakestScore) {
139
+ weakestScore = score;
140
+ weakestId = id;
141
+ }
142
+ }
143
+ if (weakestId) {
144
+ const evicted = this.shortTermMemory.get(weakestId);
145
+ this.shortTermMemory.delete(weakestId);
146
+ this.removeAssociations(evicted);
147
+ }
148
+ }
149
+ addToLongTermMemory(memory) {
150
+ // Enforce long-term capacity - evict weakest if full
151
+ if (this.longTermMemory.size >= MEMORY_LIMITS.LONG_TERM) {
152
+ this.evictWeakestFromLongTerm();
153
+ }
154
+ this.longTermMemory.set(memory.id, memory);
155
+ }
156
+ evictWeakestFromLongTerm() {
157
+ let weakestId = null;
158
+ let weakestRetention = Infinity;
159
+ for (const [id, memory] of this.longTermMemory) {
160
+ const retention = this.getRetention(memory);
161
+ if (retention < weakestRetention) {
162
+ weakestRetention = retention;
163
+ weakestId = id;
164
+ }
165
+ }
166
+ if (weakestId) {
167
+ const evicted = this.longTermMemory.get(weakestId);
168
+ this.longTermMemory.delete(weakestId);
169
+ this.removeAssociations(evicted);
124
170
  }
125
171
  }
126
172
  // ============================================================================
@@ -252,7 +298,6 @@ class MemoryAgent extends base_agent_js_1.BaseAgent {
252
298
  * 5. Prune weak memories
253
299
  */
254
300
  consolidate() {
255
- this.log('Starting consolidation cycle...');
256
301
  let consolidated = 0;
257
302
  let forgotten = 0;
258
303
  let kept = 0;
@@ -260,9 +305,9 @@ class MemoryAgent extends base_agent_js_1.BaseAgent {
260
305
  for (const [id, memory] of this.shortTermMemory) {
261
306
  const score = this.calculateConsolidationScore(memory);
262
307
  if (score >= MEMORY_THRESHOLDS.CONSOLIDATE) {
263
- // Move to long-term
308
+ // Move to long-term (with size limit enforcement)
264
309
  memory.consolidated = true;
265
- this.longTermMemory.set(id, memory);
310
+ this.addToLongTermMemory(memory);
266
311
  this.shortTermMemory.delete(id);
267
312
  consolidated++;
268
313
  }
@@ -286,15 +331,20 @@ class MemoryAgent extends base_agent_js_1.BaseAgent {
286
331
  }
287
332
  }
288
333
  this.lastConsolidation = new Date();
289
- this.log(`Consolidation complete: ${consolidated} consolidated, ${forgotten} forgotten, ${kept} kept`);
290
- // Broadcast consolidation event
291
- this.broadcast('MEMORY_STORE', {
292
- event: 'consolidation',
293
- consolidated,
294
- forgotten,
295
- kept,
296
- totalMemories: this.getTotalMemoryCount(),
297
- });
334
+ // Only log if something happened
335
+ if (consolidated > 0 || forgotten > 0) {
336
+ this.log(`Consolidation: ${consolidated} consolidated, ${forgotten} forgotten, ${kept} kept`);
337
+ }
338
+ // Broadcast consolidation event only if something changed
339
+ if (consolidated > 0 || forgotten > 0) {
340
+ this.broadcast('MEMORY_STORE', {
341
+ event: 'consolidation',
342
+ consolidated,
343
+ forgotten,
344
+ kept,
345
+ totalMemories: this.getTotalMemoryCount(),
346
+ });
347
+ }
298
348
  }
299
349
  calculateConsolidationScore(memory) {
300
350
  const retention = this.getRetention(memory);
@@ -38,6 +38,7 @@
38
38
  * ```
39
39
  */
40
40
  import { BrainState, BrainConfig, BrainMetrics, BrainEventHandler } from './types.js';
41
+ import { UnifiedMemoryQuery } from '../memory/unified-query.js';
41
42
  export declare class Brain {
42
43
  private config;
43
44
  private workspace;
@@ -54,6 +55,7 @@ export declare class Brain {
54
55
  private worldModel;
55
56
  private darwinGodel;
56
57
  private persistence;
58
+ private unifiedQuery;
57
59
  private toolCache;
58
60
  private readonly TOOL_CACHE_TTL;
59
61
  private readonly TOOL_CACHE_MAX_SIZE;
@@ -68,6 +70,35 @@ export declare class Brain {
68
70
  * v7.18: Connect real PhiMonitor and dispatcher for full integration
69
71
  */
70
72
  private initializeV713Modules;
73
+ /**
74
+ * v10.4.2: Wire all memory sources to the unified query interface
75
+ */
76
+ private wireUnifiedMemoryQuery;
77
+ /**
78
+ * v10.4.1: Register Brain modules as GWT modules for proper cognitive broadcasting
79
+ */
80
+ private registerModulesInGlobalWorkspace;
81
+ /**
82
+ * Create a GWT memory module adapter for the Cognitive Workspace
83
+ */
84
+ private createMemoryModule;
85
+ /**
86
+ * Create a GWT executive module adapter for the Thinking Engine
87
+ */
88
+ private createExecutiveModule;
89
+ /**
90
+ * Create a GWT perceptual/motor module adapter for the LLM Bridge
91
+ */
92
+ private createLLMModule;
93
+ /**
94
+ * v10.4.1: Wire PhiMonitor to real system state for actual φ calculation
95
+ * Without this, PhiMonitor just simulates random values
96
+ */
97
+ private wirePhiMonitorToRealState;
98
+ /**
99
+ * Build SystemState from actual Brain components for φ calculation
100
+ */
101
+ private buildSystemState;
71
102
  /**
72
103
  * Start the brain (initializes consciousness monitoring)
73
104
  */
@@ -286,6 +317,18 @@ export declare class Brain {
286
317
  * Reset metrics
287
318
  */
288
319
  resetMetrics(): void;
320
+ /**
321
+ * v10.4.2: Get unified memory query for cross-store searches
322
+ */
323
+ getUnifiedQuery(): UnifiedMemoryQuery;
324
+ /**
325
+ * v10.4.2: Search all memory sources with a single query
326
+ */
327
+ searchAllMemory(query: string, options?: {
328
+ limit?: number;
329
+ types?: ('episodic' | 'semantic' | 'procedural' | 'item')[];
330
+ minImportance?: number;
331
+ }): Promise<import('../memory/unified-query.js').UnifiedSearchResult>;
289
332
  /**
290
333
  * Subscribe to brain events
291
334
  */