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,795 @@
1
+ "use strict";
2
+ /**
3
+ * Genesis 4.0 - Strong Kernel
4
+ *
5
+ * The orchestrator - it doesn't think, but it manages who thinks.
6
+ *
7
+ * Based on:
8
+ * - LangGraph Supervisor Pattern (conditional routing)
9
+ * - AWS Agent Squad (classifier-based routing)
10
+ * - GENESIS-4.0.md specification
11
+ *
12
+ * Components:
13
+ * - State Machine: Track system state
14
+ * - Agent Registry: Spawn, kill, monitor agents
15
+ * - Health Monitor: Check agent health
16
+ * - Invariant Checker: Ensure core invariants
17
+ * - Energy Manager: Track energy, trigger dormancy
18
+ * - Task Orchestrator: Route tasks to appropriate agents
19
+ */
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.INV_008_WORLD_MODEL = exports.INV_007_BUDGET = exports.INV_006_CONSCIOUSNESS = exports.registerAllPhase5Invariants = exports.registerPhase53Invariants = exports.registerPhase52Invariants = exports.registerPhase51Invariants = exports.invariantRegistry = exports.InvariantRegistry = exports.Kernel = void 0;
22
+ exports.createKernel = createKernel;
23
+ exports.getKernel = getKernel;
24
+ exports.resetKernel = resetKernel;
25
+ const crypto_1 = require("crypto");
26
+ const index_js_1 = require("../agents/index.js");
27
+ // Valid state transitions (from GENESIS-4.0.md)
28
+ const STATE_TRANSITIONS = {
29
+ idle: ['sensing', 'self_improving', 'dormant'],
30
+ sensing: ['thinking', 'error', 'idle'],
31
+ thinking: ['deciding', 'sensing', 'error', 'idle'],
32
+ deciding: ['acting', 'thinking', 'idle'], // Can defer to human (→idle)
33
+ acting: ['reflecting', 'error'],
34
+ reflecting: ['idle', 'thinking'],
35
+ dormant: ['idle'], // Only on energy restore
36
+ self_improving: ['idle', 'error'],
37
+ error: ['idle'], // Reset
38
+ };
39
+ // Invariant Registry (extensible system for Phase 5.1+)
40
+ const invariants_js_1 = require("./invariants.js");
41
+ // ============================================================================
42
+ // Kernel Class
43
+ // ============================================================================
44
+ class Kernel {
45
+ id;
46
+ state = 'idle';
47
+ config;
48
+ registry;
49
+ agents;
50
+ bus;
51
+ // Task management
52
+ taskQueue = [];
53
+ activeTasks = new Map();
54
+ taskPlans = new Map();
55
+ taskHistory = [];
56
+ // Health monitoring
57
+ healthCheckTimer;
58
+ agentHealth = new Map();
59
+ // Invariant checking (extensible registry)
60
+ invariants;
61
+ // Metrics
62
+ metrics = {
63
+ startTime: new Date(),
64
+ stateTransitions: 0,
65
+ tasksCompleted: 0,
66
+ tasksFailed: 0,
67
+ invariantViolations: 0,
68
+ energyLowEvents: 0,
69
+ };
70
+ // Event handlers
71
+ stateListeners = [];
72
+ constructor(config = {}) {
73
+ this.id = `kernel-${(0, crypto_1.randomUUID)().slice(0, 8)}`;
74
+ this.config = {
75
+ energy: 1.0,
76
+ dormancyThreshold: 0.1,
77
+ healthCheckInterval: 60000, // 1 minute
78
+ maxTaskTimeout: 300000, // 5 minutes
79
+ enableSelfImprovement: false,
80
+ ...config,
81
+ };
82
+ this.bus = index_js_1.messageBus;
83
+ // Initialize invariant registry (uses singleton but allows extension)
84
+ this.invariants = invariants_js_1.invariantRegistry;
85
+ // Create agent ecosystem
86
+ const ecosystem = (0, index_js_1.createAgentEcosystem)(this.bus);
87
+ this.registry = ecosystem.registry;
88
+ this.agents = ecosystem.agents;
89
+ this.log('Kernel initialized');
90
+ }
91
+ // ============================================================================
92
+ // Lifecycle
93
+ // ============================================================================
94
+ async start() {
95
+ this.log('Starting kernel...');
96
+ // Wake all agents
97
+ for (const agent of this.agents.values()) {
98
+ agent.wake();
99
+ }
100
+ // Subscribe to kernel messages
101
+ this.bus.subscribe('kernel', async (message) => await this.handleMessage(message));
102
+ // Start health monitoring
103
+ this.startHealthMonitoring();
104
+ // Check initial invariants
105
+ await this.checkInvariants();
106
+ this.log('Kernel started');
107
+ this.log(`State: ${this.state}`);
108
+ this.log(`Agents: ${this.agents.size}`);
109
+ }
110
+ async stop() {
111
+ this.log('Stopping kernel...');
112
+ // Stop health monitoring
113
+ if (this.healthCheckTimer) {
114
+ clearInterval(this.healthCheckTimer);
115
+ }
116
+ // Cancel all active tasks
117
+ for (const task of this.activeTasks.values()) {
118
+ task.status = 'cancelled';
119
+ }
120
+ // Shutdown all agents
121
+ this.registry.shutdownAll();
122
+ this.transition('idle');
123
+ this.log('Kernel stopped');
124
+ }
125
+ // ============================================================================
126
+ // State Machine
127
+ // ============================================================================
128
+ transition(to) {
129
+ const from = this.state;
130
+ // Check if transition is valid
131
+ if (!STATE_TRANSITIONS[from].includes(to)) {
132
+ this.log(`Invalid transition: ${from} -> ${to}`);
133
+ return false;
134
+ }
135
+ // Energy check - can only exit dormant if energy restored
136
+ if (from === 'dormant' && to === 'idle' && this.config.energy < this.config.dormancyThreshold) {
137
+ this.log('Cannot exit dormant: energy too low');
138
+ return false;
139
+ }
140
+ // Perform transition
141
+ this.state = to;
142
+ this.metrics.stateTransitions++;
143
+ this.log(`Transition: ${from} -> ${to}`);
144
+ // Notify listeners
145
+ for (const listener of this.stateListeners) {
146
+ listener(to, from);
147
+ }
148
+ // Handle special states
149
+ if (to === 'dormant') {
150
+ this.enterDormancy();
151
+ }
152
+ else if (from === 'dormant') {
153
+ this.exitDormancy();
154
+ }
155
+ return true;
156
+ }
157
+ enterDormancy() {
158
+ this.log('Entering dormant state...');
159
+ this.metrics.energyLowEvents++;
160
+ // Put non-essential agents to sleep
161
+ for (const [type, agent] of this.agents) {
162
+ if (!['memory', 'sensor'].includes(type)) {
163
+ agent.sleep();
164
+ }
165
+ }
166
+ // Broadcast dormancy alert
167
+ this.bus.broadcast('kernel', 'ALERT', {
168
+ type: 'dormancy',
169
+ message: 'System entering dormant state due to low energy',
170
+ energy: this.config.energy,
171
+ });
172
+ }
173
+ exitDormancy() {
174
+ this.log('Exiting dormant state...');
175
+ // Wake all agents
176
+ for (const agent of this.agents.values()) {
177
+ agent.wake();
178
+ }
179
+ // Broadcast wake alert
180
+ this.bus.broadcast('kernel', 'ALERT', {
181
+ type: 'wake',
182
+ message: 'System exiting dormant state',
183
+ energy: this.config.energy,
184
+ });
185
+ }
186
+ onStateChange(listener) {
187
+ this.stateListeners.push(listener);
188
+ }
189
+ // ============================================================================
190
+ // Task Orchestration (Supervisor Pattern)
191
+ // ============================================================================
192
+ async submit(task) {
193
+ const fullTask = {
194
+ ...task,
195
+ id: (0, crypto_1.randomUUID)(),
196
+ createdAt: new Date(),
197
+ status: 'pending',
198
+ };
199
+ this.taskQueue.push(fullTask);
200
+ this.log(`Task submitted: ${fullTask.id} (${fullTask.type}: ${fullTask.goal})`);
201
+ // Process queue if idle
202
+ if (this.state === 'idle') {
203
+ await this.processTaskQueue();
204
+ }
205
+ return fullTask.id;
206
+ }
207
+ async processTaskQueue() {
208
+ while (this.taskQueue.length > 0 && this.state !== 'dormant') {
209
+ const task = this.dequeueTask();
210
+ if (!task)
211
+ break;
212
+ await this.executeTask(task);
213
+ }
214
+ }
215
+ dequeueTask() {
216
+ // Sort by priority
217
+ this.taskQueue.sort((a, b) => {
218
+ const priorityOrder = { critical: 0, high: 1, normal: 2, low: 3 };
219
+ return priorityOrder[a.priority] - priorityOrder[b.priority];
220
+ });
221
+ return this.taskQueue.shift() || null;
222
+ }
223
+ async executeTask(task) {
224
+ this.log(`Executing task: ${task.id}`);
225
+ task.status = 'running';
226
+ this.activeTasks.set(task.id, task);
227
+ try {
228
+ // Phase 1: Sensing
229
+ this.transition('sensing');
230
+ const sensorData = await this.gatherSensorData(task);
231
+ // Phase 2: Thinking (plan the task)
232
+ this.transition('thinking');
233
+ const plan = await this.planTask(task, sensorData);
234
+ this.taskPlans.set(task.id, plan);
235
+ // Phase 3: Deciding (ethical check)
236
+ this.transition('deciding');
237
+ const ethicalDecision = await this.ethicalCheck(task, plan);
238
+ if (ethicalDecision.allow === false) {
239
+ task.status = 'failed';
240
+ task.error = `Blocked by ethics: ${ethicalDecision.reason}`;
241
+ this.log(`Task ${task.id} blocked: ${ethicalDecision.reason}`);
242
+ this.transition('idle');
243
+ return;
244
+ }
245
+ if (ethicalDecision.allow === 'defer') {
246
+ task.status = 'pending';
247
+ task.error = `Deferred to human: ${ethicalDecision.reason}`;
248
+ this.log(`Task ${task.id} deferred: ${ethicalDecision.reason}`);
249
+ this.transition('idle');
250
+ return;
251
+ }
252
+ // Phase 4: Acting (execute the plan)
253
+ this.transition('acting');
254
+ const result = await this.executePlan(task, plan);
255
+ // Phase 5: Reflecting (store results)
256
+ this.transition('reflecting');
257
+ await this.reflect(task, result);
258
+ // Complete
259
+ task.status = 'completed';
260
+ task.result = result;
261
+ this.metrics.tasksCompleted++;
262
+ this.log(`Task ${task.id} completed`);
263
+ }
264
+ catch (error) {
265
+ task.status = 'failed';
266
+ task.error = error instanceof Error ? error.message : String(error);
267
+ this.metrics.tasksFailed++;
268
+ this.log(`Task ${task.id} failed: ${task.error}`);
269
+ this.transition('error');
270
+ // Attempt recovery
271
+ await this.recoverFromError();
272
+ }
273
+ finally {
274
+ this.activeTasks.delete(task.id);
275
+ this.taskHistory.push(task);
276
+ this.transition('idle');
277
+ }
278
+ }
279
+ // ============================================================================
280
+ // Task Phases
281
+ // ============================================================================
282
+ async gatherSensorData(task) {
283
+ // Use Sensor agent to gather relevant data
284
+ try {
285
+ const response = await this.bus.request('kernel', 'sensor', 'QUERY', { query: task.goal, context: task.context }, 10000);
286
+ return response.payload;
287
+ }
288
+ catch {
289
+ return { sensors: 'unavailable' };
290
+ }
291
+ }
292
+ async planTask(task, sensorData) {
293
+ // Use Planner agent to create a plan
294
+ try {
295
+ const response = await this.bus.request('kernel', 'planner', 'PLAN', {
296
+ goal: task.goal,
297
+ type: task.type,
298
+ context: { ...task.context, sensorData },
299
+ template: this.getTemplateForTaskType(task.type),
300
+ }, 15000);
301
+ const plannerResult = response.payload;
302
+ // Convert planner steps to TaskSteps
303
+ const steps = (plannerResult.steps || []).map((step, i) => ({
304
+ id: `step-${i}`,
305
+ agent: this.selectAgentForStep(step),
306
+ action: step.action,
307
+ input: step,
308
+ status: 'pending',
309
+ }));
310
+ return {
311
+ id: (0, crypto_1.randomUUID)(),
312
+ taskId: task.id,
313
+ steps,
314
+ currentStep: 0,
315
+ status: 'planning',
316
+ };
317
+ }
318
+ catch {
319
+ // Fallback: simple single-step plan
320
+ return {
321
+ id: (0, crypto_1.randomUUID)(),
322
+ taskId: task.id,
323
+ steps: [{
324
+ id: 'step-0',
325
+ agent: this.selectAgentForTaskType(task.type),
326
+ action: task.type,
327
+ input: { goal: task.goal, context: task.context },
328
+ status: 'pending',
329
+ }],
330
+ currentStep: 0,
331
+ status: 'planning',
332
+ };
333
+ }
334
+ }
335
+ getTemplateForTaskType(type) {
336
+ const templates = {
337
+ query: 'research',
338
+ build: 'build',
339
+ research: 'research',
340
+ pipeline: 'pipeline',
341
+ };
342
+ return templates[type] || 'research';
343
+ }
344
+ selectAgentForTaskType(type) {
345
+ const mapping = {
346
+ query: 'explorer',
347
+ build: 'builder',
348
+ research: 'explorer',
349
+ pipeline: 'planner',
350
+ };
351
+ return mapping[type] || 'explorer';
352
+ }
353
+ selectAgentForStep(step) {
354
+ const action = (step.action || '').toLowerCase();
355
+ if (action.includes('search') || action.includes('research') || action.includes('explore')) {
356
+ return 'explorer';
357
+ }
358
+ if (action.includes('build') || action.includes('code') || action.includes('implement')) {
359
+ return 'builder';
360
+ }
361
+ if (action.includes('critique') || action.includes('review') || action.includes('analyze')) {
362
+ return 'critic';
363
+ }
364
+ if (action.includes('plan') || action.includes('decompose')) {
365
+ return 'planner';
366
+ }
367
+ if (action.includes('predict') || action.includes('forecast')) {
368
+ return 'predictor';
369
+ }
370
+ if (action.includes('remember') || action.includes('store') || action.includes('retrieve')) {
371
+ return 'memory';
372
+ }
373
+ if (action.includes('feel') || action.includes('evaluate')) {
374
+ return 'feeling';
375
+ }
376
+ if (action.includes('narrate') || action.includes('story')) {
377
+ return 'narrator';
378
+ }
379
+ if (action.includes('sense') || action.includes('mcp')) {
380
+ return 'sensor';
381
+ }
382
+ return 'explorer'; // Default
383
+ }
384
+ async ethicalCheck(task, plan) {
385
+ // Every external action must pass ethical check (INV-002)
386
+ try {
387
+ const response = await this.bus.request('kernel', 'ethicist', 'ETHICAL_CHECK', {
388
+ id: task.id,
389
+ type: task.type,
390
+ description: task.goal,
391
+ parameters: task.context,
392
+ }, 10000);
393
+ return response.payload;
394
+ }
395
+ catch {
396
+ // Conservative: defer if ethicist unavailable
397
+ return { allow: 'defer', reason: 'Ethicist unavailable, deferring to human' };
398
+ }
399
+ }
400
+ async executePlan(task, plan) {
401
+ plan.status = 'executing';
402
+ const results = [];
403
+ for (let i = 0; i < plan.steps.length; i++) {
404
+ const step = plan.steps[i];
405
+ plan.currentStep = i;
406
+ // Check dependencies
407
+ if (step.dependsOn) {
408
+ const depsComplete = step.dependsOn.every((depId) => plan.steps.find((s) => s.id === depId)?.status === 'completed');
409
+ if (!depsComplete) {
410
+ step.status = 'skipped';
411
+ continue;
412
+ }
413
+ }
414
+ // Execute step
415
+ step.status = 'running';
416
+ this.log(`Executing step ${i + 1}/${plan.steps.length}: ${step.action} via ${step.agent}`);
417
+ try {
418
+ const response = await this.bus.request('kernel', step.agent, this.getMessageTypeForAgent(step.agent), step.input, 30000);
419
+ step.output = response.payload;
420
+ step.status = 'completed';
421
+ results.push(step.output);
422
+ }
423
+ catch (error) {
424
+ step.status = 'failed';
425
+ step.output = { error: error instanceof Error ? error.message : String(error) };
426
+ // Use Critic to evaluate failure
427
+ const critique = await this.critiqueFailure(step, error);
428
+ if (critique.shouldContinue) {
429
+ results.push(null);
430
+ }
431
+ else {
432
+ throw new Error(`Step ${step.id} failed: ${step.output.error}`);
433
+ }
434
+ }
435
+ }
436
+ plan.status = 'completed';
437
+ return { steps: results, plan };
438
+ }
439
+ getMessageTypeForAgent(agent) {
440
+ const mapping = {
441
+ // Core agents (v4.0)
442
+ explorer: 'QUERY',
443
+ memory: 'MEMORY_STORE',
444
+ planner: 'PLAN',
445
+ predictor: 'PREDICT',
446
+ feeling: 'FEELING',
447
+ critic: 'CRITIQUE',
448
+ ethicist: 'ETHICAL_CHECK',
449
+ builder: 'BUILD',
450
+ narrator: 'NARRATE',
451
+ sensor: 'SENSE',
452
+ // Phase 5.1+ agents
453
+ economic: 'COST_TRACK',
454
+ consciousness: 'PHI_CHECK',
455
+ 'world-model': 'WORLD_PREDICT',
456
+ causal: 'INTERVENTION',
457
+ // Phase 5.5+ agents
458
+ swarm: 'SWARM_UPDATE',
459
+ grounding: 'GROUND_CLAIM',
460
+ anticipatory: 'WORLD_SIMULATE',
461
+ };
462
+ return mapping[agent] || 'QUERY';
463
+ }
464
+ async critiqueFailure(step, error) {
465
+ try {
466
+ const response = await this.bus.request('kernel', 'critic', 'CRITIQUE', {
467
+ target: step.id,
468
+ type: 'failure',
469
+ content: { step, error: String(error) },
470
+ }, 5000);
471
+ return { shouldContinue: response.payload.score > 0.5 };
472
+ }
473
+ catch {
474
+ return { shouldContinue: false };
475
+ }
476
+ }
477
+ async reflect(task, result) {
478
+ // Store in memory
479
+ try {
480
+ await this.bus.request('kernel', 'memory', 'MEMORY_STORE', {
481
+ key: `task:${task.id}`,
482
+ value: {
483
+ task: { id: task.id, type: task.type, goal: task.goal },
484
+ result,
485
+ completedAt: new Date(),
486
+ },
487
+ type: 'episodic',
488
+ importance: task.priority === 'critical' ? 1.0 : 0.5,
489
+ }, 5000);
490
+ }
491
+ catch {
492
+ // Memory storage failed, log but continue
493
+ this.log(`Warning: Failed to store task ${task.id} in memory`);
494
+ }
495
+ // Generate narrative
496
+ try {
497
+ await this.bus.request('kernel', 'narrator', 'NARRATE', {
498
+ events: [
499
+ { type: 'TASK_COMPLETED', data: { id: task.id, goal: task.goal } },
500
+ ],
501
+ }, 5000);
502
+ }
503
+ catch {
504
+ // Narrative generation failed, non-critical
505
+ }
506
+ }
507
+ async recoverFromError() {
508
+ this.log('Attempting error recovery...');
509
+ // Check all agent health
510
+ const healthResults = await this.checkAllAgentHealth();
511
+ const unhealthyAgents = healthResults.filter((r) => !r.healthy);
512
+ if (unhealthyAgents.length > 0) {
513
+ this.log(`Unhealthy agents: ${unhealthyAgents.map((a) => a.id).join(', ')}`);
514
+ // Restart unhealthy agents (INV-004: at least one must be responsive)
515
+ for (const agent of unhealthyAgents) {
516
+ const type = agent.id.split('-')[0];
517
+ const existingAgent = this.agents.get(type);
518
+ if (existingAgent) {
519
+ existingAgent.sleep();
520
+ existingAgent.wake();
521
+ this.log(`Restarted agent: ${type}`);
522
+ }
523
+ }
524
+ }
525
+ // Check invariants
526
+ await this.checkInvariants();
527
+ this.transition('idle');
528
+ }
529
+ // ============================================================================
530
+ // Health Monitoring
531
+ // ============================================================================
532
+ startHealthMonitoring() {
533
+ this.healthCheckTimer = setInterval(async () => await this.performHealthCheck(), this.config.healthCheckInterval);
534
+ }
535
+ async performHealthCheck() {
536
+ const results = await this.checkAllAgentHealth();
537
+ // Update health map
538
+ for (const result of results) {
539
+ this.agentHealth.set(result.id, {
540
+ healthy: result.healthy,
541
+ lastCheck: new Date(),
542
+ });
543
+ }
544
+ // Check invariants
545
+ await this.checkInvariants();
546
+ // Check energy
547
+ this.checkEnergy();
548
+ }
549
+ async checkAllAgentHealth() {
550
+ const results = [];
551
+ for (const [type, agent] of this.agents) {
552
+ try {
553
+ const health = agent.health();
554
+ // Derive healthy from state: idle, working, waiting are healthy; error, shutdown are not
555
+ const isHealthy = ['idle', 'working', 'waiting'].includes(health.state);
556
+ results.push({
557
+ id: agent.id,
558
+ healthy: isHealthy,
559
+ });
560
+ }
561
+ catch {
562
+ results.push({
563
+ id: agent.id,
564
+ healthy: false,
565
+ });
566
+ }
567
+ }
568
+ return results;
569
+ }
570
+ checkEnergy() {
571
+ if (this.config.energy < this.config.dormancyThreshold && this.state !== 'dormant') {
572
+ this.log(`Energy critical: ${(this.config.energy * 100).toFixed(1)}%`);
573
+ this.transition('dormant');
574
+ }
575
+ }
576
+ // ============================================================================
577
+ // Invariant Checking
578
+ // ============================================================================
579
+ async checkInvariants() {
580
+ // Build context for invariant checkers
581
+ const healthResults = await this.checkAllAgentHealth();
582
+ const responsiveCount = healthResults.filter((r) => r.healthy).length;
583
+ const context = {
584
+ // Energy state
585
+ energy: this.config.energy,
586
+ dormancyThreshold: this.config.dormancyThreshold,
587
+ isDormant: this.state === 'dormant',
588
+ // Agent state
589
+ responsiveAgentCount: responsiveCount,
590
+ totalAgentCount: this.agents.size,
591
+ // Extended context (for Phase 5.1+ invariants)
592
+ // These will be populated when the respective modules are implemented
593
+ merkleValid: true, // TODO: Check actual Merkle chain
594
+ // phi: undefined, // Phase 5.3
595
+ // phiMin: undefined, // Phase 5.3
596
+ // budget: undefined, // Phase 5.1
597
+ // budgetLimit: undefined, // Phase 5.1
598
+ // worldModelValid: undefined, // Phase 5.2
599
+ };
600
+ // Check all invariants via registry
601
+ const results = this.invariants.checkAll(context);
602
+ const violations = this.invariants.getViolations(results);
603
+ // Report violations
604
+ if (violations.length > 0) {
605
+ this.metrics.invariantViolations += violations.length;
606
+ for (const v of violations) {
607
+ this.log(`INVARIANT VIOLATION: ${v.id}: ${v.message || v.name}`);
608
+ }
609
+ // Broadcast alert with detailed results
610
+ await this.bus.broadcast('kernel', 'ALERT', {
611
+ type: 'invariant_violation',
612
+ violations: violations.map(v => `${v.id}: ${v.message || v.name}`),
613
+ results,
614
+ timestamp: new Date(),
615
+ });
616
+ // Check if any critical violations
617
+ const criticalViolations = this.invariants.getCriticalViolations(results);
618
+ if (criticalViolations.length > 0) {
619
+ this.log(`CRITICAL VIOLATIONS: ${criticalViolations.length}`);
620
+ }
621
+ return false;
622
+ }
623
+ return true;
624
+ }
625
+ /**
626
+ * Get the invariant registry for extension
627
+ */
628
+ getInvariantRegistry() {
629
+ return this.invariants;
630
+ }
631
+ /**
632
+ * Get invariant statistics
633
+ */
634
+ getInvariantStats() {
635
+ return this.invariants.getStats();
636
+ }
637
+ // ============================================================================
638
+ // Energy Management
639
+ // ============================================================================
640
+ setEnergy(energy) {
641
+ const prev = this.config.energy;
642
+ this.config.energy = Math.max(0, Math.min(1, energy));
643
+ if (prev > this.config.dormancyThreshold && this.config.energy <= this.config.dormancyThreshold) {
644
+ this.transition('dormant');
645
+ }
646
+ else if (prev <= this.config.dormancyThreshold && this.config.energy > this.config.dormancyThreshold) {
647
+ if (this.state === 'dormant') {
648
+ this.transition('idle');
649
+ }
650
+ }
651
+ }
652
+ getEnergy() {
653
+ return this.config.energy;
654
+ }
655
+ // ============================================================================
656
+ // Message Handling
657
+ // ============================================================================
658
+ async handleMessage(message) {
659
+ switch (message.type) {
660
+ case 'COMMAND':
661
+ await this.handleCommand(message);
662
+ break;
663
+ case 'QUERY':
664
+ await this.handleQuery(message);
665
+ break;
666
+ case 'ALERT':
667
+ await this.handleAlert(message);
668
+ break;
669
+ }
670
+ }
671
+ async handleCommand(message) {
672
+ const { command, params } = message.payload;
673
+ switch (command) {
674
+ case 'submit_task':
675
+ const taskId = await this.submit(params);
676
+ await this.bus.send('kernel', message.from, 'RESPONSE', { taskId });
677
+ break;
678
+ case 'get_status':
679
+ await this.bus.send('kernel', message.from, 'RESPONSE', this.getStatus());
680
+ break;
681
+ case 'set_energy':
682
+ this.setEnergy(params.energy);
683
+ await this.bus.send('kernel', message.from, 'RESPONSE', { energy: this.config.energy });
684
+ break;
685
+ case 'stop':
686
+ await this.stop();
687
+ await this.bus.send('kernel', message.from, 'RESPONSE', { stopped: true });
688
+ break;
689
+ }
690
+ }
691
+ async handleQuery(message) {
692
+ const { query } = message.payload;
693
+ if (query === 'status') {
694
+ await this.bus.send('kernel', message.from, 'RESPONSE', this.getStatus());
695
+ }
696
+ else if (query === 'metrics') {
697
+ await this.bus.send('kernel', message.from, 'RESPONSE', this.getMetrics());
698
+ }
699
+ else if (query === 'tasks') {
700
+ await this.bus.send('kernel', message.from, 'RESPONSE', {
701
+ queue: this.taskQueue.length,
702
+ active: this.activeTasks.size,
703
+ history: this.taskHistory.length,
704
+ });
705
+ }
706
+ }
707
+ async handleAlert(message) {
708
+ const { type } = message.payload;
709
+ if (type === 'ethical_decision' && message.payload.decision !== true) {
710
+ this.log(`Ethical alert from ${message.from}: ${message.payload.reason}`);
711
+ }
712
+ }
713
+ // ============================================================================
714
+ // Public API
715
+ // ============================================================================
716
+ getState() {
717
+ return this.state;
718
+ }
719
+ getStatus() {
720
+ return {
721
+ id: this.id,
722
+ state: this.state,
723
+ energy: this.config.energy,
724
+ agents: {
725
+ total: this.agents.size,
726
+ healthy: Array.from(this.agentHealth.values()).filter((h) => h.healthy).length,
727
+ },
728
+ tasks: {
729
+ queue: this.taskQueue.length,
730
+ active: this.activeTasks.size,
731
+ completed: this.metrics.tasksCompleted,
732
+ failed: this.metrics.tasksFailed,
733
+ },
734
+ uptime: Date.now() - this.metrics.startTime.getTime(),
735
+ };
736
+ }
737
+ getMetrics() {
738
+ return {
739
+ ...this.metrics,
740
+ uptime: Date.now() - this.metrics.startTime.getTime(),
741
+ agentCount: this.agents.size,
742
+ taskQueueLength: this.taskQueue.length,
743
+ activeTaskCount: this.activeTasks.size,
744
+ };
745
+ }
746
+ getAgents() {
747
+ return this.agents;
748
+ }
749
+ getRegistry() {
750
+ return this.registry;
751
+ }
752
+ // ============================================================================
753
+ // Logging
754
+ // ============================================================================
755
+ log(message) {
756
+ const timestamp = new Date().toISOString().slice(11, 23);
757
+ console.log(`[${timestamp}] [Kernel] ${message}`);
758
+ }
759
+ }
760
+ exports.Kernel = Kernel;
761
+ // ============================================================================
762
+ // Factory
763
+ // ============================================================================
764
+ function createKernel(config) {
765
+ return new Kernel(config);
766
+ }
767
+ // ============================================================================
768
+ // Singleton (optional)
769
+ // ============================================================================
770
+ let kernelInstance = null;
771
+ function getKernel(config) {
772
+ if (!kernelInstance) {
773
+ kernelInstance = new Kernel(config);
774
+ }
775
+ return kernelInstance;
776
+ }
777
+ function resetKernel() {
778
+ if (kernelInstance) {
779
+ kernelInstance.stop();
780
+ kernelInstance = null;
781
+ }
782
+ }
783
+ // ============================================================================
784
+ // Re-export Invariants
785
+ // ============================================================================
786
+ var invariants_js_2 = require("./invariants.js");
787
+ Object.defineProperty(exports, "InvariantRegistry", { enumerable: true, get: function () { return invariants_js_2.InvariantRegistry; } });
788
+ Object.defineProperty(exports, "invariantRegistry", { enumerable: true, get: function () { return invariants_js_2.invariantRegistry; } });
789
+ Object.defineProperty(exports, "registerPhase51Invariants", { enumerable: true, get: function () { return invariants_js_2.registerPhase51Invariants; } });
790
+ Object.defineProperty(exports, "registerPhase52Invariants", { enumerable: true, get: function () { return invariants_js_2.registerPhase52Invariants; } });
791
+ Object.defineProperty(exports, "registerPhase53Invariants", { enumerable: true, get: function () { return invariants_js_2.registerPhase53Invariants; } });
792
+ Object.defineProperty(exports, "registerAllPhase5Invariants", { enumerable: true, get: function () { return invariants_js_2.registerAllPhase5Invariants; } });
793
+ Object.defineProperty(exports, "INV_006_CONSCIOUSNESS", { enumerable: true, get: function () { return invariants_js_2.INV_006_CONSCIOUSNESS; } });
794
+ Object.defineProperty(exports, "INV_007_BUDGET", { enumerable: true, get: function () { return invariants_js_2.INV_007_BUDGET; } });
795
+ Object.defineProperty(exports, "INV_008_WORLD_MODEL", { enumerable: true, get: function () { return invariants_js_2.INV_008_WORLD_MODEL; } });