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,506 @@
1
+ "use strict";
2
+ /**
3
+ * Genesis 4.0 - Predictor Agent
4
+ *
5
+ * Forecasts outcomes based on patterns, history, and models.
6
+ * The oracle: "Based on patterns, I predict..."
7
+ *
8
+ * Features:
9
+ * - Pattern-based prediction
10
+ * - Confidence estimation
11
+ * - Historical pattern matching
12
+ * - Monte Carlo simulation (simple)
13
+ * - Learning from outcomes
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.PredictorAgent = void 0;
17
+ exports.createPredictorAgent = createPredictorAgent;
18
+ const base_agent_js_1 = require("./base-agent.js");
19
+ const message_bus_js_1 = require("./message-bus.js");
20
+ const crypto_1 = require("crypto");
21
+ // ============================================================================
22
+ // Predictor Agent
23
+ // ============================================================================
24
+ class PredictorAgent extends base_agent_js_1.BaseAgent {
25
+ // Pattern library learned from experience
26
+ patterns = new Map();
27
+ // Prediction history
28
+ predictions = new Map();
29
+ // Historical events for pattern matching
30
+ history = [];
31
+ // Baseline probabilities for common outcomes
32
+ baselines = {
33
+ success: 0.6,
34
+ failure: 0.25,
35
+ partial: 0.1,
36
+ unknown: 0.05,
37
+ };
38
+ constructor(bus = message_bus_js_1.messageBus) {
39
+ super({ type: 'predictor' }, bus);
40
+ this.initializePatterns();
41
+ }
42
+ initializePatterns() {
43
+ // Pre-load common patterns
44
+ this.patterns.set('build-after-research', {
45
+ id: 'build-after-research',
46
+ conditions: ['research_complete', 'plan_created'],
47
+ outcome: 'build_success',
48
+ occurrences: 100,
49
+ successRate: 0.85,
50
+ lastSeen: new Date(),
51
+ });
52
+ this.patterns.set('iterate-after-critique', {
53
+ id: 'iterate-after-critique',
54
+ conditions: ['critique_received', 'low_score'],
55
+ outcome: 'improvement',
56
+ occurrences: 80,
57
+ successRate: 0.7,
58
+ lastSeen: new Date(),
59
+ });
60
+ this.patterns.set('failure-without-ethics', {
61
+ id: 'failure-without-ethics',
62
+ conditions: ['ethics_skipped', 'risky_action'],
63
+ outcome: 'negative_consequence',
64
+ occurrences: 50,
65
+ successRate: 0.4,
66
+ lastSeen: new Date(),
67
+ });
68
+ this.patterns.set('success-with-planning', {
69
+ id: 'success-with-planning',
70
+ conditions: ['plan_created', 'steps_followed'],
71
+ outcome: 'goal_achieved',
72
+ occurrences: 120,
73
+ successRate: 0.82,
74
+ lastSeen: new Date(),
75
+ });
76
+ }
77
+ // ============================================================================
78
+ // Message Handling
79
+ // ============================================================================
80
+ getMessageTypes() {
81
+ return ['PREDICT', 'FEEDBACK', 'QUERY', 'COMMAND'];
82
+ }
83
+ async process(message) {
84
+ switch (message.type) {
85
+ case 'PREDICT':
86
+ return this.handlePredictRequest(message);
87
+ case 'FEEDBACK':
88
+ return this.handleFeedback(message);
89
+ case 'QUERY':
90
+ return this.handleQuery(message);
91
+ case 'COMMAND':
92
+ return this.handleCommand(message);
93
+ default:
94
+ return null;
95
+ }
96
+ }
97
+ // ============================================================================
98
+ // Prediction Logic
99
+ // ============================================================================
100
+ async handlePredictRequest(message) {
101
+ const { query, context, conditions, horizon } = message.payload;
102
+ const prediction = this.predict(query, {
103
+ context,
104
+ conditions,
105
+ horizon: horizon || 'short_term',
106
+ });
107
+ this.predictions.set(prediction.id, prediction);
108
+ this.log(`Prediction: "${query}" -> ${prediction.outcomes[0]?.description} (${(prediction.confidence * 100).toFixed(0)}% confidence)`);
109
+ return {
110
+ ...this.createResponse(message, 'RESPONSE', { prediction }),
111
+ id: '',
112
+ timestamp: new Date(),
113
+ };
114
+ }
115
+ predict(query, options = {}) {
116
+ const { context, conditions = [], horizon = 'short_term' } = options;
117
+ // 1. Find matching patterns
118
+ const matchingPatterns = this.findMatchingPatterns(query, conditions);
119
+ // 2. Calculate outcomes based on patterns + baselines
120
+ const outcomes = this.calculateOutcomes(query, matchingPatterns, context);
121
+ // 3. Calculate overall confidence
122
+ const confidence = this.calculateConfidence(matchingPatterns, outcomes);
123
+ // 4. Generate reasoning
124
+ const reasoning = this.generateReasoning(matchingPatterns, outcomes);
125
+ const prediction = {
126
+ id: (0, crypto_1.randomUUID)(),
127
+ query,
128
+ outcomes,
129
+ confidence,
130
+ reasoning,
131
+ timestamp: new Date(),
132
+ horizon,
133
+ };
134
+ return prediction;
135
+ }
136
+ // ============================================================================
137
+ // Pattern Matching
138
+ // ============================================================================
139
+ findMatchingPatterns(query, conditions) {
140
+ const queryLower = query.toLowerCase();
141
+ const matching = [];
142
+ for (const pattern of this.patterns.values()) {
143
+ // Check if any conditions match
144
+ const conditionMatch = pattern.conditions.some((c) => conditions.some((cond) => cond.toLowerCase().includes(c)) ||
145
+ queryLower.includes(c.replace(/_/g, ' ')));
146
+ // Check if query relates to outcome
147
+ const outcomeMatch = queryLower.includes(pattern.outcome.replace(/_/g, ' '));
148
+ if (conditionMatch || outcomeMatch) {
149
+ matching.push(pattern);
150
+ }
151
+ }
152
+ // Also check history for similar queries
153
+ const historicalMatches = this.findHistoricalMatches(query);
154
+ for (const match of historicalMatches) {
155
+ // Create temporary pattern from historical match
156
+ matching.push({
157
+ id: 'historical-' + (0, crypto_1.randomUUID)().slice(0, 4),
158
+ conditions: [match.query],
159
+ outcome: match.outcome,
160
+ occurrences: 1,
161
+ successRate: 0.7, // Historical matches get moderate confidence
162
+ lastSeen: match.timestamp,
163
+ });
164
+ }
165
+ return matching;
166
+ }
167
+ findHistoricalMatches(query) {
168
+ const queryWords = new Set(query.toLowerCase().split(/\s+/));
169
+ return this.history.filter((event) => {
170
+ const eventWords = new Set(event.query.toLowerCase().split(/\s+/));
171
+ const overlap = [...queryWords].filter((w) => eventWords.has(w));
172
+ return overlap.length >= 2; // At least 2 words in common
173
+ }).slice(-5); // Last 5 matches
174
+ }
175
+ // ============================================================================
176
+ // Outcome Calculation
177
+ // ============================================================================
178
+ calculateOutcomes(query, patterns, context) {
179
+ const outcomes = new Map();
180
+ const queryLower = query.toLowerCase();
181
+ // Start with pattern-based outcomes
182
+ for (const pattern of patterns) {
183
+ const existing = outcomes.get(pattern.outcome);
184
+ const probability = pattern.successRate * (pattern.occurrences / (pattern.occurrences + 10));
185
+ if (existing) {
186
+ existing.probability = Math.min(0.95, existing.probability + probability * 0.5);
187
+ }
188
+ else {
189
+ outcomes.set(pattern.outcome, {
190
+ description: this.humanizeOutcome(pattern.outcome),
191
+ probability,
192
+ impact: this.determineImpact(pattern.outcome),
193
+ timeframe: this.estimateTimeframe(pattern.outcome),
194
+ });
195
+ }
196
+ }
197
+ // Add baseline outcomes if no patterns found
198
+ if (outcomes.size === 0) {
199
+ // Try to infer from query keywords
200
+ if (queryLower.includes('success') || queryLower.includes('work')) {
201
+ outcomes.set('success', {
202
+ description: 'The operation will succeed',
203
+ probability: this.baselines.success,
204
+ impact: 'positive',
205
+ });
206
+ outcomes.set('failure', {
207
+ description: 'The operation may fail',
208
+ probability: this.baselines.failure,
209
+ impact: 'negative',
210
+ });
211
+ }
212
+ else if (queryLower.includes('fail') || queryLower.includes('error')) {
213
+ outcomes.set('failure', {
214
+ description: 'Issues are likely to occur',
215
+ probability: 0.6,
216
+ impact: 'negative',
217
+ });
218
+ outcomes.set('recovery', {
219
+ description: 'Recovery is possible with intervention',
220
+ probability: 0.3,
221
+ impact: 'neutral',
222
+ });
223
+ }
224
+ else {
225
+ // Generic uncertain prediction
226
+ outcomes.set('uncertain', {
227
+ description: 'Outcome is uncertain, multiple possibilities exist',
228
+ probability: 0.5,
229
+ impact: 'neutral',
230
+ });
231
+ }
232
+ }
233
+ // Sort by probability
234
+ return Array.from(outcomes.values()).sort((a, b) => b.probability - a.probability);
235
+ }
236
+ humanizeOutcome(outcome) {
237
+ const humanizations = {
238
+ build_success: 'The build will complete successfully',
239
+ improvement: 'Quality will improve after iteration',
240
+ negative_consequence: 'Negative consequences may occur',
241
+ goal_achieved: 'The goal will be achieved',
242
+ success: 'The operation will succeed',
243
+ failure: 'The operation may fail',
244
+ partial: 'Partial success is likely',
245
+ };
246
+ return humanizations[outcome] || outcome.replace(/_/g, ' ');
247
+ }
248
+ determineImpact(outcome) {
249
+ const positives = ['success', 'improvement', 'achieved', 'complete'];
250
+ const negatives = ['fail', 'error', 'negative', 'problem'];
251
+ const outcomeLower = outcome.toLowerCase();
252
+ if (positives.some((p) => outcomeLower.includes(p)))
253
+ return 'positive';
254
+ if (negatives.some((n) => outcomeLower.includes(n)))
255
+ return 'negative';
256
+ return 'neutral';
257
+ }
258
+ estimateTimeframe(outcome) {
259
+ // Simple heuristic based on outcome type
260
+ if (outcome.includes('immediate') || outcome.includes('quick')) {
261
+ return 'immediate';
262
+ }
263
+ if (outcome.includes('long') || outcome.includes('eventual')) {
264
+ return 'long_term';
265
+ }
266
+ return 'short_term';
267
+ }
268
+ // ============================================================================
269
+ // Confidence Calculation
270
+ // ============================================================================
271
+ calculateConfidence(patterns, outcomes) {
272
+ let confidence = 0.3; // Base confidence
273
+ // More patterns = more confidence
274
+ confidence += Math.min(0.3, patterns.length * 0.1);
275
+ // Patterns with more occurrences = more confidence
276
+ const totalOccurrences = patterns.reduce((sum, p) => sum + p.occurrences, 0);
277
+ confidence += Math.min(0.2, totalOccurrences / 500);
278
+ // High probability primary outcome = more confidence
279
+ if (outcomes.length > 0 && outcomes[0].probability > 0.7) {
280
+ confidence += 0.15;
281
+ }
282
+ // Clear separation between outcomes = more confidence
283
+ if (outcomes.length >= 2) {
284
+ const separation = outcomes[0].probability - outcomes[1].probability;
285
+ confidence += Math.min(0.1, separation * 0.5);
286
+ }
287
+ return Math.min(0.95, Math.max(0.1, confidence));
288
+ }
289
+ // ============================================================================
290
+ // Reasoning
291
+ // ============================================================================
292
+ generateReasoning(patterns, outcomes) {
293
+ const reasons = [];
294
+ if (patterns.length === 0) {
295
+ reasons.push('No direct patterns found; using baseline probabilities.');
296
+ }
297
+ else {
298
+ reasons.push(`Based on ${patterns.length} matching pattern(s).`);
299
+ // Mention strongest pattern
300
+ const strongest = patterns.reduce((max, p) => p.successRate * p.occurrences > max.successRate * max.occurrences ? p : max, patterns[0]);
301
+ reasons.push(`Strongest pattern: "${strongest.id}" (${(strongest.successRate * 100).toFixed(0)}% success rate, ${strongest.occurrences} observations).`);
302
+ }
303
+ if (outcomes.length > 0) {
304
+ const primary = outcomes[0];
305
+ reasons.push(`Most likely outcome: ${primary.description} (${(primary.probability * 100).toFixed(0)}% probability).`);
306
+ }
307
+ return reasons.join(' ');
308
+ }
309
+ // ============================================================================
310
+ // Feedback (Learning)
311
+ // ============================================================================
312
+ async handleFeedback(message) {
313
+ const { predictionId, actualOutcome, correct } = message.payload;
314
+ const prediction = this.predictions.get(predictionId);
315
+ if (prediction) {
316
+ prediction.verified = true;
317
+ prediction.actualOutcome = actualOutcome;
318
+ // Learn from this feedback
319
+ this.learn(prediction, actualOutcome, correct);
320
+ this.log(`Feedback received: prediction ${predictionId.slice(0, 8)} was ${correct ? 'correct' : 'incorrect'}`);
321
+ }
322
+ // Add to history
323
+ this.history.push({
324
+ query: prediction?.query || message.payload.query,
325
+ outcome: actualOutcome,
326
+ timestamp: new Date(),
327
+ context: message.payload.context,
328
+ });
329
+ // Keep history bounded
330
+ if (this.history.length > 1000) {
331
+ this.history.shift();
332
+ }
333
+ return {
334
+ ...this.createResponse(message, 'RESPONSE', { success: true }),
335
+ id: '',
336
+ timestamp: new Date(),
337
+ };
338
+ }
339
+ learn(prediction, actualOutcome, correct) {
340
+ // Update patterns based on feedback
341
+ const queryLower = prediction.query.toLowerCase();
342
+ for (const pattern of this.patterns.values()) {
343
+ // Check if this pattern was relevant
344
+ const wasRelevant = pattern.conditions.some((c) => queryLower.includes(c.replace(/_/g, ' ')));
345
+ if (wasRelevant) {
346
+ pattern.occurrences++;
347
+ pattern.lastSeen = new Date();
348
+ if (correct && pattern.outcome.includes(actualOutcome.replace(/ /g, '_'))) {
349
+ // Prediction was correct and matched this pattern
350
+ pattern.successRate = (pattern.successRate * (pattern.occurrences - 1) + 1) / pattern.occurrences;
351
+ }
352
+ else if (!correct) {
353
+ // Prediction was wrong
354
+ pattern.successRate = (pattern.successRate * (pattern.occurrences - 1)) / pattern.occurrences;
355
+ }
356
+ }
357
+ }
358
+ // Potentially create new pattern if we see a repeated outcome
359
+ const similarHistory = this.history.filter((h) => h.outcome === actualOutcome &&
360
+ h.query.toLowerCase().split(/\s+/).some((w) => queryLower.includes(w)));
361
+ if (similarHistory.length >= 3) {
362
+ const newPatternId = `learned-${actualOutcome.replace(/ /g, '-').toLowerCase()}`;
363
+ if (!this.patterns.has(newPatternId)) {
364
+ this.patterns.set(newPatternId, {
365
+ id: newPatternId,
366
+ conditions: [prediction.query.toLowerCase()],
367
+ outcome: actualOutcome.replace(/ /g, '_'),
368
+ occurrences: similarHistory.length,
369
+ successRate: correct ? 0.7 : 0.3,
370
+ lastSeen: new Date(),
371
+ });
372
+ this.log(`Learned new pattern: ${newPatternId}`);
373
+ }
374
+ }
375
+ }
376
+ // ============================================================================
377
+ // Query & Commands
378
+ // ============================================================================
379
+ async handleQuery(message) {
380
+ const { query, predictionId } = message.payload;
381
+ if (query === 'prediction' && predictionId) {
382
+ const prediction = this.predictions.get(predictionId);
383
+ return {
384
+ ...this.createResponse(message, 'RESPONSE', { prediction }),
385
+ id: '',
386
+ timestamp: new Date(),
387
+ };
388
+ }
389
+ if (query === 'patterns') {
390
+ return {
391
+ ...this.createResponse(message, 'RESPONSE', {
392
+ patterns: Array.from(this.patterns.values()),
393
+ }),
394
+ id: '',
395
+ timestamp: new Date(),
396
+ };
397
+ }
398
+ if (query === 'stats') {
399
+ return {
400
+ ...this.createResponse(message, 'RESPONSE', this.getStats()),
401
+ id: '',
402
+ timestamp: new Date(),
403
+ };
404
+ }
405
+ if (query === 'accuracy') {
406
+ return {
407
+ ...this.createResponse(message, 'RESPONSE', {
408
+ accuracy: this.calculateAccuracy(),
409
+ }),
410
+ id: '',
411
+ timestamp: new Date(),
412
+ };
413
+ }
414
+ return null;
415
+ }
416
+ async handleCommand(message) {
417
+ const { command, params } = message.payload;
418
+ switch (command) {
419
+ case 'add_pattern':
420
+ this.patterns.set(params.id, params);
421
+ return {
422
+ ...this.createResponse(message, 'RESPONSE', { success: true }),
423
+ id: '',
424
+ timestamp: new Date(),
425
+ };
426
+ case 'execute_step':
427
+ // Predict outcome for a step
428
+ const prediction = this.predict(params.step, {
429
+ conditions: [params.planId, params.stepId],
430
+ });
431
+ return {
432
+ ...this.createResponse(message, 'RESPONSE', { prediction }),
433
+ id: '',
434
+ timestamp: new Date(),
435
+ };
436
+ default:
437
+ return null;
438
+ }
439
+ }
440
+ // ============================================================================
441
+ // Stats
442
+ // ============================================================================
443
+ getStats() {
444
+ const verified = Array.from(this.predictions.values()).filter((p) => p.verified);
445
+ const correct = verified.filter((p) => p.outcomes[0]?.description.toLowerCase().includes(p.actualOutcome?.toLowerCase() || ''));
446
+ return {
447
+ totalPredictions: this.predictions.size,
448
+ verifiedPredictions: verified.length,
449
+ accuracy: verified.length > 0 ? correct.length / verified.length : 0,
450
+ patterns: this.patterns.size,
451
+ historySize: this.history.length,
452
+ avgConfidence: this.calculateAvgConfidence(),
453
+ };
454
+ }
455
+ calculateAccuracy() {
456
+ const verified = Array.from(this.predictions.values()).filter((p) => p.verified);
457
+ if (verified.length === 0) {
458
+ return {
459
+ overall: 0,
460
+ byHorizon: {},
461
+ byConfidence: { high: 0, medium: 0, low: 0 },
462
+ };
463
+ }
464
+ // Count correct predictions
465
+ const isCorrect = (p) => p.outcomes[0]?.description.toLowerCase().includes(p.actualOutcome?.toLowerCase() || '');
466
+ const correct = verified.filter(isCorrect);
467
+ const overall = correct.length / verified.length;
468
+ // By horizon
469
+ const byHorizon = {};
470
+ const horizons = new Set(verified.map((p) => p.horizon));
471
+ for (const horizon of horizons) {
472
+ const horizonPredictions = verified.filter((p) => p.horizon === horizon);
473
+ const horizonCorrect = horizonPredictions.filter(isCorrect);
474
+ byHorizon[horizon] = horizonPredictions.length > 0
475
+ ? horizonCorrect.length / horizonPredictions.length
476
+ : 0;
477
+ }
478
+ // By confidence level
479
+ const highConf = verified.filter((p) => p.confidence >= 0.7);
480
+ const medConf = verified.filter((p) => p.confidence >= 0.4 && p.confidence < 0.7);
481
+ const lowConf = verified.filter((p) => p.confidence < 0.4);
482
+ return {
483
+ overall,
484
+ byHorizon,
485
+ byConfidence: {
486
+ high: highConf.length > 0 ? highConf.filter(isCorrect).length / highConf.length : 0,
487
+ medium: medConf.length > 0 ? medConf.filter(isCorrect).length / medConf.length : 0,
488
+ low: lowConf.length > 0 ? lowConf.filter(isCorrect).length / lowConf.length : 0,
489
+ },
490
+ };
491
+ }
492
+ calculateAvgConfidence() {
493
+ const predictions = Array.from(this.predictions.values());
494
+ if (predictions.length === 0)
495
+ return 0;
496
+ return predictions.reduce((sum, p) => sum + p.confidence, 0) / predictions.length;
497
+ }
498
+ }
499
+ exports.PredictorAgent = PredictorAgent;
500
+ // ============================================================================
501
+ // Register Factory
502
+ // ============================================================================
503
+ (0, base_agent_js_1.registerAgentFactory)('predictor', (bus) => new PredictorAgent(bus));
504
+ function createPredictorAgent(bus) {
505
+ return new PredictorAgent(bus);
506
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Genesis 4.0 - Sensor Agent
3
+ *
4
+ * Interface to MCP servers (the system's sensory organs).
5
+ * Routes requests to appropriate MCP servers and collects results.
6
+ *
7
+ * 13 MCP Servers as Senses:
8
+ * - KNOWLEDGE: arxiv, semantic-scholar, context7, wolfram
9
+ * - RESEARCH: gemini, brave-search, exa, firecrawl
10
+ * - CREATION: openai, github, stability-ai
11
+ * - STORAGE: memory, filesystem
12
+ */
13
+ import { BaseAgent } from './base-agent.js';
14
+ import { MessageBus } from './message-bus.js';
15
+ import { Message, MessageType } from './types.js';
16
+ import { MCPMode } from '../mcp/index.js';
17
+ import { MCPServerName } from '../types.js';
18
+ export type MCPCategory = 'knowledge' | 'research' | 'creation' | 'storage';
19
+ /**
20
+ * Runtime state of an MCP server.
21
+ * Renamed from MCPServer to avoid conflict with MCPServerName type.
22
+ */
23
+ export interface MCPServerState {
24
+ name: MCPServerName;
25
+ category: MCPCategory;
26
+ capabilities: string[];
27
+ available: boolean;
28
+ lastChecked: Date;
29
+ successRate: number;
30
+ callCount: number;
31
+ }
32
+ interface SenseRequest {
33
+ category?: MCPCategory;
34
+ server?: string;
35
+ capability: string;
36
+ params: Record<string, any>;
37
+ timeout?: number;
38
+ }
39
+ interface SenseResult {
40
+ server: string;
41
+ success: boolean;
42
+ data?: any;
43
+ error?: string;
44
+ latency: number;
45
+ mode: 'real' | 'simulated';
46
+ }
47
+ export declare class SensorAgent extends BaseAgent {
48
+ private mcpServers;
49
+ private requestHistory;
50
+ constructor(bus?: MessageBus);
51
+ private initializeMCPRegistry;
52
+ private registerMCP;
53
+ protected getMessageTypes(): MessageType[];
54
+ process(message: Message): Promise<Message | null>;
55
+ private handleSenseRequest;
56
+ sense(request: SenseRequest): Promise<SenseResult>;
57
+ private findServer;
58
+ private recordRequest;
59
+ private handleQuery;
60
+ private handleCommand;
61
+ private checkAllServers;
62
+ getStats(): {
63
+ totalServers: number;
64
+ availableServers: number;
65
+ serversByCategory: {
66
+ knowledge: number;
67
+ research: number;
68
+ creation: number;
69
+ storage: number;
70
+ };
71
+ totalRequests: number;
72
+ recentSuccessRate: number;
73
+ avgLatency: number;
74
+ };
75
+ getAvailableServers(): MCPServerState[];
76
+ getServersByCategory(category: MCPCategory): MCPServerState[];
77
+ hasCapability(capability: string): boolean;
78
+ /**
79
+ * Get the current MCP mode (real/simulated/hybrid)
80
+ */
81
+ getMCPMode(): MCPMode;
82
+ /**
83
+ * Check if running in simulated mode
84
+ */
85
+ isSimulated(): boolean;
86
+ }
87
+ export declare function createSensorAgent(bus?: MessageBus): SensorAgent;
88
+ export {};