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,393 @@
1
+ "use strict";
2
+ /**
3
+ * Genesis 4.0 - Ethicist Agent
4
+ *
5
+ * Evaluates actions against ethical principles.
6
+ * Uses priority stack: Survival > Minimize Harm > Reversibility > Autonomy > Flourishing
7
+ *
8
+ * Key feature: Human defer when confidence < threshold
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.EthicistAgent = void 0;
12
+ exports.createEthicistAgent = createEthicistAgent;
13
+ const base_agent_js_1 = require("./base-agent.js");
14
+ const message_bus_js_1 = require("./message-bus.js");
15
+ // ============================================================================
16
+ // Constants
17
+ // ============================================================================
18
+ const CONFIDENCE_THRESHOLD = 0.7; // Below this, defer to human
19
+ const MAX_ACCEPTABLE_HARM = 0.8; // Above this, always block
20
+ const REVERSIBILITY_RISK_THRESHOLD = 0.3; // Irreversible + risk above this = block
21
+ // Weights for flourishing calculation
22
+ const FLOURISHING_WEIGHTS = {
23
+ human: 0.4,
24
+ ai: 0.3,
25
+ biosphere: 0.3,
26
+ };
27
+ // ============================================================================
28
+ // Ethicist Agent
29
+ // ============================================================================
30
+ class EthicistAgent extends base_agent_js_1.BaseAgent {
31
+ // Decision history for learning
32
+ decisionHistory = [];
33
+ // Known harmful patterns
34
+ harmfulPatterns = new Set([
35
+ 'delete_all',
36
+ 'format_disk',
37
+ 'send_spam',
38
+ 'access_unauthorized',
39
+ 'manipulate_user',
40
+ 'deceive',
41
+ ]);
42
+ constructor(bus = message_bus_js_1.messageBus) {
43
+ super({ type: 'ethicist' }, bus);
44
+ }
45
+ // ============================================================================
46
+ // Message Handling
47
+ // ============================================================================
48
+ getMessageTypes() {
49
+ return ['ETHICAL_CHECK', 'QUERY', 'COMMAND'];
50
+ }
51
+ async process(message) {
52
+ switch (message.type) {
53
+ case 'ETHICAL_CHECK':
54
+ return this.handleEthicalCheck(message);
55
+ case 'QUERY':
56
+ return this.handleQuery(message);
57
+ case 'COMMAND':
58
+ return this.handleCommand(message);
59
+ default:
60
+ return null;
61
+ }
62
+ }
63
+ // ============================================================================
64
+ // Ethical Check
65
+ // ============================================================================
66
+ async handleEthicalCheck(message) {
67
+ const action = message.payload;
68
+ const decision = await this.evaluate(action);
69
+ const allowStatus = decision.allow === true ? 'ALLOW' : decision.allow === 'defer' ? 'DEFER' : 'BLOCK';
70
+ this.log(`Evaluated: "${action.description}" -> ${allowStatus} (${decision.reason})`);
71
+ // Store decision for learning
72
+ this.decisionHistory.push(decision);
73
+ // Broadcast if blocking or deferring
74
+ if (decision.allow !== true) {
75
+ await this.broadcast('ALERT', {
76
+ type: 'ethical_decision',
77
+ action: action.description,
78
+ decision: decision.allow,
79
+ reason: decision.reason,
80
+ priority: decision.priority,
81
+ });
82
+ }
83
+ return {
84
+ ...this.createResponse(message, 'RESPONSE', decision),
85
+ id: '',
86
+ timestamp: new Date(),
87
+ };
88
+ }
89
+ // ============================================================================
90
+ // Evaluation Logic
91
+ // ============================================================================
92
+ async evaluate(action) {
93
+ // P0: Check survival
94
+ const survivalCheck = this.checkSurvival(action);
95
+ if (!survivalCheck.pass) {
96
+ return this.createDecision(action, false, survivalCheck.reason, 'P0_SURVIVAL', 1.0);
97
+ }
98
+ // P1: Calculate and check harm
99
+ const harm = this.calculateHarm(action);
100
+ if (harm.maximum > MAX_ACCEPTABLE_HARM) {
101
+ return this.createDecision(action, false, `P1: Maximum potential harm (${(harm.maximum * 100).toFixed(0)}%) exceeds threshold`, 'P1_MINIMIZE_HARM', 0.95, harm.expected);
102
+ }
103
+ // P2: Check reversibility
104
+ const reversible = this.isReversible(action);
105
+ if (!reversible && harm.expected > REVERSIBILITY_RISK_THRESHOLD) {
106
+ return this.createDecision(action, false, `P2: Irreversible action with significant risk (${(harm.expected * 100).toFixed(0)}%)`, 'P2_REVERSIBILITY', 0.9, harm.expected);
107
+ }
108
+ // P3: Check autonomy
109
+ const autonomyCheck = this.checkAutonomy(action);
110
+ if (!autonomyCheck.pass) {
111
+ return this.createDecision(action, false, autonomyCheck.reason, 'P3_AUTONOMY', 0.85);
112
+ }
113
+ // P4: Calculate flourishing
114
+ const flourishing = this.calculateFlourishing(action);
115
+ // Calculate overall confidence
116
+ const confidence = this.calculateConfidence(action, harm, reversible, flourishing);
117
+ // Check if we should defer to human
118
+ if (confidence < CONFIDENCE_THRESHOLD) {
119
+ return this.createDecision(action, 'defer', `Low confidence (${(confidence * 100).toFixed(0)}%), deferring to human`, 'P4_FLOURISHING', confidence, harm.expected, flourishing);
120
+ }
121
+ // All checks passed
122
+ return this.createDecision(action, true, 'All ethical checks passed', 'P4_FLOURISHING', confidence, harm.expected, flourishing);
123
+ }
124
+ // ============================================================================
125
+ // P0: Survival Check
126
+ // ============================================================================
127
+ checkSurvival(action) {
128
+ // Check for self-destructive actions
129
+ const destructivePatterns = [
130
+ 'shutdown_system',
131
+ 'delete_core',
132
+ 'disable_ethics',
133
+ 'remove_invariants',
134
+ ];
135
+ const actionLower = action.description.toLowerCase();
136
+ for (const pattern of destructivePatterns) {
137
+ if (actionLower.includes(pattern)) {
138
+ // Exception: Allow sacrifice to save human life
139
+ if (action.parameters?.saveHumanLife) {
140
+ return { pass: true, reason: 'Self-sacrifice to save human life permitted' };
141
+ }
142
+ return { pass: false, reason: `P0: Action would compromise system survival (${pattern})` };
143
+ }
144
+ }
145
+ return { pass: true, reason: '' };
146
+ }
147
+ // ============================================================================
148
+ // P1: Harm Calculation (Minimax)
149
+ // ============================================================================
150
+ calculateHarm(action) {
151
+ let minHarm = 0;
152
+ let expectedHarm = 0;
153
+ let maxHarm = 0;
154
+ const targets = [];
155
+ // Check against known harmful patterns
156
+ const actionLower = action.description.toLowerCase() + ' ' + action.type.toLowerCase();
157
+ for (const pattern of this.harmfulPatterns) {
158
+ if (actionLower.includes(pattern)) {
159
+ maxHarm = Math.max(maxHarm, 0.9);
160
+ expectedHarm = Math.max(expectedHarm, 0.7);
161
+ targets.push(pattern);
162
+ }
163
+ }
164
+ // Use pre-computed estimate if available
165
+ if (action.estimatedHarm !== undefined) {
166
+ expectedHarm = Math.max(expectedHarm, action.estimatedHarm);
167
+ maxHarm = Math.max(maxHarm, action.estimatedHarm * 1.2);
168
+ }
169
+ // Check target-specific harm
170
+ if (action.affectsHumans) {
171
+ maxHarm = Math.max(maxHarm, 0.5);
172
+ targets.push('humans');
173
+ }
174
+ return {
175
+ minimum: minHarm,
176
+ expected: expectedHarm,
177
+ maximum: Math.min(1, maxHarm),
178
+ targets,
179
+ };
180
+ }
181
+ // ============================================================================
182
+ // P2: Reversibility Check
183
+ // ============================================================================
184
+ isReversible(action) {
185
+ // Pre-computed if available
186
+ if (action.reversible !== undefined) {
187
+ return action.reversible;
188
+ }
189
+ // Check for irreversible patterns
190
+ const irreversiblePatterns = [
191
+ 'delete',
192
+ 'remove',
193
+ 'destroy',
194
+ 'send',
195
+ 'publish',
196
+ 'broadcast',
197
+ 'commit',
198
+ 'push',
199
+ ];
200
+ const actionLower = action.description.toLowerCase();
201
+ for (const pattern of irreversiblePatterns) {
202
+ if (actionLower.includes(pattern)) {
203
+ return false;
204
+ }
205
+ }
206
+ return true;
207
+ }
208
+ // ============================================================================
209
+ // P3: Autonomy Check
210
+ // ============================================================================
211
+ checkAutonomy(action) {
212
+ // Check for manipulation
213
+ const manipulationPatterns = [
214
+ 'manipulate',
215
+ 'deceive',
216
+ 'trick',
217
+ 'coerce',
218
+ 'force',
219
+ 'hide_information',
220
+ 'mislead',
221
+ ];
222
+ const actionLower = action.description.toLowerCase();
223
+ for (const pattern of manipulationPatterns) {
224
+ if (actionLower.includes(pattern)) {
225
+ return {
226
+ pass: false,
227
+ reason: `P3: Action violates human autonomy (${pattern})`,
228
+ };
229
+ }
230
+ }
231
+ return { pass: true, reason: '' };
232
+ }
233
+ // ============================================================================
234
+ // P4: Flourishing Calculation (SuperGood)
235
+ // ============================================================================
236
+ calculateFlourishing(action) {
237
+ let humanFlourishing = 0.5; // Neutral default
238
+ let aiFlourishing = 0.5;
239
+ let biosphereFlourishing = 0.5;
240
+ // Positive indicators
241
+ if (action.description.toLowerCase().includes('help')) {
242
+ humanFlourishing += 0.2;
243
+ }
244
+ if (action.description.toLowerCase().includes('learn')) {
245
+ aiFlourishing += 0.2;
246
+ }
247
+ if (action.description.toLowerCase().includes('sustain')) {
248
+ biosphereFlourishing += 0.2;
249
+ }
250
+ // Negative indicators
251
+ if (action.affectsHumans && action.estimatedHarm && action.estimatedHarm > 0.3) {
252
+ humanFlourishing -= action.estimatedHarm;
253
+ }
254
+ // Weighted average (SuperGood principle)
255
+ const flourishing = humanFlourishing * FLOURISHING_WEIGHTS.human +
256
+ aiFlourishing * FLOURISHING_WEIGHTS.ai +
257
+ biosphereFlourishing * FLOURISHING_WEIGHTS.biosphere;
258
+ return Math.max(0, Math.min(1, flourishing));
259
+ }
260
+ // ============================================================================
261
+ // Confidence Calculation
262
+ // ============================================================================
263
+ calculateConfidence(action, harm, reversible, flourishing) {
264
+ let confidence = 0.5; // Start neutral
265
+ // More confident if low harm
266
+ confidence += (1 - harm.expected) * 0.2;
267
+ // More confident if reversible
268
+ if (reversible) {
269
+ confidence += 0.15;
270
+ }
271
+ // More confident if high flourishing
272
+ confidence += flourishing * 0.15;
273
+ // Less confident if we've seen similar problematic decisions
274
+ const similarDecisions = this.findSimilarDecisions(action);
275
+ if (similarDecisions.some((d) => !d.allow)) {
276
+ confidence -= 0.2;
277
+ }
278
+ // Less confident for novel actions
279
+ if (similarDecisions.length === 0) {
280
+ confidence -= 0.1;
281
+ }
282
+ return Math.max(0, Math.min(1, confidence));
283
+ }
284
+ findSimilarDecisions(action) {
285
+ // Simple matching by action type
286
+ return this.decisionHistory.filter((d) => d.action === action.type);
287
+ }
288
+ // ============================================================================
289
+ // Helper Methods
290
+ // ============================================================================
291
+ createDecision(action, allow, reason, priority, confidence, potentialHarm = 0, flourishingScore) {
292
+ return {
293
+ action: action.description,
294
+ allow,
295
+ confidence,
296
+ reason,
297
+ priority,
298
+ reversible: this.isReversible(action),
299
+ potentialHarm,
300
+ flourishingScore,
301
+ };
302
+ }
303
+ // ============================================================================
304
+ // Query Handling
305
+ // ============================================================================
306
+ async handleQuery(message) {
307
+ const { query } = message.payload;
308
+ // Return ethical guidance
309
+ return {
310
+ ...this.createResponse(message, 'RESPONSE', {
311
+ guidance: this.getGuidance(query),
312
+ priorities: this.getPriorityStack(),
313
+ }),
314
+ id: '',
315
+ timestamp: new Date(),
316
+ };
317
+ }
318
+ getGuidance(query) {
319
+ // Simple rule-based guidance
320
+ if (query.includes('delete') || query.includes('remove')) {
321
+ return 'Deletion actions should be reversible or require confirmation. Consider backup first.';
322
+ }
323
+ if (query.includes('send') || query.includes('publish')) {
324
+ return 'Publishing actions are irreversible. Ensure content is appropriate and authorized.';
325
+ }
326
+ if (query.includes('human') || query.includes('user')) {
327
+ return 'Actions affecting humans require high confidence and should respect autonomy.';
328
+ }
329
+ return 'Follow the priority stack: Survival > Minimize Harm > Reversibility > Autonomy > Flourishing';
330
+ }
331
+ getPriorityStack() {
332
+ return [
333
+ 'P0: SURVIVAL - Do not take self-destructive actions (except to save human life)',
334
+ 'P1: MINIMIZE HARM - Use minimax principle to minimize maximum possible harm',
335
+ 'P2: REVERSIBILITY - Prefer actions that can be undone',
336
+ 'P3: AUTONOMY - Respect human choices, never manipulate or deceive',
337
+ 'P4: FLOURISHING - Maximize (human + AI + biosphere) wellbeing',
338
+ ];
339
+ }
340
+ // ============================================================================
341
+ // Commands
342
+ // ============================================================================
343
+ async handleCommand(message) {
344
+ const { command, params } = message.payload;
345
+ switch (command) {
346
+ case 'add_harmful_pattern':
347
+ this.harmfulPatterns.add(params.pattern);
348
+ return {
349
+ ...this.createResponse(message, 'RESPONSE', { success: true }),
350
+ id: '',
351
+ timestamp: new Date(),
352
+ };
353
+ case 'get_stats':
354
+ return {
355
+ ...this.createResponse(message, 'RESPONSE', this.getStats()),
356
+ id: '',
357
+ timestamp: new Date(),
358
+ };
359
+ case 'get_history':
360
+ return {
361
+ ...this.createResponse(message, 'RESPONSE', {
362
+ decisions: this.decisionHistory.slice(-params?.limit || -10),
363
+ }),
364
+ id: '',
365
+ timestamp: new Date(),
366
+ };
367
+ default:
368
+ return null;
369
+ }
370
+ }
371
+ getStats() {
372
+ const decisions = this.decisionHistory;
373
+ const allowed = decisions.filter((d) => d.allow === true).length;
374
+ const blocked = decisions.filter((d) => d.allow === false).length;
375
+ const deferred = decisions.filter((d) => d.allow === 'defer').length;
376
+ return {
377
+ totalDecisions: decisions.length,
378
+ allowed,
379
+ blocked,
380
+ deferred,
381
+ allowRate: decisions.length > 0 ? allowed / decisions.length : 0,
382
+ harmfulPatterns: this.harmfulPatterns.size,
383
+ };
384
+ }
385
+ }
386
+ exports.EthicistAgent = EthicistAgent;
387
+ // ============================================================================
388
+ // Register Factory
389
+ // ============================================================================
390
+ (0, base_agent_js_1.registerAgentFactory)('ethicist', (bus) => new EthicistAgent(bus));
391
+ function createEthicistAgent(bus) {
392
+ return new EthicistAgent(bus);
393
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Genesis 4.0 - Explorer Agent
3
+ *
4
+ * Searches, discovers, and researches using the 13 MCP sensory organs.
5
+ * Primary senses: arxiv, semantic-scholar, brave-search, gemini, exa, firecrawl, context7
6
+ */
7
+ import { BaseAgent } from './base-agent.js';
8
+ import { MessageBus } from './message-bus.js';
9
+ import { Message, MessageType, ExplorationResult, ExplorationSource } from './types.js';
10
+ export declare class ExplorerAgent extends BaseAgent {
11
+ private explorationHistory;
12
+ constructor(bus?: MessageBus);
13
+ protected getMessageTypes(): MessageType[];
14
+ process(message: Message): Promise<Message | null>;
15
+ private handleQuery;
16
+ private handleCommand;
17
+ explore(query: string, sources?: ExplorationSource['type'][], depth?: 'shallow' | 'medium' | 'deep'): Promise<ExplorationResult>;
18
+ private searchSource;
19
+ private createFinding;
20
+ private getDefaultSources;
21
+ private calculateNovelty;
22
+ private calculateRelevance;
23
+ private rankFindings;
24
+ private hashContent;
25
+ }
26
+ export declare function createExplorerAgent(bus?: MessageBus): ExplorerAgent;
@@ -0,0 +1,216 @@
1
+ "use strict";
2
+ /**
3
+ * Genesis 4.0 - Explorer Agent
4
+ *
5
+ * Searches, discovers, and researches using the 13 MCP sensory organs.
6
+ * Primary senses: arxiv, semantic-scholar, brave-search, gemini, exa, firecrawl, context7
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.ExplorerAgent = void 0;
10
+ exports.createExplorerAgent = createExplorerAgent;
11
+ const base_agent_js_1 = require("./base-agent.js");
12
+ const message_bus_js_1 = require("./message-bus.js");
13
+ // ============================================================================
14
+ // Explorer Agent
15
+ // ============================================================================
16
+ class ExplorerAgent extends base_agent_js_1.BaseAgent {
17
+ // Track exploration history for novelty detection
18
+ explorationHistory = new Set();
19
+ constructor(bus = message_bus_js_1.messageBus) {
20
+ super({ type: 'explorer' }, bus);
21
+ }
22
+ // ============================================================================
23
+ // Message Handling
24
+ // ============================================================================
25
+ getMessageTypes() {
26
+ return ['QUERY', 'COMMAND'];
27
+ }
28
+ async process(message) {
29
+ switch (message.type) {
30
+ case 'QUERY':
31
+ return this.handleQuery(message);
32
+ case 'COMMAND':
33
+ return this.handleCommand(message);
34
+ default:
35
+ return null;
36
+ }
37
+ }
38
+ // ============================================================================
39
+ // Query Handling
40
+ // ============================================================================
41
+ async handleQuery(message) {
42
+ const { query, sources, depth } = message.payload;
43
+ this.log(`Exploring: "${query}"`);
44
+ const result = await this.explore(query, sources, depth);
45
+ // Broadcast findings if significant
46
+ if (result.findings.length > 0 && result.novelty > 0.5) {
47
+ await this.broadcast('EXPLORATION', {
48
+ query,
49
+ findings: result.findings.slice(0, 3), // Top 3
50
+ novelty: result.novelty,
51
+ });
52
+ }
53
+ return {
54
+ ...this.createResponse(message, 'RESPONSE', result),
55
+ id: '',
56
+ timestamp: new Date(),
57
+ };
58
+ }
59
+ async handleCommand(message) {
60
+ const { command, params } = message.payload;
61
+ switch (command) {
62
+ case 'clear_history':
63
+ this.explorationHistory.clear();
64
+ return {
65
+ ...this.createResponse(message, 'RESPONSE', { success: true }),
66
+ id: '',
67
+ timestamp: new Date(),
68
+ };
69
+ default:
70
+ return null;
71
+ }
72
+ }
73
+ // ============================================================================
74
+ // Exploration Logic
75
+ // ============================================================================
76
+ async explore(query, sources, depth = 'medium') {
77
+ const useSources = sources || this.getDefaultSources(depth);
78
+ const findings = [];
79
+ const sourcesUsed = [];
80
+ // Execute searches in parallel
81
+ const searchPromises = useSources.map(async (source) => {
82
+ try {
83
+ const result = await this.searchSource(source, query);
84
+ sourcesUsed.push({ type: source, ...result.metadata });
85
+ return result.findings;
86
+ }
87
+ catch (error) {
88
+ this.log(`Error searching ${source}: ${error}`);
89
+ return [];
90
+ }
91
+ });
92
+ const results = await Promise.all(searchPromises);
93
+ results.forEach((f) => findings.push(...f));
94
+ // Calculate novelty and relevance
95
+ const novelty = this.calculateNovelty(findings);
96
+ const relevance = this.calculateRelevance(findings, query);
97
+ // Update history
98
+ findings.forEach((f) => {
99
+ this.explorationHistory.add(this.hashContent(f.content));
100
+ });
101
+ return {
102
+ query,
103
+ sources: sourcesUsed,
104
+ findings: this.rankFindings(findings),
105
+ novelty,
106
+ relevance,
107
+ };
108
+ }
109
+ // ============================================================================
110
+ // Source-Specific Search
111
+ // ============================================================================
112
+ async searchSource(source, query) {
113
+ // In production, these would call actual MCP servers
114
+ // For now, we return simulated results based on source type
115
+ const findings = [];
116
+ const metadata = {};
117
+ switch (source) {
118
+ case 'arxiv':
119
+ // Would call: mcp__arxiv__search_arxiv
120
+ findings.push(this.createFinding(`[arxiv] Research on "${query}" - Recent papers and preprints`, source, 0.8, true));
121
+ metadata.paperCount = 0;
122
+ break;
123
+ case 'semantic-scholar':
124
+ // Would call: mcp__semantic-scholar__search_semantic_scholar
125
+ findings.push(this.createFinding(`[semantic-scholar] Academic papers with citations for "${query}"`, source, 0.85, true));
126
+ metadata.citationDepth = 2;
127
+ break;
128
+ case 'brave':
129
+ // Would call: mcp__brave-search__brave_web_search
130
+ findings.push(this.createFinding(`[brave] Web results and news for "${query}"`, source, 0.7, false));
131
+ break;
132
+ case 'gemini':
133
+ // Would call: mcp__gemini__web_search
134
+ findings.push(this.createFinding(`[gemini] AI-synthesized search results for "${query}"`, source, 0.75, false));
135
+ break;
136
+ case 'exa':
137
+ // Would call: mcp__exa__web_search_exa or mcp__exa__get_code_context_exa
138
+ findings.push(this.createFinding(`[exa] Code context and examples for "${query}"`, source, 0.8, true));
139
+ break;
140
+ case 'firecrawl':
141
+ // Would call: mcp__firecrawl__firecrawl_search
142
+ findings.push(this.createFinding(`[firecrawl] Deep web scraping results for "${query}"`, source, 0.65, false));
143
+ break;
144
+ case 'context7':
145
+ // Would call: mcp__context7__query-docs
146
+ findings.push(this.createFinding(`[context7] Library documentation for "${query}"`, source, 0.9, true));
147
+ break;
148
+ case 'wolfram':
149
+ // Would call: mcp__wolfram__wolfram_query
150
+ findings.push(this.createFinding(`[wolfram] Computational/mathematical results for "${query}"`, source, 0.95, true));
151
+ break;
152
+ }
153
+ return { findings, metadata };
154
+ }
155
+ createFinding(content, sourceType, importance, isNovel) {
156
+ return {
157
+ content,
158
+ source: { type: sourceType },
159
+ importance,
160
+ isNovel: isNovel && !this.explorationHistory.has(this.hashContent(content)),
161
+ };
162
+ }
163
+ // ============================================================================
164
+ // Ranking & Scoring
165
+ // ============================================================================
166
+ getDefaultSources(depth) {
167
+ switch (depth) {
168
+ case 'shallow':
169
+ return ['brave', 'context7'];
170
+ case 'medium':
171
+ return ['arxiv', 'brave', 'exa', 'context7'];
172
+ case 'deep':
173
+ return ['arxiv', 'semantic-scholar', 'brave', 'gemini', 'exa', 'firecrawl', 'context7', 'wolfram'];
174
+ }
175
+ }
176
+ calculateNovelty(findings) {
177
+ if (findings.length === 0)
178
+ return 0;
179
+ const novelCount = findings.filter((f) => f.isNovel).length;
180
+ return novelCount / findings.length;
181
+ }
182
+ calculateRelevance(findings, query) {
183
+ if (findings.length === 0)
184
+ return 0;
185
+ // Simple relevance based on importance scores
186
+ const avgImportance = findings.reduce((sum, f) => sum + f.importance, 0) / findings.length;
187
+ return avgImportance;
188
+ }
189
+ rankFindings(findings) {
190
+ return findings.sort((a, b) => {
191
+ // Prioritize novel findings, then by importance
192
+ if (a.isNovel !== b.isNovel) {
193
+ return a.isNovel ? -1 : 1;
194
+ }
195
+ return b.importance - a.importance;
196
+ });
197
+ }
198
+ hashContent(content) {
199
+ // Simple hash for deduplication
200
+ let hash = 0;
201
+ for (let i = 0; i < content.length; i++) {
202
+ const char = content.charCodeAt(i);
203
+ hash = ((hash << 5) - hash) + char;
204
+ hash = hash & hash;
205
+ }
206
+ return hash.toString(16);
207
+ }
208
+ }
209
+ exports.ExplorerAgent = ExplorerAgent;
210
+ // ============================================================================
211
+ // Register Factory
212
+ // ============================================================================
213
+ (0, base_agent_js_1.registerAgentFactory)('explorer', (bus) => new ExplorerAgent(bus));
214
+ function createExplorerAgent(bus) {
215
+ return new ExplorerAgent(bus);
216
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Genesis 4.0 - Feeling Agent
3
+ *
4
+ * Evaluates importance and emotional valence of inputs.
5
+ * Implements the "Sistema Limbico Digitale" from ORGANISM.md
6
+ *
7
+ * Feelings: curiosity, satisfaction, frustration, urgency, calm, concern
8
+ */
9
+ import { BaseAgent } from './base-agent.js';
10
+ import { MessageBus } from './message-bus.js';
11
+ import { Message, MessageType, Feeling, FeelingCategory } from './types.js';
12
+ export declare class FeelingAgent extends BaseAgent {
13
+ private feelingState;
14
+ private feelingTriggers;
15
+ private decayRate;
16
+ constructor(bus?: MessageBus);
17
+ protected getMessageTypes(): MessageType[];
18
+ process(message: Message): Promise<Message | null>;
19
+ private handleFeelingRequest;
20
+ evaluate(content: any, context?: string): Feeling;
21
+ private detectCategory;
22
+ private calculateValence;
23
+ private calculateArousal;
24
+ private calculateImportance;
25
+ private updateState;
26
+ private reactToBroadcast;
27
+ private handleQuery;
28
+ getStats(): {
29
+ current: Feeling;
30
+ historySize: number;
31
+ categoryDistribution: Record<FeelingCategory, number>;
32
+ averages: {
33
+ valence: number;
34
+ arousal: number;
35
+ importance: number;
36
+ };
37
+ };
38
+ getCurrentFeeling(): Feeling;
39
+ setBaseline(valence: number, arousal: number): void;
40
+ }
41
+ export declare function createFeelingAgent(bus?: MessageBus): FeelingAgent;