genesis-ai-cli 7.4.5

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 (227) hide show
  1. package/.env.example +78 -0
  2. package/README.md +282 -0
  3. package/dist/src/active-inference/actions.d.ts +75 -0
  4. package/dist/src/active-inference/actions.js +250 -0
  5. package/dist/src/active-inference/autonomous-loop.d.ts +103 -0
  6. package/dist/src/active-inference/autonomous-loop.js +289 -0
  7. package/dist/src/active-inference/core.d.ts +85 -0
  8. package/dist/src/active-inference/core.js +555 -0
  9. package/dist/src/active-inference/demo-autonomous-loop.d.ts +8 -0
  10. package/dist/src/active-inference/demo-autonomous-loop.js +338 -0
  11. package/dist/src/active-inference/demo-value-integration.d.ts +8 -0
  12. package/dist/src/active-inference/demo-value-integration.js +174 -0
  13. package/dist/src/active-inference/index.d.ts +32 -0
  14. package/dist/src/active-inference/index.js +88 -0
  15. package/dist/src/active-inference/integration.d.ts +114 -0
  16. package/dist/src/active-inference/integration.js +698 -0
  17. package/dist/src/active-inference/memory-integration.d.ts +51 -0
  18. package/dist/src/active-inference/memory-integration.js +232 -0
  19. package/dist/src/active-inference/observations.d.ts +67 -0
  20. package/dist/src/active-inference/observations.js +147 -0
  21. package/dist/src/active-inference/test-active-inference.d.ts +8 -0
  22. package/dist/src/active-inference/test-active-inference.js +320 -0
  23. package/dist/src/active-inference/test-value-integration.d.ts +6 -0
  24. package/dist/src/active-inference/test-value-integration.js +168 -0
  25. package/dist/src/active-inference/types.d.ts +150 -0
  26. package/dist/src/active-inference/types.js +59 -0
  27. package/dist/src/active-inference/value-integration.d.ts +164 -0
  28. package/dist/src/active-inference/value-integration.js +459 -0
  29. package/dist/src/agents/base-agent.d.ts +53 -0
  30. package/dist/src/agents/base-agent.js +178 -0
  31. package/dist/src/agents/builder.d.ts +67 -0
  32. package/dist/src/agents/builder.js +537 -0
  33. package/dist/src/agents/critic.d.ts +35 -0
  34. package/dist/src/agents/critic.js +322 -0
  35. package/dist/src/agents/ethicist.d.ts +54 -0
  36. package/dist/src/agents/ethicist.js +393 -0
  37. package/dist/src/agents/explorer.d.ts +26 -0
  38. package/dist/src/agents/explorer.js +216 -0
  39. package/dist/src/agents/feeling.d.ts +41 -0
  40. package/dist/src/agents/feeling.js +320 -0
  41. package/dist/src/agents/index.d.ts +111 -0
  42. package/dist/src/agents/index.js +222 -0
  43. package/dist/src/agents/memory.d.ts +69 -0
  44. package/dist/src/agents/memory.js +404 -0
  45. package/dist/src/agents/message-bus.d.ts +88 -0
  46. package/dist/src/agents/message-bus.js +267 -0
  47. package/dist/src/agents/narrator.d.ts +90 -0
  48. package/dist/src/agents/narrator.js +473 -0
  49. package/dist/src/agents/planner.d.ts +38 -0
  50. package/dist/src/agents/planner.js +341 -0
  51. package/dist/src/agents/predictor.d.ts +73 -0
  52. package/dist/src/agents/predictor.js +506 -0
  53. package/dist/src/agents/sensor.d.ts +88 -0
  54. package/dist/src/agents/sensor.js +377 -0
  55. package/dist/src/agents/test-agents.d.ts +6 -0
  56. package/dist/src/agents/test-agents.js +73 -0
  57. package/dist/src/agents/types.d.ts +194 -0
  58. package/dist/src/agents/types.js +7 -0
  59. package/dist/src/brain/index.d.ts +185 -0
  60. package/dist/src/brain/index.js +843 -0
  61. package/dist/src/brain/trace.d.ts +91 -0
  62. package/dist/src/brain/trace.js +327 -0
  63. package/dist/src/brain/types.d.ts +165 -0
  64. package/dist/src/brain/types.js +51 -0
  65. package/dist/src/cli/chat.d.ts +237 -0
  66. package/dist/src/cli/chat.js +1959 -0
  67. package/dist/src/cli/dispatcher.d.ts +182 -0
  68. package/dist/src/cli/dispatcher.js +718 -0
  69. package/dist/src/cli/human-loop.d.ts +170 -0
  70. package/dist/src/cli/human-loop.js +543 -0
  71. package/dist/src/cli/index.d.ts +12 -0
  72. package/dist/src/cli/index.js +28 -0
  73. package/dist/src/cli/interactive.d.ts +141 -0
  74. package/dist/src/cli/interactive.js +757 -0
  75. package/dist/src/cli/ui.d.ts +205 -0
  76. package/dist/src/cli/ui.js +632 -0
  77. package/dist/src/consciousness/attention-schema.d.ts +154 -0
  78. package/dist/src/consciousness/attention-schema.js +432 -0
  79. package/dist/src/consciousness/global-workspace.d.ts +149 -0
  80. package/dist/src/consciousness/global-workspace.js +422 -0
  81. package/dist/src/consciousness/index.d.ts +186 -0
  82. package/dist/src/consciousness/index.js +476 -0
  83. package/dist/src/consciousness/phi-calculator.d.ts +119 -0
  84. package/dist/src/consciousness/phi-calculator.js +445 -0
  85. package/dist/src/consciousness/phi-decisions.d.ts +169 -0
  86. package/dist/src/consciousness/phi-decisions.js +383 -0
  87. package/dist/src/consciousness/phi-monitor.d.ts +153 -0
  88. package/dist/src/consciousness/phi-monitor.js +465 -0
  89. package/dist/src/consciousness/types.d.ts +260 -0
  90. package/dist/src/consciousness/types.js +44 -0
  91. package/dist/src/daemon/dream-mode.d.ts +115 -0
  92. package/dist/src/daemon/dream-mode.js +470 -0
  93. package/dist/src/daemon/index.d.ts +162 -0
  94. package/dist/src/daemon/index.js +542 -0
  95. package/dist/src/daemon/maintenance.d.ts +139 -0
  96. package/dist/src/daemon/maintenance.js +549 -0
  97. package/dist/src/daemon/process.d.ts +82 -0
  98. package/dist/src/daemon/process.js +442 -0
  99. package/dist/src/daemon/scheduler.d.ts +90 -0
  100. package/dist/src/daemon/scheduler.js +494 -0
  101. package/dist/src/daemon/types.d.ts +213 -0
  102. package/dist/src/daemon/types.js +50 -0
  103. package/dist/src/epistemic/index.d.ts +74 -0
  104. package/dist/src/epistemic/index.js +225 -0
  105. package/dist/src/grounding/epistemic-stack.d.ts +100 -0
  106. package/dist/src/grounding/epistemic-stack.js +408 -0
  107. package/dist/src/grounding/feedback.d.ts +98 -0
  108. package/dist/src/grounding/feedback.js +276 -0
  109. package/dist/src/grounding/index.d.ts +123 -0
  110. package/dist/src/grounding/index.js +224 -0
  111. package/dist/src/grounding/verifier.d.ts +149 -0
  112. package/dist/src/grounding/verifier.js +484 -0
  113. package/dist/src/healing/detector.d.ts +110 -0
  114. package/dist/src/healing/detector.js +436 -0
  115. package/dist/src/healing/fixer.d.ts +138 -0
  116. package/dist/src/healing/fixer.js +572 -0
  117. package/dist/src/healing/index.d.ts +23 -0
  118. package/dist/src/healing/index.js +43 -0
  119. package/dist/src/hooks/index.d.ts +135 -0
  120. package/dist/src/hooks/index.js +317 -0
  121. package/dist/src/index.d.ts +23 -0
  122. package/dist/src/index.js +1266 -0
  123. package/dist/src/kernel/index.d.ts +155 -0
  124. package/dist/src/kernel/index.js +795 -0
  125. package/dist/src/kernel/invariants.d.ts +153 -0
  126. package/dist/src/kernel/invariants.js +355 -0
  127. package/dist/src/kernel/test-kernel.d.ts +6 -0
  128. package/dist/src/kernel/test-kernel.js +108 -0
  129. package/dist/src/kernel/test-real-mcp.d.ts +10 -0
  130. package/dist/src/kernel/test-real-mcp.js +295 -0
  131. package/dist/src/llm/index.d.ts +146 -0
  132. package/dist/src/llm/index.js +428 -0
  133. package/dist/src/llm/router.d.ts +136 -0
  134. package/dist/src/llm/router.js +510 -0
  135. package/dist/src/mcp/index.d.ts +85 -0
  136. package/dist/src/mcp/index.js +657 -0
  137. package/dist/src/mcp/resilient.d.ts +139 -0
  138. package/dist/src/mcp/resilient.js +417 -0
  139. package/dist/src/memory/cache.d.ts +118 -0
  140. package/dist/src/memory/cache.js +356 -0
  141. package/dist/src/memory/cognitive-workspace.d.ts +231 -0
  142. package/dist/src/memory/cognitive-workspace.js +521 -0
  143. package/dist/src/memory/consolidation.d.ts +99 -0
  144. package/dist/src/memory/consolidation.js +443 -0
  145. package/dist/src/memory/episodic.d.ts +114 -0
  146. package/dist/src/memory/episodic.js +394 -0
  147. package/dist/src/memory/forgetting.d.ts +134 -0
  148. package/dist/src/memory/forgetting.js +324 -0
  149. package/dist/src/memory/index.d.ts +211 -0
  150. package/dist/src/memory/index.js +367 -0
  151. package/dist/src/memory/indexer.d.ts +123 -0
  152. package/dist/src/memory/indexer.js +479 -0
  153. package/dist/src/memory/procedural.d.ts +136 -0
  154. package/dist/src/memory/procedural.js +479 -0
  155. package/dist/src/memory/semantic.d.ts +132 -0
  156. package/dist/src/memory/semantic.js +497 -0
  157. package/dist/src/memory/types.d.ts +193 -0
  158. package/dist/src/memory/types.js +15 -0
  159. package/dist/src/orchestrator.d.ts +65 -0
  160. package/dist/src/orchestrator.js +317 -0
  161. package/dist/src/persistence/index.d.ts +257 -0
  162. package/dist/src/persistence/index.js +763 -0
  163. package/dist/src/pipeline/executor.d.ts +51 -0
  164. package/dist/src/pipeline/executor.js +695 -0
  165. package/dist/src/pipeline/index.d.ts +7 -0
  166. package/dist/src/pipeline/index.js +11 -0
  167. package/dist/src/self-production.d.ts +67 -0
  168. package/dist/src/self-production.js +205 -0
  169. package/dist/src/subagents/executor.d.ts +58 -0
  170. package/dist/src/subagents/executor.js +283 -0
  171. package/dist/src/subagents/index.d.ts +37 -0
  172. package/dist/src/subagents/index.js +53 -0
  173. package/dist/src/subagents/registry.d.ts +23 -0
  174. package/dist/src/subagents/registry.js +167 -0
  175. package/dist/src/subagents/types.d.ts +79 -0
  176. package/dist/src/subagents/types.js +14 -0
  177. package/dist/src/tools/bash.d.ts +139 -0
  178. package/dist/src/tools/bash.js +583 -0
  179. package/dist/src/tools/edit.d.ts +125 -0
  180. package/dist/src/tools/edit.js +424 -0
  181. package/dist/src/tools/git.d.ts +179 -0
  182. package/dist/src/tools/git.js +504 -0
  183. package/dist/src/tools/index.d.ts +21 -0
  184. package/dist/src/tools/index.js +163 -0
  185. package/dist/src/types.d.ts +145 -0
  186. package/dist/src/types.js +7 -0
  187. package/dist/src/world-model/decoder.d.ts +163 -0
  188. package/dist/src/world-model/decoder.js +517 -0
  189. package/dist/src/world-model/digital-twin.d.ts +219 -0
  190. package/dist/src/world-model/digital-twin.js +695 -0
  191. package/dist/src/world-model/encoder.d.ts +141 -0
  192. package/dist/src/world-model/encoder.js +564 -0
  193. package/dist/src/world-model/index.d.ts +221 -0
  194. package/dist/src/world-model/index.js +772 -0
  195. package/dist/src/world-model/predictor.d.ts +161 -0
  196. package/dist/src/world-model/predictor.js +681 -0
  197. package/dist/src/world-model/test-value-jepa.d.ts +8 -0
  198. package/dist/src/world-model/test-value-jepa.js +430 -0
  199. package/dist/src/world-model/types.d.ts +341 -0
  200. package/dist/src/world-model/types.js +69 -0
  201. package/dist/src/world-model/value-jepa.d.ts +247 -0
  202. package/dist/src/world-model/value-jepa.js +622 -0
  203. package/dist/test/brain.test.d.ts +11 -0
  204. package/dist/test/brain.test.js +358 -0
  205. package/dist/test/cli/dispatcher.test.d.ts +4 -0
  206. package/dist/test/cli/dispatcher.test.js +332 -0
  207. package/dist/test/cli/human-loop.test.d.ts +4 -0
  208. package/dist/test/cli/human-loop.test.js +270 -0
  209. package/dist/test/grounding/feedback.test.d.ts +4 -0
  210. package/dist/test/grounding/feedback.test.js +462 -0
  211. package/dist/test/grounding/verifier.test.d.ts +4 -0
  212. package/dist/test/grounding/verifier.test.js +442 -0
  213. package/dist/test/grounding.test.d.ts +6 -0
  214. package/dist/test/grounding.test.js +246 -0
  215. package/dist/test/healing/detector.test.d.ts +4 -0
  216. package/dist/test/healing/detector.test.js +266 -0
  217. package/dist/test/healing/fixer.test.d.ts +4 -0
  218. package/dist/test/healing/fixer.test.js +369 -0
  219. package/dist/test/integration.test.d.ts +5 -0
  220. package/dist/test/integration.test.js +290 -0
  221. package/dist/test/tools/bash.test.d.ts +4 -0
  222. package/dist/test/tools/bash.test.js +348 -0
  223. package/dist/test/tools/edit.test.d.ts +4 -0
  224. package/dist/test/tools/edit.test.js +350 -0
  225. package/dist/test/tools/git.test.d.ts +4 -0
  226. package/dist/test/tools/git.test.js +350 -0
  227. package/package.json +60 -0
@@ -0,0 +1,1959 @@
1
+ "use strict";
2
+ /**
3
+ * Genesis v7.1 - Integrated Chat CLI
4
+ *
5
+ * REPL interface to talk to Genesis using readline.
6
+ * No external dependencies.
7
+ *
8
+ * v7.1 Updates:
9
+ * - Brain AUTO-START by default (Phase 10 always active)
10
+ * - Active Inference integrated into response cycle
11
+ * - Value-JEPA world model connected
12
+ * - Curiosity-driven behavior enabled
13
+ * - Φ monitoring shown in every response
14
+ * - All advanced modules wired together
15
+ *
16
+ * Architecture:
17
+ * ```
18
+ * User Input → Brain → Memory + Active Inference → LLM → Grounding → Tools → Response
19
+ * ↓
20
+ * Value-JEPA (curiosity) → Expected Free Energy → Policy Selection
21
+ * ↓
22
+ * Φ Monitor → Global Workspace Broadcast
23
+ * ```
24
+ */
25
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
26
+ if (k2 === undefined) k2 = k;
27
+ var desc = Object.getOwnPropertyDescriptor(m, k);
28
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
29
+ desc = { enumerable: true, get: function() { return m[k]; } };
30
+ }
31
+ Object.defineProperty(o, k2, desc);
32
+ }) : (function(o, m, k, k2) {
33
+ if (k2 === undefined) k2 = k;
34
+ o[k2] = m[k];
35
+ }));
36
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
37
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
38
+ }) : function(o, v) {
39
+ o["default"] = v;
40
+ });
41
+ var __importStar = (this && this.__importStar) || (function () {
42
+ var ownKeys = function(o) {
43
+ ownKeys = Object.getOwnPropertyNames || function (o) {
44
+ var ar = [];
45
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
46
+ return ar;
47
+ };
48
+ return ownKeys(o);
49
+ };
50
+ return function (mod) {
51
+ if (mod && mod.__esModule) return mod;
52
+ var result = {};
53
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
54
+ __setModuleDefault(result, mod);
55
+ return result;
56
+ };
57
+ })();
58
+ Object.defineProperty(exports, "__esModule", { value: true });
59
+ exports.ChatSession = void 0;
60
+ exports.createChatSession = createChatSession;
61
+ exports.startChat = startChat;
62
+ exports.runHeadless = runHeadless;
63
+ exports.readStdin = readStdin;
64
+ const readline = __importStar(require("readline"));
65
+ const index_js_1 = require("../llm/index.js");
66
+ const index_js_2 = require("../persistence/index.js");
67
+ const dispatcher_js_1 = require("./dispatcher.js");
68
+ const index_js_3 = require("../mcp/index.js");
69
+ const index_js_4 = require("../brain/index.js");
70
+ const index_js_5 = require("../memory/index.js");
71
+ const index_js_6 = require("../healing/index.js");
72
+ const self_production_js_1 = require("../self-production.js");
73
+ // v7.1: Active Inference integration
74
+ const index_js_7 = require("../active-inference/index.js");
75
+ // v7.4: Subagent System
76
+ const index_js_8 = require("../subagents/index.js");
77
+ // v7.4.5: Hooks System
78
+ const index_js_9 = require("../hooks/index.js");
79
+ const ui_js_1 = require("./ui.js");
80
+ class ChatSession {
81
+ llm;
82
+ store;
83
+ dispatcher;
84
+ brain; // Phase 10: Brain integration
85
+ brainTrace; // Phase 10: Brain trace visualization
86
+ rl = null;
87
+ running = false;
88
+ verbose;
89
+ enableTools;
90
+ enableBrain; // Phase 10: Brain mode - DEFAULT TRUE in v7.1
91
+ enableTrace; // Phase 10: Brain trace mode
92
+ enableInference; // v7.1: Active Inference mode
93
+ enableCuriosity; // v7.1: Curiosity-driven behavior
94
+ messageCount = 0;
95
+ toolExecutions = 0;
96
+ systemPrompt = ''; // Built dynamically at start()
97
+ // v7.0: Modern UI components
98
+ spinner;
99
+ thinkingSpinner; // v7.3.8: Shows time, module, action
100
+ brainEventUnsub = null; // v7.3.8: Brain event cleanup
101
+ inputHistory;
102
+ memory; // v7.0: Memory system with consolidation
103
+ selfProduction; // v7.0: Darwin-Gödel self-improvement
104
+ // v7.1: Active Inference integration
105
+ inferenceLoop = null;
106
+ lastCuriosity = 0; // Track curiosity level
107
+ lastSurprise = 0; // Track surprise from inference
108
+ // v7.4: Subagent System
109
+ subagentExecutor;
110
+ // v7.4: Background task support
111
+ isProcessing = false; // True when processing a message
112
+ currentTaskAbort = null; // For cancelling current task
113
+ // v7.4: Headless mode
114
+ headlessMode = false;
115
+ outputFormat = 'text';
116
+ // v7.4: Session management
117
+ sessionManager;
118
+ sessionName;
119
+ resumeSessionId;
120
+ // v7.4.4: Extended Thinking visualization
121
+ thinkingSettings;
122
+ // v7.4.5: Hooks System
123
+ hooks;
124
+ constructor(options = {}) {
125
+ this.llm = (0, index_js_1.getLLMBridge)({
126
+ provider: options.provider,
127
+ model: options.model,
128
+ });
129
+ this.store = (0, index_js_2.getStateStore)({ autoSave: true, autoSaveIntervalMs: 60000 });
130
+ this.dispatcher = new dispatcher_js_1.ToolDispatcher({ verbose: options.verbose });
131
+ this.brain = (0, index_js_4.getBrain)(); // Phase 10: Initialize brain
132
+ this.brainTrace = (0, index_js_4.createBrainTrace)(this.brain); // Phase 10: Initialize trace
133
+ this.memory = (0, index_js_5.getMemorySystem)(); // v7.0: Initialize memory with consolidation
134
+ this.selfProduction = (0, self_production_js_1.createSelfProductionEngine)('7.1.0'); // v7.1: Darwin-Gödel
135
+ this.subagentExecutor = (0, index_js_8.getSubagentExecutor)(); // v7.4: Subagent system
136
+ this.subagentExecutor.setDispatcher(this.dispatcher); // v7.4: Wire dispatcher
137
+ this.verbose = options.verbose ?? false;
138
+ this.enableTools = options.enableTools ?? true; // Enabled by default
139
+ this.enableBrain = options.enableBrain ?? true; // v7.1: Brain mode ON by default!
140
+ this.enableTrace = false; // Trace off by default
141
+ this.enableInference = options.enableInference ?? true; // v7.1: Inference ON by default
142
+ this.enableCuriosity = options.enableCuriosity ?? true; // v7.1: Curiosity ON by default
143
+ this.headlessMode = options.headless ?? false; // v7.4: Headless mode
144
+ this.outputFormat = options.outputFormat ?? 'text'; // v7.4: Output format
145
+ this.sessionManager = (0, index_js_2.getSessionManager)(); // v7.4: Session manager
146
+ this.sessionName = options.sessionName; // v7.4: Session name
147
+ this.resumeSessionId = options.resume; // v7.4: Resume session
148
+ this.thinkingSettings = { ...ui_js_1.DEFAULT_THINKING_SETTINGS }; // v7.4.4: Extended thinking
149
+ this.hooks = (0, index_js_9.getHooksManager)(); // v7.4.5: Hooks system
150
+ // v7.0: Initialize UI components
151
+ this.spinner = new ui_js_1.Spinner('Thinking');
152
+ this.thinkingSpinner = new ui_js_1.ThinkingSpinner(); // v7.3.8
153
+ this.inputHistory = new ui_js_1.InputHistory(100);
154
+ // v7.3.8: Subscribe to brain events for thinking visualization
155
+ this.brainEventUnsub = this.brain.on((event) => {
156
+ if (!this.thinkingSpinner.isRunning())
157
+ return;
158
+ switch (event.type) {
159
+ case 'module_enter':
160
+ this.thinkingSpinner.setModule(event.module || '');
161
+ break;
162
+ case 'memory_recall':
163
+ this.thinkingSpinner.setAction('Recalling context');
164
+ break;
165
+ case 'memory_anticipate':
166
+ this.thinkingSpinner.setAction('Anticipating needs');
167
+ break;
168
+ case 'llm_request':
169
+ this.thinkingSpinner.setAction('Generating response');
170
+ break;
171
+ case 'tool_execute':
172
+ const toolCount = event.data?.count || 0;
173
+ this.thinkingSpinner.setAction(`Calling ${toolCount} tool(s)`);
174
+ break;
175
+ case 'grounding_check':
176
+ this.thinkingSpinner.setAction('Verifying facts');
177
+ break;
178
+ case 'healing_start':
179
+ this.thinkingSpinner.setAction('Self-healing');
180
+ break;
181
+ case 'phi_update':
182
+ const phi = event.data?.phi || 0;
183
+ this.thinkingSpinner.setAction(`φ=${phi.toFixed(2)}`);
184
+ break;
185
+ }
186
+ });
187
+ // v7.1: Initialize Active Inference loop
188
+ if (this.enableInference) {
189
+ this.inferenceLoop = (0, index_js_7.createAutonomousLoop)({
190
+ cycleInterval: 0, // No auto-cycling, we trigger manually
191
+ maxCycles: 0,
192
+ verbose: false,
193
+ stopOnGoalAchieved: false,
194
+ stopOnEnergyCritical: true,
195
+ });
196
+ }
197
+ // Restore conversation history from persisted state
198
+ const state = this.store.getState();
199
+ if (state.conversation.history.length > 0) {
200
+ for (const msg of state.conversation.history) {
201
+ this.llm.getHistory().push(msg);
202
+ }
203
+ }
204
+ }
205
+ /**
206
+ * Start interactive chat session
207
+ */
208
+ async start() {
209
+ this.printBanner();
210
+ // v7.4: Handle session resume
211
+ if (this.resumeSessionId) {
212
+ const sessionId = this.resumeSessionId === true ? 'last' : this.resumeSessionId;
213
+ const resumedState = this.sessionManager.loadSession(sessionId);
214
+ if (resumedState) {
215
+ // Restore conversation history
216
+ const history = resumedState.conversation?.history || [];
217
+ for (const msg of history) {
218
+ this.llm.getHistory().push(msg);
219
+ }
220
+ // Update store with resumed state
221
+ this.store.update(resumedState);
222
+ console.log((0, ui_js_1.success)(`✓ Resumed session: ${resumedState.session?.id?.slice(0, 8) || sessionId}`));
223
+ console.log((0, ui_js_1.muted)(` ${history.length} messages, ${resumedState.conversation?.totalTokens || 0} tokens`));
224
+ console.log();
225
+ }
226
+ else {
227
+ console.log((0, ui_js_1.warning)(`Session not found: ${sessionId}`));
228
+ console.log((0, ui_js_1.muted)('Starting new session instead.'));
229
+ console.log();
230
+ }
231
+ }
232
+ // Build dynamic system prompt from available tools (with schemas)
233
+ const tools = this.dispatcher.listToolsWithSchemas();
234
+ this.systemPrompt = await (0, index_js_1.buildSystemPrompt)(tools.mcp, tools.local);
235
+ if (this.verbose) {
236
+ console.log((0, ui_js_1.c)('System prompt built dynamically:', 'dim'));
237
+ console.log((0, ui_js_1.c)(` Local tools: ${tools.local.length}`, 'dim'));
238
+ console.log((0, ui_js_1.c)(` MCP servers: ${Object.keys(tools.mcp).length}`, 'dim'));
239
+ console.log();
240
+ }
241
+ // Check if LLM is configured
242
+ if (!this.llm.isConfigured()) {
243
+ console.log((0, ui_js_1.c)('\nWarning: No API key found!', 'yellow'));
244
+ console.log('Set OPENAI_API_KEY or ANTHROPIC_API_KEY environment variable.\n');
245
+ console.log('Example:');
246
+ console.log((0, ui_js_1.c)(' export OPENAI_API_KEY=sk-...', 'dim'));
247
+ console.log((0, ui_js_1.c)(' export ANTHROPIC_API_KEY=sk-ant-...', 'dim'));
248
+ console.log();
249
+ }
250
+ const status = this.llm.status();
251
+ console.log((0, ui_js_1.c)(`Provider: ${status.provider}`, 'dim'));
252
+ console.log((0, ui_js_1.c)(`Model: ${status.model}`, 'dim'));
253
+ console.log((0, ui_js_1.c)(`Status: ${status.configured ? 'Ready' : 'Not configured'}`, status.configured ? 'green' : 'yellow'));
254
+ // v7.1: Auto-start Brain (always on by default)
255
+ if (this.enableBrain) {
256
+ this.brain.start();
257
+ console.log((0, ui_js_1.c)(`Brain: ${(0, ui_js_1.c)('ACTIVE', 'green')} (Phase 10 Neural Integration)`, 'dim'));
258
+ }
259
+ else {
260
+ console.log((0, ui_js_1.c)(`Brain: ${(0, ui_js_1.c)('OFF', 'yellow')} (use /brain to enable)`, 'dim'));
261
+ }
262
+ // v7.1: Show Active Inference status
263
+ if (this.enableInference) {
264
+ console.log((0, ui_js_1.c)(`Inference: ${(0, ui_js_1.c)('ACTIVE', 'green')} (Active Inference + Value-JEPA)`, 'dim'));
265
+ }
266
+ if (this.enableCuriosity) {
267
+ console.log((0, ui_js_1.c)(`Curiosity: ${(0, ui_js_1.c)('ACTIVE', 'green')} (Intrinsic motivation enabled)`, 'dim'));
268
+ }
269
+ console.log();
270
+ // v7.3.6: Pre-warm critical MCP servers in background to avoid cold start timeouts
271
+ this.preWarmMCPServers();
272
+ // v7.4.5: Execute session-start hook
273
+ if (this.hooks.hasHooks()) {
274
+ const hookResult = await this.hooks.execute('session-start', {
275
+ event: 'session-start',
276
+ sessionId: this.store.getState().session?.id,
277
+ workingDir: process.cwd(),
278
+ });
279
+ if (hookResult?.blocked) {
280
+ console.log((0, ui_js_1.error)('Session blocked by hook'));
281
+ process.exit(1);
282
+ }
283
+ }
284
+ this.printHelp();
285
+ this.rl = readline.createInterface({
286
+ input: process.stdin,
287
+ output: process.stdout,
288
+ });
289
+ // v7.4: Enable keypress events for shortcuts (Ctrl+B, Ctrl+R, etc.)
290
+ if (process.stdin.isTTY) {
291
+ readline.emitKeypressEvents(process.stdin, this.rl);
292
+ process.stdin.on('keypress', (str, key) => {
293
+ this.handleKeypress(str, key);
294
+ });
295
+ }
296
+ this.running = true;
297
+ await this.chatLoop();
298
+ }
299
+ /**
300
+ * v7.4: Handle keyboard shortcuts
301
+ */
302
+ handleKeypress(_str, key) {
303
+ if (!key)
304
+ return;
305
+ // Ctrl+B: Background current task
306
+ if (key.ctrl && key.name === 'b') {
307
+ if (this.isProcessing) {
308
+ console.log();
309
+ console.log((0, ui_js_1.warning)('⏸ Backgrounding current task...'));
310
+ console.log((0, ui_js_1.c)(' Task continues in background. Use /tasks to monitor.', 'dim'));
311
+ console.log();
312
+ // Signal that user wants to background the task
313
+ this.currentTaskAbort?.abort();
314
+ }
315
+ else {
316
+ console.log((0, ui_js_1.c)('\n[Ctrl+B: No task running to background]', 'dim'));
317
+ }
318
+ return;
319
+ }
320
+ // Ctrl+R: Reverse history search (TODO: implement full readline history)
321
+ if (key.ctrl && key.name === 'r') {
322
+ // For now, just show hint - full implementation needs custom readline
323
+ console.log((0, ui_js_1.c)('\n[Ctrl+R: History search - use /history for now]', 'dim'));
324
+ return;
325
+ }
326
+ // Ctrl+L: Clear screen (keep conversation)
327
+ if (key.ctrl && key.name === 'l') {
328
+ console.clear();
329
+ this.printBanner();
330
+ console.log((0, ui_js_1.c)('Screen cleared. Conversation preserved.', 'dim'));
331
+ console.log();
332
+ return;
333
+ }
334
+ // Ctrl+O: Toggle verbose output
335
+ if (key.ctrl && key.name === 'o') {
336
+ this.verbose = !this.verbose;
337
+ console.log((0, ui_js_1.c)(`\n[Verbose: ${this.verbose ? 'ON' : 'OFF'}]`, 'dim'));
338
+ return;
339
+ }
340
+ }
341
+ /**
342
+ * Main chat loop
343
+ */
344
+ async chatLoop() {
345
+ while (this.running && this.rl) {
346
+ const input = await this.prompt();
347
+ if (!input)
348
+ continue;
349
+ // Handle commands
350
+ if (input.startsWith('/')) {
351
+ await this.handleCommand(input);
352
+ continue;
353
+ }
354
+ // Send to LLM
355
+ await this.sendMessage(input);
356
+ }
357
+ }
358
+ /**
359
+ * Prompt for user input (v7.0: with history support)
360
+ */
361
+ prompt() {
362
+ return new Promise((resolve) => {
363
+ this.rl?.question((0, ui_js_1.c)('You: ', 'green'), (answer) => {
364
+ const trimmed = answer.trim();
365
+ // v7.0: Add to history if not empty and not a duplicate
366
+ if (trimmed) {
367
+ this.inputHistory.add(trimmed);
368
+ }
369
+ resolve(trimmed);
370
+ });
371
+ });
372
+ }
373
+ /**
374
+ * Send message to LLM (or Brain if enabled)
375
+ */
376
+ async sendMessage(message) {
377
+ if (!this.llm.isConfigured()) {
378
+ console.log((0, ui_js_1.c)('Error: LLM not configured. Set API key first.', 'red'));
379
+ return;
380
+ }
381
+ // Phase 10: Use Brain for integrated processing
382
+ if (this.enableBrain) {
383
+ await this.sendMessageViaBrain(message);
384
+ return;
385
+ }
386
+ // v7.4: Track processing state for Ctrl+B
387
+ this.isProcessing = true;
388
+ // v7.0: Modern spinner instead of static text
389
+ this.spinner.start('Thinking');
390
+ try {
391
+ const response = await this.llm.chat(message, this.systemPrompt);
392
+ this.messageCount++;
393
+ // v7.0: Stop spinner and print formatted response
394
+ this.spinner.stop();
395
+ // v7.4.4: Process thinking blocks before display
396
+ const { formatted, hasThinking, thinkingCount } = (0, ui_js_1.formatResponseWithThinking)(response.content, this.thinkingSettings.enabled, this.thinkingSettings.collapsed);
397
+ console.log((0, ui_js_1.c)('Genesis: ', 'cyan') + formatted);
398
+ if (this.verbose) {
399
+ console.log((0, ui_js_1.c)(` [${response.latency}ms, ${response.usage?.outputTokens || '?'} tokens]`, 'dim'));
400
+ }
401
+ // Check for tool calls if tools are enabled
402
+ if (this.enableTools) {
403
+ const toolCalls = this.dispatcher.parseToolCalls(response.content);
404
+ if (toolCalls.length > 0) {
405
+ // v7.0: Progress bar for multi-tool execution
406
+ const progress = new ui_js_1.ProgressBar(toolCalls.length, (0, ui_js_1.info)('Tools'));
407
+ console.log();
408
+ progress.update(0);
409
+ const dispatchResult = await this.dispatcher.dispatch(toolCalls);
410
+ this.toolExecutions += toolCalls.length;
411
+ progress.update(toolCalls.length);
412
+ console.log(); // New line after progress
413
+ // Format results for re-injection
414
+ const toolResults = this.formatToolResults(dispatchResult.results);
415
+ if (this.verbose) {
416
+ console.log((0, ui_js_1.muted)(` Completed in ${(0, ui_js_1.formatDuration)(dispatchResult.totalDuration)}`));
417
+ }
418
+ // v7.0: Show results in a cleaner format
419
+ console.log((0, ui_js_1.c)('\n Tool Results:', 'magenta'));
420
+ for (const result of dispatchResult.results) {
421
+ const status = result.success ? (0, ui_js_1.success)('✓') : (0, ui_js_1.error)('✗');
422
+ const data = result.success
423
+ ? (0, ui_js_1.truncate)(typeof result.data === 'string' ? result.data : JSON.stringify(result.data), 200)
424
+ : result.error;
425
+ console.log(` ${status} ${result.name}: ${data}`);
426
+ }
427
+ console.log();
428
+ // Feed results back to LLM for continued response
429
+ this.spinner.start('Processing results');
430
+ const followUp = await this.llm.chat(`Tool execution results:\n${toolResults}\n\nPlease provide a final response based on these results.`);
431
+ this.spinner.stop();
432
+ // v7.4.4: Process thinking blocks in follow-up
433
+ const followUpFormatted = (0, ui_js_1.formatResponseWithThinking)(followUp.content, this.thinkingSettings.enabled, this.thinkingSettings.collapsed);
434
+ console.log((0, ui_js_1.c)('Genesis: ', 'cyan') + followUpFormatted.formatted);
435
+ }
436
+ }
437
+ // Persist conversation to state
438
+ this.store.updateConversation(this.llm.getHistory(), response.usage?.outputTokens);
439
+ this.store.recordInteraction();
440
+ this.isProcessing = false; // v7.4: Done processing
441
+ console.log();
442
+ }
443
+ catch (err) {
444
+ this.isProcessing = false; // v7.4: Done processing (error)
445
+ // v7.0: Stop spinner on error
446
+ this.spinner.stop();
447
+ const errorMessage = err instanceof Error ? err.message : String(err);
448
+ console.log((0, ui_js_1.error)(`Genesis: Error - ${errorMessage}`));
449
+ console.log();
450
+ }
451
+ }
452
+ /**
453
+ * Format tool results for LLM consumption
454
+ */
455
+ formatToolResults(results) {
456
+ return results.map(r => {
457
+ if (r.success) {
458
+ const data = typeof r.data === 'string' ? r.data : JSON.stringify(r.data, null, 2);
459
+ return `[${r.name}] SUCCESS:\n${data}`;
460
+ }
461
+ else {
462
+ return `[${r.name}] ERROR: ${r.error}`;
463
+ }
464
+ }).join('\n\n');
465
+ }
466
+ /**
467
+ * v7.1: Send message via Brain with Active Inference integration
468
+ *
469
+ * Full pipeline:
470
+ * 1. Active Inference cycle (update beliefs, compute surprise)
471
+ * 2. Curiosity computation (novelty of input)
472
+ * 3. Memory → LLM → Grounding → Tools → Response (via Brain)
473
+ * 4. Φ monitoring and broadcast
474
+ * 5. Value update from outcome
475
+ *
476
+ * Routes through: Memory → LLM → Grounding → Tools → Response
477
+ * With: φ monitoring, Global Workspace broadcasting, self-healing
478
+ */
479
+ async sendMessageViaBrain(message) {
480
+ this.isProcessing = true; // v7.4: Track processing state for Ctrl+B
481
+ // v7.4.5: Execute pre-message hook
482
+ if (this.hooks.hasHooks()) {
483
+ const hookResult = await this.hooks.execute('pre-message', {
484
+ event: 'pre-message',
485
+ message,
486
+ sessionId: this.store.getState().session?.id,
487
+ workingDir: process.cwd(),
488
+ });
489
+ if (hookResult?.blocked) {
490
+ console.log((0, ui_js_1.warning)('Message blocked by hook'));
491
+ this.isProcessing = false;
492
+ return;
493
+ }
494
+ }
495
+ // v7.1: Run Active Inference cycle BEFORE processing
496
+ if (this.enableInference && this.inferenceLoop) {
497
+ try {
498
+ // Run one inference cycle to update beliefs
499
+ const action = await this.inferenceLoop.cycle();
500
+ const stats = this.inferenceLoop.getStats();
501
+ this.lastSurprise = stats.avgSurprise;
502
+ // Compute curiosity based on message novelty
503
+ if (this.enableCuriosity) {
504
+ // Simple heuristic: longer messages with questions = more curious
505
+ const hasQuestion = message.includes('?');
506
+ const wordCount = message.split(/\s+/).length;
507
+ const noveltyKeywords = ['new', 'novel', 'interesting', 'unknown', 'explore', 'discover', 'why', 'how', 'what'];
508
+ const noveltyScore = noveltyKeywords.filter(k => message.toLowerCase().includes(k)).length;
509
+ this.lastCuriosity = Math.min(1, (noveltyScore * 0.15) + (hasQuestion ? 0.2 : 0) + (wordCount > 20 ? 0.1 : 0));
510
+ }
511
+ }
512
+ catch (err) {
513
+ // Inference failure is non-fatal
514
+ if (this.verbose) {
515
+ console.log((0, ui_js_1.c)(` [Inference: ${err instanceof Error ? err.message : err}]`, 'dim'));
516
+ }
517
+ }
518
+ }
519
+ // v7.3.8: Use ThinkingSpinner for Brain processing (shows time, module, action)
520
+ if (!this.enableTrace) {
521
+ this.thinkingSpinner.start();
522
+ }
523
+ try {
524
+ const response = await this.brain.process(message);
525
+ this.messageCount++;
526
+ // v7.3.8: Stop thinking spinner
527
+ if (!this.enableTrace) {
528
+ this.thinkingSpinner.stop();
529
+ }
530
+ // v7.4.4: Process thinking blocks in brain response
531
+ const brainFormatted = (0, ui_js_1.formatResponseWithThinking)(response, this.thinkingSettings.enabled, this.thinkingSettings.collapsed);
532
+ console.log((0, ui_js_1.c)('Genesis: ', 'cyan') + brainFormatted.formatted);
533
+ // v7.1: ALWAYS show Φ and key metrics (not just in verbose mode)
534
+ const metrics = this.brain.getMetrics();
535
+ const phi = metrics.avgPhi;
536
+ const phiIcon = phi >= 0.5 ? '🧠' : phi >= 0.3 ? '💭' : '○';
537
+ const curiosityIcon = this.lastCuriosity >= 0.5 ? '✨' : this.lastCuriosity >= 0.2 ? '?' : '';
538
+ // Compact status line
539
+ const statusParts = [
540
+ `φ=${phi.toFixed(2)}`,
541
+ ];
542
+ if (this.enableCuriosity && this.lastCuriosity > 0) {
543
+ statusParts.push(`curiosity=${this.lastCuriosity.toFixed(2)}`);
544
+ }
545
+ if (this.enableInference && this.lastSurprise > 0) {
546
+ statusParts.push(`surprise=${this.lastSurprise.toFixed(2)}`);
547
+ }
548
+ console.log((0, ui_js_1.c)(` ${phiIcon} [${statusParts.join(', ')}]${curiosityIcon}`, 'dim'));
549
+ // Show more details in verbose mode
550
+ if (this.verbose) {
551
+ const reuseRate = metrics.memoryReuseRate * 100;
552
+ console.log((0, ui_js_1.c)(` [reuse=${reuseRate.toFixed(0)}%, cycles=${metrics.totalCycles}]`, 'dim'));
553
+ }
554
+ // Persist interaction (Brain manages its own conversation context)
555
+ this.store.recordInteraction();
556
+ // v7.4.5: Execute post-message hook
557
+ if (this.hooks.hasHooks()) {
558
+ this.hooks.execute('post-message', {
559
+ event: 'post-message',
560
+ message,
561
+ response: brainFormatted.formatted,
562
+ sessionId: this.store.getState().session?.id,
563
+ workingDir: process.cwd(),
564
+ });
565
+ }
566
+ this.isProcessing = false; // v7.4: Done processing
567
+ console.log();
568
+ }
569
+ catch (err) {
570
+ this.isProcessing = false; // v7.4: Done processing (error)
571
+ // v7.3.8: Stop thinking spinner on error
572
+ if (!this.enableTrace) {
573
+ this.thinkingSpinner.stop();
574
+ }
575
+ const errorMessage = err instanceof Error ? err.message : String(err);
576
+ console.log((0, ui_js_1.error)(`Genesis: Brain error - ${errorMessage}`));
577
+ // Fallback to direct LLM if brain fails
578
+ console.log((0, ui_js_1.warning)(' [Falling back to direct LLM...]'));
579
+ this.enableBrain = false; // Temporarily disable
580
+ await this.sendMessage(message);
581
+ this.enableBrain = true; // Re-enable for next message
582
+ }
583
+ }
584
+ /**
585
+ * Handle slash commands
586
+ */
587
+ async handleCommand(input) {
588
+ const [cmd, ...args] = input.slice(1).split(' ');
589
+ switch (cmd.toLowerCase()) {
590
+ case 'help':
591
+ case 'h':
592
+ this.printHelp();
593
+ break;
594
+ case 'clear':
595
+ case 'c':
596
+ this.llm.clearHistory();
597
+ console.log((0, ui_js_1.c)('Conversation history cleared.', 'yellow'));
598
+ console.log();
599
+ break;
600
+ case 'history':
601
+ this.printHistory();
602
+ break;
603
+ case 'status':
604
+ case 's':
605
+ this.printStatus();
606
+ break;
607
+ case 'verbose':
608
+ case 'v':
609
+ this.verbose = !this.verbose;
610
+ console.log((0, ui_js_1.c)(`Verbose mode: ${this.verbose ? 'ON' : 'OFF'}`, 'yellow'));
611
+ console.log();
612
+ break;
613
+ case 'quit':
614
+ case 'exit':
615
+ case 'q':
616
+ this.stop();
617
+ break;
618
+ case 'system':
619
+ if (args.length > 0) {
620
+ console.log((0, ui_js_1.c)('Custom system prompts not yet supported.', 'yellow'));
621
+ }
622
+ else {
623
+ console.log((0, ui_js_1.c)('System Prompt (dynamically built):', 'cyan'));
624
+ console.log((0, ui_js_1.c)('─'.repeat(60), 'dim'));
625
+ console.log(this.systemPrompt || index_js_1.GENESIS_IDENTITY_PROMPT);
626
+ console.log((0, ui_js_1.c)('─'.repeat(60), 'dim'));
627
+ // Show tool stats with schemas
628
+ const tools = this.dispatcher.listToolsWithSchemas();
629
+ console.log((0, ui_js_1.c)(`\nTools discovered:`, 'yellow'));
630
+ console.log(` Local: ${tools.local.length}`);
631
+ for (const tool of tools.local) {
632
+ const desc = tool.description ? `: ${tool.description.slice(0, 40)}...` : '';
633
+ console.log(` - ${tool.name}${desc}`);
634
+ }
635
+ console.log(` MCP servers: ${Object.keys(tools.mcp).length}`);
636
+ for (const [server, serverTools] of Object.entries(tools.mcp)) {
637
+ console.log(` ${server}: ${serverTools.length} tools`);
638
+ }
639
+ }
640
+ console.log();
641
+ break;
642
+ case 'save':
643
+ await this.store.save();
644
+ console.log((0, ui_js_1.c)('State saved.', 'green'));
645
+ console.log();
646
+ break;
647
+ case 'load':
648
+ await this.store.load();
649
+ // Restore conversation history
650
+ this.llm.clearHistory();
651
+ const state = this.store.getState();
652
+ for (const msg of state.conversation.history) {
653
+ this.llm.getHistory().push(msg);
654
+ }
655
+ console.log((0, ui_js_1.c)(`State loaded. ${state.conversation.history.length} messages restored.`, 'green'));
656
+ console.log();
657
+ break;
658
+ case 'export':
659
+ if (args.length > 0) {
660
+ await this.store.export(args[0]);
661
+ console.log((0, ui_js_1.c)(`State exported to: ${args[0]}`, 'green'));
662
+ }
663
+ else {
664
+ console.log((0, ui_js_1.c)('Usage: /export <filename>', 'yellow'));
665
+ }
666
+ console.log();
667
+ break;
668
+ case 'reset':
669
+ this.store.reset();
670
+ this.llm.clearHistory();
671
+ console.log((0, ui_js_1.c)('State reset to empty.', 'yellow'));
672
+ console.log();
673
+ break;
674
+ case 'state':
675
+ this.printStateInfo();
676
+ break;
677
+ case 'tools':
678
+ this.enableTools = !this.enableTools;
679
+ console.log((0, ui_js_1.c)(`MCP Tools: ${this.enableTools ? 'ENABLED' : 'DISABLED'}`, 'yellow'));
680
+ console.log();
681
+ break;
682
+ case 'toolstatus':
683
+ console.log((0, ui_js_1.c)('Tool Status:', 'bold'));
684
+ console.log(` Enabled: ${this.enableTools ? (0, ui_js_1.c)('Yes', 'green') : (0, ui_js_1.c)('No', 'red')}`);
685
+ console.log(` Executions: ${this.toolExecutions}`);
686
+ console.log();
687
+ break;
688
+ case 'mcptest':
689
+ case 'mcp':
690
+ await this.runMCPDiagnostics();
691
+ break;
692
+ // Phase 10: Brain commands
693
+ case 'brain':
694
+ this.enableBrain = !this.enableBrain;
695
+ if (this.enableBrain) {
696
+ this.brain.start();
697
+ console.log((0, ui_js_1.c)(`Brain: ${(0, ui_js_1.c)('ACTIVE', 'green')} (Neural Integration enabled)`, 'bold'));
698
+ console.log((0, ui_js_1.c)(' Routes: Memory → LLM → Grounding → Tools → Response', 'dim'));
699
+ console.log((0, ui_js_1.c)(' With: φ monitoring, Global Workspace, self-healing', 'dim'));
700
+ }
701
+ else {
702
+ this.brain.stop();
703
+ console.log((0, ui_js_1.c)(`Brain: ${(0, ui_js_1.c)('OFF', 'yellow')} (Direct LLM mode)`, 'bold'));
704
+ }
705
+ console.log();
706
+ break;
707
+ case 'phi':
708
+ const phi = this.brain.getMetrics().avgPhi;
709
+ const phiBar = this.renderPhiBar(phi);
710
+ console.log((0, ui_js_1.c)('Consciousness Level (φ):', 'bold'));
711
+ console.log(` Current: ${phi.toFixed(3)}`);
712
+ console.log(` Level: ${phiBar}`);
713
+ console.log(` Ignited: ${phi > 0.3 ? (0, ui_js_1.c)('Yes (broadcasting)', 'green') : (0, ui_js_1.c)('No', 'dim')}`);
714
+ console.log();
715
+ break;
716
+ case 'brainmetrics':
717
+ case 'bm':
718
+ this.printBrainMetrics();
719
+ break;
720
+ case 'brainstatus':
721
+ case 'bs':
722
+ this.printBrainStatus();
723
+ break;
724
+ case 'braintrace':
725
+ case 'trace':
726
+ case 'bt':
727
+ this.enableTrace = !this.enableTrace;
728
+ if (this.enableTrace) {
729
+ this.brainTrace.enable();
730
+ console.log((0, ui_js_1.c)(`Brain Trace: ${(0, ui_js_1.c)('ON', 'green')} - Shows internal thinking process`, 'bold'));
731
+ console.log((0, ui_js_1.c)(' You will see: memory recalls, LLM requests, grounding checks, etc.', 'dim'));
732
+ if (!this.enableBrain) {
733
+ console.log((0, ui_js_1.c)(' Note: Enable /brain for trace to show during chat', 'yellow'));
734
+ }
735
+ }
736
+ else {
737
+ this.brainTrace.disable();
738
+ console.log((0, ui_js_1.c)(`Brain Trace: ${(0, ui_js_1.c)('OFF', 'yellow')}`, 'bold'));
739
+ }
740
+ console.log();
741
+ break;
742
+ // v7.0: Memory commands
743
+ case 'memory':
744
+ case 'mem':
745
+ this.printMemoryStatus();
746
+ break;
747
+ case 'remember':
748
+ if (args.length > 0) {
749
+ const factText = args.join(' ');
750
+ this.memory.learn({
751
+ concept: 'user-fact',
752
+ definition: factText,
753
+ properties: { source: 'user-input', timestamp: new Date() },
754
+ category: 'user-facts',
755
+ sources: ['chat-input'],
756
+ importance: 0.7,
757
+ tags: ['user', 'remembered'],
758
+ });
759
+ console.log((0, ui_js_1.success)(`✓ Remembered: "${factText}"`));
760
+ }
761
+ else {
762
+ console.log((0, ui_js_1.warning)('Usage: /remember <text to remember>'));
763
+ }
764
+ console.log();
765
+ break;
766
+ case 'forget':
767
+ // Requires confirmation
768
+ console.log((0, ui_js_1.warning)('This will clear all memories. Use /forget confirm to proceed.'));
769
+ if (args[0] === 'confirm') {
770
+ this.memory.shutdown();
771
+ console.log((0, ui_js_1.success)('✓ Memory cleared.'));
772
+ }
773
+ console.log();
774
+ break;
775
+ case 'consolidate':
776
+ console.log((0, ui_js_1.info)('Running memory consolidation...'));
777
+ this.memory.consolidation.backgroundConsolidate().then(result => {
778
+ console.log((0, ui_js_1.success)(`✓ Consolidation complete:`));
779
+ console.log(` Episodic processed: ${result.episodicProcessed}`);
780
+ console.log(` Semantic created: ${result.semanticCreated}`);
781
+ console.log(` Procedural updated: ${result.proceduralUpdated}`);
782
+ console.log(` Forgotten: ${result.forgotten}`);
783
+ console.log(` Duration: ${(0, ui_js_1.formatDuration)(result.duration)}`);
784
+ }).catch(err => {
785
+ console.log((0, ui_js_1.error)(`Consolidation error: ${err instanceof Error ? err.message : err}`));
786
+ });
787
+ break;
788
+ // v7.0: Darwin-Gödel self-improvement commands
789
+ case 'heal':
790
+ this.printHealingStatus();
791
+ break;
792
+ case 'analyze':
793
+ this.runSelfAnalysis();
794
+ break;
795
+ case 'improve':
796
+ if (args[0] === 'confirm') {
797
+ this.runSelfImprovement();
798
+ }
799
+ else {
800
+ console.log((0, ui_js_1.warning)('This will trigger self-improvement. Use /improve confirm to proceed.'));
801
+ console.log((0, ui_js_1.muted)(' Safety: Git commit created before any changes'));
802
+ }
803
+ console.log();
804
+ break;
805
+ // v7.1: Active Inference commands
806
+ case 'inference':
807
+ case 'infer':
808
+ this.enableInference = !this.enableInference;
809
+ if (this.enableInference) {
810
+ if (!this.inferenceLoop) {
811
+ this.inferenceLoop = (0, index_js_7.createAutonomousLoop)({
812
+ cycleInterval: 0,
813
+ maxCycles: 0,
814
+ verbose: false,
815
+ stopOnGoalAchieved: false,
816
+ stopOnEnergyCritical: true,
817
+ });
818
+ }
819
+ console.log((0, ui_js_1.c)(`Inference: ${(0, ui_js_1.c)('ACTIVE', 'green')} (Active Inference + Value-JEPA)`, 'bold'));
820
+ console.log((0, ui_js_1.c)(' Runs inference cycle before each response', 'dim'));
821
+ console.log((0, ui_js_1.c)(' Computes: beliefs, surprise, Expected Free Energy', 'dim'));
822
+ }
823
+ else {
824
+ console.log((0, ui_js_1.c)(`Inference: ${(0, ui_js_1.c)('OFF', 'yellow')}`, 'bold'));
825
+ }
826
+ console.log();
827
+ break;
828
+ case 'curiosity':
829
+ this.enableCuriosity = !this.enableCuriosity;
830
+ if (this.enableCuriosity) {
831
+ console.log((0, ui_js_1.c)(`Curiosity: ${(0, ui_js_1.c)('ACTIVE', 'green')} (Intrinsic motivation)`, 'bold'));
832
+ console.log((0, ui_js_1.c)(' Computes novelty score for each message', 'dim'));
833
+ console.log((0, ui_js_1.c)(' Higher curiosity → more exploratory responses', 'dim'));
834
+ }
835
+ else {
836
+ console.log((0, ui_js_1.c)(`Curiosity: ${(0, ui_js_1.c)('OFF', 'yellow')}`, 'bold'));
837
+ }
838
+ console.log();
839
+ break;
840
+ case 'beliefs':
841
+ this.printBeliefs();
842
+ break;
843
+ // v7.4: Subagent commands
844
+ case 'task':
845
+ await this.runSubagentTask(args);
846
+ break;
847
+ case 'tasks':
848
+ this.printRunningTasks();
849
+ break;
850
+ case 'taskwait':
851
+ if (args[0]) {
852
+ await this.waitForTask(args[0]);
853
+ }
854
+ else {
855
+ console.log((0, ui_js_1.warning)('Usage: /taskwait <taskId>'));
856
+ }
857
+ break;
858
+ case 'taskcancel':
859
+ if (args[0]) {
860
+ const cancelled = this.subagentExecutor.cancelTask(args[0]);
861
+ if (cancelled) {
862
+ console.log((0, ui_js_1.success)(`✓ Task ${args[0]} cancelled`));
863
+ }
864
+ else {
865
+ console.log((0, ui_js_1.error)(`Task ${args[0]} not found or not running`));
866
+ }
867
+ }
868
+ else {
869
+ console.log((0, ui_js_1.warning)('Usage: /taskcancel <taskId>'));
870
+ }
871
+ console.log();
872
+ break;
873
+ case 'agents':
874
+ this.printAvailableAgents();
875
+ break;
876
+ // v7.4: Session management commands
877
+ case 'sessions':
878
+ this.printSessions();
879
+ break;
880
+ case 'session':
881
+ if (args[0] === 'name' && args[1]) {
882
+ this.sessionName = args.slice(1).join(' ');
883
+ console.log((0, ui_js_1.success)(`Session named: ${this.sessionName}`));
884
+ }
885
+ else if (args[0] === 'save') {
886
+ const state = this.store.getState();
887
+ this.store.updateConversation(this.llm.getHistory());
888
+ const name = args.slice(1).join(' ') || this.sessionName;
889
+ const id = this.sessionManager.saveSession(this.store.getState(), name);
890
+ console.log((0, ui_js_1.success)(`Session saved: ${id.slice(0, 8)}${name ? ` (${name})` : ''}`));
891
+ }
892
+ else if (args[0] === 'fork') {
893
+ const currentState = this.store.getState();
894
+ this.store.updateConversation(this.llm.getHistory());
895
+ const name = args.slice(1).join(' ') || `Fork at ${new Date().toLocaleTimeString()}`;
896
+ const id = this.sessionManager.saveSession(this.store.getState(), name);
897
+ // Create new session ID for current session
898
+ this.store.newSession();
899
+ console.log((0, ui_js_1.success)(`Session forked: ${id.slice(0, 8)}`));
900
+ console.log((0, ui_js_1.muted)('Continuing in new session.'));
901
+ }
902
+ else if (args[0] === 'delete' && args[1]) {
903
+ const deleted = this.sessionManager.deleteSession(args[1]);
904
+ if (deleted) {
905
+ console.log((0, ui_js_1.success)(`Session deleted: ${args[1]}`));
906
+ }
907
+ else {
908
+ console.log((0, ui_js_1.error)(`Session not found: ${args[1]}`));
909
+ }
910
+ }
911
+ else {
912
+ console.log((0, ui_js_1.info)('Session commands:'));
913
+ console.log(' /session name <name> - Name current session');
914
+ console.log(' /session save [name] - Save session checkpoint');
915
+ console.log(' /session fork [name] - Fork session (save and start new)');
916
+ console.log(' /session delete <id> - Delete a saved session');
917
+ console.log(' /sessions - List all sessions');
918
+ }
919
+ console.log();
920
+ break;
921
+ // v7.4.5: Hooks System
922
+ case 'hooks':
923
+ if (args[0] === 'init') {
924
+ const targetPath = args[1] || '.genesis-hooks.json';
925
+ try {
926
+ (0, index_js_9.createSampleHooksConfig)(targetPath);
927
+ console.log((0, ui_js_1.success)(`✓ Created sample hooks config: ${targetPath}`));
928
+ }
929
+ catch (err) {
930
+ console.log((0, ui_js_1.error)(`Failed to create hooks config: ${err}`));
931
+ }
932
+ }
933
+ else if (args[0] === 'reload') {
934
+ this.hooks.reload();
935
+ console.log((0, ui_js_1.success)('✓ Hooks configuration reloaded'));
936
+ }
937
+ else if (args[0] === 'on') {
938
+ this.hooks.setEnabled(true);
939
+ console.log((0, ui_js_1.success)('✓ Hooks enabled'));
940
+ }
941
+ else if (args[0] === 'off') {
942
+ this.hooks.setEnabled(false);
943
+ console.log((0, ui_js_1.warning)('Hooks disabled'));
944
+ }
945
+ else {
946
+ // Show hooks status
947
+ const hasHooks = this.hooks.hasHooks();
948
+ const configPath = this.hooks.getConfigPath();
949
+ const configured = this.hooks.getConfiguredHooks();
950
+ console.log((0, ui_js_1.c)('Hooks System (v7.4.5):', 'bold'));
951
+ console.log(` Status: ${hasHooks ? (0, ui_js_1.c)('Active', 'green') : (0, ui_js_1.c)('No hooks configured', 'yellow')}`);
952
+ if (configPath) {
953
+ console.log(` Config: ${configPath}`);
954
+ }
955
+ if (configured.length > 0) {
956
+ console.log(` Configured: ${configured.join(', ')}`);
957
+ }
958
+ console.log();
959
+ console.log((0, ui_js_1.muted)('Commands:'));
960
+ console.log((0, ui_js_1.muted)(' /hooks init [path] - Create sample hooks config'));
961
+ console.log((0, ui_js_1.muted)(' /hooks reload - Reload hooks configuration'));
962
+ console.log((0, ui_js_1.muted)(' /hooks on/off - Enable/disable hooks'));
963
+ console.log();
964
+ console.log((0, ui_js_1.muted)('Events: session-start, session-end, pre-message, post-message,'));
965
+ console.log((0, ui_js_1.muted)(' pre-tool, post-tool, pre-subagent, post-subagent, error'));
966
+ }
967
+ console.log();
968
+ break;
969
+ // v7.4.4: Extended Thinking visualization
970
+ case 'thinking':
971
+ case 'think':
972
+ if (args[0] === 'on') {
973
+ this.thinkingSettings.enabled = true;
974
+ this.thinkingSettings.collapsed = false;
975
+ console.log((0, ui_js_1.c)(`Extended Thinking: ${(0, ui_js_1.c)('ON', 'green')} (expanded view)`, 'bold'));
976
+ }
977
+ else if (args[0] === 'off') {
978
+ this.thinkingSettings.enabled = false;
979
+ console.log((0, ui_js_1.c)(`Extended Thinking: ${(0, ui_js_1.c)('OFF', 'yellow')}`, 'bold'));
980
+ }
981
+ else if (args[0] === 'collapsed' || args[0] === 'compact') {
982
+ this.thinkingSettings.enabled = true;
983
+ this.thinkingSettings.collapsed = true;
984
+ console.log((0, ui_js_1.c)(`Extended Thinking: ${(0, ui_js_1.c)('ON', 'green')} (collapsed view)`, 'bold'));
985
+ }
986
+ else if (args[0] === 'expanded' || args[0] === 'full') {
987
+ this.thinkingSettings.enabled = true;
988
+ this.thinkingSettings.collapsed = false;
989
+ console.log((0, ui_js_1.c)(`Extended Thinking: ${(0, ui_js_1.c)('ON', 'green')} (expanded view)`, 'bold'));
990
+ }
991
+ else {
992
+ // Toggle or show status
993
+ if (!args[0]) {
994
+ this.thinkingSettings.enabled = !this.thinkingSettings.enabled;
995
+ }
996
+ const status = this.thinkingSettings.enabled ? (0, ui_js_1.c)('ON', 'green') : (0, ui_js_1.c)('OFF', 'yellow');
997
+ const mode = this.thinkingSettings.collapsed ? 'collapsed' : 'expanded';
998
+ console.log((0, ui_js_1.c)(`Extended Thinking: ${status} (${mode} view)`, 'bold'));
999
+ console.log((0, ui_js_1.muted)(' Shows model reasoning in <think>...</think> blocks'));
1000
+ console.log((0, ui_js_1.muted)(' Commands:'));
1001
+ console.log((0, ui_js_1.muted)(' /thinking on - Enable (expanded)'));
1002
+ console.log((0, ui_js_1.muted)(' /thinking off - Disable'));
1003
+ console.log((0, ui_js_1.muted)(' /thinking collapsed - Enable (one-line preview)'));
1004
+ console.log((0, ui_js_1.muted)(' /thinking expanded - Enable (full view)'));
1005
+ }
1006
+ console.log();
1007
+ break;
1008
+ default:
1009
+ console.log((0, ui_js_1.c)(`Unknown command: /${cmd}`, 'red'));
1010
+ console.log('Type /help for available commands.');
1011
+ console.log();
1012
+ }
1013
+ }
1014
+ /**
1015
+ * Print banner (v7.0: Uses modern UI component)
1016
+ */
1017
+ printBanner() {
1018
+ (0, ui_js_1.banner)('GENESIS - System Creator', 'Powered by 13 MCP Servers');
1019
+ }
1020
+ /**
1021
+ * Print help
1022
+ */
1023
+ printHelp() {
1024
+ console.log((0, ui_js_1.c)('Commands:', 'bold'));
1025
+ console.log(' /help, /h Show this help');
1026
+ console.log(' /clear, /c Clear conversation history');
1027
+ console.log(' /history Show conversation history');
1028
+ console.log(' /status, /s Show LLM status');
1029
+ console.log(' /verbose, /v Toggle verbose mode');
1030
+ console.log(' /system Show system prompt');
1031
+ console.log();
1032
+ console.log((0, ui_js_1.c)('Tools:', 'bold'));
1033
+ console.log(' /tools Toggle MCP tool execution');
1034
+ console.log(' /toolstatus Show tool execution stats');
1035
+ console.log();
1036
+ console.log((0, ui_js_1.c)('Brain (Phase 10):', 'bold'));
1037
+ console.log(' /brain Toggle Brain integration');
1038
+ console.log(' /braintrace Toggle visible thinking trace');
1039
+ console.log(' /phi Show consciousness level (φ)');
1040
+ console.log(' /brainstatus Show brain status');
1041
+ console.log(' /brainmetrics Show detailed brain metrics');
1042
+ console.log();
1043
+ console.log((0, ui_js_1.c)('Active Inference (v7.1):', 'bold'));
1044
+ console.log(' /inference Toggle Active Inference loop');
1045
+ console.log(' /curiosity Toggle curiosity-driven behavior');
1046
+ console.log(' /beliefs Show current beliefs (viability, world, coupling, goal)');
1047
+ console.log();
1048
+ console.log((0, ui_js_1.c)('Memory (v7.0):', 'bold'));
1049
+ console.log(' /memory Show memory status');
1050
+ console.log(' /remember <t> Store a fact in memory');
1051
+ console.log(' /consolidate Run memory consolidation');
1052
+ console.log(' /forget Clear all memory (confirm)');
1053
+ console.log();
1054
+ console.log((0, ui_js_1.c)('Darwin-Gödel (v7.0):', 'bold'));
1055
+ console.log(' /heal Show self-healing status');
1056
+ console.log(' /analyze Run self-analysis');
1057
+ console.log(' /improve Trigger self-improvement (confirm)');
1058
+ console.log();
1059
+ console.log((0, ui_js_1.c)('Subagents (v7.4):', 'bold'));
1060
+ console.log(' /task <t> <p> Run subagent task (explore, plan, code, research, general)');
1061
+ console.log(' /tasks List running background tasks');
1062
+ console.log(' /taskwait <id> Wait for task completion');
1063
+ console.log(' /taskcancel <id> Cancel running task');
1064
+ console.log(' /agents Show available subagents');
1065
+ console.log();
1066
+ console.log((0, ui_js_1.c)('Sessions (v7.4):', 'bold'));
1067
+ console.log(' /sessions List saved sessions');
1068
+ console.log(' /session name <n> Name current session');
1069
+ console.log(' /session save Save session checkpoint');
1070
+ console.log(' /session fork Fork session (save & continue new)');
1071
+ console.log();
1072
+ console.log((0, ui_js_1.c)('Extended Thinking (v7.4.4):', 'bold'));
1073
+ console.log(' /thinking Toggle thinking block visibility');
1074
+ console.log(' /thinking on Show thinking blocks (expanded)');
1075
+ console.log(' /thinking off Hide thinking blocks');
1076
+ console.log(' /thinking collapsed Show thinking (one-line)');
1077
+ console.log();
1078
+ console.log((0, ui_js_1.c)('Hooks (v7.4.5):', 'bold'));
1079
+ console.log(' /hooks Show hooks status');
1080
+ console.log(' /hooks init Create sample hooks config');
1081
+ console.log(' /hooks reload Reload hooks configuration');
1082
+ console.log(' /hooks on/off Enable/disable hooks');
1083
+ console.log();
1084
+ console.log((0, ui_js_1.c)('State:', 'bold'));
1085
+ console.log(' /save Save state to disk');
1086
+ console.log(' /load Load state from disk');
1087
+ console.log(' /export <f> Export state to file');
1088
+ console.log(' /reset Reset state to empty');
1089
+ console.log(' /state Show state info');
1090
+ console.log();
1091
+ console.log(' /quit, /q Exit chat (auto-saves)');
1092
+ console.log();
1093
+ console.log((0, ui_js_1.c)('Keyboard Shortcuts (v7.4):', 'bold'));
1094
+ console.log(' Ctrl+B Background current task');
1095
+ console.log(' Ctrl+L Clear screen (keep conversation)');
1096
+ console.log(' Ctrl+O Toggle verbose output');
1097
+ console.log(' Ctrl+R History search hint');
1098
+ console.log();
1099
+ }
1100
+ /**
1101
+ * Print conversation history
1102
+ */
1103
+ printHistory() {
1104
+ const history = this.llm.getHistory();
1105
+ if (history.length === 0) {
1106
+ console.log((0, ui_js_1.c)('No conversation history.', 'dim'));
1107
+ }
1108
+ else {
1109
+ console.log((0, ui_js_1.c)(`Conversation history (${history.length} messages):`, 'cyan'));
1110
+ for (const msg of history) {
1111
+ const role = msg.role === 'user' ? (0, ui_js_1.c)('You:', 'green') : (0, ui_js_1.c)('Genesis:', 'cyan');
1112
+ const content = msg.content.length > 100
1113
+ ? msg.content.substring(0, 100) + '...'
1114
+ : msg.content;
1115
+ console.log(` ${role} ${content}`);
1116
+ }
1117
+ }
1118
+ console.log();
1119
+ }
1120
+ /**
1121
+ * Print status
1122
+ */
1123
+ printStatus() {
1124
+ const status = this.llm.status();
1125
+ const history = this.llm.getHistory();
1126
+ console.log((0, ui_js_1.c)('Status:', 'bold'));
1127
+ console.log(` Provider: ${status.provider}`);
1128
+ console.log(` Model: ${status.model}`);
1129
+ console.log(` Configured: ${status.configured ? (0, ui_js_1.c)('Yes', 'green') : (0, ui_js_1.c)('No', 'red')}`);
1130
+ console.log(` Messages: ${history.length}`);
1131
+ console.log(` Verbose: ${this.verbose ? 'ON' : 'OFF'}`);
1132
+ console.log(` MCP Tools: ${this.enableTools ? (0, ui_js_1.c)('ON', 'green') : (0, ui_js_1.c)('OFF', 'yellow')}`);
1133
+ console.log(` Tool Calls: ${this.toolExecutions}`);
1134
+ console.log();
1135
+ // Phase 10: Brain status
1136
+ const brainMetrics = this.brain.getMetrics();
1137
+ console.log((0, ui_js_1.c)('Brain (Phase 10):', 'cyan'));
1138
+ console.log(` Mode: ${this.enableBrain ? (0, ui_js_1.c)('ACTIVE', 'green') : (0, ui_js_1.c)('OFF', 'yellow')}`);
1139
+ console.log(` φ Level: ${brainMetrics.avgPhi.toFixed(3)}`);
1140
+ console.log(` Cycles: ${brainMetrics.totalCycles}`);
1141
+ console.log(` Mem Reuse: ${(brainMetrics.memoryReuseRate * 100).toFixed(1)}%`);
1142
+ console.log();
1143
+ // v7.1: Active Inference status
1144
+ console.log((0, ui_js_1.c)('Active Inference (v7.1):', 'cyan'));
1145
+ console.log(` Inference: ${this.enableInference ? (0, ui_js_1.c)('ACTIVE', 'green') : (0, ui_js_1.c)('OFF', 'yellow')}`);
1146
+ console.log(` Curiosity: ${this.enableCuriosity ? (0, ui_js_1.c)('ACTIVE', 'green') : (0, ui_js_1.c)('OFF', 'yellow')}`);
1147
+ if (this.inferenceLoop) {
1148
+ const stats = this.inferenceLoop.getStats();
1149
+ const beliefs = this.inferenceLoop.getMostLikelyState();
1150
+ console.log(` Viability: ${beliefs.viability}`);
1151
+ console.log(` World State: ${beliefs.worldState}`);
1152
+ console.log(` Surprise: ${stats.avgSurprise.toFixed(3)}`);
1153
+ console.log(` Last Curiosity: ${this.lastCuriosity.toFixed(3)}`);
1154
+ }
1155
+ console.log();
1156
+ }
1157
+ /**
1158
+ * Print state info
1159
+ */
1160
+ printStateInfo() {
1161
+ const stats = this.store.stats();
1162
+ const state = this.store.getState();
1163
+ console.log((0, ui_js_1.c)('State Info:', 'bold'));
1164
+ console.log(` Data dir: ${stats.dataDir}`);
1165
+ console.log(` State exists: ${stats.stateExists ? (0, ui_js_1.c)('Yes', 'green') : (0, ui_js_1.c)('No', 'yellow')}`);
1166
+ console.log(` State size: ${stats.stateSize} bytes`);
1167
+ console.log(` Backups: ${stats.backupCount}`);
1168
+ console.log(` Dirty: ${stats.isDirty ? (0, ui_js_1.c)('Yes', 'yellow') : 'No'}`);
1169
+ console.log(` Last modified: ${stats.lastModified}`);
1170
+ console.log();
1171
+ console.log((0, ui_js_1.c)('Memory:', 'cyan'));
1172
+ console.log(` Episodes: ${state.memory.stats.totalEpisodes}`);
1173
+ console.log(` Facts: ${state.memory.stats.totalFacts}`);
1174
+ console.log(` Skills: ${state.memory.stats.totalSkills}`);
1175
+ console.log();
1176
+ console.log((0, ui_js_1.c)('Session:', 'cyan'));
1177
+ console.log(` ID: ${state.session.id.substring(0, 8)}...`);
1178
+ console.log(` Interactions: ${state.session.interactions}`);
1179
+ console.log(` Started: ${state.session.startTime}`);
1180
+ console.log();
1181
+ }
1182
+ // ==========================================================================
1183
+ // Phase 10: Brain Integration Helpers
1184
+ // ==========================================================================
1185
+ /**
1186
+ * Render φ (consciousness level) as a visual bar
1187
+ */
1188
+ renderPhiBar(phi) {
1189
+ const width = 20;
1190
+ const filled = Math.round(phi * width);
1191
+ const empty = width - filled;
1192
+ const bar = '█'.repeat(filled) + '░'.repeat(empty);
1193
+ // Color based on level
1194
+ if (phi >= 0.7)
1195
+ return (0, ui_js_1.c)(bar, 'green') + ` (High - Global Workspace active)`;
1196
+ if (phi >= 0.3)
1197
+ return (0, ui_js_1.c)(bar, 'yellow') + ` (Medium - Ignition threshold)`;
1198
+ return (0, ui_js_1.c)(bar, 'dim') + ` (Low - Local processing)`;
1199
+ }
1200
+ /**
1201
+ * v7.1: Print current beliefs from Active Inference
1202
+ */
1203
+ printBeliefs() {
1204
+ console.log((0, ui_js_1.c)('Active Inference Beliefs (v7.1):', 'bold'));
1205
+ console.log();
1206
+ if (!this.inferenceLoop) {
1207
+ console.log((0, ui_js_1.warning)('Active Inference not initialized.'));
1208
+ console.log((0, ui_js_1.muted)('Use /inference to enable.'));
1209
+ console.log();
1210
+ return;
1211
+ }
1212
+ const beliefs = this.inferenceLoop.getMostLikelyState();
1213
+ const stats = this.inferenceLoop.getStats();
1214
+ // Viability bar
1215
+ const viabilityMap = { 'critical': 0.1, 'low': 0.3, 'medium': 0.5, 'high': 0.7, 'optimal': 0.9 };
1216
+ const viabilityValue = viabilityMap[beliefs.viability] || 0.5;
1217
+ const viabilityBar = this.renderBar(viabilityValue, 15);
1218
+ console.log((0, ui_js_1.c)('Current State:', 'cyan'));
1219
+ console.log(` Viability: ${viabilityBar} ${beliefs.viability}`);
1220
+ console.log(` World State: ${beliefs.worldState}`);
1221
+ console.log(` Coupling: ${beliefs.coupling}`);
1222
+ console.log(` Goal Progress: ${beliefs.goalProgress}`);
1223
+ console.log();
1224
+ console.log((0, ui_js_1.c)('Inference Stats:', 'cyan'));
1225
+ console.log(` Cycles: ${stats.cycles}`);
1226
+ console.log(` Avg Surprise: ${stats.avgSurprise.toFixed(4)}`);
1227
+ console.log(` Last Curiosity: ${this.lastCuriosity.toFixed(4)}`);
1228
+ console.log();
1229
+ console.log((0, ui_js_1.c)('Actions Taken:', 'cyan'));
1230
+ for (const [action, count] of Object.entries(stats.actions)) {
1231
+ const pct = stats.cycles > 0 ? (count / stats.cycles * 100).toFixed(1) : '0';
1232
+ console.log(` ${action}: ${count} (${pct}%)`);
1233
+ }
1234
+ console.log();
1235
+ }
1236
+ // ============================================================================
1237
+ // v7.4: Subagent Commands
1238
+ // ============================================================================
1239
+ /**
1240
+ * Run a subagent task
1241
+ */
1242
+ async runSubagentTask(args) {
1243
+ if (args.length < 2) {
1244
+ console.log((0, ui_js_1.c)('Usage: /task <type> <prompt>', 'yellow'));
1245
+ console.log((0, ui_js_1.c)(' Types: explore, plan, code, research, general', 'dim'));
1246
+ console.log((0, ui_js_1.c)(' Example: /task explore Find all authentication handlers', 'dim'));
1247
+ console.log((0, ui_js_1.c)(' Add --bg at end to run in background', 'dim'));
1248
+ console.log();
1249
+ return;
1250
+ }
1251
+ const subagentType = args[0];
1252
+ const availableTypes = (0, index_js_8.getSubagentNames)();
1253
+ if (!availableTypes.includes(subagentType)) {
1254
+ console.log((0, ui_js_1.error)(`Unknown agent type: ${subagentType}`));
1255
+ console.log((0, ui_js_1.c)(`Available: ${availableTypes.join(', ')}`, 'dim'));
1256
+ console.log();
1257
+ return;
1258
+ }
1259
+ // Check for background flag
1260
+ const isBackground = args[args.length - 1] === '--bg';
1261
+ const promptArgs = isBackground ? args.slice(1, -1) : args.slice(1);
1262
+ const prompt = promptArgs.join(' ');
1263
+ const request = {
1264
+ description: prompt.slice(0, 30) + (prompt.length > 30 ? '...' : ''),
1265
+ prompt,
1266
+ subagentType,
1267
+ runInBackground: isBackground,
1268
+ };
1269
+ if (isBackground) {
1270
+ // Background execution
1271
+ try {
1272
+ const taskId = await this.subagentExecutor.executeBackground(request);
1273
+ console.log((0, ui_js_1.success)(`✓ Task ${taskId} started in background`));
1274
+ console.log((0, ui_js_1.c)(` Agent: ${subagentType}`, 'dim'));
1275
+ console.log((0, ui_js_1.c)(` Use /tasks to see status, /taskwait ${taskId} to wait`, 'dim'));
1276
+ }
1277
+ catch (err) {
1278
+ console.log((0, ui_js_1.error)(`Failed to start task: ${err instanceof Error ? err.message : err}`));
1279
+ }
1280
+ }
1281
+ else {
1282
+ // Foreground execution with spinner
1283
+ this.thinkingSpinner.start();
1284
+ this.thinkingSpinner.setModule(subagentType);
1285
+ this.thinkingSpinner.setAction('Running task');
1286
+ try {
1287
+ const result = await this.subagentExecutor.execute(request);
1288
+ this.thinkingSpinner.stop();
1289
+ if (result.success) {
1290
+ console.log((0, ui_js_1.success)(`✓ Task completed in ${(0, ui_js_1.formatDuration)(result.duration)}`));
1291
+ console.log();
1292
+ console.log((0, ui_js_1.formatMarkdown)(result.result || 'No output'));
1293
+ }
1294
+ else {
1295
+ console.log((0, ui_js_1.error)(`Task failed: ${result.error}`));
1296
+ }
1297
+ }
1298
+ catch (err) {
1299
+ this.thinkingSpinner.stop();
1300
+ console.log((0, ui_js_1.error)(`Task error: ${err instanceof Error ? err.message : err}`));
1301
+ }
1302
+ }
1303
+ console.log();
1304
+ }
1305
+ /**
1306
+ * Print running tasks
1307
+ */
1308
+ printRunningTasks() {
1309
+ const tasks = this.subagentExecutor.getTasks();
1310
+ console.log((0, ui_js_1.c)('Background Tasks (v7.4):', 'bold'));
1311
+ console.log();
1312
+ if (tasks.length === 0) {
1313
+ console.log((0, ui_js_1.muted)('No tasks running.'));
1314
+ console.log();
1315
+ return;
1316
+ }
1317
+ const taskData = tasks.map(t => {
1318
+ const statusColor = t.status === 'completed' ? 'green' :
1319
+ t.status === 'running' ? 'cyan' :
1320
+ t.status === 'failed' ? 'red' : 'yellow';
1321
+ const duration = t.endTime
1322
+ ? (0, ui_js_1.formatDuration)(t.endTime - t.startTime)
1323
+ : (0, ui_js_1.formatDuration)(Date.now() - t.startTime);
1324
+ return {
1325
+ id: t.taskId,
1326
+ status: (0, ui_js_1.c)(t.status, statusColor),
1327
+ agent: t.subagentType,
1328
+ description: (0, ui_js_1.truncate)(t.description, 30),
1329
+ duration,
1330
+ };
1331
+ });
1332
+ console.log((0, ui_js_1.table)(taskData, [
1333
+ { header: 'ID', key: 'id' },
1334
+ { header: 'Status', key: 'status' },
1335
+ { header: 'Agent', key: 'agent' },
1336
+ { header: 'Description', key: 'description' },
1337
+ { header: 'Duration', key: 'duration', align: 'right' },
1338
+ ]));
1339
+ console.log();
1340
+ }
1341
+ /**
1342
+ * Wait for a task to complete
1343
+ */
1344
+ async waitForTask(taskId) {
1345
+ console.log((0, ui_js_1.info)(`Waiting for task ${taskId}...`));
1346
+ try {
1347
+ const result = await this.subagentExecutor.waitForTask(taskId);
1348
+ if (result.success) {
1349
+ console.log((0, ui_js_1.success)(`✓ Task completed in ${(0, ui_js_1.formatDuration)(result.duration)}`));
1350
+ console.log();
1351
+ console.log((0, ui_js_1.formatMarkdown)(result.result || 'No output'));
1352
+ }
1353
+ else {
1354
+ console.log((0, ui_js_1.error)(`Task failed: ${result.error}`));
1355
+ }
1356
+ }
1357
+ catch (err) {
1358
+ console.log((0, ui_js_1.error)(`Error: ${err instanceof Error ? err.message : err}`));
1359
+ }
1360
+ console.log();
1361
+ }
1362
+ /**
1363
+ * Print available agents
1364
+ */
1365
+ printAvailableAgents() {
1366
+ console.log((0, ui_js_1.c)('Available Subagents (v7.4):', 'bold'));
1367
+ console.log();
1368
+ const agentData = [
1369
+ { agent: 'explore', desc: 'Fast codebase exploration', caps: 'read-only, fast searches', model: 'fast' },
1370
+ { agent: 'plan', desc: 'Architecture planning', caps: 'design strategies, no code changes', model: 'powerful' },
1371
+ { agent: 'code', desc: 'Code generation', caps: 'write and modify code', model: 'balanced' },
1372
+ { agent: 'research', desc: 'Web/paper research', caps: 'external sources, citations', model: 'balanced' },
1373
+ { agent: 'general', desc: 'General-purpose', caps: 'complex multi-step tasks', model: 'powerful' },
1374
+ ];
1375
+ console.log((0, ui_js_1.table)(agentData, [
1376
+ { header: 'Agent', key: 'agent' },
1377
+ { header: 'Description', key: 'desc' },
1378
+ { header: 'Capabilities', key: 'caps' },
1379
+ { header: 'Model', key: 'model' },
1380
+ ]));
1381
+ console.log();
1382
+ console.log((0, ui_js_1.c)('Usage:', 'cyan'));
1383
+ console.log((0, ui_js_1.c)(' /task <agent> <prompt> Run task in foreground', 'dim'));
1384
+ console.log((0, ui_js_1.c)(' /task <agent> <prompt> --bg Run task in background', 'dim'));
1385
+ console.log((0, ui_js_1.c)(' /tasks List running tasks', 'dim'));
1386
+ console.log((0, ui_js_1.c)(' /taskwait <id> Wait for task completion', 'dim'));
1387
+ console.log((0, ui_js_1.c)(' /taskcancel <id> Cancel running task', 'dim'));
1388
+ console.log();
1389
+ }
1390
+ /**
1391
+ * v7.4: Print saved sessions
1392
+ */
1393
+ printSessions() {
1394
+ const sessions = this.sessionManager.listSessions();
1395
+ if (sessions.length === 0) {
1396
+ console.log((0, ui_js_1.muted)('No saved sessions.'));
1397
+ console.log((0, ui_js_1.muted)('Use /session save to save the current session.'));
1398
+ console.log();
1399
+ return;
1400
+ }
1401
+ console.log((0, ui_js_1.c)('Saved Sessions (v7.4):', 'bold'));
1402
+ console.log();
1403
+ const sessionData = sessions.slice(0, 10).map(s => ({
1404
+ id: s.id.slice(0, 8),
1405
+ name: s.name || '-',
1406
+ messages: s.messageCount.toString(),
1407
+ tokens: s.tokenCount.toString(),
1408
+ modified: new Date(s.lastModified).toLocaleString(),
1409
+ summary: (0, ui_js_1.truncate)(s.summary || '', 40),
1410
+ }));
1411
+ console.log((0, ui_js_1.table)(sessionData, [
1412
+ { header: 'ID', key: 'id' },
1413
+ { header: 'Name', key: 'name' },
1414
+ { header: 'Msgs', key: 'messages' },
1415
+ { header: 'Tokens', key: 'tokens' },
1416
+ { header: 'Modified', key: 'modified' },
1417
+ { header: 'Summary', key: 'summary' },
1418
+ ]));
1419
+ if (sessions.length > 10) {
1420
+ console.log((0, ui_js_1.muted)(`... and ${sessions.length - 10} more sessions`));
1421
+ }
1422
+ console.log();
1423
+ console.log((0, ui_js_1.c)('Usage:', 'cyan'));
1424
+ console.log((0, ui_js_1.c)(' genesis chat --resume Resume last session', 'dim'));
1425
+ console.log((0, ui_js_1.c)(' genesis chat --resume <id> Resume specific session', 'dim'));
1426
+ console.log((0, ui_js_1.c)(' /session fork Fork current session', 'dim'));
1427
+ console.log((0, ui_js_1.c)(' /session delete <id> Delete a session', 'dim'));
1428
+ console.log();
1429
+ }
1430
+ /**
1431
+ * Render a simple bar
1432
+ */
1433
+ renderBar(value, width) {
1434
+ const filled = Math.round(value * width);
1435
+ const empty = width - filled;
1436
+ const bar = '█'.repeat(filled) + '░'.repeat(empty);
1437
+ if (value >= 0.7)
1438
+ return (0, ui_js_1.c)(bar, 'green');
1439
+ if (value >= 0.3)
1440
+ return (0, ui_js_1.c)(bar, 'yellow');
1441
+ return (0, ui_js_1.c)(bar, 'red');
1442
+ }
1443
+ /**
1444
+ * Print brain metrics (Phase 10)
1445
+ */
1446
+ printBrainMetrics() {
1447
+ const metrics = this.brain.getMetrics();
1448
+ console.log((0, ui_js_1.c)('Brain Metrics (Phase 10):', 'bold'));
1449
+ console.log();
1450
+ console.log((0, ui_js_1.c)('Processing:', 'cyan'));
1451
+ console.log(` Total cycles: ${metrics.totalCycles}`);
1452
+ console.log(` Successful: ${metrics.successfulCycles}`);
1453
+ console.log(` Failed: ${metrics.failedCycles}`);
1454
+ console.log(` Avg cycle time: ${metrics.avgCycleTime.toFixed(0)}ms`);
1455
+ console.log();
1456
+ console.log((0, ui_js_1.c)('Memory (Cognitive Workspace):', 'cyan'));
1457
+ console.log(` Recalls: ${metrics.memoryRecalls}`);
1458
+ console.log(` Reuse rate: ${(metrics.memoryReuseRate * 100).toFixed(1)}% ${metrics.memoryReuseRate >= 0.54 ? (0, ui_js_1.c)('(target: 54-60%)', 'green') : (0, ui_js_1.c)('(target: 54-60%)', 'yellow')}`);
1459
+ console.log(` Anticipation hits: ${metrics.anticipationHits}`);
1460
+ console.log(` Anticipation miss: ${metrics.anticipationMisses}`);
1461
+ console.log();
1462
+ console.log((0, ui_js_1.c)('Grounding (Epistemic Stack):', 'cyan'));
1463
+ console.log(` Checks: ${metrics.groundingChecks}`);
1464
+ console.log(` Passes: ${metrics.groundingPasses}`);
1465
+ console.log(` Failures: ${metrics.groundingFailures}`);
1466
+ console.log(` Human consults: ${metrics.humanConsultations}`);
1467
+ console.log();
1468
+ console.log((0, ui_js_1.c)('Tools:', 'cyan'));
1469
+ console.log(` Executions: ${metrics.toolExecutions}`);
1470
+ console.log(` Successes: ${metrics.toolSuccesses}`);
1471
+ console.log(` Failures: ${metrics.toolFailures}`);
1472
+ console.log();
1473
+ console.log((0, ui_js_1.c)('Healing (Darwin-Gödel):', 'cyan'));
1474
+ console.log(` Attempts: ${metrics.healingAttempts}`);
1475
+ console.log(` Successes: ${metrics.healingSuccesses}`);
1476
+ console.log(` Failures: ${metrics.healingFailures}`);
1477
+ console.log();
1478
+ console.log((0, ui_js_1.c)('Consciousness (φ Monitor):', 'cyan'));
1479
+ console.log(` Avg φ: ${metrics.avgPhi.toFixed(3)}`);
1480
+ console.log(` φ violations: ${metrics.phiViolations}`);
1481
+ console.log(` Broadcasts: ${metrics.broadcasts}`);
1482
+ console.log();
1483
+ // Module transitions
1484
+ if (Object.keys(metrics.moduleTransitions).length > 0) {
1485
+ console.log((0, ui_js_1.c)('Module Transitions:', 'cyan'));
1486
+ for (const [transition, count] of Object.entries(metrics.moduleTransitions)) {
1487
+ console.log(` ${transition}: ${count}`);
1488
+ }
1489
+ console.log();
1490
+ }
1491
+ }
1492
+ /**
1493
+ * Print memory status (v7.0)
1494
+ */
1495
+ printMemoryStatus() {
1496
+ const stats = this.memory.getStats();
1497
+ const consolidationStats = this.memory.consolidation.getStats();
1498
+ console.log((0, ui_js_1.c)('Memory Status (v7.0):', 'bold'));
1499
+ console.log();
1500
+ console.log((0, ui_js_1.c)('Stores:', 'cyan'));
1501
+ console.log(` Episodic: ${stats.episodic.total} memories`);
1502
+ console.log(` Semantic: ${stats.semantic.total} facts`);
1503
+ console.log(` Procedural: ${stats.procedural.total} skills`);
1504
+ console.log();
1505
+ console.log((0, ui_js_1.c)('Consolidation:', 'cyan'));
1506
+ console.log(` Background: ${consolidationStats.backgroundRunning ? (0, ui_js_1.success)('RUNNING') : (0, ui_js_1.muted)('STOPPED')}`);
1507
+ console.log(` Last run: ${consolidationStats.lastConsolidation?.toLocaleString() || (0, ui_js_1.muted)('Never')}`);
1508
+ console.log(` Total runs: ${consolidationStats.totalConsolidations}`);
1509
+ console.log();
1510
+ console.log((0, ui_js_1.c)('Forgetting (Ebbinghaus):', 'cyan'));
1511
+ console.log(` Episodic weak: ${consolidationStats.memoryStats.episodic.weak}/${consolidationStats.memoryStats.episodic.total}`);
1512
+ console.log(` Semantic weak: ${consolidationStats.memoryStats.semantic.weak}/${consolidationStats.memoryStats.semantic.total}`);
1513
+ console.log(` Procedural weak: ${consolidationStats.memoryStats.procedural.weak}/${consolidationStats.memoryStats.procedural.total}`);
1514
+ console.log();
1515
+ console.log((0, ui_js_1.c)('Commands:', 'dim'));
1516
+ console.log((0, ui_js_1.muted)(' /remember <text> Add a fact to memory'));
1517
+ console.log((0, ui_js_1.muted)(' /consolidate Run consolidation now'));
1518
+ console.log((0, ui_js_1.muted)(' /forget confirm Clear all memory'));
1519
+ console.log();
1520
+ }
1521
+ /**
1522
+ * Print healing status (v7.0 Darwin-Gödel)
1523
+ */
1524
+ printHealingStatus() {
1525
+ const brainMetrics = this.brain.getMetrics();
1526
+ console.log((0, ui_js_1.c)('Darwin-Gödel Self-Healing (v7.0):', 'bold'));
1527
+ console.log();
1528
+ console.log((0, ui_js_1.c)('Healing Status:', 'cyan'));
1529
+ console.log(` Enabled: ${(0, ui_js_1.success)('YES')}`);
1530
+ console.log(` Auto-heal: ${(0, ui_js_1.success)('YES')}`);
1531
+ console.log(` Max attempts: 3`);
1532
+ console.log();
1533
+ console.log((0, ui_js_1.c)('Metrics:', 'cyan'));
1534
+ console.log(` Attempts: ${brainMetrics.healingAttempts}`);
1535
+ console.log(` Successes: ${brainMetrics.healingSuccesses}`);
1536
+ console.log(` Failures: ${brainMetrics.healingFailures}`);
1537
+ console.log();
1538
+ console.log((0, ui_js_1.c)('Error Detector:', 'cyan'));
1539
+ const detector = index_js_6.healing.getDetector();
1540
+ console.log(` Patterns: TypeScript, Python, Bash, Generic`);
1541
+ console.log(` Categories: syntax, type, runtime, dependency, config, network`);
1542
+ console.log();
1543
+ console.log((0, ui_js_1.c)('Auto-Fixer:', 'cyan'));
1544
+ const fixer = index_js_6.healing.getFixer();
1545
+ const config = fixer.getConfig();
1546
+ console.log(` Max candidates: ${config.maxCandidates}`);
1547
+ console.log(` Max iterations: ${config.maxIterations}`);
1548
+ console.log(` Working dir: ${config.workingDirectory}`);
1549
+ console.log();
1550
+ }
1551
+ /**
1552
+ * Run self-analysis (v7.0 Darwin-Gödel)
1553
+ */
1554
+ runSelfAnalysis() {
1555
+ console.log((0, ui_js_1.c)('Darwin-Gödel Self-Analysis (v7.0):', 'bold'));
1556
+ console.log();
1557
+ // Collect metrics
1558
+ const brainMetrics = this.brain.getMetrics();
1559
+ const memoryStats = this.memory.getStats();
1560
+ // Calculate system health
1561
+ const successRate = brainMetrics.totalCycles > 0
1562
+ ? brainMetrics.successfulCycles / brainMetrics.totalCycles
1563
+ : 1;
1564
+ const errorRate = brainMetrics.totalCycles > 0
1565
+ ? brainMetrics.failedCycles / brainMetrics.totalCycles
1566
+ : 0;
1567
+ // Analyze for improvements
1568
+ const improvements = this.selfProduction.analyzeForImprovements({
1569
+ avgPipelineDuration: brainMetrics.avgCycleTime,
1570
+ errorRate,
1571
+ systemsCreated: this.messageCount,
1572
+ cacheHitRate: brainMetrics.memoryReuseRate,
1573
+ hasAdvancedTemplates: false,
1574
+ });
1575
+ console.log((0, ui_js_1.c)('System Health:', 'cyan'));
1576
+ const healthBar = this.renderHealthBar(successRate);
1577
+ console.log(` Success rate: ${healthBar} ${(successRate * 100).toFixed(1)}%`);
1578
+ console.log(` Error rate: ${(errorRate * 100).toFixed(1)}%`);
1579
+ console.log(` Avg cycle time: ${brainMetrics.avgCycleTime.toFixed(0)}ms`);
1580
+ console.log(` Memory reuse: ${(brainMetrics.memoryReuseRate * 100).toFixed(1)}%`);
1581
+ console.log();
1582
+ console.log((0, ui_js_1.c)('Self-Production:', 'cyan'));
1583
+ console.log(` Current version: ${this.selfProduction.getVersion()}`);
1584
+ console.log(` History: ${this.selfProduction.getHistory().length} productions`);
1585
+ console.log();
1586
+ if (improvements.length > 0) {
1587
+ console.log((0, ui_js_1.c)('Suggested Improvements:', 'yellow'));
1588
+ for (const imp of improvements) {
1589
+ const priorityColor = imp.priority === 'critical' ? 'red' : imp.priority === 'high' ? 'yellow' : 'dim';
1590
+ console.log(` [${(0, ui_js_1.c)(imp.priority.toUpperCase(), priorityColor)}] ${imp.description}`);
1591
+ console.log((0, ui_js_1.muted)(` Type: ${imp.type}, Impact: ${(imp.estimatedImpact * 100).toFixed(0)}%`));
1592
+ }
1593
+ }
1594
+ else {
1595
+ console.log((0, ui_js_1.c)('No improvements needed. System is healthy!', 'green'));
1596
+ }
1597
+ console.log();
1598
+ }
1599
+ /**
1600
+ * Render health bar
1601
+ */
1602
+ renderHealthBar(health) {
1603
+ const width = 15;
1604
+ const filled = Math.round(health * width);
1605
+ const empty = width - filled;
1606
+ const bar = '█'.repeat(filled) + '░'.repeat(empty);
1607
+ if (health >= 0.9)
1608
+ return (0, ui_js_1.c)(bar, 'green');
1609
+ if (health >= 0.7)
1610
+ return (0, ui_js_1.c)(bar, 'yellow');
1611
+ return (0, ui_js_1.c)(bar, 'red');
1612
+ }
1613
+ /**
1614
+ * Run self-improvement (v7.0 Darwin-Gödel)
1615
+ */
1616
+ async runSelfImprovement() {
1617
+ console.log((0, ui_js_1.c)('Darwin-Gödel Self-Improvement (v7.0):', 'bold'));
1618
+ console.log();
1619
+ // First, run analysis
1620
+ const brainMetrics = this.brain.getMetrics();
1621
+ const errorRate = brainMetrics.totalCycles > 0
1622
+ ? brainMetrics.failedCycles / brainMetrics.totalCycles
1623
+ : 0;
1624
+ const improvements = this.selfProduction.analyzeForImprovements({
1625
+ avgPipelineDuration: brainMetrics.avgCycleTime,
1626
+ errorRate,
1627
+ systemsCreated: this.messageCount,
1628
+ cacheHitRate: brainMetrics.memoryReuseRate,
1629
+ hasAdvancedTemplates: false,
1630
+ });
1631
+ if (improvements.length === 0) {
1632
+ console.log((0, ui_js_1.success)('✓ No improvements needed. System is already optimal.'));
1633
+ return;
1634
+ }
1635
+ console.log((0, ui_js_1.info)(`Found ${improvements.length} potential improvements.`));
1636
+ // Filter to high priority
1637
+ const highPriority = improvements.filter(i => i.priority === 'critical' || i.priority === 'high');
1638
+ if (highPriority.length === 0) {
1639
+ console.log((0, ui_js_1.muted)('No critical or high priority improvements. Skipping.'));
1640
+ return;
1641
+ }
1642
+ console.log((0, ui_js_1.warning)('Self-improvement would modify the system. This is currently simulated.'));
1643
+ console.log((0, ui_js_1.muted)('In a real scenario, the following steps would occur:'));
1644
+ console.log((0, ui_js_1.muted)(' 1. Git commit created as safety checkpoint'));
1645
+ console.log((0, ui_js_1.muted)(' 2. Code modifications generated by LLM'));
1646
+ console.log((0, ui_js_1.muted)(' 3. Tests run to validate changes'));
1647
+ console.log((0, ui_js_1.muted)(' 4. On failure: git revert to checkpoint'));
1648
+ console.log((0, ui_js_1.muted)(' 5. On success: new version tagged'));
1649
+ console.log();
1650
+ // Simulate the production
1651
+ const spec = {
1652
+ currentVersion: this.selfProduction.getVersion(),
1653
+ targetVersion: '7.0.1',
1654
+ improvements: highPriority,
1655
+ preserveInvariants: this.selfProduction.getInvariants(),
1656
+ };
1657
+ console.log((0, ui_js_1.info)('Simulating production...'));
1658
+ const result = await this.selfProduction.produce(spec);
1659
+ if (result.success) {
1660
+ console.log((0, ui_js_1.success)(`✓ Self-improvement successful! New version: ${result.newVersion}`));
1661
+ }
1662
+ else {
1663
+ console.log((0, ui_js_1.warning)('Self-improvement simulation completed (no actual changes made).'));
1664
+ }
1665
+ console.log();
1666
+ }
1667
+ /**
1668
+ * Print brain status (Phase 10)
1669
+ */
1670
+ printBrainStatus() {
1671
+ const metrics = this.brain.getMetrics();
1672
+ const phi = metrics.avgPhi;
1673
+ console.log((0, ui_js_1.c)('Brain Status (Phase 10 Neural Integration):', 'bold'));
1674
+ console.log();
1675
+ console.log((0, ui_js_1.c)('Mode:', 'cyan'));
1676
+ console.log(` Brain: ${this.enableBrain ? (0, ui_js_1.c)('ACTIVE', 'green') : (0, ui_js_1.c)('OFF', 'yellow')}`);
1677
+ console.log(` Running: ${this.brain.isRunning() ? (0, ui_js_1.c)('Yes', 'green') : (0, ui_js_1.c)('No', 'dim')}`);
1678
+ console.log();
1679
+ console.log((0, ui_js_1.c)('Consciousness:', 'cyan'));
1680
+ console.log(` φ Level: ${phi.toFixed(3)}`);
1681
+ console.log(` φ Bar: ${this.renderPhiBar(phi)}`);
1682
+ console.log(` Ignited: ${phi > 0.3 ? (0, ui_js_1.c)('Yes', 'green') : (0, ui_js_1.c)('No', 'dim')}`);
1683
+ console.log();
1684
+ console.log((0, ui_js_1.c)('Performance:', 'cyan'));
1685
+ const successRate = metrics.totalCycles > 0
1686
+ ? (metrics.successfulCycles / metrics.totalCycles * 100).toFixed(1)
1687
+ : '0';
1688
+ console.log(` Cycles: ${metrics.totalCycles}`);
1689
+ console.log(` Success: ${successRate}%`);
1690
+ console.log(` Avg time: ${metrics.avgCycleTime.toFixed(0)}ms`);
1691
+ console.log(` Mem reuse: ${(metrics.memoryReuseRate * 100).toFixed(1)}%`);
1692
+ console.log();
1693
+ console.log((0, ui_js_1.c)('Modules Connected:', 'cyan'));
1694
+ console.log(' ✓ Memory (Cognitive Workspace)');
1695
+ console.log(' ✓ LLM (Hybrid Router)');
1696
+ console.log(' ✓ Grounding (Epistemic Stack)');
1697
+ console.log(' ✓ Tools (Dispatcher)');
1698
+ console.log(' ✓ Healing (Darwin-Gödel)');
1699
+ console.log(' ✓ Consciousness (φ Monitor)');
1700
+ console.log(' ✓ Kernel (Agent Orchestration)');
1701
+ console.log();
1702
+ }
1703
+ /**
1704
+ * v7.3.6: Run MCP Diagnostics - test all MCP servers and show status
1705
+ */
1706
+ async runMCPDiagnostics() {
1707
+ console.log((0, ui_js_1.c)('MCP Server Diagnostics:', 'bold'));
1708
+ console.log();
1709
+ const client = (0, index_js_3.getMCPClient)();
1710
+ const servers = Object.keys(index_js_3.MCP_SERVER_REGISTRY);
1711
+ // Check required API keys
1712
+ const requiredKeys = {
1713
+ 'wolfram': ['WOLFRAM_APP_ID'],
1714
+ 'brave-search': ['BRAVE_API_KEY'],
1715
+ 'exa': ['EXA_API_KEY'],
1716
+ 'firecrawl': ['FIRECRAWL_API_KEY'],
1717
+ 'openai': ['OPENAI_API_KEY'],
1718
+ 'github': ['GITHUB_PERSONAL_ACCESS_TOKEN', 'GITHUB_TOKEN'],
1719
+ 'stability-ai': ['STABILITY_AI_API_KEY'],
1720
+ 'gemini': ['GOOGLE_API_KEY', 'GEMINI_API_KEY'],
1721
+ };
1722
+ const results = [];
1723
+ console.log((0, ui_js_1.info)('Testing MCP servers...'));
1724
+ console.log();
1725
+ for (const server of servers) {
1726
+ process.stdout.write(` ${server}: `);
1727
+ // Check API keys first
1728
+ const keys = requiredKeys[server];
1729
+ if (keys) {
1730
+ const hasKey = keys.some(k => !!process.env[k]);
1731
+ if (!hasKey) {
1732
+ console.log((0, ui_js_1.warning)(`MISSING API KEY (${keys.join(' or ')})`));
1733
+ results.push({ server, status: 'no-key', tools: 0, message: `Missing: ${keys.join(' or ')}` });
1734
+ continue;
1735
+ }
1736
+ }
1737
+ // Try to connect and list tools
1738
+ try {
1739
+ const available = await client.isAvailable(server);
1740
+ if (available) {
1741
+ const tools = await client.listTools(server);
1742
+ console.log((0, ui_js_1.success)(`✓ OK (${tools.length} tools)`));
1743
+ results.push({ server, status: 'ok', tools: tools.length });
1744
+ }
1745
+ else {
1746
+ console.log((0, ui_js_1.error)('✗ NOT AVAILABLE'));
1747
+ results.push({ server, status: 'error', tools: 0, message: 'Connection failed' });
1748
+ }
1749
+ }
1750
+ catch (err) {
1751
+ const msg = err instanceof Error ? err.message : String(err);
1752
+ console.log((0, ui_js_1.error)(`✗ ERROR: ${msg.slice(0, 50)}`));
1753
+ results.push({ server, status: 'error', tools: 0, message: msg });
1754
+ }
1755
+ }
1756
+ console.log();
1757
+ // Summary
1758
+ const okCount = results.filter(r => r.status === 'ok').length;
1759
+ const errorCount = results.filter(r => r.status === 'error').length;
1760
+ const noKeyCount = results.filter(r => r.status === 'no-key').length;
1761
+ const totalTools = results.reduce((sum, r) => sum + r.tools, 0);
1762
+ console.log((0, ui_js_1.c)('Summary:', 'cyan'));
1763
+ console.log(` Servers OK: ${(0, ui_js_1.success)(String(okCount))}/${servers.length}`);
1764
+ console.log(` Servers Error: ${errorCount > 0 ? (0, ui_js_1.error)(String(errorCount)) : (0, ui_js_1.muted)('0')}`);
1765
+ console.log(` Missing API Keys: ${noKeyCount > 0 ? (0, ui_js_1.warning)(String(noKeyCount)) : (0, ui_js_1.muted)('0')}`);
1766
+ console.log(` Total Tools: ${totalTools}`);
1767
+ console.log();
1768
+ // Show local tools
1769
+ const localTools = this.dispatcher.listTools().local;
1770
+ console.log((0, ui_js_1.c)('Local Tools:', 'cyan'));
1771
+ console.log(` Available: ${localTools.length}`);
1772
+ console.log(` Tools: ${localTools.slice(0, 5).join(', ')}${localTools.length > 5 ? '...' : ''}`);
1773
+ console.log();
1774
+ // Mode info
1775
+ console.log((0, ui_js_1.c)('Mode:', 'cyan'));
1776
+ console.log(` MCP Mode: ${client.getMode()}`);
1777
+ console.log(` Tools Enabled: ${this.enableTools ? (0, ui_js_1.success)('YES') : (0, ui_js_1.warning)('NO')}`);
1778
+ console.log();
1779
+ }
1780
+ /**
1781
+ * v7.3.6: Pre-warm critical MCP servers in background
1782
+ * This prevents cold start timeouts when Genesis needs to use tools
1783
+ */
1784
+ preWarmMCPServers() {
1785
+ // Don't block startup - warm up in background
1786
+ const client = (0, index_js_3.getMCPClient)();
1787
+ const criticalServers = ['memory', 'filesystem', 'github'];
1788
+ // Fire and forget - we don't need to wait
1789
+ Promise.all(criticalServers.map(async (server) => {
1790
+ try {
1791
+ await client.isAvailable(server);
1792
+ }
1793
+ catch {
1794
+ // Ignore errors during pre-warming
1795
+ }
1796
+ })).catch(() => {
1797
+ // Silently ignore any errors
1798
+ });
1799
+ }
1800
+ /**
1801
+ * v7.4: Run in headless mode (non-interactive, for scripting/CI-CD)
1802
+ * Processes a single prompt and outputs the response to stdout
1803
+ */
1804
+ async runHeadless(prompt) {
1805
+ // Initialize without UI
1806
+ await this.initializeHeadless();
1807
+ try {
1808
+ let response;
1809
+ if (this.enableBrain) {
1810
+ // Use Brain for processing
1811
+ response = await this.brain.process(prompt);
1812
+ }
1813
+ else {
1814
+ // Direct LLM call
1815
+ const result = await this.llm.chat(prompt, this.systemPrompt);
1816
+ response = result.content;
1817
+ }
1818
+ // Output based on format
1819
+ if (this.outputFormat === 'json') {
1820
+ const metrics = this.enableBrain ? this.brain.getMetrics() : null;
1821
+ const output = {
1822
+ success: true,
1823
+ response,
1824
+ metrics: metrics ? {
1825
+ phi: metrics.avgPhi,
1826
+ cycles: metrics.totalCycles,
1827
+ memoryReuseRate: metrics.memoryReuseRate,
1828
+ } : undefined,
1829
+ };
1830
+ console.log(JSON.stringify(output));
1831
+ }
1832
+ else {
1833
+ // Plain text output
1834
+ console.log(response);
1835
+ }
1836
+ // Cleanup
1837
+ this.cleanupHeadless();
1838
+ process.exit(0);
1839
+ }
1840
+ catch (err) {
1841
+ if (this.outputFormat === 'json') {
1842
+ console.log(JSON.stringify({
1843
+ success: false,
1844
+ error: err instanceof Error ? err.message : String(err),
1845
+ }));
1846
+ }
1847
+ else {
1848
+ console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
1849
+ }
1850
+ this.cleanupHeadless();
1851
+ process.exit(1);
1852
+ }
1853
+ }
1854
+ /**
1855
+ * v7.4: Initialize for headless mode (minimal setup, no UI)
1856
+ */
1857
+ async initializeHeadless() {
1858
+ // Build system prompt dynamically
1859
+ const toolsWithSchemas = this.dispatcher.listToolsWithSchemas();
1860
+ this.systemPrompt = await (0, index_js_1.buildSystemPrompt)(toolsWithSchemas.mcp, toolsWithSchemas.local);
1861
+ // Start brain if enabled
1862
+ if (this.enableBrain && !this.brain.isRunning()) {
1863
+ this.brain.start();
1864
+ }
1865
+ }
1866
+ /**
1867
+ * v7.4: Cleanup for headless mode
1868
+ */
1869
+ cleanupHeadless() {
1870
+ if (this.enableBrain) {
1871
+ this.brain.stop();
1872
+ }
1873
+ if (this.brainEventUnsub) {
1874
+ this.brainEventUnsub();
1875
+ this.brainEventUnsub = null;
1876
+ }
1877
+ this.store.close();
1878
+ }
1879
+ /**
1880
+ * Stop chat session
1881
+ */
1882
+ stop() {
1883
+ this.running = false;
1884
+ // v7.4.5: Execute session-end hook
1885
+ if (this.hooks.hasHooks()) {
1886
+ // Fire and forget (async but we don't wait)
1887
+ this.hooks.execute('session-end', {
1888
+ event: 'session-end',
1889
+ sessionId: this.store.getState().session?.id,
1890
+ workingDir: process.cwd(),
1891
+ });
1892
+ }
1893
+ // v7.3.8: Cleanup brain event subscription
1894
+ if (this.brainEventUnsub) {
1895
+ this.brainEventUnsub();
1896
+ this.brainEventUnsub = null;
1897
+ }
1898
+ // Stop brain if running
1899
+ if (this.enableBrain) {
1900
+ console.log((0, ui_js_1.c)('\nStopping brain...', 'dim'));
1901
+ this.brain.stop();
1902
+ }
1903
+ // Save state before exit
1904
+ console.log((0, ui_js_1.c)('Saving state...', 'dim'));
1905
+ this.store.updateConversation(this.llm.getHistory());
1906
+ // v7.4: Save session for resume
1907
+ const state = this.store.getState();
1908
+ const sessionId = this.sessionManager.saveSession(state, this.sessionName);
1909
+ console.log((0, ui_js_1.c)(`Session saved: ${sessionId.slice(0, 8)}`, 'dim'));
1910
+ this.store.close();
1911
+ console.log((0, ui_js_1.c)('Goodbye! Genesis signing off.\n', 'cyan'));
1912
+ this.rl?.close();
1913
+ process.exit(0);
1914
+ }
1915
+ }
1916
+ exports.ChatSession = ChatSession;
1917
+ // ============================================================================
1918
+ // Factory
1919
+ // ============================================================================
1920
+ function createChatSession(options) {
1921
+ return new ChatSession(options);
1922
+ }
1923
+ /**
1924
+ * Start interactive chat (convenience function)
1925
+ */
1926
+ async function startChat(options) {
1927
+ const session = createChatSession(options);
1928
+ // v7.4: Headless mode support
1929
+ if (options?.headless && options?.prompt) {
1930
+ await session.runHeadless(options.prompt);
1931
+ return;
1932
+ }
1933
+ await session.start();
1934
+ }
1935
+ /**
1936
+ * v7.4: Run headless mode with prompt from stdin or argument
1937
+ * Used by CLI for -p/--print flag
1938
+ */
1939
+ async function runHeadless(prompt, options) {
1940
+ const session = createChatSession({ ...options, headless: true });
1941
+ await session.runHeadless(prompt);
1942
+ }
1943
+ /**
1944
+ * v7.4: Read prompt from stdin (for piping)
1945
+ */
1946
+ function readStdin() {
1947
+ return new Promise((resolve, reject) => {
1948
+ if (process.stdin.isTTY) {
1949
+ // No piped input
1950
+ resolve('');
1951
+ return;
1952
+ }
1953
+ let data = '';
1954
+ process.stdin.setEncoding('utf8');
1955
+ process.stdin.on('data', chunk => { data += chunk; });
1956
+ process.stdin.on('end', () => resolve(data.trim()));
1957
+ process.stdin.on('error', reject);
1958
+ });
1959
+ }