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,549 @@
1
+ "use strict";
2
+ /**
3
+ * Genesis 6.0 - Maintenance Service
4
+ *
5
+ * Self-repair and health maintenance for the Genesis system.
6
+ *
7
+ * Features:
8
+ * - Health monitoring (agent responsiveness)
9
+ * - Memory cleanup (weak memories, cache)
10
+ * - State repair (invariant violations)
11
+ * - Resource management
12
+ * - Automatic recovery
13
+ *
14
+ * Based on:
15
+ * - Kubernetes liveness/readiness probes
16
+ * - Self-healing systems patterns
17
+ * - Autonomic computing (IBM, 2001)
18
+ *
19
+ * Usage:
20
+ * ```typescript
21
+ * import { createMaintenanceService } from './daemon/maintenance.js';
22
+ *
23
+ * const maintenance = createMaintenanceService({
24
+ * autoRepair: true,
25
+ * intervalMs: 300000, // 5 minutes
26
+ * });
27
+ *
28
+ * // Run maintenance cycle
29
+ * const report = await maintenance.runCycle();
30
+ *
31
+ * // Check specific component
32
+ * const issues = await maintenance.checkHealth();
33
+ * ```
34
+ */
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.MaintenanceService = void 0;
37
+ exports.createMaintenanceService = createMaintenanceService;
38
+ const crypto_1 = require("crypto");
39
+ const types_js_1 = require("./types.js");
40
+ class MaintenanceService {
41
+ config;
42
+ context;
43
+ tasks = new Map();
44
+ issues = [];
45
+ cycleTimer = null;
46
+ running = false;
47
+ eventHandlers = new Set();
48
+ // Stats
49
+ cyclesRun = 0;
50
+ issuesDetected = 0;
51
+ issuesResolved = 0;
52
+ lastCycleAt = null;
53
+ constructor(config = {}, context = {}) {
54
+ this.config = { ...types_js_1.DEFAULT_DAEMON_CONFIG.maintenance, ...config };
55
+ this.context = context;
56
+ }
57
+ // ============================================================================
58
+ // Lifecycle
59
+ // ============================================================================
60
+ start() {
61
+ if (this.running)
62
+ return;
63
+ this.running = true;
64
+ if (this.config.enabled) {
65
+ this.cycleTimer = setInterval(() => this.runCycle(), this.config.intervalMs);
66
+ // Run initial cycle
67
+ this.runCycle();
68
+ }
69
+ }
70
+ stop() {
71
+ if (!this.running)
72
+ return;
73
+ this.running = false;
74
+ if (this.cycleTimer) {
75
+ clearInterval(this.cycleTimer);
76
+ this.cycleTimer = null;
77
+ }
78
+ }
79
+ isRunning() {
80
+ return this.running;
81
+ }
82
+ setContext(context) {
83
+ this.context = { ...this.context, ...context };
84
+ }
85
+ // ============================================================================
86
+ // Main Cycle
87
+ // ============================================================================
88
+ async runCycle() {
89
+ const startTime = Date.now();
90
+ this.emit({ type: 'cycle_started' });
91
+ this.log('Starting maintenance cycle');
92
+ const report = {
93
+ timestamp: new Date(),
94
+ duration: 0,
95
+ tasksRun: 0,
96
+ tasksSucceeded: 0,
97
+ tasksFailed: 0,
98
+ issues: [],
99
+ actions: [],
100
+ };
101
+ try {
102
+ // 1. Health checks
103
+ const healthIssues = await this.checkHealth();
104
+ report.issues.push(...healthIssues);
105
+ // 2. Memory cleanup (if configured)
106
+ const memoryIssues = await this.checkMemory();
107
+ report.issues.push(...memoryIssues);
108
+ // 3. Invariant checks
109
+ const invariantIssues = await this.checkInvariants();
110
+ report.issues.push(...invariantIssues);
111
+ // 4. Resource checks
112
+ const resourceIssues = await this.checkResources();
113
+ report.issues.push(...resourceIssues);
114
+ // Track detected issues
115
+ this.issuesDetected += report.issues.length;
116
+ // 5. Auto-repair if enabled
117
+ if (this.config.autoRepair && report.issues.length > 0) {
118
+ const actions = await this.autoRepair(report.issues);
119
+ report.actions.push(...actions);
120
+ report.tasksRun = actions.length;
121
+ report.tasksSucceeded = actions.filter((a) => a.success).length;
122
+ report.tasksFailed = actions.filter((a) => !a.success).length;
123
+ // Update resolved count
124
+ this.issuesResolved += report.issues.filter((i) => i.resolved).length;
125
+ }
126
+ }
127
+ catch (err) {
128
+ this.log(`Maintenance cycle error: ${err}`, 'error');
129
+ }
130
+ report.duration = Date.now() - startTime;
131
+ this.cyclesRun++;
132
+ this.lastCycleAt = new Date();
133
+ this.emit({ type: 'cycle_completed', data: report });
134
+ this.log(`Maintenance cycle completed: ${report.issues.length} issues, ${report.tasksRun} actions`);
135
+ return report;
136
+ }
137
+ // ============================================================================
138
+ // Health Checks
139
+ // ============================================================================
140
+ async checkHealth() {
141
+ const issues = [];
142
+ if (!this.context.checkAgentHealth) {
143
+ return issues; // No health checker available
144
+ }
145
+ try {
146
+ const results = await this.context.checkAgentHealth();
147
+ for (const result of results) {
148
+ if (!result.healthy) {
149
+ const issue = {
150
+ type: 'agent_unhealthy',
151
+ severity: 'warning',
152
+ description: `Agent ${result.id} is not responding`,
153
+ detected: new Date(),
154
+ resolved: false,
155
+ };
156
+ issues.push(issue);
157
+ this.issues.push(issue);
158
+ this.emit({ type: 'issue_detected', data: issue });
159
+ }
160
+ // Check latency
161
+ if (result.latency && result.latency > this.config.unhealthyAgentThreshold * 1000) {
162
+ const issue = {
163
+ type: 'agent_slow',
164
+ severity: 'info',
165
+ description: `Agent ${result.id} response time: ${result.latency}ms`,
166
+ detected: new Date(),
167
+ resolved: false,
168
+ };
169
+ issues.push(issue);
170
+ this.issues.push(issue);
171
+ }
172
+ }
173
+ }
174
+ catch (err) {
175
+ this.log(`Health check failed: ${err}`, 'error');
176
+ }
177
+ return issues;
178
+ }
179
+ // ============================================================================
180
+ // Memory Checks
181
+ // ============================================================================
182
+ async checkMemory() {
183
+ const issues = [];
184
+ if (!this.context.getMemoryStats) {
185
+ return issues;
186
+ }
187
+ try {
188
+ const stats = this.context.getMemoryStats();
189
+ // Check retention threshold
190
+ if (stats.avgRetention < this.config.memoryRetentionThreshold) {
191
+ const issue = {
192
+ type: 'memory_weak',
193
+ severity: 'info',
194
+ description: `Average memory retention (${(stats.avgRetention * 100).toFixed(1)}%) below threshold`,
195
+ detected: new Date(),
196
+ resolved: false,
197
+ };
198
+ issues.push(issue);
199
+ this.issues.push(issue);
200
+ }
201
+ // Check total count (might indicate memory leak)
202
+ if (stats.total > 10000) {
203
+ const issue = {
204
+ type: 'memory_overflow',
205
+ severity: 'warning',
206
+ description: `Memory count (${stats.total}) exceeds recommended limit`,
207
+ detected: new Date(),
208
+ resolved: false,
209
+ };
210
+ issues.push(issue);
211
+ this.issues.push(issue);
212
+ }
213
+ }
214
+ catch (err) {
215
+ this.log(`Memory check failed: ${err}`, 'error');
216
+ }
217
+ return issues;
218
+ }
219
+ // ============================================================================
220
+ // Invariant Checks
221
+ // ============================================================================
222
+ async checkInvariants() {
223
+ const issues = [];
224
+ if (!this.context.checkInvariants) {
225
+ return issues;
226
+ }
227
+ try {
228
+ const results = await this.context.checkInvariants();
229
+ for (const result of results) {
230
+ if (!result.satisfied) {
231
+ const issue = {
232
+ type: 'invariant_violation',
233
+ severity: 'critical',
234
+ description: `Invariant ${result.id} violated: ${result.message || 'unknown reason'}`,
235
+ detected: new Date(),
236
+ resolved: false,
237
+ };
238
+ issues.push(issue);
239
+ this.issues.push(issue);
240
+ this.emit({ type: 'issue_detected', data: issue });
241
+ }
242
+ }
243
+ }
244
+ catch (err) {
245
+ this.log(`Invariant check failed: ${err}`, 'error');
246
+ }
247
+ return issues;
248
+ }
249
+ // ============================================================================
250
+ // Resource Checks
251
+ // ============================================================================
252
+ async checkResources() {
253
+ const issues = [];
254
+ try {
255
+ // Check memory usage (Node.js)
256
+ const memUsage = process.memoryUsage();
257
+ const heapUsed = memUsage.heapUsed / memUsage.heapTotal;
258
+ if (heapUsed > this.config.resourceUsageThreshold) {
259
+ const issue = {
260
+ type: 'resource_memory_high',
261
+ severity: 'warning',
262
+ description: `Heap usage (${(heapUsed * 100).toFixed(1)}%) exceeds threshold`,
263
+ detected: new Date(),
264
+ resolved: false,
265
+ };
266
+ issues.push(issue);
267
+ this.issues.push(issue);
268
+ }
269
+ // Check energy level
270
+ if (this.context.getState) {
271
+ const state = this.context.getState();
272
+ if (state.energy < 0.1) {
273
+ const issue = {
274
+ type: 'energy_low',
275
+ severity: 'critical',
276
+ description: `Energy level (${(state.energy * 100).toFixed(1)}%) critically low`,
277
+ detected: new Date(),
278
+ resolved: false,
279
+ };
280
+ issues.push(issue);
281
+ this.issues.push(issue);
282
+ }
283
+ }
284
+ }
285
+ catch (err) {
286
+ this.log(`Resource check failed: ${err}`, 'error');
287
+ }
288
+ return issues;
289
+ }
290
+ // ============================================================================
291
+ // Auto-Repair
292
+ // ============================================================================
293
+ async autoRepair(issues) {
294
+ const actions = [];
295
+ const concurrentTasks = [];
296
+ // Group by severity and type
297
+ const byType = new Map();
298
+ for (const issue of issues) {
299
+ const existing = byType.get(issue.type) || [];
300
+ existing.push(issue);
301
+ byType.set(issue.type, existing);
302
+ }
303
+ // Create repair tasks
304
+ for (const [type, typeIssues] of byType) {
305
+ const action = this.getRepairAction(type);
306
+ if (!action)
307
+ continue;
308
+ // Limit concurrent repairs
309
+ if (concurrentTasks.length >= this.config.maxConcurrentTasks) {
310
+ await Promise.race(concurrentTasks);
311
+ }
312
+ const task = this.createTask(action, typeIssues[0].description);
313
+ actions.push(task);
314
+ const promise = this.executeRepair(task, typeIssues);
315
+ concurrentTasks.push(promise);
316
+ }
317
+ await Promise.all(concurrentTasks);
318
+ return actions;
319
+ }
320
+ getRepairAction(issueType) {
321
+ switch (issueType) {
322
+ case 'agent_unhealthy':
323
+ case 'agent_slow':
324
+ return 'agent_restart';
325
+ case 'memory_weak':
326
+ case 'memory_overflow':
327
+ return 'memory_cleanup';
328
+ case 'invariant_violation':
329
+ return 'invariant_repair';
330
+ case 'resource_memory_high':
331
+ return 'cache_clear';
332
+ case 'energy_low':
333
+ return 'state_reset'; // Enter dormancy
334
+ default:
335
+ return null;
336
+ }
337
+ }
338
+ createTask(action, reason) {
339
+ return {
340
+ id: (0, crypto_1.randomUUID)(),
341
+ action,
342
+ priority: this.getActionPriority(action),
343
+ state: 'pending',
344
+ reason,
345
+ };
346
+ }
347
+ getActionPriority(action) {
348
+ switch (action) {
349
+ case 'invariant_repair':
350
+ case 'state_reset':
351
+ return 'critical';
352
+ case 'agent_restart':
353
+ return 'high';
354
+ case 'memory_cleanup':
355
+ case 'health_check':
356
+ return 'normal';
357
+ case 'cache_clear':
358
+ case 'log_rotation':
359
+ case 'resource_reclaim':
360
+ return 'low';
361
+ default:
362
+ return 'normal';
363
+ }
364
+ }
365
+ async executeRepair(task, issues) {
366
+ task.state = 'running';
367
+ task.startedAt = new Date();
368
+ this.tasks.set(task.id, task);
369
+ this.emit({ type: 'action_started', data: task });
370
+ try {
371
+ switch (task.action) {
372
+ case 'agent_restart':
373
+ // Agent restart is handled by kernel
374
+ this.log(`Would restart agents for: ${task.reason}`);
375
+ task.success = true;
376
+ break;
377
+ case 'memory_cleanup':
378
+ if (this.context.runMemoryForgetting) {
379
+ const result = this.context.runMemoryForgetting();
380
+ task.details = `Forgot ${result.forgotten} memories`;
381
+ task.success = true;
382
+ }
383
+ break;
384
+ case 'invariant_repair':
385
+ if (this.context.repairInvariant) {
386
+ // Extract invariant ID from issue
387
+ const match = issues[0]?.description.match(/Invariant (\S+)/);
388
+ if (match) {
389
+ const repaired = await this.context.repairInvariant(match[1]);
390
+ task.success = repaired;
391
+ task.details = repaired ? 'Invariant repaired' : 'Repair failed';
392
+ }
393
+ }
394
+ break;
395
+ case 'cache_clear':
396
+ // Force garbage collection if available
397
+ if (global.gc) {
398
+ global.gc();
399
+ task.details = 'Forced garbage collection';
400
+ }
401
+ task.success = true;
402
+ break;
403
+ case 'state_reset':
404
+ if (this.context.resetState) {
405
+ this.context.resetState();
406
+ task.details = 'State reset to safe mode';
407
+ task.success = true;
408
+ }
409
+ break;
410
+ case 'health_check':
411
+ await this.checkHealth();
412
+ task.success = true;
413
+ break;
414
+ default:
415
+ task.details = `Unknown action: ${task.action}`;
416
+ task.success = false;
417
+ }
418
+ // Mark issues as resolved if repair succeeded
419
+ if (task.success) {
420
+ for (const issue of issues) {
421
+ issue.resolved = true;
422
+ issue.resolution = task.details;
423
+ this.emit({ type: 'issue_resolved', data: issue });
424
+ }
425
+ }
426
+ task.state = task.success ? 'completed' : 'failed';
427
+ this.emit({ type: 'action_completed', data: task });
428
+ }
429
+ catch (err) {
430
+ task.state = 'failed';
431
+ task.details = `Error: ${err}`;
432
+ task.success = false;
433
+ this.emit({ type: 'action_failed', data: { task, error: err } });
434
+ }
435
+ task.completedAt = new Date();
436
+ }
437
+ // ============================================================================
438
+ // Manual Actions
439
+ // ============================================================================
440
+ async runAction(action, target) {
441
+ const task = this.createTask(action, target || 'Manual trigger');
442
+ task.target = target;
443
+ await this.executeRepair(task, []);
444
+ return task;
445
+ }
446
+ async cleanupMemory() {
447
+ let forgotten = 0;
448
+ let consolidated = 0;
449
+ if (this.context.runMemoryForgetting) {
450
+ const result = this.context.runMemoryForgetting();
451
+ forgotten = result.forgotten;
452
+ }
453
+ if (this.context.runMemoryConsolidation) {
454
+ const result = await this.context.runMemoryConsolidation();
455
+ consolidated = result.consolidated;
456
+ }
457
+ return { forgotten, consolidated };
458
+ }
459
+ // ============================================================================
460
+ // Query
461
+ // ============================================================================
462
+ getIssues(options = {}) {
463
+ let result = [...this.issues];
464
+ if (options.severity) {
465
+ result = result.filter((i) => i.severity === options.severity);
466
+ }
467
+ if (options.resolved !== undefined) {
468
+ result = result.filter((i) => i.resolved === options.resolved);
469
+ }
470
+ // Sort by date (newest first)
471
+ result.sort((a, b) => b.detected.getTime() - a.detected.getTime());
472
+ if (options.limit) {
473
+ result = result.slice(0, options.limit);
474
+ }
475
+ return result;
476
+ }
477
+ getOpenIssues() {
478
+ return this.getIssues({ resolved: false });
479
+ }
480
+ getTasks() {
481
+ return Array.from(this.tasks.values());
482
+ }
483
+ // ============================================================================
484
+ // Stats
485
+ // ============================================================================
486
+ stats() {
487
+ const tasks = this.getTasks();
488
+ return {
489
+ cyclesRun: this.cyclesRun,
490
+ issuesDetected: this.issuesDetected,
491
+ issuesResolved: this.issuesResolved,
492
+ openIssues: this.getOpenIssues().length,
493
+ lastCycleAt: this.lastCycleAt,
494
+ tasksTotal: tasks.length,
495
+ tasksSucceeded: tasks.filter((t) => t.success).length,
496
+ tasksFailed: tasks.filter((t) => t.success === false).length,
497
+ };
498
+ }
499
+ // ============================================================================
500
+ // Events
501
+ // ============================================================================
502
+ on(handler) {
503
+ this.eventHandlers.add(handler);
504
+ return () => this.eventHandlers.delete(handler);
505
+ }
506
+ emit(event) {
507
+ for (const handler of this.eventHandlers) {
508
+ try {
509
+ handler(event);
510
+ }
511
+ catch (err) {
512
+ console.error('Maintenance event handler error:', err);
513
+ }
514
+ }
515
+ }
516
+ // ============================================================================
517
+ // Logging
518
+ // ============================================================================
519
+ log(message, level = 'info') {
520
+ if (this.context.log) {
521
+ this.context.log(message, level);
522
+ }
523
+ else {
524
+ const prefix = '[Maintenance]';
525
+ switch (level) {
526
+ case 'debug':
527
+ if (process.env.LOG_LEVEL === 'debug')
528
+ console.log(`${prefix} ${message}`);
529
+ break;
530
+ case 'info':
531
+ console.log(`${prefix} ${message}`);
532
+ break;
533
+ case 'warn':
534
+ console.warn(`${prefix} ${message}`);
535
+ break;
536
+ case 'error':
537
+ console.error(`${prefix} ${message}`);
538
+ break;
539
+ }
540
+ }
541
+ }
542
+ }
543
+ exports.MaintenanceService = MaintenanceService;
544
+ // ============================================================================
545
+ // Factory
546
+ // ============================================================================
547
+ function createMaintenanceService(config, context) {
548
+ return new MaintenanceService(config, context);
549
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Genesis 6.0 - Daemon Process Manager
3
+ *
4
+ * Handles background process spawning, PID management, and IPC.
5
+ *
6
+ * Architecture:
7
+ * - Parent process spawns detached child
8
+ * - Child creates Unix socket for IPC
9
+ * - CLI commands communicate via socket
10
+ */
11
+ declare const DATA_DIR: string;
12
+ declare const PID_FILE: string;
13
+ declare const SOCKET_PATH: string;
14
+ declare const LOG_FILE: string;
15
+ export interface IPCRequest {
16
+ id: string;
17
+ method: 'status' | 'stop' | 'dream' | 'maintenance' | 'tasks' | 'ping';
18
+ params?: Record<string, any>;
19
+ }
20
+ export interface IPCResponse {
21
+ id: string;
22
+ success: boolean;
23
+ data?: any;
24
+ error?: string;
25
+ }
26
+ export interface DaemonProcessInfo {
27
+ running: boolean;
28
+ pid: number | null;
29
+ uptime: number | null;
30
+ socketPath: string;
31
+ }
32
+ export declare class DaemonProcessManager {
33
+ private daemon;
34
+ private server;
35
+ private logStream;
36
+ constructor();
37
+ private ensureDataDir;
38
+ private writePid;
39
+ private readPid;
40
+ private removePid;
41
+ private isProcessRunning;
42
+ private cleanupSocket;
43
+ private initLogging;
44
+ private closeLogging;
45
+ private startIPCServer;
46
+ private handleIPCRequest;
47
+ private sendResponse;
48
+ private stopIPCServer;
49
+ /**
50
+ * Start daemon in current process (for background mode)
51
+ */
52
+ startDaemon(): void;
53
+ /**
54
+ * Stop daemon
55
+ */
56
+ stopDaemon(): void;
57
+ /**
58
+ * Check if daemon is running
59
+ */
60
+ getInfo(): DaemonProcessInfo;
61
+ /**
62
+ * Spawn daemon as background process
63
+ */
64
+ spawn(): Promise<{
65
+ success: boolean;
66
+ pid?: number;
67
+ error?: string;
68
+ }>;
69
+ /**
70
+ * Stop running daemon via IPC
71
+ */
72
+ kill(): Promise<{
73
+ success: boolean;
74
+ error?: string;
75
+ }>;
76
+ /**
77
+ * Send IPC command to daemon
78
+ */
79
+ ipcCall(method: IPCRequest['method'], params?: Record<string, any>): Promise<IPCResponse>;
80
+ }
81
+ export declare function getProcessManager(): DaemonProcessManager;
82
+ export { DATA_DIR, PID_FILE, SOCKET_PATH, LOG_FILE };