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,772 @@
1
+ "use strict";
2
+ /**
3
+ * Genesis 6.0 - World Model Module
4
+ *
5
+ * Unified world model for prediction, simulation, and dreaming.
6
+ *
7
+ * This module provides:
8
+ * - Latent space encoding (JEPA-style)
9
+ * - Predictive modeling and multi-step simulation
10
+ * - Digital twin capabilities
11
+ * - Physics/common sense reasoning
12
+ * - Dream mode for memory consolidation
13
+ *
14
+ * The world model enables the system to:
15
+ * - Predict consequences of actions
16
+ * - Run what-if scenarios safely
17
+ * - Maintain synchronized models of external systems
18
+ * - Reason about physical causality
19
+ *
20
+ * Key invariant: INV-008 - World model consistency
21
+ *
22
+ * Usage:
23
+ * ```typescript
24
+ * import { createWorldModelSystem } from './world-model/index.js';
25
+ *
26
+ * const worldModel = createWorldModelSystem();
27
+ *
28
+ * // Encode observation
29
+ * const state = worldModel.encode({ modality: 'text', data: 'User logged in' });
30
+ *
31
+ * // Predict next state
32
+ * const prediction = worldModel.predict(state, action);
33
+ *
34
+ * // Simulate trajectory
35
+ * const trajectory = worldModel.simulate(state, actions, 100);
36
+ *
37
+ * // Create digital twin
38
+ * const twin = worldModel.createTwin('server-1', 'Production Server');
39
+ *
40
+ * // Run dream cycle
41
+ * const dreamResult = await worldModel.dream();
42
+ * ```
43
+ */
44
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
45
+ if (k2 === undefined) k2 = k;
46
+ var desc = Object.getOwnPropertyDescriptor(m, k);
47
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
48
+ desc = { enumerable: true, get: function() { return m[k]; } };
49
+ }
50
+ Object.defineProperty(o, k2, desc);
51
+ }) : (function(o, m, k, k2) {
52
+ if (k2 === undefined) k2 = k;
53
+ o[k2] = m[k];
54
+ }));
55
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
56
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
57
+ };
58
+ Object.defineProperty(exports, "__esModule", { value: true });
59
+ exports.WorldModelSystem = exports.DEFAULT_VALUE_CONFIG = exports.createValueGuidedJEPA = exports.resetValueFunction = exports.getValueFunction = exports.createValueFunction = exports.ValueGuidedJEPA = exports.ValueFunction = exports.createDigitalTwinManager = exports.createDigitalTwin = exports.DigitalTwinManager = exports.DigitalTwinInstance = exports.createAction = exports.createWorldModelPredictor = exports.WorldModelPredictor = exports.createLatentDecoder = exports.LatentDecoder = exports.createLatentEncoder = exports.LatentEncoder = void 0;
60
+ exports.createWorldModelSystem = createWorldModelSystem;
61
+ exports.getWorldModelSystem = getWorldModelSystem;
62
+ exports.resetWorldModelSystem = resetWorldModelSystem;
63
+ // Re-export types
64
+ __exportStar(require("./types.js"), exports);
65
+ // Re-export components
66
+ var encoder_js_1 = require("./encoder.js");
67
+ Object.defineProperty(exports, "LatentEncoder", { enumerable: true, get: function () { return encoder_js_1.LatentEncoder; } });
68
+ Object.defineProperty(exports, "createLatentEncoder", { enumerable: true, get: function () { return encoder_js_1.createLatentEncoder; } });
69
+ var decoder_js_1 = require("./decoder.js");
70
+ Object.defineProperty(exports, "LatentDecoder", { enumerable: true, get: function () { return decoder_js_1.LatentDecoder; } });
71
+ Object.defineProperty(exports, "createLatentDecoder", { enumerable: true, get: function () { return decoder_js_1.createLatentDecoder; } });
72
+ var predictor_js_1 = require("./predictor.js");
73
+ Object.defineProperty(exports, "WorldModelPredictor", { enumerable: true, get: function () { return predictor_js_1.WorldModelPredictor; } });
74
+ Object.defineProperty(exports, "createWorldModelPredictor", { enumerable: true, get: function () { return predictor_js_1.createWorldModelPredictor; } });
75
+ Object.defineProperty(exports, "createAction", { enumerable: true, get: function () { return predictor_js_1.createAction; } });
76
+ var digital_twin_js_1 = require("./digital-twin.js");
77
+ Object.defineProperty(exports, "DigitalTwinInstance", { enumerable: true, get: function () { return digital_twin_js_1.DigitalTwinInstance; } });
78
+ Object.defineProperty(exports, "DigitalTwinManager", { enumerable: true, get: function () { return digital_twin_js_1.DigitalTwinManager; } });
79
+ Object.defineProperty(exports, "createDigitalTwin", { enumerable: true, get: function () { return digital_twin_js_1.createDigitalTwin; } });
80
+ Object.defineProperty(exports, "createDigitalTwinManager", { enumerable: true, get: function () { return digital_twin_js_1.createDigitalTwinManager; } });
81
+ // Value-Guided JEPA (Genesis 6.2)
82
+ var value_jepa_js_1 = require("./value-jepa.js");
83
+ Object.defineProperty(exports, "ValueFunction", { enumerable: true, get: function () { return value_jepa_js_1.ValueFunction; } });
84
+ Object.defineProperty(exports, "ValueGuidedJEPA", { enumerable: true, get: function () { return value_jepa_js_1.ValueGuidedJEPA; } });
85
+ Object.defineProperty(exports, "createValueFunction", { enumerable: true, get: function () { return value_jepa_js_1.createValueFunction; } });
86
+ Object.defineProperty(exports, "getValueFunction", { enumerable: true, get: function () { return value_jepa_js_1.getValueFunction; } });
87
+ Object.defineProperty(exports, "resetValueFunction", { enumerable: true, get: function () { return value_jepa_js_1.resetValueFunction; } });
88
+ Object.defineProperty(exports, "createValueGuidedJEPA", { enumerable: true, get: function () { return value_jepa_js_1.createValueGuidedJEPA; } });
89
+ Object.defineProperty(exports, "DEFAULT_VALUE_CONFIG", { enumerable: true, get: function () { return value_jepa_js_1.DEFAULT_VALUE_CONFIG; } });
90
+ const types_js_1 = require("./types.js");
91
+ const encoder_js_2 = require("./encoder.js");
92
+ const decoder_js_2 = require("./decoder.js");
93
+ const predictor_js_2 = require("./predictor.js");
94
+ const digital_twin_js_2 = require("./digital-twin.js");
95
+ // ============================================================================
96
+ // World Model System
97
+ // ============================================================================
98
+ class WorldModelSystem {
99
+ config;
100
+ // Components
101
+ encoder;
102
+ decoder;
103
+ predictor;
104
+ twinManager;
105
+ // State
106
+ running = false;
107
+ entities = new Map();
108
+ relations = new Map();
109
+ eventHandlers = new Set();
110
+ // Dream state
111
+ dreamConfig;
112
+ pendingConsolidation = [];
113
+ dreamHistory = [];
114
+ // Consistency check timer
115
+ consistencyTimer = null;
116
+ constructor(config = {}) {
117
+ this.config = this.mergeConfig(config);
118
+ this.dreamConfig = { ...types_js_1.DEFAULT_DREAM_CONFIG, ...config.dream };
119
+ // Create components
120
+ this.encoder = (0, encoder_js_2.createLatentEncoder)(this.config.encoder);
121
+ this.decoder = (0, decoder_js_2.createLatentDecoder)();
122
+ this.predictor = (0, predictor_js_2.createWorldModelPredictor)(this.config.predictor);
123
+ this.twinManager = (0, digital_twin_js_2.createDigitalTwinManager)();
124
+ // Setup event forwarding
125
+ this.setupEventForwarding();
126
+ }
127
+ // ============================================================================
128
+ // Lifecycle
129
+ // ============================================================================
130
+ start() {
131
+ if (this.running)
132
+ return;
133
+ this.running = true;
134
+ // Start consistency checking if enabled
135
+ if (this.config.consistencyCheckEnabled) {
136
+ this.consistencyTimer = setInterval(() => this.runConsistencyCheck(), this.config.predictor.consistencyCheckIntervalMs || 5000);
137
+ }
138
+ }
139
+ stop() {
140
+ if (!this.running)
141
+ return;
142
+ this.running = false;
143
+ // Stop consistency checking
144
+ if (this.consistencyTimer) {
145
+ clearInterval(this.consistencyTimer);
146
+ this.consistencyTimer = null;
147
+ }
148
+ // Stop all twins
149
+ for (const twin of this.twinManager.getAllTwins()) {
150
+ twin.stopSync();
151
+ }
152
+ }
153
+ isRunning() {
154
+ return this.running;
155
+ }
156
+ // ============================================================================
157
+ // Encoding / Decoding
158
+ // ============================================================================
159
+ /**
160
+ * Encode input to latent space
161
+ */
162
+ encode(input) {
163
+ const state = this.encoder.encode(input);
164
+ // Add to pending consolidation
165
+ this.pendingConsolidation.push(state);
166
+ if (this.pendingConsolidation.length > 1000) {
167
+ this.pendingConsolidation.shift();
168
+ }
169
+ return state;
170
+ }
171
+ /**
172
+ * Fuse multiple states
173
+ */
174
+ fuse(states) {
175
+ return this.encoder.fuse(states);
176
+ }
177
+ /**
178
+ * Decode to text
179
+ */
180
+ decodeToText(state) {
181
+ return this.decoder.decodeToText(state);
182
+ }
183
+ /**
184
+ * Decode to structured state
185
+ */
186
+ decodeToState(state) {
187
+ return this.decoder.decodeToState(state);
188
+ }
189
+ /**
190
+ * Calculate similarity between states
191
+ */
192
+ similarity(a, b) {
193
+ return this.encoder.similarity(a, b);
194
+ }
195
+ /**
196
+ * Interpolate between states
197
+ */
198
+ interpolate(a, b, t) {
199
+ return this.decoder.interpolate(a, b, t);
200
+ }
201
+ // ============================================================================
202
+ // Prediction / Simulation
203
+ // ============================================================================
204
+ /**
205
+ * Predict next state
206
+ */
207
+ predict(currentState, action) {
208
+ const prediction = this.predictor.predict(currentState, action);
209
+ this.emit({ type: 'state_predicted', timestamp: new Date(), data: prediction });
210
+ return prediction;
211
+ }
212
+ /**
213
+ * Simulate trajectory
214
+ */
215
+ simulate(initialState, actions, horizon) {
216
+ const trajectory = this.predictor.simulate(initialState, actions, horizon);
217
+ this.emit({ type: 'simulation_complete', timestamp: new Date(), data: trajectory });
218
+ return trajectory;
219
+ }
220
+ /**
221
+ * Get uncertainty of prediction
222
+ */
223
+ uncertainty(prediction) {
224
+ return this.predictor.uncertainty(prediction);
225
+ }
226
+ /**
227
+ * Physics/common sense reasoning
228
+ */
229
+ reason(query) {
230
+ return this.predictor.reason(query);
231
+ }
232
+ // ============================================================================
233
+ // Digital Twins
234
+ // ============================================================================
235
+ /**
236
+ * Create a digital twin
237
+ */
238
+ createTwin(realSystemId, name) {
239
+ const twin = this.twinManager.createTwin(realSystemId, name, this.config.twin);
240
+ // Forward events
241
+ twin.on((event) => {
242
+ this.emit({
243
+ type: event.type === 'synced' ? 'twin_synced' : 'twin_drifted',
244
+ timestamp: new Date(),
245
+ data: { twinId: twin.id, eventData: event.data },
246
+ });
247
+ });
248
+ return twin;
249
+ }
250
+ /**
251
+ * Get twin by ID
252
+ */
253
+ getTwin(id) {
254
+ return this.twinManager.getTwin(id);
255
+ }
256
+ /**
257
+ * Get all twins
258
+ */
259
+ getAllTwins() {
260
+ return this.twinManager.getAllTwins();
261
+ }
262
+ /**
263
+ * Remove twin
264
+ */
265
+ removeTwin(id) {
266
+ return this.twinManager.removeTwin(id);
267
+ }
268
+ // ============================================================================
269
+ // Entity Management
270
+ // ============================================================================
271
+ /**
272
+ * Add entity to world model
273
+ */
274
+ addEntity(entity) {
275
+ this.entities.set(entity.id, entity);
276
+ this.predictor.addEntity(entity);
277
+ this.emit({ type: 'entity_created', timestamp: new Date(), data: entity });
278
+ }
279
+ /**
280
+ * Get entity
281
+ */
282
+ getEntity(id) {
283
+ return this.entities.get(id);
284
+ }
285
+ /**
286
+ * Update entity
287
+ */
288
+ updateEntity(id, updates) {
289
+ const entity = this.entities.get(id);
290
+ if (!entity)
291
+ return false;
292
+ Object.assign(entity, updates, { lastUpdated: new Date() });
293
+ this.emit({ type: 'entity_updated', timestamp: new Date(), data: entity });
294
+ return true;
295
+ }
296
+ /**
297
+ * Remove entity
298
+ */
299
+ removeEntity(id) {
300
+ const removed = this.entities.delete(id);
301
+ if (removed) {
302
+ this.predictor.removeEntity(id);
303
+ this.emit({ type: 'entity_deleted', timestamp: new Date(), data: { id } });
304
+ }
305
+ return removed;
306
+ }
307
+ /**
308
+ * Add relation between entities
309
+ */
310
+ addRelation(relation) {
311
+ this.relations.set(relation.id, relation);
312
+ this.predictor.addRelation(relation);
313
+ this.emit({ type: 'relation_added', timestamp: new Date(), data: relation });
314
+ }
315
+ /**
316
+ * Remove relation
317
+ */
318
+ removeRelation(id) {
319
+ const removed = this.relations.delete(id);
320
+ if (removed) {
321
+ this.emit({ type: 'relation_removed', timestamp: new Date(), data: { id } });
322
+ }
323
+ return removed;
324
+ }
325
+ // ============================================================================
326
+ // Consistency (INV-008)
327
+ // ============================================================================
328
+ /**
329
+ * Check world model consistency
330
+ */
331
+ checkConsistency() {
332
+ const issues = [];
333
+ // Check entity consistency
334
+ for (const [id, entity] of this.entities) {
335
+ // Check for orphan relations
336
+ for (const relation of entity.relations) {
337
+ if (!this.entities.has(relation.target)) {
338
+ issues.push({
339
+ type: 'orphan',
340
+ severity: 'medium',
341
+ description: `Entity ${id} has relation to non-existent entity ${relation.target}`,
342
+ affectedEntities: [id, relation.target],
343
+ });
344
+ }
345
+ }
346
+ // Check for stale entities
347
+ const age = Date.now() - entity.lastUpdated.getTime();
348
+ if (age > this.config.entityTTL) {
349
+ issues.push({
350
+ type: 'drift',
351
+ severity: 'low',
352
+ description: `Entity ${id} has not been updated in ${Math.round(age / 1000)}s`,
353
+ affectedEntities: [id],
354
+ suggestedFix: 'Update entity or remove if no longer relevant',
355
+ });
356
+ }
357
+ }
358
+ // Check twin consistency
359
+ for (const twin of this.twinManager.getAllTwins()) {
360
+ const twinCheck = twin.checkConsistency();
361
+ issues.push(...twinCheck.issues);
362
+ }
363
+ // Check for circular relations
364
+ const circularRelations = this.detectCircularRelations();
365
+ if (circularRelations.length > 0) {
366
+ issues.push({
367
+ type: 'cycle',
368
+ severity: 'medium',
369
+ description: `Circular relations detected`,
370
+ affectedEntities: circularRelations,
371
+ });
372
+ }
373
+ const inconsistencyScore = issues.reduce((sum, issue) => {
374
+ const severityScores = { low: 0.1, medium: 0.3, high: 0.6, critical: 1.0 };
375
+ return sum + severityScores[issue.severity];
376
+ }, 0);
377
+ const check = {
378
+ id: `check-${Date.now()}`,
379
+ timestamp: new Date(),
380
+ passed: issues.length === 0,
381
+ checks: {
382
+ stateConsistency: issues.filter((i) => i.type === 'contradiction').length === 0,
383
+ temporalConsistency: issues.filter((i) => i.type === 'drift').length === 0,
384
+ causalConsistency: issues.filter((i) => i.type === 'gap').length === 0,
385
+ entityConsistency: issues.filter((i) => i.type === 'orphan').length === 0,
386
+ },
387
+ issues,
388
+ inconsistencyScore: Math.min(1, inconsistencyScore),
389
+ };
390
+ this.emit({ type: 'consistency_check', timestamp: new Date(), data: check });
391
+ if (!check.passed) {
392
+ this.emit({ type: 'consistency_violation', timestamp: new Date(), data: check });
393
+ }
394
+ return check;
395
+ }
396
+ /**
397
+ * Run consistency check (called by timer)
398
+ */
399
+ runConsistencyCheck() {
400
+ const check = this.checkConsistency();
401
+ // Auto-repair if enabled
402
+ if (!check.passed && this.config.autoRepairEnabled) {
403
+ this.autoRepair(check.issues);
404
+ }
405
+ }
406
+ /**
407
+ * Auto-repair consistency issues
408
+ */
409
+ autoRepair(issues) {
410
+ for (const issue of issues) {
411
+ switch (issue.type) {
412
+ case 'orphan':
413
+ // Remove orphan relations
414
+ for (const entityId of issue.affectedEntities) {
415
+ const entity = this.entities.get(entityId);
416
+ if (entity) {
417
+ entity.relations = entity.relations.filter((r) => this.entities.has(r.target));
418
+ }
419
+ }
420
+ break;
421
+ case 'drift':
422
+ // Remove stale entities
423
+ for (const entityId of issue.affectedEntities) {
424
+ const entity = this.entities.get(entityId);
425
+ if (entity && entity.confidence < 0.3) {
426
+ this.removeEntity(entityId);
427
+ }
428
+ }
429
+ break;
430
+ }
431
+ }
432
+ }
433
+ /**
434
+ * Detect circular relations
435
+ */
436
+ detectCircularRelations() {
437
+ const visited = new Set();
438
+ const stack = new Set();
439
+ const circular = [];
440
+ const dfs = (entityId) => {
441
+ if (stack.has(entityId)) {
442
+ circular.push(entityId);
443
+ return true;
444
+ }
445
+ if (visited.has(entityId))
446
+ return false;
447
+ visited.add(entityId);
448
+ stack.add(entityId);
449
+ const entity = this.entities.get(entityId);
450
+ if (entity) {
451
+ for (const relation of entity.relations) {
452
+ if (dfs(relation.target)) {
453
+ circular.push(entityId);
454
+ }
455
+ }
456
+ }
457
+ stack.delete(entityId);
458
+ return false;
459
+ };
460
+ for (const entityId of this.entities.keys()) {
461
+ dfs(entityId);
462
+ }
463
+ return [...new Set(circular)];
464
+ }
465
+ // ============================================================================
466
+ // Dream Mode
467
+ // ============================================================================
468
+ /**
469
+ * Check if should dream
470
+ */
471
+ shouldDream(energy) {
472
+ if (energy !== undefined && energy < this.dreamConfig.triggerThreshold) {
473
+ return true;
474
+ }
475
+ if (this.pendingConsolidation.length >= this.dreamConfig.minPendingMemories) {
476
+ return true;
477
+ }
478
+ return false;
479
+ }
480
+ /**
481
+ * Run dream cycle
482
+ */
483
+ async dream() {
484
+ const startTime = new Date();
485
+ this.emit({ type: 'dream_started', timestamp: startTime, data: {} });
486
+ // Phase 1: Slow-wave replay
487
+ const slowWaveResult = await this.slowWaveReplay();
488
+ // Phase 2: REM abstraction
489
+ const remResult = await this.remAbstraction();
490
+ // Phase 3: Consolidation
491
+ const consolidationResult = await this.consolidate();
492
+ const endTime = new Date();
493
+ const dreamResult = {
494
+ startTime,
495
+ endTime,
496
+ duration: endTime.getTime() - startTime.getTime(),
497
+ slowWaveReplay: slowWaveResult,
498
+ remAbstraction: remResult,
499
+ consolidation: consolidationResult,
500
+ memoriesConsolidated: consolidationResult.strengthened,
501
+ patternsExtracted: remResult.patternsFound.length,
502
+ modelImproved: consolidationResult.newConnections > 0,
503
+ };
504
+ this.dreamHistory.push(dreamResult);
505
+ if (this.dreamHistory.length > 100) {
506
+ this.dreamHistory.shift();
507
+ }
508
+ // Clear pending consolidation
509
+ this.pendingConsolidation = [];
510
+ this.emit({ type: 'dream_complete', timestamp: endTime, data: dreamResult });
511
+ return dreamResult;
512
+ }
513
+ /**
514
+ * Slow-wave replay phase
515
+ */
516
+ async slowWaveReplay() {
517
+ // Simulate slow-wave sleep - replay recent experiences
518
+ const experiences = this.pendingConsolidation.slice(-50);
519
+ // Sort by confidence (strongest memories)
520
+ experiences.sort((a, b) => b.confidence - a.confidence);
521
+ const strongestMemories = experiences
522
+ .slice(0, 10)
523
+ .map((e) => e.sourceId);
524
+ // Simulate replay time
525
+ await this.sleep(Math.min(this.dreamConfig.slowWaveDuration, 1000));
526
+ return {
527
+ experiencesReplayed: experiences.length,
528
+ strongestMemories,
529
+ replayDuration: this.dreamConfig.slowWaveDuration,
530
+ };
531
+ }
532
+ /**
533
+ * REM abstraction phase
534
+ */
535
+ async remAbstraction() {
536
+ const patterns = [];
537
+ // Find sequence patterns
538
+ const sequences = this.findSequencePatterns();
539
+ patterns.push(...sequences);
540
+ // Find structural patterns
541
+ const structural = this.findStructuralPatterns();
542
+ patterns.push(...structural);
543
+ // Creative combinations (random associations)
544
+ let creativeCombinations = 0;
545
+ for (let i = 0; i < 5; i++) {
546
+ if (this.pendingConsolidation.length >= 2) {
547
+ const idx1 = Math.floor(Math.random() * this.pendingConsolidation.length);
548
+ const idx2 = Math.floor(Math.random() * this.pendingConsolidation.length);
549
+ if (idx1 !== idx2) {
550
+ const fused = this.encoder.fuse([
551
+ this.pendingConsolidation[idx1],
552
+ this.pendingConsolidation[idx2],
553
+ ]);
554
+ creativeCombinations++;
555
+ }
556
+ }
557
+ }
558
+ // Simulate abstraction time
559
+ await this.sleep(Math.min(this.dreamConfig.remDuration, 1000));
560
+ return {
561
+ patternsFound: patterns,
562
+ abstractionLevel: patterns.length > 5 ? 0.8 : patterns.length * 0.15,
563
+ creativeCombinations,
564
+ };
565
+ }
566
+ /**
567
+ * Find sequence patterns in pending consolidation
568
+ */
569
+ findSequencePatterns() {
570
+ const patterns = [];
571
+ if (this.pendingConsolidation.length < 3)
572
+ return patterns;
573
+ // Look for similar consecutive states
574
+ for (let i = 0; i < this.pendingConsolidation.length - 2; i++) {
575
+ const sim1 = this.encoder.similarity(this.pendingConsolidation[i], this.pendingConsolidation[i + 1]);
576
+ const sim2 = this.encoder.similarity(this.pendingConsolidation[i + 1], this.pendingConsolidation[i + 2]);
577
+ if (sim1 > 0.7 && sim2 > 0.7) {
578
+ patterns.push({
579
+ id: `seq-${i}`,
580
+ type: 'sequence',
581
+ elements: [
582
+ this.pendingConsolidation[i].sourceId,
583
+ this.pendingConsolidation[i + 1].sourceId,
584
+ this.pendingConsolidation[i + 2].sourceId,
585
+ ],
586
+ confidence: (sim1 + sim2) / 2,
587
+ novelty: 0.5,
588
+ });
589
+ }
590
+ }
591
+ return patterns;
592
+ }
593
+ /**
594
+ * Find structural patterns
595
+ */
596
+ findStructuralPatterns() {
597
+ const patterns = [];
598
+ // Group by modality
599
+ const modalityGroups = new Map();
600
+ for (const state of this.pendingConsolidation) {
601
+ const group = modalityGroups.get(state.sourceModality) || [];
602
+ group.push(state);
603
+ modalityGroups.set(state.sourceModality, group);
604
+ }
605
+ // Find patterns within modalities
606
+ for (const [modality, states] of modalityGroups) {
607
+ if (states.length >= 3) {
608
+ patterns.push({
609
+ id: `struct-${modality}`,
610
+ type: 'structure',
611
+ elements: states.slice(0, 5).map((s) => s.sourceId),
612
+ confidence: 0.6,
613
+ novelty: 0.4,
614
+ });
615
+ }
616
+ }
617
+ return patterns;
618
+ }
619
+ /**
620
+ * Consolidation phase
621
+ */
622
+ async consolidate() {
623
+ let modelUpdates = 0;
624
+ let pruned = 0;
625
+ let strengthened = 0;
626
+ let newConnections = 0;
627
+ // Strengthen frequently occurring patterns
628
+ for (const state of this.pendingConsolidation) {
629
+ if (state.confidence > 0.7) {
630
+ strengthened++;
631
+ }
632
+ }
633
+ // Prune low-confidence states
634
+ const beforeCount = this.entities.size;
635
+ for (const [id, entity] of this.entities) {
636
+ if (entity.confidence < 0.2) {
637
+ const age = Date.now() - entity.lastUpdated.getTime();
638
+ if (age > this.config.entityTTL / 2) {
639
+ this.entities.delete(id);
640
+ pruned++;
641
+ }
642
+ }
643
+ }
644
+ // Create new connections based on patterns
645
+ const similarPairs = this.findSimilarStatePairs();
646
+ for (const [s1, s2] of similarPairs) {
647
+ newConnections++;
648
+ }
649
+ modelUpdates = strengthened + pruned + newConnections;
650
+ // Simulate consolidation time
651
+ await this.sleep(Math.min(this.dreamConfig.consolidationDuration, 500));
652
+ return {
653
+ modelUpdates,
654
+ pruned,
655
+ strengthened,
656
+ newConnections,
657
+ };
658
+ }
659
+ /**
660
+ * Find similar state pairs
661
+ */
662
+ findSimilarStatePairs() {
663
+ const pairs = [];
664
+ for (let i = 0; i < this.pendingConsolidation.length; i++) {
665
+ for (let j = i + 1; j < this.pendingConsolidation.length; j++) {
666
+ const sim = this.encoder.similarity(this.pendingConsolidation[i], this.pendingConsolidation[j]);
667
+ if (sim > 0.8) {
668
+ pairs.push([this.pendingConsolidation[i], this.pendingConsolidation[j]]);
669
+ }
670
+ }
671
+ }
672
+ return pairs.slice(0, 10); // Limit
673
+ }
674
+ /**
675
+ * Sleep helper
676
+ */
677
+ sleep(ms) {
678
+ return new Promise((resolve) => setTimeout(resolve, ms));
679
+ }
680
+ // ============================================================================
681
+ // Events
682
+ // ============================================================================
683
+ on(handler) {
684
+ this.eventHandlers.add(handler);
685
+ return () => this.eventHandlers.delete(handler);
686
+ }
687
+ emit(event) {
688
+ for (const handler of this.eventHandlers) {
689
+ try {
690
+ handler(event);
691
+ }
692
+ catch (err) {
693
+ console.error('World model event handler error:', err);
694
+ }
695
+ }
696
+ }
697
+ setupEventForwarding() {
698
+ // Forward encoder events
699
+ this.encoder.on((event) => {
700
+ if (event.type === 'encoded') {
701
+ this.emit({
702
+ type: 'entity_created',
703
+ timestamp: new Date(),
704
+ data: event.data,
705
+ });
706
+ }
707
+ });
708
+ // Forward predictor events
709
+ this.predictor.on((event) => {
710
+ if (event.type === 'prediction_made') {
711
+ this.emit({
712
+ type: 'state_predicted',
713
+ timestamp: new Date(),
714
+ data: event.data,
715
+ });
716
+ }
717
+ });
718
+ }
719
+ // ============================================================================
720
+ // Stats
721
+ // ============================================================================
722
+ stats() {
723
+ return {
724
+ encoder: this.encoder.stats(),
725
+ decoder: this.decoder.stats(),
726
+ predictor: this.predictor.stats(),
727
+ twins: this.twinManager.getOverallHealth(),
728
+ entities: this.entities.size,
729
+ relations: this.relations.size,
730
+ pendingConsolidation: this.pendingConsolidation.length,
731
+ dreamCount: this.dreamHistory.length,
732
+ };
733
+ }
734
+ // ============================================================================
735
+ // Helpers
736
+ // ============================================================================
737
+ mergeConfig(partial) {
738
+ return {
739
+ encoder: { ...types_js_1.DEFAULT_WORLD_MODEL_SYSTEM_CONFIG.encoder, ...partial.encoder },
740
+ predictor: { ...types_js_1.DEFAULT_WORLD_MODEL_SYSTEM_CONFIG.predictor, ...partial.predictor },
741
+ twin: { ...types_js_1.DEFAULT_WORLD_MODEL_SYSTEM_CONFIG.twin, ...partial.twin },
742
+ dream: { ...types_js_1.DEFAULT_WORLD_MODEL_SYSTEM_CONFIG.dream, ...partial.dream },
743
+ maxEntities: partial.maxEntities ?? types_js_1.DEFAULT_WORLD_MODEL_SYSTEM_CONFIG.maxEntities,
744
+ entityTTL: partial.entityTTL ?? types_js_1.DEFAULT_WORLD_MODEL_SYSTEM_CONFIG.entityTTL,
745
+ consistencyCheckEnabled: partial.consistencyCheckEnabled ?? types_js_1.DEFAULT_WORLD_MODEL_SYSTEM_CONFIG.consistencyCheckEnabled,
746
+ autoRepairEnabled: partial.autoRepairEnabled ?? types_js_1.DEFAULT_WORLD_MODEL_SYSTEM_CONFIG.autoRepairEnabled,
747
+ };
748
+ }
749
+ }
750
+ exports.WorldModelSystem = WorldModelSystem;
751
+ // ============================================================================
752
+ // Factory
753
+ // ============================================================================
754
+ function createWorldModelSystem(config) {
755
+ return new WorldModelSystem(config);
756
+ }
757
+ // ============================================================================
758
+ // Singleton Instance (optional)
759
+ // ============================================================================
760
+ let worldModelInstance = null;
761
+ function getWorldModelSystem(config) {
762
+ if (!worldModelInstance) {
763
+ worldModelInstance = createWorldModelSystem(config);
764
+ }
765
+ return worldModelInstance;
766
+ }
767
+ function resetWorldModelSystem() {
768
+ if (worldModelInstance) {
769
+ worldModelInstance.stop();
770
+ worldModelInstance = null;
771
+ }
772
+ }