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,572 @@
1
+ "use strict";
2
+ /**
3
+ * Genesis Auto-Fix Engine (Darwin-Gödel Pattern)
4
+ *
5
+ * Automatically fixes detected errors using:
6
+ * 1. Mutate: Generate N fix candidates via LLM
7
+ * 2. Test: Run test suite on each
8
+ * 3. Select: Keep the one that passes most tests
9
+ * 4. Iterate: If none pass, analyze failures and retry
10
+ */
11
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
12
+ if (k2 === undefined) k2 = k;
13
+ var desc = Object.getOwnPropertyDescriptor(m, k);
14
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
15
+ desc = { enumerable: true, get: function() { return m[k]; } };
16
+ }
17
+ Object.defineProperty(o, k2, desc);
18
+ }) : (function(o, m, k, k2) {
19
+ if (k2 === undefined) k2 = k;
20
+ o[k2] = m[k];
21
+ }));
22
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
23
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
24
+ }) : function(o, v) {
25
+ o["default"] = v;
26
+ });
27
+ var __importStar = (this && this.__importStar) || (function () {
28
+ var ownKeys = function(o) {
29
+ ownKeys = Object.getOwnPropertyNames || function (o) {
30
+ var ar = [];
31
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
32
+ return ar;
33
+ };
34
+ return ownKeys(o);
35
+ };
36
+ return function (mod) {
37
+ if (mod && mod.__esModule) return mod;
38
+ var result = {};
39
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
40
+ __setModuleDefault(result, mod);
41
+ return result;
42
+ };
43
+ })();
44
+ Object.defineProperty(exports, "__esModule", { value: true });
45
+ exports.AutoFixer = void 0;
46
+ exports.getAutoFixer = getAutoFixer;
47
+ exports.resetAutoFixer = resetAutoFixer;
48
+ exports.autoFix = autoFix;
49
+ exports.generateFixes = generateFixes;
50
+ const fs = __importStar(require("fs"));
51
+ const path = __importStar(require("path"));
52
+ const detector_js_1 = require("./detector.js");
53
+ const bash_js_1 = require("../tools/bash.js");
54
+ const edit_js_1 = require("../tools/edit.js");
55
+ const FIX_PATTERNS = [
56
+ // Missing semicolon
57
+ {
58
+ categories: ['syntax'],
59
+ messagePattern: /missing semicolon/i,
60
+ generateFix: (error, content) => {
61
+ if (!error.line)
62
+ return [];
63
+ const lines = content.split('\n');
64
+ const lineIdx = error.line - 1;
65
+ if (lineIdx >= lines.length)
66
+ return [];
67
+ const line = lines[lineIdx];
68
+ if (!line.trim().endsWith(';')) {
69
+ const fixed = [...lines];
70
+ fixed[lineIdx] = line.trimEnd() + ';';
71
+ return [{
72
+ id: `fix-semicolon-${error.line}`,
73
+ description: `Add missing semicolon at line ${error.line}`,
74
+ file: error.file || '',
75
+ original: content,
76
+ fixed: fixed.join('\n'),
77
+ confidence: 0.9,
78
+ source: 'pattern',
79
+ }];
80
+ }
81
+ return [];
82
+ },
83
+ },
84
+ // Undefined variable - add declaration
85
+ {
86
+ categories: ['runtime', 'type'],
87
+ messagePattern: /is not defined|Cannot find name/i,
88
+ generateFix: (error, content) => {
89
+ // Extract variable name from error
90
+ const match = error.message.match(/'(\w+)' is not defined|Cannot find name '(\w+)'/);
91
+ if (!match)
92
+ return [];
93
+ const varName = match[1] || match[2];
94
+ const lines = content.split('\n');
95
+ // Add declaration at the top of the file (after imports)
96
+ let insertIdx = 0;
97
+ for (let i = 0; i < lines.length; i++) {
98
+ if (lines[i].startsWith('import ') || lines[i].startsWith('export ')) {
99
+ insertIdx = i + 1;
100
+ }
101
+ }
102
+ const fixed = [...lines];
103
+ fixed.splice(insertIdx, 0, `let ${varName}: any; // TODO: Add proper type`);
104
+ return [{
105
+ id: `fix-undefined-${varName}`,
106
+ description: `Declare undefined variable '${varName}'`,
107
+ file: error.file || '',
108
+ original: content,
109
+ fixed: fixed.join('\n'),
110
+ confidence: 0.5,
111
+ source: 'heuristic',
112
+ }];
113
+ },
114
+ },
115
+ // Missing import
116
+ {
117
+ categories: ['dependency'],
118
+ messagePattern: /Cannot find module '(.+)'/,
119
+ generateFix: (error) => {
120
+ const match = error.message.match(/Cannot find module '(.+)'/);
121
+ if (!match)
122
+ return [];
123
+ const moduleName = match[1];
124
+ // This is a special case - we return a "command" fix
125
+ return [{
126
+ id: `fix-import-${moduleName}`,
127
+ description: `Install missing module '${moduleName}'`,
128
+ file: 'package.json',
129
+ original: '',
130
+ fixed: `npm install ${moduleName}`,
131
+ confidence: 0.8,
132
+ source: 'pattern',
133
+ }];
134
+ },
135
+ },
136
+ // Type assertion fix
137
+ {
138
+ categories: ['type'],
139
+ messagePattern: /Type '(.+)' is not assignable to type '(.+)'/,
140
+ generateFix: (error, content) => {
141
+ if (!error.line || !error.column)
142
+ return [];
143
+ const match = error.message.match(/Type '(.+)' is not assignable to type '(.+)'/);
144
+ if (!match)
145
+ return [];
146
+ const [, actualType, expectedType] = match;
147
+ const lines = content.split('\n');
148
+ const lineIdx = error.line - 1;
149
+ const line = lines[lineIdx];
150
+ // Try to find the expression and add type assertion
151
+ // This is a simplistic approach
152
+ const candidates = [];
153
+ // Option 1: Add 'as' assertion
154
+ const col = error.column - 1;
155
+ // Find the end of the expression
156
+ let endCol = col;
157
+ while (endCol < line.length && /[\w\.\[\]()]/.test(line[endCol])) {
158
+ endCol++;
159
+ }
160
+ if (endCol > col) {
161
+ const expr = line.slice(col, endCol);
162
+ const fixedLine = line.slice(0, endCol) + ` as ${expectedType}` + line.slice(endCol);
163
+ const fixed = [...lines];
164
+ fixed[lineIdx] = fixedLine;
165
+ candidates.push({
166
+ id: `fix-type-assertion-${error.line}`,
167
+ description: `Add type assertion 'as ${expectedType}'`,
168
+ file: error.file || '',
169
+ original: content,
170
+ fixed: fixed.join('\n'),
171
+ confidence: 0.6,
172
+ source: 'heuristic',
173
+ });
174
+ }
175
+ return candidates;
176
+ },
177
+ },
178
+ // Null check fix
179
+ {
180
+ categories: ['type', 'runtime'],
181
+ messagePattern: /possibly 'null'|possibly 'undefined'|is possibly/i,
182
+ generateFix: (error, content) => {
183
+ if (!error.line)
184
+ return [];
185
+ const lines = content.split('\n');
186
+ const lineIdx = error.line - 1;
187
+ const line = lines[lineIdx];
188
+ // Find property access that might be null
189
+ const match = line.match(/(\w+(?:\.\w+)*)\./);
190
+ if (!match)
191
+ return [];
192
+ const expr = match[1];
193
+ const candidates = [];
194
+ // Option 1: Optional chaining
195
+ const fixed1 = line.replace(new RegExp(`${expr}\\.`), `${expr}?.`);
196
+ if (fixed1 !== line) {
197
+ const fixedLines1 = [...lines];
198
+ fixedLines1[lineIdx] = fixed1;
199
+ candidates.push({
200
+ id: `fix-optional-chain-${error.line}`,
201
+ description: `Use optional chaining for '${expr}'`,
202
+ file: error.file || '',
203
+ original: content,
204
+ fixed: fixedLines1.join('\n'),
205
+ confidence: 0.7,
206
+ source: 'heuristic',
207
+ });
208
+ }
209
+ // Option 2: Null check
210
+ const indent = line.match(/^(\s*)/)?.[1] || '';
211
+ const fixedLines2 = [...lines];
212
+ fixedLines2.splice(lineIdx, 0, `${indent}if (${expr}) {`);
213
+ fixedLines2[lineIdx + 1] = indent + ' ' + line.trim();
214
+ fixedLines2.splice(lineIdx + 2, 0, `${indent}}`);
215
+ candidates.push({
216
+ id: `fix-null-check-${error.line}`,
217
+ description: `Add null check for '${expr}'`,
218
+ file: error.file || '',
219
+ original: content,
220
+ fixed: fixedLines2.join('\n'),
221
+ confidence: 0.5,
222
+ source: 'heuristic',
223
+ });
224
+ return candidates;
225
+ },
226
+ },
227
+ ];
228
+ // ============================================================================
229
+ // Auto-Fixer Class
230
+ // ============================================================================
231
+ class AutoFixer {
232
+ config;
233
+ patterns;
234
+ constructor(config) {
235
+ this.config = {
236
+ maxCandidates: 5,
237
+ maxIterations: 3,
238
+ testCommand: 'npm test',
239
+ buildCommand: 'npm run build',
240
+ workingDirectory: process.cwd(),
241
+ createBackup: true,
242
+ ...config,
243
+ };
244
+ this.patterns = [...FIX_PATTERNS];
245
+ }
246
+ // --------------------------------------------------------------------------
247
+ // Main Fix Flow
248
+ // --------------------------------------------------------------------------
249
+ /**
250
+ * Attempt to fix errors automatically (Darwin-Gödel pattern)
251
+ */
252
+ async fix(errors) {
253
+ if (errors.length === 0) {
254
+ return { success: true, candidates: [], evaluations: [], iterations: 0 };
255
+ }
256
+ const allCandidates = [];
257
+ const allEvaluations = [];
258
+ let iterations = 0;
259
+ let currentErrors = [...errors];
260
+ while (iterations < this.config.maxIterations && currentErrors.length > 0) {
261
+ iterations++;
262
+ // 1. MUTATE: Generate fix candidates
263
+ const candidates = await this.generateCandidates(currentErrors);
264
+ allCandidates.push(...candidates);
265
+ if (candidates.length === 0) {
266
+ return {
267
+ success: false,
268
+ candidates: allCandidates,
269
+ evaluations: allEvaluations,
270
+ iterations,
271
+ error: 'No fix candidates could be generated',
272
+ };
273
+ }
274
+ // 2. TEST: Evaluate each candidate
275
+ const evaluations = await this.evaluateCandidates(candidates);
276
+ allEvaluations.push(...evaluations);
277
+ // 3. SELECT: Find the best candidate
278
+ const best = this.selectBest(evaluations);
279
+ if (best && best.testsPass && best.buildSuccess) {
280
+ // Success! Apply the fix
281
+ const applied = await this.applyFix(best.candidate);
282
+ if (applied) {
283
+ return {
284
+ success: true,
285
+ appliedFix: best.candidate,
286
+ candidates: allCandidates,
287
+ evaluations: allEvaluations,
288
+ iterations,
289
+ };
290
+ }
291
+ }
292
+ // 4. ITERATE: Analyze failures and retry with new context
293
+ if (best) {
294
+ // Update errors based on what was partially fixed
295
+ currentErrors = best.newErrors;
296
+ }
297
+ else {
298
+ // No progress, break
299
+ break;
300
+ }
301
+ }
302
+ return {
303
+ success: false,
304
+ candidates: allCandidates,
305
+ evaluations: allEvaluations,
306
+ iterations,
307
+ error: `Could not fix all errors after ${iterations} iterations`,
308
+ };
309
+ }
310
+ // --------------------------------------------------------------------------
311
+ // Candidate Generation
312
+ // --------------------------------------------------------------------------
313
+ /**
314
+ * Generate fix candidates for errors
315
+ */
316
+ async generateCandidates(errors) {
317
+ const candidates = [];
318
+ for (const error of errors) {
319
+ // Skip errors without file information
320
+ if (!error.file)
321
+ continue;
322
+ const filePath = path.isAbsolute(error.file)
323
+ ? error.file
324
+ : path.join(this.config.workingDirectory, error.file);
325
+ if (!fs.existsSync(filePath))
326
+ continue;
327
+ // Skip directories
328
+ try {
329
+ if (!fs.statSync(filePath).isFile())
330
+ continue;
331
+ }
332
+ catch {
333
+ continue;
334
+ }
335
+ const content = fs.readFileSync(filePath, 'utf-8');
336
+ // Try pattern-based fixes first
337
+ for (const pattern of this.patterns) {
338
+ if (!pattern.categories.includes(error.category))
339
+ continue;
340
+ if (pattern.messagePattern && !pattern.messagePattern.test(error.message))
341
+ continue;
342
+ if (pattern.codePattern && error.code && !pattern.codePattern.test(error.code))
343
+ continue;
344
+ const patternCandidates = pattern.generateFix(error, content);
345
+ candidates.push(...patternCandidates);
346
+ }
347
+ // Try LLM-based fixes if available
348
+ if (this.config.llmFixGenerator) {
349
+ try {
350
+ const llmCandidates = await this.config.llmFixGenerator(error, content);
351
+ candidates.push(...llmCandidates);
352
+ }
353
+ catch {
354
+ // LLM generation failed, continue with pattern-based fixes
355
+ }
356
+ }
357
+ }
358
+ // Deduplicate and limit
359
+ const seen = new Set();
360
+ return candidates
361
+ .filter(c => {
362
+ if (seen.has(c.id))
363
+ return false;
364
+ seen.add(c.id);
365
+ return true;
366
+ })
367
+ .slice(0, this.config.maxCandidates * errors.length);
368
+ }
369
+ // --------------------------------------------------------------------------
370
+ // Candidate Evaluation
371
+ // --------------------------------------------------------------------------
372
+ /**
373
+ * Evaluate fix candidates
374
+ */
375
+ async evaluateCandidates(candidates) {
376
+ const results = [];
377
+ for (const candidate of candidates) {
378
+ const result = await this.evaluateCandidate(candidate);
379
+ results.push(result);
380
+ }
381
+ return results;
382
+ }
383
+ /**
384
+ * Evaluate a single candidate
385
+ */
386
+ async evaluateCandidate(candidate) {
387
+ const filePath = path.isAbsolute(candidate.file)
388
+ ? candidate.file
389
+ : path.join(this.config.workingDirectory, candidate.file);
390
+ // Special case: npm install command
391
+ if (candidate.fixed.startsWith('npm install')) {
392
+ const installResult = await (0, bash_js_1.bash)(candidate.fixed, {
393
+ cwd: this.config.workingDirectory,
394
+ timeout: 60000,
395
+ });
396
+ return {
397
+ candidate,
398
+ testsPass: installResult.success,
399
+ testsPassed: installResult.success ? 1 : 0,
400
+ testsTotal: 1,
401
+ buildSuccess: installResult.success,
402
+ newErrors: [],
403
+ fixedErrors: [],
404
+ score: installResult.success ? 1 : 0,
405
+ };
406
+ }
407
+ // Create backup
408
+ let backup;
409
+ if (this.config.createBackup && fs.existsSync(filePath)) {
410
+ backup = candidate.original;
411
+ }
412
+ // Apply fix temporarily
413
+ try {
414
+ fs.writeFileSync(filePath, candidate.fixed, 'utf-8');
415
+ }
416
+ catch {
417
+ return {
418
+ candidate,
419
+ testsPass: false,
420
+ testsPassed: 0,
421
+ testsTotal: 0,
422
+ buildSuccess: false,
423
+ newErrors: [],
424
+ fixedErrors: [],
425
+ score: 0,
426
+ };
427
+ }
428
+ // Run build
429
+ const buildResult = await (0, bash_js_1.bash)(this.config.buildCommand, {
430
+ cwd: this.config.workingDirectory,
431
+ timeout: 60000,
432
+ });
433
+ // Detect new errors
434
+ const buildErrors = (0, detector_js_1.detectErrors)(buildResult.stdout + '\n' + buildResult.stderr);
435
+ // Run tests if build succeeded
436
+ let testResult;
437
+ let testErrors = { errors: [], success: true };
438
+ if (buildResult.success) {
439
+ testResult = await (0, bash_js_1.bash)(this.config.testCommand, {
440
+ cwd: this.config.workingDirectory,
441
+ timeout: 120000,
442
+ });
443
+ testErrors = (0, detector_js_1.detectErrors)(testResult.stdout + '\n' + testResult.stderr);
444
+ }
445
+ // Restore original
446
+ if (backup !== undefined) {
447
+ fs.writeFileSync(filePath, backup, 'utf-8');
448
+ }
449
+ // Calculate score
450
+ const newErrors = [...buildErrors.errors, ...testErrors.errors];
451
+ const score = this.calculateScore(buildResult.success, testResult?.success || false, newErrors.length);
452
+ return {
453
+ candidate,
454
+ testsPass: testResult?.success || false,
455
+ testsPassed: testResult?.success ? 1 : 0, // Simplified
456
+ testsTotal: 1,
457
+ buildSuccess: buildResult.success,
458
+ newErrors,
459
+ fixedErrors: [], // Would need to compare with original errors
460
+ score,
461
+ };
462
+ }
463
+ /**
464
+ * Calculate evaluation score
465
+ */
466
+ calculateScore(buildSuccess, testsPass, newErrorCount) {
467
+ let score = 0;
468
+ if (buildSuccess)
469
+ score += 0.4;
470
+ if (testsPass)
471
+ score += 0.4;
472
+ score += Math.max(0, 0.2 - (newErrorCount * 0.05)); // Penalize new errors
473
+ return Math.max(0, Math.min(1, score));
474
+ }
475
+ // --------------------------------------------------------------------------
476
+ // Selection and Application
477
+ // --------------------------------------------------------------------------
478
+ /**
479
+ * Select the best candidate from evaluations
480
+ */
481
+ selectBest(evaluations) {
482
+ if (evaluations.length === 0)
483
+ return null;
484
+ return evaluations.reduce((best, current) => {
485
+ if (!best)
486
+ return current;
487
+ return current.score > best.score ? current : best;
488
+ }, null);
489
+ }
490
+ /**
491
+ * Apply a fix permanently
492
+ */
493
+ async applyFix(candidate) {
494
+ // Special case: npm install command
495
+ if (candidate.fixed.startsWith('npm install')) {
496
+ const result = await (0, bash_js_1.bash)(candidate.fixed, {
497
+ cwd: this.config.workingDirectory,
498
+ timeout: 60000,
499
+ });
500
+ return result.success;
501
+ }
502
+ const filePath = path.isAbsolute(candidate.file)
503
+ ? candidate.file
504
+ : path.join(this.config.workingDirectory, candidate.file);
505
+ try {
506
+ // Use edit tool for atomic write with backup
507
+ const result = await (0, edit_js_1.edit)({
508
+ file_path: filePath,
509
+ old_string: candidate.original,
510
+ new_string: candidate.fixed,
511
+ });
512
+ return result.success;
513
+ }
514
+ catch {
515
+ return false;
516
+ }
517
+ }
518
+ // --------------------------------------------------------------------------
519
+ // Configuration
520
+ // --------------------------------------------------------------------------
521
+ getConfig() {
522
+ return { ...this.config };
523
+ }
524
+ updateConfig(config) {
525
+ this.config = { ...this.config, ...config };
526
+ }
527
+ /**
528
+ * Add a custom fix pattern
529
+ */
530
+ addPattern(pattern) {
531
+ this.patterns.push(pattern);
532
+ }
533
+ /**
534
+ * Set LLM fix generator
535
+ */
536
+ setLLMGenerator(generator) {
537
+ this.config.llmFixGenerator = generator;
538
+ }
539
+ }
540
+ exports.AutoFixer = AutoFixer;
541
+ // ============================================================================
542
+ // Singleton Instance
543
+ // ============================================================================
544
+ let fixerInstance = null;
545
+ function getAutoFixer(config) {
546
+ if (!fixerInstance) {
547
+ fixerInstance = new AutoFixer(config);
548
+ }
549
+ else if (config) {
550
+ fixerInstance.updateConfig(config);
551
+ }
552
+ return fixerInstance;
553
+ }
554
+ function resetAutoFixer() {
555
+ fixerInstance = null;
556
+ }
557
+ // ============================================================================
558
+ // Convenience Functions
559
+ // ============================================================================
560
+ /**
561
+ * Attempt to fix errors in output
562
+ */
563
+ async function autoFix(output, config) {
564
+ const errors = (0, detector_js_1.detectErrors)(output).errors.filter(e => e.severity === 'error');
565
+ return getAutoFixer(config).fix(errors);
566
+ }
567
+ /**
568
+ * Generate fix candidates for an error
569
+ */
570
+ async function generateFixes(error) {
571
+ return getAutoFixer().generateCandidates([error]);
572
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Genesis Self-Healing Module
3
+ *
4
+ * Darwin-Gödel pattern for automatic error recovery:
5
+ * - Detect errors from command output
6
+ * - Generate fix candidates
7
+ * - Evaluate and select best fix
8
+ * - Apply and verify
9
+ */
10
+ export * from './detector.js';
11
+ export * from './fixer.js';
12
+ import { detectErrors, hasErrors, formatErrorReport, getErrorDetector } from './detector.js';
13
+ import { autoFix, generateFixes, getAutoFixer } from './fixer.js';
14
+ export declare const healing: {
15
+ detectErrors: typeof detectErrors;
16
+ hasErrors: typeof hasErrors;
17
+ formatErrorReport: typeof formatErrorReport;
18
+ getDetector: typeof getErrorDetector;
19
+ autoFix: typeof autoFix;
20
+ generateFixes: typeof generateFixes;
21
+ getFixer: typeof getAutoFixer;
22
+ };
23
+ export default healing;
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ /**
3
+ * Genesis Self-Healing Module
4
+ *
5
+ * Darwin-Gödel pattern for automatic error recovery:
6
+ * - Detect errors from command output
7
+ * - Generate fix candidates
8
+ * - Evaluate and select best fix
9
+ * - Apply and verify
10
+ */
11
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
12
+ if (k2 === undefined) k2 = k;
13
+ var desc = Object.getOwnPropertyDescriptor(m, k);
14
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
15
+ desc = { enumerable: true, get: function() { return m[k]; } };
16
+ }
17
+ Object.defineProperty(o, k2, desc);
18
+ }) : (function(o, m, k, k2) {
19
+ if (k2 === undefined) k2 = k;
20
+ o[k2] = m[k];
21
+ }));
22
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
23
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.healing = void 0;
27
+ __exportStar(require("./detector.js"), exports);
28
+ __exportStar(require("./fixer.js"), exports);
29
+ // Re-export main functions for convenience
30
+ const detector_js_1 = require("./detector.js");
31
+ const fixer_js_1 = require("./fixer.js");
32
+ exports.healing = {
33
+ // Detection
34
+ detectErrors: detector_js_1.detectErrors,
35
+ hasErrors: detector_js_1.hasErrors,
36
+ formatErrorReport: detector_js_1.formatErrorReport,
37
+ getDetector: detector_js_1.getErrorDetector,
38
+ // Fixing
39
+ autoFix: fixer_js_1.autoFix,
40
+ generateFixes: fixer_js_1.generateFixes,
41
+ getFixer: fixer_js_1.getAutoFixer,
42
+ };
43
+ exports.default = exports.healing;