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,470 @@
1
+ "use strict";
2
+ /**
3
+ * Genesis 6.0 - Dream Mode
4
+ *
5
+ * Offline consolidation and creative synthesis during "sleep".
6
+ *
7
+ * Based on sleep neuroscience research:
8
+ * - Light Sleep (N1/N2): Initial memory processing
9
+ * - Deep Sleep (N3/SWS): Memory consolidation (episodic → semantic)
10
+ * - REM Sleep: Creative synthesis, pattern integration
11
+ *
12
+ * References:
13
+ * - Walker, M. (2017). Why We Sleep
14
+ * - Born, J. (2010). Slow-wave sleep and memory
15
+ * - Stickgold, R. (2005). Sleep-dependent memory consolidation
16
+ *
17
+ * Usage:
18
+ * ```typescript
19
+ * import { createDreamService } from './daemon/dream-mode.js';
20
+ *
21
+ * const dream = createDreamService({
22
+ * minDreamDurationMs: 60000, // 1 minute
23
+ * maxDreamDurationMs: 600000, // 10 minutes
24
+ * });
25
+ *
26
+ * // Start a dream session
27
+ * const session = await dream.startDream();
28
+ *
29
+ * // Wait for completion
30
+ * const results = await dream.waitForWake();
31
+ * ```
32
+ */
33
+ Object.defineProperty(exports, "__esModule", { value: true });
34
+ exports.DreamService = void 0;
35
+ exports.createDreamService = createDreamService;
36
+ const crypto_1 = require("crypto");
37
+ const types_js_1 = require("./types.js");
38
+ class DreamService {
39
+ config;
40
+ context;
41
+ currentSession = null;
42
+ metrics;
43
+ eventHandlers = new Set();
44
+ wakeResolvers = [];
45
+ inactivityTimer = null;
46
+ lastActivity = new Date();
47
+ constructor(config = {}, context = {}) {
48
+ this.config = { ...types_js_1.DEFAULT_DAEMON_CONFIG.dream, ...config };
49
+ this.context = context;
50
+ this.metrics = {
51
+ totalDreamTime: 0,
52
+ dreamCycles: 0,
53
+ avgCycleDuration: 0,
54
+ consolidationRate: 0,
55
+ patternExtractionRate: 0,
56
+ lastDreamAt: null,
57
+ nextScheduledDream: null,
58
+ };
59
+ }
60
+ // ============================================================================
61
+ // Lifecycle
62
+ // ============================================================================
63
+ setContext(context) {
64
+ this.context = { ...this.context, ...context };
65
+ }
66
+ startAutoTrigger() {
67
+ if (!this.config.autoTrigger)
68
+ return;
69
+ this.resetInactivityTimer();
70
+ }
71
+ stopAutoTrigger() {
72
+ if (this.inactivityTimer) {
73
+ clearTimeout(this.inactivityTimer);
74
+ this.inactivityTimer = null;
75
+ }
76
+ }
77
+ recordActivity() {
78
+ this.lastActivity = new Date();
79
+ this.resetInactivityTimer();
80
+ }
81
+ resetInactivityTimer() {
82
+ if (this.inactivityTimer) {
83
+ clearTimeout(this.inactivityTimer);
84
+ }
85
+ if (this.config.autoTrigger && !this.isDreaming()) {
86
+ this.inactivityTimer = setTimeout(() => this.startDream(), this.config.inactivityThresholdMs);
87
+ this.metrics.nextScheduledDream = new Date(Date.now() + this.config.inactivityThresholdMs);
88
+ }
89
+ }
90
+ // ============================================================================
91
+ // Dream Session
92
+ // ============================================================================
93
+ isDreaming() {
94
+ return this.currentSession !== null && !this.currentSession.endedAt;
95
+ }
96
+ async startDream(options = {}) {
97
+ if (this.isDreaming()) {
98
+ throw new Error('Already dreaming');
99
+ }
100
+ const duration = options.duration ||
101
+ this.config.minDreamDurationMs +
102
+ Math.random() * (this.config.maxDreamDurationMs - this.config.minDreamDurationMs);
103
+ const session = {
104
+ id: (0, crypto_1.randomUUID)(),
105
+ startedAt: new Date(),
106
+ phase: 'light',
107
+ phaseHistory: [{
108
+ phase: 'light',
109
+ enteredAt: new Date(),
110
+ }],
111
+ interrupted: false,
112
+ };
113
+ this.currentSession = session;
114
+ this.emit({ type: 'dream_started', session });
115
+ this.log(`Dream started (${Math.round(duration / 1000)}s)`);
116
+ // Run the dream cycle
117
+ this.runDreamCycle(session, duration);
118
+ return session;
119
+ }
120
+ async interruptDream(reason) {
121
+ if (!this.currentSession)
122
+ return null;
123
+ this.currentSession.interrupted = true;
124
+ this.currentSession.interruptReason = reason;
125
+ this.emit({ type: 'dream_interrupted', session: this.currentSession });
126
+ this.log(`Dream interrupted: ${reason}`, 'warn');
127
+ // Return partial results
128
+ return this.currentSession.results || this.createEmptyResults();
129
+ }
130
+ waitForWake() {
131
+ if (!this.isDreaming()) {
132
+ return Promise.resolve(this.currentSession?.results || this.createEmptyResults());
133
+ }
134
+ return new Promise((resolve) => {
135
+ this.wakeResolvers.push(resolve);
136
+ });
137
+ }
138
+ getCurrentSession() {
139
+ return this.currentSession;
140
+ }
141
+ // ============================================================================
142
+ // Dream Cycle
143
+ // ============================================================================
144
+ async runDreamCycle(session, totalDuration) {
145
+ const startTime = Date.now();
146
+ const results = this.createEmptyResults();
147
+ // Calculate phase durations
148
+ const lightDuration = totalDuration * this.config.lightSleepRatio;
149
+ const deepDuration = totalDuration * this.config.deepSleepRatio;
150
+ const remDuration = totalDuration * this.config.remSleepRatio;
151
+ try {
152
+ // Light sleep phase
153
+ await this.runPhase(session, 'light', lightDuration, results);
154
+ if (session.interrupted)
155
+ return this.finishDream(session, results);
156
+ // Deep sleep phase (consolidation)
157
+ await this.runPhase(session, 'deep', deepDuration, results);
158
+ if (session.interrupted)
159
+ return this.finishDream(session, results);
160
+ // REM phase (creativity)
161
+ await this.runPhase(session, 'rem', remDuration, results);
162
+ if (session.interrupted)
163
+ return this.finishDream(session, results);
164
+ // Wake phase
165
+ await this.runPhase(session, 'wake', 1000, results);
166
+ }
167
+ catch (err) {
168
+ this.log(`Dream cycle error: ${err}`, 'error');
169
+ }
170
+ this.finishDream(session, results);
171
+ }
172
+ async runPhase(session, phase, duration, results) {
173
+ // Transition phase
174
+ this.transitionPhase(session, phase);
175
+ const phaseStart = Date.now();
176
+ const phaseEnd = phaseStart + duration;
177
+ switch (phase) {
178
+ case 'light':
179
+ await this.lightSleepPhase(results, duration);
180
+ break;
181
+ case 'deep':
182
+ await this.deepSleepPhase(results, duration);
183
+ break;
184
+ case 'rem':
185
+ await this.remSleepPhase(results, duration);
186
+ break;
187
+ case 'wake':
188
+ await this.wakePhase(results);
189
+ break;
190
+ }
191
+ // Wait remaining duration
192
+ const elapsed = Date.now() - phaseStart;
193
+ if (elapsed < duration && !session.interrupted) {
194
+ await this.sleep(duration - elapsed);
195
+ }
196
+ }
197
+ transitionPhase(session, newPhase) {
198
+ // Close previous phase
199
+ const lastPhase = session.phaseHistory[session.phaseHistory.length - 1];
200
+ if (lastPhase && !lastPhase.exitedAt) {
201
+ lastPhase.exitedAt = new Date();
202
+ }
203
+ // Start new phase
204
+ session.phase = newPhase;
205
+ session.phaseHistory.push({
206
+ phase: newPhase,
207
+ enteredAt: new Date(),
208
+ });
209
+ this.emit({ type: 'phase_changed', session, data: { phase: newPhase } });
210
+ this.log(`Dream phase: ${newPhase}`, 'debug');
211
+ }
212
+ // ============================================================================
213
+ // Phase Implementations
214
+ // ============================================================================
215
+ async lightSleepPhase(results, duration) {
216
+ // Light sleep: Initial processing, prepare for consolidation
217
+ // Energy restoration begins
218
+ if (this.context.rechargeEnergy) {
219
+ this.context.rechargeEnergy(0.05); // Small recharge
220
+ }
221
+ // Count episodes to process
222
+ if (this.context.getEpisodicMemories) {
223
+ const episodes = this.context.getEpisodicMemories();
224
+ results.episodesProcessed = episodes.filter((e) => !e.consolidated).length;
225
+ }
226
+ }
227
+ async deepSleepPhase(results, duration) {
228
+ // Deep sleep: Memory consolidation (episodic → semantic)
229
+ // This is where the heavy processing happens
230
+ if (!this.context.getEpisodicMemories || !this.context.consolidateMemory) {
231
+ return;
232
+ }
233
+ const episodes = this.context.getEpisodicMemories()
234
+ .filter((e) => !e.consolidated)
235
+ .sort((a, b) => b.importance - a.importance);
236
+ // Process episodes in batches
237
+ const batchSize = 10;
238
+ const batches = Math.ceil(episodes.length / batchSize);
239
+ const timePerBatch = duration / (batches || 1);
240
+ for (let i = 0; i < batches && !this.currentSession?.interrupted; i++) {
241
+ const batch = episodes.slice(i * batchSize, (i + 1) * batchSize);
242
+ for (const episode of batch) {
243
+ try {
244
+ const result = await this.context.consolidateMemory(episode.id);
245
+ if (result) {
246
+ results.memoriesConsolidated++;
247
+ this.emit({ type: 'consolidation_done', data: { episode, result } });
248
+ }
249
+ }
250
+ catch (err) {
251
+ this.log(`Consolidation error: ${err}`, 'error');
252
+ }
253
+ }
254
+ // Pattern extraction from related episodes
255
+ if (this.context.extractPattern && batch.length >= this.config.patternExtractionThreshold) {
256
+ const relatedGroups = this.groupByTags(batch);
257
+ for (const [tag, group] of relatedGroups) {
258
+ if (group.length >= this.config.patternExtractionThreshold) {
259
+ try {
260
+ const pattern = await this.context.extractPattern(group.map((e) => e.id));
261
+ if (pattern && pattern.confidence > 0.5) {
262
+ results.patternsExtracted++;
263
+ this.emit({ type: 'pattern_extracted', data: pattern });
264
+ }
265
+ }
266
+ catch (err) {
267
+ this.log(`Pattern extraction error: ${err}`, 'error');
268
+ }
269
+ }
270
+ }
271
+ }
272
+ await this.sleep(timePerBatch);
273
+ }
274
+ // Energy restoration during deep sleep
275
+ if (this.context.rechargeEnergy) {
276
+ this.context.rechargeEnergy(0.2); // Significant recharge
277
+ }
278
+ // Skill reinforcement
279
+ if (this.context.getProceduralMemories && this.context.reinforceSkill) {
280
+ const skills = this.context.getProceduralMemories()
281
+ .filter((s) => s.successRate > 0.5)
282
+ .sort((a, b) => a.successRate - b.successRate)
283
+ .slice(0, 5);
284
+ for (const skill of skills) {
285
+ if (await this.context.reinforceSkill(skill.id)) {
286
+ results.skillsReinforced++;
287
+ }
288
+ }
289
+ }
290
+ }
291
+ async remSleepPhase(results, duration) {
292
+ // REM sleep: Creative synthesis, novel associations
293
+ // This is where new ideas emerge from combining memories
294
+ if (!this.context.getSemanticMemories) {
295
+ return;
296
+ }
297
+ const concepts = this.context.getSemanticMemories();
298
+ // Generate novel associations (simplified creative process)
299
+ const associations = this.generateNovelAssociations(concepts.map((c) => c.concept), this.config.creativityTemperature);
300
+ results.newAssociations = associations.length;
301
+ results.novelIdeas = associations.slice(0, 5); // Keep top 5
302
+ // Energy boost from REM
303
+ if (this.context.rechargeEnergy) {
304
+ this.context.rechargeEnergy(0.1);
305
+ }
306
+ // Memory forgetting (weak memories fade during sleep)
307
+ if (this.context.getEpisodicMemories && this.context.forgetMemory) {
308
+ const episodes = this.context.getEpisodicMemories();
309
+ const toForget = episodes
310
+ .filter((e) => e.importance < 0.2)
311
+ .slice(0, Math.floor(episodes.length * 0.1)); // Forget up to 10%
312
+ for (const episode of toForget) {
313
+ if (this.context.forgetMemory(episode.id)) {
314
+ results.memoriesForgotten++;
315
+ }
316
+ }
317
+ }
318
+ }
319
+ async wakePhase(results) {
320
+ // Wake: Health check and invariant verification
321
+ if (this.context.checkInvariants) {
322
+ const allSatisfied = await this.context.checkInvariants();
323
+ results.invariantsChecked++;
324
+ if (!allSatisfied && this.context.repairState) {
325
+ results.stateRepairs = await this.context.repairState();
326
+ }
327
+ }
328
+ // Final energy boost
329
+ if (this.context.rechargeEnergy) {
330
+ this.context.rechargeEnergy(0.05);
331
+ }
332
+ }
333
+ // ============================================================================
334
+ // Helper Methods
335
+ // ============================================================================
336
+ groupByTags(episodes) {
337
+ const groups = new Map();
338
+ for (const episode of episodes) {
339
+ for (const tag of episode.tags) {
340
+ const group = groups.get(tag) || [];
341
+ group.push(episode);
342
+ groups.set(tag, group);
343
+ }
344
+ }
345
+ return groups;
346
+ }
347
+ generateNovelAssociations(concepts, temperature) {
348
+ // Simplified creative association generator
349
+ // In a real implementation, this would use embeddings and semantic similarity
350
+ const associations = [];
351
+ const numAssociations = Math.floor(concepts.length * temperature);
352
+ for (let i = 0; i < numAssociations && i < concepts.length - 1; i++) {
353
+ const idx1 = Math.floor(Math.random() * concepts.length);
354
+ let idx2 = Math.floor(Math.random() * concepts.length);
355
+ while (idx2 === idx1) {
356
+ idx2 = Math.floor(Math.random() * concepts.length);
357
+ }
358
+ const concept1 = concepts[idx1];
359
+ const concept2 = concepts[idx2];
360
+ // Generate a hypothetical association
361
+ associations.push(`${concept1} relates to ${concept2}`);
362
+ }
363
+ return associations;
364
+ }
365
+ createEmptyResults() {
366
+ return {
367
+ episodesProcessed: 0,
368
+ memoriesConsolidated: 0,
369
+ patternsExtracted: 0,
370
+ skillsReinforced: 0,
371
+ memoriesForgotten: 0,
372
+ newAssociations: 0,
373
+ novelIdeas: [],
374
+ stateRepairs: 0,
375
+ invariantsChecked: 0,
376
+ };
377
+ }
378
+ finishDream(session, results) {
379
+ session.endedAt = new Date();
380
+ session.results = results;
381
+ // Close last phase
382
+ const lastPhase = session.phaseHistory[session.phaseHistory.length - 1];
383
+ if (lastPhase && !lastPhase.exitedAt) {
384
+ lastPhase.exitedAt = session.endedAt;
385
+ }
386
+ // Update metrics
387
+ const duration = session.endedAt.getTime() - session.startedAt.getTime();
388
+ this.metrics.totalDreamTime += duration;
389
+ this.metrics.dreamCycles++;
390
+ this.metrics.avgCycleDuration =
391
+ (this.metrics.avgCycleDuration * (this.metrics.dreamCycles - 1) + duration) /
392
+ this.metrics.dreamCycles;
393
+ this.metrics.lastDreamAt = session.endedAt;
394
+ // Calculate rates
395
+ const durationHours = duration / (1000 * 60 * 60);
396
+ if (durationHours > 0) {
397
+ this.metrics.consolidationRate = results.memoriesConsolidated / durationHours;
398
+ }
399
+ this.metrics.patternExtractionRate = results.patternsExtracted / Math.max(1, this.metrics.dreamCycles);
400
+ this.log(`Dream completed: ${results.memoriesConsolidated} consolidated, ` +
401
+ `${results.patternsExtracted} patterns, ${results.skillsReinforced} skills`);
402
+ this.emit({ type: 'dream_completed', session });
403
+ // Notify waiters
404
+ for (const resolve of this.wakeResolvers) {
405
+ resolve(results);
406
+ }
407
+ this.wakeResolvers = [];
408
+ // Reset inactivity timer for next dream
409
+ this.resetInactivityTimer();
410
+ }
411
+ sleep(ms) {
412
+ return new Promise((resolve) => setTimeout(resolve, ms));
413
+ }
414
+ // ============================================================================
415
+ // Stats
416
+ // ============================================================================
417
+ getMetrics() {
418
+ return { ...this.metrics };
419
+ }
420
+ // ============================================================================
421
+ // Events
422
+ // ============================================================================
423
+ on(handler) {
424
+ this.eventHandlers.add(handler);
425
+ return () => this.eventHandlers.delete(handler);
426
+ }
427
+ emit(event) {
428
+ for (const handler of this.eventHandlers) {
429
+ try {
430
+ handler(event);
431
+ }
432
+ catch (err) {
433
+ console.error('Dream event handler error:', err);
434
+ }
435
+ }
436
+ }
437
+ // ============================================================================
438
+ // Logging
439
+ // ============================================================================
440
+ log(message, level = 'info') {
441
+ if (this.context.log) {
442
+ this.context.log(message, level);
443
+ }
444
+ else {
445
+ const prefix = '[Dream]';
446
+ switch (level) {
447
+ case 'debug':
448
+ if (process.env.LOG_LEVEL === 'debug')
449
+ console.log(`${prefix} ${message}`);
450
+ break;
451
+ case 'info':
452
+ console.log(`${prefix} ${message}`);
453
+ break;
454
+ case 'warn':
455
+ console.warn(`${prefix} ${message}`);
456
+ break;
457
+ case 'error':
458
+ console.error(`${prefix} ${message}`);
459
+ break;
460
+ }
461
+ }
462
+ }
463
+ }
464
+ exports.DreamService = DreamService;
465
+ // ============================================================================
466
+ // Factory
467
+ // ============================================================================
468
+ function createDreamService(config, context) {
469
+ return new DreamService(config, context);
470
+ }
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Genesis 6.0 - Daemon Module
3
+ *
4
+ * Unified daemon for background task scheduling, self-maintenance, and dream mode.
5
+ *
6
+ * This module provides:
7
+ * - Scheduler: Background task execution with priorities and retries
8
+ * - Maintenance: Self-repair and health monitoring
9
+ * - Dream Mode: Offline memory consolidation and creative synthesis
10
+ *
11
+ * Usage:
12
+ * ```typescript
13
+ * import { createDaemon } from './daemon/index.js';
14
+ * import { createMemorySystem } from './memory/index.js';
15
+ *
16
+ * const memory = createMemorySystem();
17
+ * const daemon = createDaemon({ memory });
18
+ *
19
+ * // Start the daemon
20
+ * daemon.start();
21
+ *
22
+ * // Schedule a custom task
23
+ * daemon.schedule({
24
+ * name: 'my-task',
25
+ * schedule: { type: 'interval', intervalMs: 60000 },
26
+ * handler: async (ctx) => {
27
+ * ctx.logger.info('Running my task');
28
+ * return { success: true, duration: 100 };
29
+ * },
30
+ * });
31
+ *
32
+ * // Trigger a dream session
33
+ * await daemon.dream();
34
+ *
35
+ * // Check status
36
+ * console.log(daemon.status());
37
+ *
38
+ * // Stop the daemon
39
+ * daemon.stop();
40
+ * ```
41
+ */
42
+ export * from './types.js';
43
+ export { Scheduler, createScheduler, type SchedulerConfig } from './scheduler.js';
44
+ export { MaintenanceService, createMaintenanceService, type MaintenanceContext } from './maintenance.js';
45
+ export { DreamService, createDreamService, type DreamContext } from './dream-mode.js';
46
+ import { DaemonConfig, DaemonState, DaemonStatus, DaemonEventHandler, ScheduledTask, CreateTaskOptions, MaintenanceReport, DreamResults } from './types.js';
47
+ import { Scheduler } from './scheduler.js';
48
+ import { MaintenanceService } from './maintenance.js';
49
+ import { DreamService } from './dream-mode.js';
50
+ export interface DaemonDependencies {
51
+ memory?: {
52
+ episodic: {
53
+ getAll: () => Array<{
54
+ id: string;
55
+ content: {
56
+ what: string;
57
+ };
58
+ importance: number;
59
+ tags: string[];
60
+ consolidated: boolean;
61
+ }>;
62
+ runForgetting: () => {
63
+ forgotten: number;
64
+ };
65
+ };
66
+ semantic: {
67
+ getAll: () => Array<{
68
+ id: string;
69
+ concept: string;
70
+ confidence: number;
71
+ }>;
72
+ };
73
+ procedural: {
74
+ getAll: () => Array<{
75
+ id: string;
76
+ name: string;
77
+ successRate: number;
78
+ }>;
79
+ };
80
+ consolidation: {
81
+ sleep: () => Promise<{
82
+ consolidated: number;
83
+ }>;
84
+ };
85
+ getStats: () => {
86
+ total: number;
87
+ episodic: {
88
+ total: number;
89
+ };
90
+ semantic: {
91
+ total: number;
92
+ };
93
+ procedural: {
94
+ total: number;
95
+ };
96
+ };
97
+ };
98
+ kernel?: {
99
+ checkAgentHealth: () => Promise<Array<{
100
+ id: string;
101
+ healthy: boolean;
102
+ latency?: number;
103
+ }>>;
104
+ checkInvariants: () => Promise<Array<{
105
+ id: string;
106
+ satisfied: boolean;
107
+ message?: string;
108
+ }>>;
109
+ repairInvariant: (id: string) => Promise<boolean>;
110
+ getState: () => {
111
+ state: string;
112
+ energy: number;
113
+ };
114
+ rechargeEnergy: (amount: number) => void;
115
+ resetState: () => void;
116
+ };
117
+ log?: (message: string, level?: 'debug' | 'info' | 'warn' | 'error') => void;
118
+ }
119
+ export declare class Daemon {
120
+ private config;
121
+ private state;
122
+ private startedAt;
123
+ private errors;
124
+ private eventHandlers;
125
+ private heartbeatTimer;
126
+ readonly scheduler: Scheduler;
127
+ readonly maintenance: MaintenanceService;
128
+ readonly dreamService: DreamService;
129
+ private deps;
130
+ constructor(deps?: DaemonDependencies, config?: Partial<DaemonConfig>);
131
+ start(): void;
132
+ stop(): void;
133
+ restart(): void;
134
+ getState(): DaemonState;
135
+ isRunning(): boolean;
136
+ schedule(options: CreateTaskOptions): ScheduledTask;
137
+ cancelTask(taskId: string): boolean;
138
+ triggerTask(taskId: string): boolean;
139
+ getTasks(): ScheduledTask[];
140
+ runMaintenance(): Promise<MaintenanceReport>;
141
+ getMaintenanceIssues(): import("./types.js").MaintenanceIssue[];
142
+ dream(options?: {
143
+ duration?: number;
144
+ }): Promise<DreamResults>;
145
+ interruptDream(reason: string): Promise<DreamResults | null>;
146
+ isDreaming(): boolean;
147
+ getDreamMetrics(): import("./types.js").DreamMetrics;
148
+ recordActivity(): void;
149
+ status(): DaemonStatus;
150
+ on(handler: DaemonEventHandler): () => void;
151
+ private emit;
152
+ private heartbeat;
153
+ private setupEventForwarding;
154
+ private setupDefaultTasks;
155
+ private buildMaintenanceContext;
156
+ private buildDreamContext;
157
+ private log;
158
+ private recordError;
159
+ }
160
+ export declare function createDaemon(deps?: DaemonDependencies, config?: Partial<DaemonConfig>): Daemon;
161
+ export declare function getDaemon(deps?: DaemonDependencies, config?: Partial<DaemonConfig>): Daemon;
162
+ export declare function resetDaemon(): void;