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,681 @@
1
+ "use strict";
2
+ /**
3
+ * Genesis 6.0 - World Model Predictor
4
+ *
5
+ * Unified predictor and simulator for the world model.
6
+ *
7
+ * Capabilities:
8
+ * - Single-step prediction: Predict next state given current state and action
9
+ * - Multi-step simulation: Generate trajectories over time horizon
10
+ * - Uncertainty estimation: Quantify epistemic uncertainty in predictions
11
+ * - Physics reasoning: Common sense physical reasoning
12
+ *
13
+ * This module merges the original World Model (v5.2) and World Simulator (v6.0)
14
+ * into a unified predictive system.
15
+ *
16
+ * Key concepts:
17
+ * - Transition model: P(s' | s, a) - probability of next state
18
+ * - Trajectory: Sequence of (state, action) pairs
19
+ * - Branching: Multiple possible futures with probabilities
20
+ *
21
+ * References:
22
+ * - World Models (Ha & Schmidhuber, 2018)
23
+ * - Dreamer (Hafner et al., 2020)
24
+ * - MuZero (Schrittwieser et al., 2020)
25
+ *
26
+ * Usage:
27
+ * ```typescript
28
+ * import { createWorldModelPredictor } from './world-model/predictor.js';
29
+ *
30
+ * const predictor = createWorldModelPredictor();
31
+ *
32
+ * // Single-step prediction
33
+ * const nextState = predictor.predict(currentState, action);
34
+ *
35
+ * // Multi-step simulation
36
+ * const trajectory = predictor.simulate(state, actions, 100);
37
+ *
38
+ * // Physics reasoning
39
+ * const answer = predictor.reason({ type: 'collision', ... });
40
+ * ```
41
+ */
42
+ Object.defineProperty(exports, "__esModule", { value: true });
43
+ exports.WorldModelPredictor = void 0;
44
+ exports.createWorldModelPredictor = createWorldModelPredictor;
45
+ exports.createAction = createAction;
46
+ const crypto_1 = require("crypto");
47
+ const types_js_1 = require("./types.js");
48
+ const encoder_js_1 = require("./encoder.js");
49
+ class WorldModelPredictor {
50
+ config;
51
+ encoder;
52
+ transitionWeights = new Map();
53
+ eventHandlers = new Set();
54
+ // Statistics
55
+ predictionCount = 0;
56
+ simulationCount = 0;
57
+ totalPredictionTime = 0;
58
+ // Entity tracking for physics reasoning
59
+ entities = new Map();
60
+ relations = new Map();
61
+ constructor(config = {}) {
62
+ this.config = { ...types_js_1.DEFAULT_WORLD_MODEL_CONFIG, ...config };
63
+ this.encoder = (0, encoder_js_1.createLatentEncoder)();
64
+ this.initializeTransitionModels();
65
+ }
66
+ // ============================================================================
67
+ // Initialization
68
+ // ============================================================================
69
+ initializeTransitionModels() {
70
+ // Initialize simple transition weights for each action type
71
+ // In production, these would be learned
72
+ const actionTypes = [
73
+ 'observe', 'query', 'execute', 'communicate',
74
+ 'transform', 'create', 'delete', 'navigate',
75
+ ];
76
+ for (const actionType of actionTypes) {
77
+ // Create a simple transition matrix (identity + perturbation)
78
+ const dim = 512; // Match encoder dim
79
+ const weights = [];
80
+ for (let i = 0; i < dim; i++) {
81
+ const row = new Array(dim).fill(0);
82
+ row[i] = 0.9; // Identity component
83
+ // Add action-specific perturbations
84
+ const perturbIdx = (i + this.actionTypeOffset(actionType)) % dim;
85
+ row[perturbIdx] += 0.1;
86
+ weights.push(row);
87
+ }
88
+ this.transitionWeights.set(actionType, weights);
89
+ }
90
+ }
91
+ actionTypeOffset(type) {
92
+ const offsets = {
93
+ observe: 10,
94
+ query: 20,
95
+ execute: 50,
96
+ communicate: 30,
97
+ transform: 100,
98
+ create: 150,
99
+ delete: -50,
100
+ navigate: 70,
101
+ };
102
+ return offsets[type];
103
+ }
104
+ // ============================================================================
105
+ // Single-Step Prediction
106
+ // ============================================================================
107
+ /**
108
+ * Predict next state given current state and action
109
+ */
110
+ predict(currentState, action) {
111
+ const startTime = Date.now();
112
+ // Get transition model for action type
113
+ const weights = this.transitionWeights.get(action.type);
114
+ if (!weights) {
115
+ throw new Error(`No transition model for action type: ${action.type}`);
116
+ }
117
+ // Apply transition
118
+ const nextVector = this.applyTransition(currentState.vector, weights, action);
119
+ // Calculate uncertainty
120
+ const uncertainty = this.calculateUncertainty(currentState, action);
121
+ // Generate alternative states if uncertainty is high
122
+ const alternativeStates = [];
123
+ if (uncertainty > 0.3 && this.config.branchingFactor > 1) {
124
+ for (let i = 0; i < this.config.branchingFactor - 1; i++) {
125
+ alternativeStates.push(this.generateAlternative(currentState, action, i));
126
+ }
127
+ }
128
+ // Create predicted state
129
+ const predictedState = {
130
+ vector: nextVector,
131
+ dimensions: nextVector.length,
132
+ sourceModality: currentState.sourceModality,
133
+ sourceId: `pred-${currentState.sourceId}-${action.id}`,
134
+ timestamp: new Date(),
135
+ confidence: currentState.confidence * (1 - uncertainty),
136
+ entropy: this.calculateEntropy(nextVector),
137
+ };
138
+ const prediction = {
139
+ state: predictedState,
140
+ action,
141
+ probability: 1 - uncertainty,
142
+ uncertainty,
143
+ alternativeStates,
144
+ predictionTime: Date.now() - startTime,
145
+ };
146
+ // Update stats
147
+ this.predictionCount++;
148
+ this.totalPredictionTime += prediction.predictionTime;
149
+ // Emit events
150
+ this.emit({ type: 'prediction_made', data: { actionType: action.type, uncertainty } });
151
+ if (uncertainty > this.config.uncertaintyThreshold) {
152
+ this.emit({ type: 'uncertainty_high', data: { uncertainty, threshold: this.config.uncertaintyThreshold } });
153
+ }
154
+ return prediction;
155
+ }
156
+ /**
157
+ * Apply transition model to state
158
+ */
159
+ applyTransition(vector, weights, action) {
160
+ const dim = Math.min(vector.length, weights.length);
161
+ const result = new Array(dim).fill(0);
162
+ // Matrix-vector multiplication
163
+ for (let i = 0; i < dim; i++) {
164
+ for (let j = 0; j < dim; j++) {
165
+ result[i] += weights[i][j] * vector[j];
166
+ }
167
+ }
168
+ // Add action-specific modulation
169
+ const actionEmbedding = this.encodeAction(action);
170
+ for (let i = 0; i < dim; i++) {
171
+ result[i] += actionEmbedding[i % actionEmbedding.length] * 0.1;
172
+ }
173
+ // Normalize
174
+ return this.normalize(result);
175
+ }
176
+ /**
177
+ * Encode action to vector
178
+ */
179
+ encodeAction(action) {
180
+ const embedding = new Array(64).fill(0);
181
+ // Action type encoding
182
+ const typeIdx = this.actionTypeOffset(action.type) % 64;
183
+ embedding[typeIdx] = 1.0;
184
+ // Parameter encoding
185
+ const params = action.parameters;
186
+ let paramIdx = 0;
187
+ for (const [key, value] of Object.entries(params)) {
188
+ if (typeof value === 'number') {
189
+ embedding[(10 + paramIdx) % 64] = value / (Math.abs(value) + 1);
190
+ }
191
+ else if (typeof value === 'string') {
192
+ embedding[(20 + paramIdx) % 64] = this.simpleHash(value) / 1000000;
193
+ }
194
+ paramIdx++;
195
+ }
196
+ return embedding;
197
+ }
198
+ /**
199
+ * Generate alternative state (for branching)
200
+ */
201
+ generateAlternative(state, action, branchIdx) {
202
+ const noise = this.generateNoise(state.vector.length, branchIdx);
203
+ const altVector = state.vector.map((v, i) => v + noise[i] * 0.2);
204
+ return {
205
+ vector: this.normalize(altVector),
206
+ dimensions: altVector.length,
207
+ sourceModality: state.sourceModality,
208
+ sourceId: `alt-${branchIdx}-${state.sourceId}`,
209
+ timestamp: new Date(),
210
+ confidence: state.confidence * 0.7,
211
+ entropy: this.calculateEntropy(altVector),
212
+ };
213
+ }
214
+ /**
215
+ * Generate deterministic noise based on index
216
+ */
217
+ generateNoise(dim, seed) {
218
+ const noise = new Array(dim);
219
+ for (let i = 0; i < dim; i++) {
220
+ // Deterministic pseudo-random based on seed and index
221
+ noise[i] = Math.sin((seed + 1) * (i + 1) * 0.1) * 0.5;
222
+ }
223
+ return noise;
224
+ }
225
+ // ============================================================================
226
+ // Multi-Step Simulation
227
+ // ============================================================================
228
+ /**
229
+ * Simulate multiple steps into the future
230
+ */
231
+ simulate(initialState, actions, horizon = this.config.maxHorizon) {
232
+ const startTime = Date.now();
233
+ this.emit({ type: 'simulation_started', data: { horizon, actionCount: actions.length } });
234
+ const states = [];
235
+ let currentState = initialState;
236
+ let totalProbability = 1.0;
237
+ let step = 0;
238
+ while (step < horizon) {
239
+ // Get action for this step (cycle through if needed)
240
+ const action = actions[step % actions.length];
241
+ // Predict next state
242
+ const prediction = this.predict(currentState, action);
243
+ states.push(prediction);
244
+ // Update cumulative probability
245
+ totalProbability *= prediction.probability;
246
+ // Emit step event
247
+ this.emit({
248
+ type: 'simulation_step',
249
+ data: { step, probability: prediction.probability, uncertainty: prediction.uncertainty },
250
+ });
251
+ // Check termination conditions
252
+ if (prediction.uncertainty > this.config.uncertaintyThreshold) {
253
+ break; // Too uncertain to continue
254
+ }
255
+ if (totalProbability < 0.01) {
256
+ break; // Trajectory too unlikely
257
+ }
258
+ currentState = prediction.state;
259
+ step++;
260
+ }
261
+ const trajectory = {
262
+ id: (0, crypto_1.randomUUID)(),
263
+ initialState,
264
+ actions: actions.slice(0, step),
265
+ states,
266
+ totalProbability,
267
+ horizon: step,
268
+ simulationTime: Date.now() - startTime,
269
+ };
270
+ this.simulationCount++;
271
+ this.emit({ type: 'simulation_complete', data: { steps: step, totalProbability } });
272
+ return trajectory;
273
+ }
274
+ /**
275
+ * Generate multiple trajectories (Monte Carlo)
276
+ */
277
+ simulateMultiple(initialState, actions, numTrajectories, horizon = this.config.maxHorizon) {
278
+ const trajectories = [];
279
+ for (let i = 0; i < numTrajectories; i++) {
280
+ // Add noise to initial state for diversity
281
+ const noisyState = {
282
+ ...initialState,
283
+ vector: initialState.vector.map((v) => v + (Math.random() - 0.5) * 0.1),
284
+ };
285
+ const trajectory = this.simulate(noisyState, actions, horizon);
286
+ trajectories.push(trajectory);
287
+ }
288
+ // Sort by total probability
289
+ trajectories.sort((a, b) => b.totalProbability - a.totalProbability);
290
+ return trajectories;
291
+ }
292
+ // ============================================================================
293
+ // Uncertainty Estimation
294
+ // ============================================================================
295
+ /**
296
+ * Calculate uncertainty of prediction
297
+ */
298
+ calculateUncertainty(state, action) {
299
+ let uncertainty = 0;
300
+ // Base uncertainty from state confidence
301
+ uncertainty += (1 - state.confidence) * 0.3;
302
+ // Action-specific uncertainty
303
+ const actionUncertainty = this.getActionUncertainty(action.type);
304
+ uncertainty += actionUncertainty * 0.3;
305
+ // Entropy-based uncertainty
306
+ uncertainty += state.entropy * 0.2;
307
+ // Time-based decay
308
+ const age = Date.now() - state.timestamp.getTime();
309
+ const ageFactor = 1 - Math.exp(-age / 60000); // Increases over 1 minute
310
+ uncertainty += ageFactor * 0.2;
311
+ return Math.min(1, Math.max(0, uncertainty));
312
+ }
313
+ getActionUncertainty(type) {
314
+ const uncertainties = {
315
+ observe: 0.1, // Low uncertainty - passive
316
+ query: 0.2, // Low-medium
317
+ navigate: 0.3, // Medium
318
+ communicate: 0.4, // Medium
319
+ execute: 0.5, // Medium-high
320
+ transform: 0.6, // High
321
+ create: 0.7, // High
322
+ delete: 0.8, // Very high - irreversible
323
+ };
324
+ return uncertainties[type];
325
+ }
326
+ /**
327
+ * Get uncertainty for a prediction (external interface)
328
+ */
329
+ uncertainty(prediction) {
330
+ return prediction.uncertainty;
331
+ }
332
+ // ============================================================================
333
+ // Physics Reasoning
334
+ // ============================================================================
335
+ /**
336
+ * Answer physics/common sense queries
337
+ */
338
+ reason(query) {
339
+ this.emit({ type: 'physics_query', data: { type: query.type } });
340
+ const reasoning = [];
341
+ let answer;
342
+ let confidence = 0.5;
343
+ switch (query.type) {
344
+ case 'collision':
345
+ reasoning.push(...this.reasonCollision(query));
346
+ answer = this.checkCollision(query.objects);
347
+ confidence = 0.6;
348
+ break;
349
+ case 'stability':
350
+ answer = this.checkStability(query.objects);
351
+ reasoning.push('Checked center of mass and support polygon');
352
+ confidence = 0.7;
353
+ break;
354
+ case 'containment':
355
+ answer = this.checkContainment(query.objects);
356
+ reasoning.push('Compared bounding boxes');
357
+ confidence = 0.8;
358
+ break;
359
+ case 'reachability':
360
+ answer = this.checkReachability(query.objects);
361
+ reasoning.push('Computed path existence');
362
+ confidence = 0.6;
363
+ break;
364
+ case 'causation':
365
+ answer = this.checkCausation(query);
366
+ reasoning.push('Analyzed causal chain');
367
+ confidence = 0.5;
368
+ break;
369
+ case 'trajectory':
370
+ answer = this.computeTrajectory(query.objects);
371
+ reasoning.push('Simulated physics forward');
372
+ confidence = 0.6;
373
+ break;
374
+ default:
375
+ answer = 'Unknown query type';
376
+ confidence = 0;
377
+ }
378
+ return {
379
+ query,
380
+ answer,
381
+ confidence,
382
+ reasoning,
383
+ };
384
+ }
385
+ /**
386
+ * Check collision between objects
387
+ */
388
+ checkCollision(objects) {
389
+ if (objects.length < 2)
390
+ return false;
391
+ const obj1 = objects[0];
392
+ const obj2 = objects[1];
393
+ if (!obj1.position || !obj2.position)
394
+ return false;
395
+ // Simple bounding sphere check
396
+ const distance = Math.sqrt((obj1.position[0] - obj2.position[0]) ** 2 +
397
+ (obj1.position[1] - obj2.position[1]) ** 2 +
398
+ (obj1.position[2] - obj2.position[2]) ** 2);
399
+ // Assume radius from mass
400
+ const radius1 = obj1.mass ? Math.cbrt(obj1.mass) : 1;
401
+ const radius2 = obj2.mass ? Math.cbrt(obj2.mass) : 1;
402
+ return distance < (radius1 + radius2);
403
+ }
404
+ reasonCollision(query) {
405
+ return [
406
+ 'Computing bounding volumes',
407
+ 'Checking intersection',
408
+ 'Considering velocities for future collision',
409
+ ];
410
+ }
411
+ /**
412
+ * Check stability of configuration
413
+ */
414
+ checkStability(objects) {
415
+ if (objects.length === 0)
416
+ return true;
417
+ // Simple check: all objects have support
418
+ for (const obj of objects) {
419
+ if (obj.position && obj.position[2] > 0) {
420
+ // Object is above ground, check if supported
421
+ const hasSupport = objects.some((other) => other !== obj &&
422
+ other.position &&
423
+ other.position[2] < obj.position[2] &&
424
+ Math.abs(other.position[0] - obj.position[0]) < 2 &&
425
+ Math.abs(other.position[1] - obj.position[1]) < 2);
426
+ if (!hasSupport)
427
+ return false;
428
+ }
429
+ }
430
+ return true;
431
+ }
432
+ /**
433
+ * Check containment (A inside B)
434
+ */
435
+ checkContainment(objects) {
436
+ if (objects.length < 2)
437
+ return false;
438
+ const inner = objects[0];
439
+ const outer = objects[1];
440
+ if (!inner.position || !outer.position)
441
+ return false;
442
+ // Simple check: inner center is within outer bounds
443
+ const outerRadius = outer.mass ? Math.cbrt(outer.mass) * 2 : 5;
444
+ const distance = Math.sqrt((inner.position[0] - outer.position[0]) ** 2 +
445
+ (inner.position[1] - outer.position[1]) ** 2 +
446
+ (inner.position[2] - outer.position[2]) ** 2);
447
+ return distance < outerRadius;
448
+ }
449
+ /**
450
+ * Check reachability (can A reach B)
451
+ */
452
+ checkReachability(objects) {
453
+ if (objects.length < 2)
454
+ return false;
455
+ const from = objects[0];
456
+ const to = objects[1];
457
+ if (!from.position || !to.position)
458
+ return false;
459
+ // Simple check: direct path exists
460
+ const distance = Math.sqrt((from.position[0] - to.position[0]) ** 2 +
461
+ (from.position[1] - to.position[1]) ** 2 +
462
+ (from.position[2] - to.position[2]) ** 2);
463
+ // Assume reachable if within reasonable distance
464
+ return distance < 100;
465
+ }
466
+ /**
467
+ * Check causation (will A cause B)
468
+ */
469
+ checkCausation(query) {
470
+ // Simple heuristic: check for interaction potential
471
+ if (query.objects.length < 2)
472
+ return false;
473
+ const cause = query.objects[0];
474
+ const effect = query.objects[1];
475
+ // Check if cause can influence effect
476
+ if (cause.velocity && effect.position && cause.position) {
477
+ // Will cause move toward effect?
478
+ const towardEffect = [
479
+ effect.position[0] - cause.position[0],
480
+ effect.position[1] - cause.position[1],
481
+ effect.position[2] - cause.position[2],
482
+ ];
483
+ const dotProduct = cause.velocity[0] * towardEffect[0] +
484
+ cause.velocity[1] * towardEffect[1] +
485
+ cause.velocity[2] * towardEffect[2];
486
+ return dotProduct > 0;
487
+ }
488
+ return false;
489
+ }
490
+ /**
491
+ * Compute trajectory of object
492
+ */
493
+ computeTrajectory(objects) {
494
+ if (objects.length === 0)
495
+ return 'No object specified';
496
+ const obj = objects[0];
497
+ if (!obj.position || !obj.velocity) {
498
+ return 'Object has no position or velocity';
499
+ }
500
+ // Simple forward simulation
501
+ const steps = 10;
502
+ const dt = 0.1;
503
+ const positions = [];
504
+ let pos = [...obj.position];
505
+ let vel = [...obj.velocity];
506
+ for (let i = 0; i < steps; i++) {
507
+ // Apply gravity
508
+ vel[2] -= 9.8 * dt;
509
+ // Update position
510
+ pos[0] += vel[0] * dt;
511
+ pos[1] += vel[1] * dt;
512
+ pos[2] += vel[2] * dt;
513
+ // Ground collision
514
+ if (pos[2] < 0) {
515
+ pos[2] = 0;
516
+ vel[2] = -vel[2] * 0.5; // Bounce with damping
517
+ }
518
+ positions.push(`(${pos[0].toFixed(1)}, ${pos[1].toFixed(1)}, ${pos[2].toFixed(1)})`);
519
+ }
520
+ return `Trajectory: ${positions.join(' -> ')}`;
521
+ }
522
+ // ============================================================================
523
+ // Agent Training (in simulation)
524
+ // ============================================================================
525
+ /**
526
+ * Train agent in simulated environment
527
+ * Returns reward signal based on trajectory quality
528
+ */
529
+ trainAgent(agent, policy, episodes, maxSteps) {
530
+ let totalReward = 0;
531
+ let bestTrajectory = null;
532
+ let bestReward = -Infinity;
533
+ for (let ep = 0; ep < episodes; ep++) {
534
+ // Generate initial state
535
+ const initialState = this.generateRandomState();
536
+ const actions = [];
537
+ // Rollout policy
538
+ let state = initialState;
539
+ for (let step = 0; step < maxSteps; step++) {
540
+ const action = policy(state);
541
+ action.agent = agent;
542
+ actions.push(action);
543
+ const prediction = this.predict(state, action);
544
+ state = prediction.state;
545
+ if (prediction.uncertainty > this.config.uncertaintyThreshold) {
546
+ break;
547
+ }
548
+ }
549
+ // Simulate trajectory
550
+ const trajectory = this.simulate(initialState, actions, maxSteps);
551
+ // Calculate reward (higher probability = better)
552
+ const reward = trajectory.totalProbability * trajectory.horizon;
553
+ totalReward += reward;
554
+ if (reward > bestReward) {
555
+ bestReward = reward;
556
+ bestTrajectory = trajectory;
557
+ }
558
+ }
559
+ return {
560
+ avgReward: totalReward / episodes,
561
+ bestTrajectory,
562
+ };
563
+ }
564
+ /**
565
+ * Generate random initial state for training
566
+ */
567
+ generateRandomState() {
568
+ const dim = 512;
569
+ const vector = new Array(dim);
570
+ for (let i = 0; i < dim; i++) {
571
+ vector[i] = (Math.random() - 0.5) * 2;
572
+ }
573
+ return {
574
+ vector: this.normalize(vector),
575
+ dimensions: dim,
576
+ sourceModality: 'state',
577
+ sourceId: `random-${Date.now()}`,
578
+ timestamp: new Date(),
579
+ confidence: 1.0,
580
+ entropy: 0.5,
581
+ };
582
+ }
583
+ // ============================================================================
584
+ // Utilities
585
+ // ============================================================================
586
+ normalize(vector) {
587
+ const magnitude = Math.sqrt(vector.reduce((sum, v) => sum + v * v, 0));
588
+ if (magnitude === 0)
589
+ return vector;
590
+ return vector.map((v) => v / magnitude);
591
+ }
592
+ calculateEntropy(vector) {
593
+ const absSum = vector.reduce((sum, v) => sum + Math.abs(v), 0);
594
+ if (absSum === 0)
595
+ return 0;
596
+ const probs = vector.map((v) => Math.abs(v) / absSum);
597
+ let entropy = 0;
598
+ for (const p of probs) {
599
+ if (p > 0) {
600
+ entropy -= p * Math.log2(p);
601
+ }
602
+ }
603
+ return entropy / Math.log2(vector.length);
604
+ }
605
+ simpleHash(str) {
606
+ let hash = 0;
607
+ for (let i = 0; i < str.length; i++) {
608
+ hash = ((hash << 5) - hash) + str.charCodeAt(i);
609
+ hash = hash & hash;
610
+ }
611
+ return Math.abs(hash);
612
+ }
613
+ // ============================================================================
614
+ // Entity Management (for physics)
615
+ // ============================================================================
616
+ addEntity(entity) {
617
+ this.entities.set(entity.id, entity);
618
+ }
619
+ removeEntity(entityId) {
620
+ return this.entities.delete(entityId);
621
+ }
622
+ getEntity(entityId) {
623
+ return this.entities.get(entityId);
624
+ }
625
+ addRelation(relation) {
626
+ this.relations.set(relation.id, relation);
627
+ }
628
+ // ============================================================================
629
+ // Events
630
+ // ============================================================================
631
+ on(handler) {
632
+ this.eventHandlers.add(handler);
633
+ return () => this.eventHandlers.delete(handler);
634
+ }
635
+ emit(event) {
636
+ for (const handler of this.eventHandlers) {
637
+ try {
638
+ handler(event);
639
+ }
640
+ catch (err) {
641
+ console.error('Predictor event handler error:', err);
642
+ }
643
+ }
644
+ }
645
+ // ============================================================================
646
+ // Stats
647
+ // ============================================================================
648
+ stats() {
649
+ return {
650
+ predictionCount: this.predictionCount,
651
+ simulationCount: this.simulationCount,
652
+ avgPredictionTime: this.predictionCount > 0
653
+ ? this.totalPredictionTime / this.predictionCount
654
+ : 0,
655
+ entityCount: this.entities.size,
656
+ relationCount: this.relations.size,
657
+ };
658
+ }
659
+ getConfig() {
660
+ return { ...this.config };
661
+ }
662
+ }
663
+ exports.WorldModelPredictor = WorldModelPredictor;
664
+ // ============================================================================
665
+ // Factory
666
+ // ============================================================================
667
+ function createWorldModelPredictor(config) {
668
+ return new WorldModelPredictor(config);
669
+ }
670
+ // ============================================================================
671
+ // Action Factory
672
+ // ============================================================================
673
+ function createAction(type, parameters, agent) {
674
+ return {
675
+ id: (0, crypto_1.randomUUID)(),
676
+ type,
677
+ parameters,
678
+ agent,
679
+ timestamp: new Date(),
680
+ };
681
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Genesis 6.2 - Value-Guided JEPA Tests
3
+ *
4
+ * Tests for the value function and value-guided prediction.
5
+ *
6
+ * Run: node --test dist/world-model/test-value-jepa.js
7
+ */
8
+ export {};