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,695 @@
1
+ "use strict";
2
+ /**
3
+ * Genesis 6.0 - Pipeline Executor
4
+ *
5
+ * Executes the full system creation pipeline using real MCP servers.
6
+ *
7
+ * Pipeline Stages:
8
+ * 1. Research - Gather knowledge using arxiv, semantic-scholar, context7
9
+ * 2. Design - Create architecture using openai
10
+ * 3. Generate - Generate code using openai, write using filesystem
11
+ * 4. Visualize - Create images using openai (DALL-E)
12
+ * 5. Persist - Store in memory knowledge graph
13
+ * 6. Publish - Create GitHub repository (optional)
14
+ */
15
+ var __importDefault = (this && this.__importDefault) || function (mod) {
16
+ return (mod && mod.__esModule) ? mod : { "default": mod };
17
+ };
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.PipelineExecutor = void 0;
20
+ exports.createPipelineExecutor = createPipelineExecutor;
21
+ const fs_1 = __importDefault(require("fs"));
22
+ const path_1 = __importDefault(require("path"));
23
+ const index_js_1 = require("../mcp/index.js");
24
+ // ============================================================================
25
+ // Pipeline Executor
26
+ // ============================================================================
27
+ class PipelineExecutor {
28
+ mcp;
29
+ verbose;
30
+ outputDir;
31
+ constructor(options = {}) {
32
+ this.mcp = (0, index_js_1.getMCPClient)({ logCalls: options.verbose });
33
+ this.verbose = options.verbose ?? false;
34
+ this.outputDir = options.outputDir ?? process.cwd();
35
+ }
36
+ log(message, level = 'info') {
37
+ if (!this.verbose && level === 'debug')
38
+ return;
39
+ const colors = {
40
+ info: '\x1b[36m',
41
+ success: '\x1b[32m',
42
+ error: '\x1b[31m',
43
+ debug: '\x1b[90m',
44
+ };
45
+ const reset = '\x1b[0m';
46
+ const prefix = level === 'success' ? '✓' : level === 'error' ? '✗' : '→';
47
+ console.log(`${colors[level]}${prefix} [Pipeline] ${message}${reset}`);
48
+ }
49
+ // ============================================================================
50
+ // Main Pipeline
51
+ // ============================================================================
52
+ async execute(spec, options = {}) {
53
+ const results = [];
54
+ const context = { spec };
55
+ const stages = options.stages ?? [
56
+ 'research',
57
+ 'design',
58
+ 'generate',
59
+ 'persist',
60
+ ];
61
+ // Add visualize and publish if not skipped
62
+ if (!options.skipPublish && !stages.includes('publish')) {
63
+ // Optional stages can be added explicitly
64
+ }
65
+ this.log(`Starting pipeline for: ${spec.name}`, 'info');
66
+ this.log(`Type: ${spec.type}, Features: ${spec.features.join(', ')}`, 'debug');
67
+ for (const stage of stages) {
68
+ const start = Date.now();
69
+ try {
70
+ this.log(`Stage: ${stage}`, 'info');
71
+ switch (stage) {
72
+ case 'research':
73
+ context.research = await this.stageResearch(spec);
74
+ break;
75
+ case 'design':
76
+ context.architecture = await this.stageDesign(spec, context.research);
77
+ break;
78
+ case 'generate':
79
+ context.code = await this.stageGenerate(spec, context.architecture);
80
+ break;
81
+ case 'visualize':
82
+ context.visuals = await this.stageVisualize(spec, context.architecture);
83
+ break;
84
+ case 'persist':
85
+ await this.stagePersist(spec, context);
86
+ break;
87
+ case 'publish':
88
+ context.repoUrl = await this.stagePublish(spec, context.code);
89
+ break;
90
+ }
91
+ const duration = Date.now() - start;
92
+ this.log(`${stage} completed in ${duration}ms`, 'success');
93
+ results.push({
94
+ stage,
95
+ success: true,
96
+ data: context,
97
+ duration,
98
+ mcpsUsed: this.getMCPsForStage(stage),
99
+ });
100
+ }
101
+ catch (error) {
102
+ const duration = Date.now() - start;
103
+ const errorMsg = error instanceof Error ? error.message : String(error);
104
+ this.log(`${stage} failed: ${errorMsg}`, 'error');
105
+ results.push({
106
+ stage,
107
+ success: false,
108
+ error: errorMsg,
109
+ duration,
110
+ mcpsUsed: this.getMCPsForStage(stage),
111
+ });
112
+ // Stop on failure
113
+ break;
114
+ }
115
+ }
116
+ return results;
117
+ }
118
+ getMCPsForStage(stage) {
119
+ const mapping = {
120
+ research: ['semantic-scholar', 'context7'],
121
+ design: ['openai'],
122
+ generate: ['openai', 'filesystem'],
123
+ visualize: ['openai'],
124
+ persist: ['memory'],
125
+ publish: ['github'],
126
+ };
127
+ return mapping[stage];
128
+ }
129
+ // ============================================================================
130
+ // Stage 1: Research
131
+ // ============================================================================
132
+ async stageResearch(spec) {
133
+ const result = {
134
+ papers: [],
135
+ documentation: [],
136
+ codeExamples: [],
137
+ webResults: [],
138
+ insights: [],
139
+ };
140
+ // Search for academic papers
141
+ try {
142
+ this.log('Searching academic papers...', 'debug');
143
+ const searchQuery = `${spec.name} ${spec.type} ${spec.features.slice(0, 3).join(' ')}`;
144
+ const papersResponse = await this.mcp.call('semantic-scholar', 'search_papers', {
145
+ query: searchQuery,
146
+ source: 'crossref', // Use crossref for broader results
147
+ });
148
+ if (papersResponse.success && papersResponse.data) {
149
+ const papersData = typeof papersResponse.data === 'string'
150
+ ? papersResponse.data
151
+ : JSON.stringify(papersResponse.data);
152
+ // Parse papers from response
153
+ result.papers = this.parsePapers(papersData);
154
+ result.insights.push(`Found ${result.papers.length} relevant papers`);
155
+ }
156
+ }
157
+ catch (err) {
158
+ this.log(`Paper search failed: ${err}`, 'debug');
159
+ }
160
+ // Search for documentation if features mention libraries
161
+ try {
162
+ this.log('Searching documentation...', 'debug');
163
+ // Determine library based on type
164
+ const libraryId = spec.type === 'agent' ? '/langchain-ai/langchainjs'
165
+ : spec.type === 'autopoietic' ? '/statelyai/xstate'
166
+ : '/microsoft/typescript';
167
+ const docsResponse = await this.mcp.call('context7', 'query-docs', {
168
+ libraryId,
169
+ query: spec.features.join(' '),
170
+ });
171
+ if (docsResponse.success && docsResponse.data) {
172
+ const docsData = typeof docsResponse.data === 'string'
173
+ ? docsResponse.data
174
+ : JSON.stringify(docsResponse.data);
175
+ result.documentation.push({
176
+ library: libraryId,
177
+ source: 'context7',
178
+ content: docsData.substring(0, 2000), // Truncate for readability
179
+ examples: [],
180
+ });
181
+ result.insights.push(`Retrieved documentation for ${libraryId}`);
182
+ }
183
+ }
184
+ catch (err) {
185
+ this.log(`Documentation search failed: ${err}`, 'debug');
186
+ }
187
+ // Generate insights summary
188
+ result.insights.push(`System type: ${spec.type}`, `Key features: ${spec.features.join(', ')}`, spec.inspirations ? `Inspired by: ${spec.inspirations.join(', ')}` : '');
189
+ return result;
190
+ }
191
+ parsePapers(data) {
192
+ // Simple parser for paper search results
193
+ const papers = [];
194
+ try {
195
+ // Try to extract paper info from response
196
+ const lines = data.split('\n');
197
+ let currentPaper = null;
198
+ for (const line of lines) {
199
+ if (line.includes('title') || line.includes('Title')) {
200
+ if (currentPaper?.title) {
201
+ papers.push(currentPaper);
202
+ }
203
+ currentPaper = {
204
+ title: line.replace(/.*title[:\s]+/i, '').trim().replace(/[",]/g, ''),
205
+ authors: [],
206
+ year: new Date().getFullYear(),
207
+ source: 'semantic-scholar',
208
+ url: '',
209
+ summary: '',
210
+ relevance: 0.8,
211
+ };
212
+ }
213
+ if (currentPaper && line.includes('author')) {
214
+ currentPaper.authors = [line.replace(/.*author[s]?[:\s]+/i, '').trim()];
215
+ }
216
+ }
217
+ if (currentPaper?.title) {
218
+ papers.push(currentPaper);
219
+ }
220
+ }
221
+ catch {
222
+ // Return empty if parsing fails
223
+ }
224
+ return papers.slice(0, 5); // Limit to 5 papers
225
+ }
226
+ // ============================================================================
227
+ // Stage 2: Design
228
+ // ============================================================================
229
+ async stageDesign(spec, research) {
230
+ const prompt = this.buildDesignPrompt(spec, research);
231
+ const response = await this.mcp.call('openai', 'openai_chat_completion', {
232
+ model: 'gpt-4',
233
+ messages: [
234
+ {
235
+ role: 'system',
236
+ content: 'You are a software architect. Return ONLY valid JSON, no markdown.',
237
+ },
238
+ {
239
+ role: 'user',
240
+ content: prompt,
241
+ },
242
+ ],
243
+ });
244
+ if (!response.success) {
245
+ throw new Error(`Design failed: ${response.error}`);
246
+ }
247
+ // Parse architecture from response
248
+ return this.parseArchitecture(response.data, spec);
249
+ }
250
+ buildDesignPrompt(spec, research) {
251
+ return `Design a ${spec.type} system called "${spec.name}".
252
+
253
+ Description: ${spec.description}
254
+ Features: ${spec.features.join(', ')}
255
+ ${spec.constraints ? `Constraints: ${spec.constraints.join(', ')}` : ''}
256
+
257
+ Research insights:
258
+ ${research.insights.slice(0, 5).join('\n')}
259
+
260
+ Return a JSON object with this exact structure:
261
+ {
262
+ "components": [
263
+ {"id": "string", "name": "string", "type": "core|service|adapter|util", "description": "string", "dependencies": []}
264
+ ],
265
+ "relations": [
266
+ {"from": "componentId", "to": "componentId", "type": "uses|extends|implements|triggers"}
267
+ ],
268
+ "invariants": ["string"],
269
+ "operations": [
270
+ {"id": "string", "name": "string", "description": "string", "inputs": [], "outputs": [], "complexity": 1}
271
+ ],
272
+ "events": [
273
+ {"name": "string", "payload": {}}
274
+ ]
275
+ }
276
+
277
+ Design 3-5 components. Be specific and practical.`;
278
+ }
279
+ parseArchitecture(data, spec) {
280
+ // Default architecture if parsing fails
281
+ const defaultArch = {
282
+ components: [
283
+ {
284
+ id: 'core',
285
+ name: `${spec.name}Core`,
286
+ type: 'core',
287
+ description: `Core ${spec.type} implementation`,
288
+ dependencies: [],
289
+ },
290
+ {
291
+ id: 'state',
292
+ name: 'StateManager',
293
+ type: 'service',
294
+ description: 'State management',
295
+ dependencies: ['core'],
296
+ },
297
+ {
298
+ id: 'events',
299
+ name: 'EventBus',
300
+ type: 'service',
301
+ description: 'Event handling',
302
+ dependencies: [],
303
+ },
304
+ ],
305
+ relations: [
306
+ { from: 'core', to: 'state', type: 'uses' },
307
+ { from: 'core', to: 'events', type: 'uses' },
308
+ ],
309
+ invariants: [
310
+ 'State must be consistent',
311
+ 'Events must be ordered',
312
+ ],
313
+ operations: [
314
+ {
315
+ id: 'init',
316
+ name: 'initialize',
317
+ description: 'Initialize the system',
318
+ inputs: [],
319
+ outputs: [{ name: 'success', type: 'boolean', required: true }],
320
+ complexity: 1,
321
+ },
322
+ {
323
+ id: 'process',
324
+ name: 'process',
325
+ description: 'Process input',
326
+ inputs: [{ name: 'input', type: 'any', required: true }],
327
+ outputs: [{ name: 'result', type: 'any', required: true }],
328
+ complexity: 2,
329
+ },
330
+ ],
331
+ events: [
332
+ { name: 'initialized', payload: {} },
333
+ { name: 'processed', payload: { result: 'any' } },
334
+ ],
335
+ };
336
+ try {
337
+ // Try to parse JSON from response
338
+ let jsonStr = typeof data === 'string' ? data : JSON.stringify(data);
339
+ // Extract JSON from potential markdown code block
340
+ const jsonMatch = jsonStr.match(/```(?:json)?\s*([\s\S]*?)```/);
341
+ if (jsonMatch) {
342
+ jsonStr = jsonMatch[1];
343
+ }
344
+ // Try to find JSON object
345
+ const objMatch = jsonStr.match(/\{[\s\S]*\}/);
346
+ if (objMatch) {
347
+ const parsed = JSON.parse(objMatch[0]);
348
+ if (parsed.components && Array.isArray(parsed.components)) {
349
+ return {
350
+ components: parsed.components,
351
+ relations: parsed.relations || [],
352
+ invariants: parsed.invariants || defaultArch.invariants,
353
+ operations: parsed.operations || defaultArch.operations,
354
+ events: parsed.events || defaultArch.events,
355
+ };
356
+ }
357
+ }
358
+ }
359
+ catch {
360
+ this.log('Using default architecture template', 'debug');
361
+ }
362
+ return defaultArch;
363
+ }
364
+ // ============================================================================
365
+ // Stage 3: Generate
366
+ // ============================================================================
367
+ async stageGenerate(spec, architecture) {
368
+ const prompt = this.buildCodePrompt(spec, architecture);
369
+ const response = await this.mcp.call('openai', 'openai_chat_completion', {
370
+ model: 'gpt-4',
371
+ messages: [
372
+ {
373
+ role: 'system',
374
+ content: 'You are an expert TypeScript developer. Generate clean, well-documented code.',
375
+ },
376
+ {
377
+ role: 'user',
378
+ content: prompt,
379
+ },
380
+ ],
381
+ });
382
+ if (!response.success) {
383
+ throw new Error(`Code generation failed: ${response.error}`);
384
+ }
385
+ // Parse code from response
386
+ const files = this.parseCodeFiles(response.data, spec, architecture);
387
+ // Write files to disk
388
+ await this.writeCodeFiles(spec.name, files);
389
+ return {
390
+ files,
391
+ language: 'typescript',
392
+ tests: [],
393
+ };
394
+ }
395
+ buildCodePrompt(spec, architecture) {
396
+ const componentList = architecture.components
397
+ .map(c => `- ${c.name} (${c.type}): ${c.description}`)
398
+ .join('\n');
399
+ const operationList = architecture.operations
400
+ .map(o => `- ${o.name}: ${o.description}`)
401
+ .join('\n');
402
+ return `Generate TypeScript code for "${spec.name}".
403
+
404
+ Type: ${spec.type}
405
+ Features: ${spec.features.join(', ')}
406
+
407
+ Components:
408
+ ${componentList}
409
+
410
+ Operations:
411
+ ${operationList}
412
+
413
+ Invariants:
414
+ ${architecture.invariants.map(i => `- ${i}`).join('\n')}
415
+
416
+ Requirements:
417
+ 1. Create a main module that exports all components
418
+ 2. Use TypeScript interfaces for type safety
419
+ 3. Include JSDoc comments
420
+ 4. Make it runnable with a simple CLI
421
+
422
+ Return the code as a single TypeScript file. Start with imports, then interfaces, then classes, then exports.`;
423
+ }
424
+ parseCodeFiles(data, spec, architecture) {
425
+ let content = typeof data === 'string' ? data : JSON.stringify(data, null, 2);
426
+ // Extract code from markdown code block if present
427
+ const codeMatch = content.match(/```(?:typescript|ts)?\s*([\s\S]*?)```/);
428
+ if (codeMatch) {
429
+ content = codeMatch[1];
430
+ }
431
+ // If no code extracted, generate a template
432
+ if (!content.includes('export') && !content.includes('class')) {
433
+ content = this.generateCodeTemplate(spec, architecture);
434
+ }
435
+ return [
436
+ {
437
+ path: `src/${spec.name.toLowerCase()}.ts`,
438
+ content: content.trim(),
439
+ description: `Main module for ${spec.name}`,
440
+ },
441
+ {
442
+ path: 'src/index.ts',
443
+ content: `export * from './${spec.name.toLowerCase()}.js';\n`,
444
+ description: 'Main exports',
445
+ },
446
+ ];
447
+ }
448
+ generateCodeTemplate(spec, architecture) {
449
+ const className = spec.name.replace(/[^a-zA-Z0-9]/g, '');
450
+ return `/**
451
+ * ${spec.name}
452
+ * ${spec.description}
453
+ *
454
+ * Type: ${spec.type}
455
+ * Features: ${spec.features.join(', ')}
456
+ */
457
+
458
+ // ============================================================================
459
+ // Types
460
+ // ============================================================================
461
+
462
+ export interface ${className}State {
463
+ initialized: boolean;
464
+ data: Record<string, any>;
465
+ }
466
+
467
+ export interface ${className}Event {
468
+ type: string;
469
+ payload: any;
470
+ timestamp: number;
471
+ }
472
+
473
+ // ============================================================================
474
+ // Main Class
475
+ // ============================================================================
476
+
477
+ export class ${className} {
478
+ private state: ${className}State;
479
+ private events: ${className}Event[] = [];
480
+
481
+ constructor() {
482
+ this.state = {
483
+ initialized: false,
484
+ data: {},
485
+ };
486
+ }
487
+
488
+ /**
489
+ * Initialize the system
490
+ */
491
+ async initialize(): Promise<void> {
492
+ this.state.initialized = true;
493
+ this.emit('initialized', {});
494
+ console.log('${spec.name} initialized');
495
+ }
496
+
497
+ /**
498
+ * Process input
499
+ */
500
+ async process(input: any): Promise<any> {
501
+ if (!this.state.initialized) {
502
+ throw new Error('System not initialized');
503
+ }
504
+
505
+ const result = { processed: true, input };
506
+ this.emit('processed', result);
507
+ return result;
508
+ }
509
+
510
+ /**
511
+ * Emit an event
512
+ */
513
+ private emit(type: string, payload: any): void {
514
+ this.events.push({
515
+ type,
516
+ payload,
517
+ timestamp: Date.now(),
518
+ });
519
+ }
520
+
521
+ /**
522
+ * Get current state
523
+ */
524
+ getState(): ${className}State {
525
+ return { ...this.state };
526
+ }
527
+
528
+ /**
529
+ * Get event history
530
+ */
531
+ getEvents(): ${className}Event[] {
532
+ return [...this.events];
533
+ }
534
+ }
535
+
536
+ // ============================================================================
537
+ // CLI Entry Point
538
+ // ============================================================================
539
+
540
+ if (import.meta.url === \`file://\${process.argv[1]}\`) {
541
+ const system = new ${className}();
542
+ system.initialize()
543
+ .then(() => system.process({ test: true }))
544
+ .then(result => console.log('Result:', result))
545
+ .catch(err => console.error('Error:', err));
546
+ }
547
+ `;
548
+ }
549
+ async writeCodeFiles(name, files) {
550
+ const baseDir = path_1.default.join(this.outputDir, `${name.toLowerCase()}-generated`);
551
+ for (const file of files) {
552
+ const fullPath = path_1.default.join(baseDir, file.path);
553
+ const dir = path_1.default.dirname(fullPath);
554
+ try {
555
+ // Create directory using Node.js fs (always works, regardless of MCP mode)
556
+ fs_1.default.mkdirSync(dir, { recursive: true });
557
+ // Write file using Node.js fs
558
+ fs_1.default.writeFileSync(fullPath, file.content, 'utf-8');
559
+ this.log(`Written: ${fullPath}`, 'debug');
560
+ }
561
+ catch (err) {
562
+ this.log(`Failed to write ${fullPath}: ${err}`, 'error');
563
+ }
564
+ }
565
+ }
566
+ // ============================================================================
567
+ // Stage 4: Visualize (Optional)
568
+ // ============================================================================
569
+ async stageVisualize(spec, architecture) {
570
+ const visuals = [];
571
+ try {
572
+ const prompt = `Technical architecture diagram for "${spec.name}". ` +
573
+ `Components: ${architecture.components.map(c => c.name).join(', ')}. ` +
574
+ `Clean, professional, dark background, glowing connections, minimalist.`;
575
+ const response = await this.mcp.call('openai', 'openai_generate_image', {
576
+ prompt,
577
+ model: 'dall-e-3',
578
+ size: '1024x1024',
579
+ quality: 'standard',
580
+ });
581
+ if (response.success) {
582
+ visuals.push({
583
+ type: 'architecture',
584
+ prompt,
585
+ path: response.data?.url || '',
586
+ });
587
+ }
588
+ }
589
+ catch (err) {
590
+ this.log(`Image generation failed: ${err}`, 'debug');
591
+ }
592
+ return visuals;
593
+ }
594
+ // ============================================================================
595
+ // Stage 5: Persist
596
+ // ============================================================================
597
+ async stagePersist(spec, context) {
598
+ const entities = [
599
+ {
600
+ name: spec.name,
601
+ type: 'System',
602
+ observations: [
603
+ `Type: ${spec.type}`,
604
+ `Description: ${spec.description}`,
605
+ `Features: ${spec.features.join(', ')}`,
606
+ `Created: ${new Date().toISOString()}`,
607
+ context.architecture
608
+ ? `Components: ${context.architecture.components.map(c => c.name).join(', ')}`
609
+ : '',
610
+ context.code
611
+ ? `Files: ${context.code.files.map(f => f.path).join(', ')}`
612
+ : '',
613
+ ].filter(Boolean),
614
+ },
615
+ ];
616
+ // Add component entities
617
+ if (context.architecture) {
618
+ for (const comp of context.architecture.components) {
619
+ entities.push({
620
+ name: comp.name,
621
+ type: 'Component',
622
+ observations: [
623
+ `Part of: ${spec.name}`,
624
+ `Type: ${comp.type}`,
625
+ `Description: ${comp.description}`,
626
+ ],
627
+ });
628
+ }
629
+ }
630
+ try {
631
+ await this.mcp.call('memory', 'create_entities', { entities });
632
+ this.log(`Persisted ${entities.length} entities to knowledge graph`, 'debug');
633
+ }
634
+ catch (err) {
635
+ this.log(`Memory persist failed: ${err}`, 'error');
636
+ throw err;
637
+ }
638
+ // Create relations
639
+ if (context.architecture) {
640
+ const relations = context.architecture.components.map(comp => ({
641
+ from: spec.name,
642
+ to: comp.name,
643
+ relationType: 'contains',
644
+ }));
645
+ try {
646
+ await this.mcp.call('memory', 'create_relations', { relations });
647
+ }
648
+ catch {
649
+ // Relations may fail if entities don't exist
650
+ }
651
+ }
652
+ }
653
+ // ============================================================================
654
+ // Stage 6: Publish (Optional)
655
+ // ============================================================================
656
+ async stagePublish(spec, code) {
657
+ const repoName = spec.name.toLowerCase().replace(/[^a-z0-9-]/g, '-');
658
+ try {
659
+ // Create repository
660
+ const createResponse = await this.mcp.call('github', 'create_repository', {
661
+ name: repoName,
662
+ description: spec.description,
663
+ private: false,
664
+ autoInit: true,
665
+ });
666
+ if (!createResponse.success) {
667
+ throw new Error(createResponse.error || 'Failed to create repository');
668
+ }
669
+ // Push files
670
+ const files = code.files.map(f => ({
671
+ path: f.path,
672
+ content: f.content,
673
+ }));
674
+ await this.mcp.call('github', 'push_files', {
675
+ owner: process.env.GITHUB_USER || 'rossignoliluca',
676
+ repo: repoName,
677
+ branch: 'main',
678
+ files,
679
+ message: `Initial commit: ${spec.name}\n\nGenerated by Genesis 6.0`,
680
+ });
681
+ return `https://github.com/${process.env.GITHUB_USER || 'rossignoliluca'}/${repoName}`;
682
+ }
683
+ catch (err) {
684
+ this.log(`Publish failed: ${err}`, 'error');
685
+ throw err;
686
+ }
687
+ }
688
+ }
689
+ exports.PipelineExecutor = PipelineExecutor;
690
+ // ============================================================================
691
+ // Factory
692
+ // ============================================================================
693
+ function createPipelineExecutor(options) {
694
+ return new PipelineExecutor(options);
695
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Genesis 6.0 - Pipeline Module
3
+ *
4
+ * Exports pipeline execution functionality.
5
+ */
6
+ export { PipelineExecutor, createPipelineExecutor } from './executor.js';
7
+ export type { PipelineOptions, PipelineContext } from './executor.js';