@vishal_20/basetree 1.0.0

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 (149) hide show
  1. package/.env.example +10 -0
  2. package/README.md +369 -0
  3. package/dist/agents/alignmentAgent.js +68 -0
  4. package/dist/agents/governanceOrchestrator.js +152 -0
  5. package/dist/agents/planet/climateAgent.js +39 -0
  6. package/dist/agents/planet/diplomacyAgent.js +52 -0
  7. package/dist/agents/planet/discoveryAgent.js +41 -0
  8. package/dist/agents/planet/economicAgent.js +64 -0
  9. package/dist/agents/planet/educationAgent.js +41 -0
  10. package/dist/agents/planet/governanceCouncilAgent.js +76 -0
  11. package/dist/agents/planet/healthcareAgent.js +42 -0
  12. package/dist/agents/planet/infrastructureAgent.js +49 -0
  13. package/dist/agents/planet/planetAgent.js +5 -0
  14. package/dist/agents/planet/riskStabilityAgent.js +84 -0
  15. package/dist/agents/planet/urbanSystemsAgent.js +42 -0
  16. package/dist/agents/policyAgent.js +31 -0
  17. package/dist/agents/promptGenomeAgent.js +120 -0
  18. package/dist/agents/reasoningOptimizerAgent.js +72 -0
  19. package/dist/agents/regressionAgent.js +162 -0
  20. package/dist/agents/reinforcementLearnerAgent.js +108 -0
  21. package/dist/agents/riskEvaluationAgent.js +131 -0
  22. package/dist/agents/rollbackAgent.js +53 -0
  23. package/dist/agents/stabilityAgent.js +90 -0
  24. package/dist/agents/strategyMutationAgent.js +74 -0
  25. package/dist/agents/systemIntrospectionAgent.js +274 -0
  26. package/dist/agents/upgradeExecutorAgent.js +146 -0
  27. package/dist/agents/upgradePlannerAgent.js +80 -0
  28. package/dist/agents/venture/businessModelAgent.js +81 -0
  29. package/dist/agents/venture/growthAgent.js +82 -0
  30. package/dist/agents/venture/ideationAgent.js +89 -0
  31. package/dist/agents/venture/investorAgent.js +90 -0
  32. package/dist/agents/venture/legalAgent.js +112 -0
  33. package/dist/agents/venture/marketResearchAgent.js +80 -0
  34. package/dist/agents/venture/productAgent.js +96 -0
  35. package/dist/agents/venture/revenueAgent.js +63 -0
  36. package/dist/agents/venture/validationAgent.js +189 -0
  37. package/dist/bootstrap.js +200 -0
  38. package/dist/cli.js +453 -0
  39. package/dist/cognitiveGraph/cognitiveGraphEngine.js +180 -0
  40. package/dist/cognitiveGraph/graphStore.js +81 -0
  41. package/dist/cognitiveGraph/reasoningStreamBus.js +190 -0
  42. package/dist/config/config.js +76 -0
  43. package/dist/core/agent/AdaptivePlanner.js +49 -0
  44. package/dist/core/agent/AutoFixEngine.js +37 -0
  45. package/dist/core/agent/ExecutorAgent.js +79 -0
  46. package/dist/core/agent/LearningMemoryAgent.js +67 -0
  47. package/dist/core/agent/MemoryAgent.js +35 -0
  48. package/dist/core/agent/MetaCognitionAgent.js +38 -0
  49. package/dist/core/agent/PlannerAgent.js +59 -0
  50. package/dist/core/agent/ReflectionLoop.js +34 -0
  51. package/dist/core/agent/ReviewerAgent.js +34 -0
  52. package/dist/core/agent/VerificationAgent.js +20 -0
  53. package/dist/core/agent/specialists/SpecializedAgents.js +43 -0
  54. package/dist/core/ai/GeminiProvider.js +113 -0
  55. package/dist/core/ai/listModels.js +73 -0
  56. package/dist/core/monitor/PerformanceMonitor.js +18 -0
  57. package/dist/core/swarm/AgentSwarm.js +56 -0
  58. package/dist/core/swarm/ReasoningBus.js +26 -0
  59. package/dist/core/swarm/SwarmOrchestrator.js +36 -0
  60. package/dist/discovery/experimentOrchestrator.js +75 -0
  61. package/dist/discovery/hypothesisEngine.js +79 -0
  62. package/dist/discovery/knowledgeSynthesizer.js +83 -0
  63. package/dist/discovery/simulationPipeline.js +57 -0
  64. package/dist/experiments/experimentationEngine.js +174 -0
  65. package/dist/index.js +67 -0
  66. package/dist/kernel/eventBus.js +89 -0
  67. package/dist/kernel/kernel.js +146 -0
  68. package/dist/llm/tokenEfficiencyOptimizer.js +91 -0
  69. package/dist/memory/civilizationMemory.js +147 -0
  70. package/dist/memory/globalVectorMemory.js +87 -0
  71. package/dist/mesh/crossOrgProtocol.js +110 -0
  72. package/dist/mesh/globalReasoningBus.js +99 -0
  73. package/dist/observability/businessDashboard.js +103 -0
  74. package/dist/observability/businessMetrics.js +105 -0
  75. package/dist/observability/cognitiveMetrics.js +119 -0
  76. package/dist/observability/failureSurfaceMapper.js +135 -0
  77. package/dist/observability/metricsCollector.js +94 -0
  78. package/dist/observability/planetaryDashboard.js +97 -0
  79. package/dist/observability/planetaryMetrics.js +127 -0
  80. package/dist/observability/reportRenderer.js +100 -0
  81. package/dist/performance/memoryProfiler.js +107 -0
  82. package/dist/performance/profiler.js +130 -0
  83. package/dist/pipelines/evolvePipeline.js +150 -0
  84. package/dist/pipelines/governanceReviewPipeline.js +68 -0
  85. package/dist/pipelines/introspectPipeline.js +73 -0
  86. package/dist/pipelines/venture/growPipeline.js +51 -0
  87. package/dist/pipelines/venture/launchPipeline.js +55 -0
  88. package/dist/pipelines/venture/monetizePipeline.js +46 -0
  89. package/dist/pipelines/venture/shutdownPipeline.js +40 -0
  90. package/dist/pipelines/venture/startupPipeline.js +145 -0
  91. package/dist/pipelines/venture/validatePipeline.js +40 -0
  92. package/dist/planet/controlPlane.js +131 -0
  93. package/dist/planet/executionEngine.js +142 -0
  94. package/dist/planet/globalTypes.js +5 -0
  95. package/dist/planet/regionManager.js +114 -0
  96. package/dist/quality/codeQualityAuditor.js +161 -0
  97. package/dist/safety/containmentProtocols.js +87 -0
  98. package/dist/safety/integrityChecker.js +110 -0
  99. package/dist/safety/kernelGuard.js +57 -0
  100. package/dist/safety/killSwitch.js +100 -0
  101. package/dist/safety/planetaryKernel.js +92 -0
  102. package/dist/safety/policyEngine.js +129 -0
  103. package/dist/safety/rollbackManager.js +141 -0
  104. package/dist/safety/sandbox.js +143 -0
  105. package/dist/server/mindmapServer.js +102 -0
  106. package/dist/state/distributedState.js +241 -0
  107. package/dist/state/fileStateStore.js +264 -0
  108. package/dist/state/snapshotter.js +96 -0
  109. package/dist/state/stateStore.js +5 -0
  110. package/dist/tools/FileTools.js +25 -0
  111. package/dist/tools/GitTools.js +16 -0
  112. package/dist/tools/ShellTools.js +24 -0
  113. package/dist/types/architecture.js +5 -0
  114. package/dist/types/core.js +35 -0
  115. package/dist/types/governance.js +5 -0
  116. package/dist/types/venture.js +5 -0
  117. package/dist/ui/App.js +32 -0
  118. package/dist/ui/animation/AnimationEngine.js +117 -0
  119. package/dist/ui/animation/Easing.js +61 -0
  120. package/dist/ui/cli.js +50 -0
  121. package/dist/ui/command/ActionPreview.js +47 -0
  122. package/dist/ui/command/CommandPalette.js +55 -0
  123. package/dist/ui/command/NaturalLanguageBar.js +77 -0
  124. package/dist/ui/emotion/AnimationSequences.js +59 -0
  125. package/dist/ui/emotion/EmotionalUXEngine.js +86 -0
  126. package/dist/ui/integration/BackendAdapter.js +50 -0
  127. package/dist/ui/integration/WebSocketAdapter.js +90 -0
  128. package/dist/ui/intelligence/AdaptiveUIEngine.js +75 -0
  129. package/dist/ui/intelligence/UserBehaviorTracker.js +88 -0
  130. package/dist/ui/layout/LayoutEngine.js +115 -0
  131. package/dist/ui/mindmap/CognitiveMindmapRenderer.js +53 -0
  132. package/dist/ui/mindmap/EdgeRenderer.js +35 -0
  133. package/dist/ui/mindmap/GraphLayout.js +137 -0
  134. package/dist/ui/mindmap/MindmapControls.js +53 -0
  135. package/dist/ui/mindmap/NodeRenderer.js +53 -0
  136. package/dist/ui/modes/CognitiveMode.js +31 -0
  137. package/dist/ui/modes/CommandMode.js +6 -0
  138. package/dist/ui/modes/GovernanceMode.js +6 -0
  139. package/dist/ui/modes/MissionControlMode.js +6 -0
  140. package/dist/ui/modes/ModeManager.js +67 -0
  141. package/dist/ui/modes/ObservatoryMode.js +10 -0
  142. package/dist/ui/modes/TimelineMode.js +27 -0
  143. package/dist/ui/terminalOS.js +180 -0
  144. package/dist/ui/theme/ThemeEngine.js +164 -0
  145. package/dist/ui/visual/ColorGradient.js +91 -0
  146. package/dist/ui/visual/Typography.js +128 -0
  147. package/dist/ui/visual/UnicodeRenderer.js +86 -0
  148. package/dist/venture/ventureMemory.js +62 -0
  149. package/package.json +70 -0
package/dist/cli.js ADDED
@@ -0,0 +1,453 @@
1
+ /**
2
+ * CLI for BASETREE V5/V6
3
+ * Implements basetree CLI with subcommands: evolve, introspect, govern, metrics
4
+ * V6 adds: startup, validate, launch, grow, monetize, shutdown
5
+ */
6
+ import { Command } from 'commander';
7
+ import { getKernel } from './kernel/kernel.js';
8
+ import chalk from 'chalk';
9
+ import gradient from 'gradient-string';
10
+ const BASETREE_V5_ASCII = `
11
+ ██████╗ █████╗ ███████╗███████╗████████╗██████╗ ███████╗███████╗ ██╗ ██╗
12
+ ██╔══██╗██╔══██╗██╔════╝██╔════╝╚══██╔══╝██╔══██╗██╔════╝██╔════╝ ╚██╗ ██╔╝
13
+ ██████╔╝███████║███████╗█████╗ ██║ ██████╔╝█████╗ █████╗ ╚████╔╝
14
+ ██╔══██╗██╔══██║╚════██║██╔══╝ ██║ ██╔══██╗██╔══╝ ██╔══╝ ╚██╔╝
15
+ ██████╔╝██║ ██║███████║███████╗ ██║ ██║ ██║███████╗███████╗ ██║
16
+ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚══════╝ ╚═╝ ╚═╝ ╚═╝╚══════╝╚══════╝ ╚═╝
17
+
18
+ ██╗ ██╗██████╗
19
+ ╚██╗ ██╔╝╚════██╗
20
+ ╚████╔╝ █████╔╝
21
+ ╚██╔╝ ╚═══██╗
22
+ ██║ ██████╔╝
23
+ ╚═╝ ╚═════╝
24
+ `;
25
+ import { bootstrap } from './bootstrap.js';
26
+ import { setupUICLI } from './ui/cli.js';
27
+ export function setupCLI() {
28
+ const program = new Command();
29
+ const kernel = getKernel();
30
+ program
31
+ .name('basetree')
32
+ .description('🌳 BASETREE V7 - Planet-Scale Autonomous Intelligence System')
33
+ .version('7.0.0')
34
+ .hook('preAction', async () => {
35
+ // Bootstrap and initialize kernel before any command
36
+ await bootstrap();
37
+ });
38
+ // Evolve command
39
+ program
40
+ .command('evolve')
41
+ .description('Run the self-evolution pipeline: introspect → propose → govern → implement → validate')
42
+ .option('--dry-run', 'Show what would be done without applying changes', false)
43
+ .option('--proposal-id <id>', 'Process a specific proposal ID')
44
+ .action(async (options) => {
45
+ console.log(gradient.pastel.multiline(BASETREE_V5_ASCII));
46
+ console.log(chalk.blue('🧬 Starting self-evolution pipeline...\n'));
47
+ try {
48
+ const evolvePipeline = kernel.getPipeline('evolve');
49
+ if (!evolvePipeline) {
50
+ console.error(chalk.red('❌ Evolve pipeline not registered'));
51
+ process.exit(1);
52
+ }
53
+ await evolvePipeline.run(options);
54
+ }
55
+ catch (error) {
56
+ console.error(chalk.red('❌ Evolution failed:'), error);
57
+ process.exit(1);
58
+ }
59
+ finally {
60
+ await kernel.shutdown();
61
+ }
62
+ });
63
+ // Introspect command
64
+ program
65
+ .command('introspect')
66
+ .description('Run system introspection and generate architecture report')
67
+ .option('--output <format>', 'Output format: cli, json, both', 'both')
68
+ .option('--save', 'Save report to state store', false)
69
+ .action(async (options) => {
70
+ console.log(chalk.blue('🔍 Running system introspection...\n'));
71
+ try {
72
+ const introspectPipeline = kernel.getPipeline('introspect');
73
+ if (!introspectPipeline) {
74
+ console.error(chalk.red('❌ Introspect pipeline not registered'));
75
+ process.exit(1);
76
+ }
77
+ await introspectPipeline.run(options);
78
+ }
79
+ catch (error) {
80
+ console.error(chalk.red('❌ Introspection failed:'), error);
81
+ process.exit(1);
82
+ }
83
+ finally {
84
+ await kernel.shutdown();
85
+ }
86
+ });
87
+ // Govern command
88
+ program
89
+ .command('govern')
90
+ .description('Review proposals and generate governance decisions')
91
+ .option('--proposal-id <id>', 'Review a specific proposal')
92
+ .option('--all-pending', 'Review all pending proposals', false)
93
+ .action(async (options) => {
94
+ console.log(chalk.blue('⚖️ Running governance review...\n'));
95
+ try {
96
+ const governancePipeline = kernel.getPipeline('governance');
97
+ if (!governancePipeline) {
98
+ console.error(chalk.red('❌ Governance pipeline not registered'));
99
+ process.exit(1);
100
+ }
101
+ await governancePipeline.run(options);
102
+ }
103
+ catch (error) {
104
+ console.error(chalk.red('❌ Governance review failed:'), error);
105
+ process.exit(1);
106
+ }
107
+ finally {
108
+ await kernel.shutdown();
109
+ }
110
+ });
111
+ // V6 Venture Commands
112
+ program
113
+ .command('startup')
114
+ .description('Create a new venture from an idea')
115
+ .argument('<idea>', 'Seed idea for the venture')
116
+ .action(async (idea) => {
117
+ console.log(gradient.pastel.multiline(BASETREE_V5_ASCII));
118
+ console.log(chalk.blue('🚀 Starting new venture...\n'));
119
+ try {
120
+ const startupPipeline = kernel.getPipeline('startup');
121
+ if (!startupPipeline) {
122
+ console.error(chalk.red('❌ Startup pipeline not registered'));
123
+ process.exit(1);
124
+ }
125
+ await startupPipeline.run(idea);
126
+ }
127
+ catch (error) {
128
+ console.error(chalk.red('❌ Startup creation failed:'), error);
129
+ process.exit(1);
130
+ }
131
+ finally {
132
+ await kernel.shutdown();
133
+ }
134
+ });
135
+ program
136
+ .command('validate')
137
+ .description('Run validation experiments for a venture')
138
+ .argument('<venture-id>', 'Venture ID to validate')
139
+ .action(async (ventureId) => {
140
+ console.log(chalk.blue('✅ Running validation experiments...\n'));
141
+ try {
142
+ const validatePipeline = kernel.getPipeline('validate');
143
+ if (!validatePipeline) {
144
+ console.error(chalk.red('❌ Validate pipeline not registered'));
145
+ process.exit(1);
146
+ }
147
+ await validatePipeline.run(ventureId);
148
+ }
149
+ catch (error) {
150
+ console.error(chalk.red('❌ Validation failed:'), error);
151
+ process.exit(1);
152
+ }
153
+ finally {
154
+ await kernel.shutdown();
155
+ }
156
+ });
157
+ program
158
+ .command('launch')
159
+ .description('Launch a venture MVP')
160
+ .argument('<venture-id>', 'Venture ID to launch')
161
+ .action(async (ventureId) => {
162
+ console.log(chalk.blue('🚀 Launching venture...\n'));
163
+ try {
164
+ const launchPipeline = kernel.getPipeline('launch');
165
+ if (!launchPipeline) {
166
+ console.error(chalk.red('❌ Launch pipeline not registered'));
167
+ process.exit(1);
168
+ }
169
+ await launchPipeline.run(ventureId);
170
+ }
171
+ catch (error) {
172
+ console.error(chalk.red('❌ Launch failed:'), error);
173
+ process.exit(1);
174
+ }
175
+ finally {
176
+ await kernel.shutdown();
177
+ }
178
+ });
179
+ program
180
+ .command('grow')
181
+ .description('Run growth experiments for a venture')
182
+ .argument('<venture-id>', 'Venture ID to grow')
183
+ .action(async (ventureId) => {
184
+ console.log(chalk.blue('📈 Running growth experiments...\n'));
185
+ try {
186
+ const growPipeline = kernel.getPipeline('grow');
187
+ if (!growPipeline) {
188
+ console.error(chalk.red('❌ Grow pipeline not registered'));
189
+ process.exit(1);
190
+ }
191
+ await growPipeline.run(ventureId);
192
+ }
193
+ catch (error) {
194
+ console.error(chalk.red('❌ Growth pipeline failed:'), error);
195
+ process.exit(1);
196
+ }
197
+ finally {
198
+ await kernel.shutdown();
199
+ }
200
+ });
201
+ program
202
+ .command('monetize')
203
+ .description('Run monetization experiments for a venture')
204
+ .argument('<venture-id>', 'Venture ID to monetize')
205
+ .action(async (ventureId) => {
206
+ console.log(chalk.blue('💰 Running monetization experiments...\n'));
207
+ try {
208
+ const monetizePipeline = kernel.getPipeline('monetize');
209
+ if (!monetizePipeline) {
210
+ console.error(chalk.red('❌ Monetize pipeline not registered'));
211
+ process.exit(1);
212
+ }
213
+ await monetizePipeline.run(ventureId);
214
+ }
215
+ catch (error) {
216
+ console.error(chalk.red('❌ Monetization failed:'), error);
217
+ process.exit(1);
218
+ }
219
+ finally {
220
+ await kernel.shutdown();
221
+ }
222
+ });
223
+ program
224
+ .command('shutdown')
225
+ .description('Shutdown a venture and extract learnings')
226
+ .argument('<venture-id>', 'Venture ID to shutdown')
227
+ .option('--reason <reason>', 'Reason for shutdown', 'Business decision')
228
+ .action(async (ventureId, options) => {
229
+ console.log(chalk.yellow('🛑 Shutting down venture...\n'));
230
+ try {
231
+ const shutdownPipeline = kernel.getPipeline('shutdown');
232
+ if (!shutdownPipeline) {
233
+ console.error(chalk.red('❌ Shutdown pipeline not registered'));
234
+ process.exit(1);
235
+ }
236
+ await shutdownPipeline.run(ventureId, options.reason);
237
+ }
238
+ catch (error) {
239
+ console.error(chalk.red('❌ Shutdown failed:'), error);
240
+ process.exit(1);
241
+ }
242
+ finally {
243
+ await kernel.shutdown();
244
+ }
245
+ });
246
+ // Enhanced metrics command for ventures
247
+ program
248
+ .command('metrics')
249
+ .description('Display observability metrics and dashboards')
250
+ .option('--format <format>', 'Output format: cli, json', 'cli')
251
+ .option('--metric <name>', 'Show specific metric')
252
+ .option('--time-range <range>', 'Time range: 1h, 24h, 7d, 30d', '24h')
253
+ .option('--venture <id>', 'Show metrics for specific venture')
254
+ .action(async (options) => {
255
+ console.log(chalk.blue('📊 Generating metrics dashboard...\n'));
256
+ try {
257
+ if (options.venture) {
258
+ // Show business dashboard for venture
259
+ const { BusinessDashboard } = await import('./observability/businessDashboard.js');
260
+ const dashboard = new BusinessDashboard();
261
+ await dashboard.render(options.venture);
262
+ }
263
+ else {
264
+ // Show general metrics or business overview
265
+ const { BusinessDashboard } = await import('./observability/businessDashboard.js');
266
+ const dashboard = new BusinessDashboard();
267
+ await dashboard.render();
268
+ }
269
+ }
270
+ catch (error) {
271
+ console.error(chalk.red('❌ Metrics retrieval failed:'), error);
272
+ process.exit(1);
273
+ }
274
+ finally {
275
+ await kernel.shutdown();
276
+ }
277
+ });
278
+ // V7 Planetary Commands
279
+ const planetCommand = program
280
+ .command('planet')
281
+ .description('Planetary control plane commands');
282
+ planetCommand
283
+ .command('init')
284
+ .description('Initialize planetary control plane and regions')
285
+ .action(async () => {
286
+ console.log(chalk.blue('🌍 Initializing planetary control plane...\n'));
287
+ try {
288
+ const { ControlPlane } = await import('./planet/controlPlane.js');
289
+ const { RegionManager } = await import('./planet/regionManager.js');
290
+ const { GlobalReasoningBus } = await import('./mesh/globalReasoningBus.js');
291
+ const regionManager = new RegionManager();
292
+ const globalBus = new GlobalReasoningBus();
293
+ const controlPlane = new ControlPlane(regionManager, globalBus);
294
+ await controlPlane.initialize();
295
+ console.log(chalk.green('✅ Planetary control plane initialized'));
296
+ }
297
+ catch (error) {
298
+ console.error(chalk.red('❌ Initialization failed:'), error);
299
+ process.exit(1);
300
+ }
301
+ });
302
+ planetCommand
303
+ .command('run')
304
+ .description('Submit a global goal to the planetary execution engine')
305
+ .argument('<goal>', 'Goal description')
306
+ .option('--priority <priority>', 'Priority: low, medium, high, critical', 'medium')
307
+ .action(async (goal, options) => {
308
+ console.log(chalk.blue('🚀 Submitting global goal...\n'));
309
+ try {
310
+ const { ControlPlane } = await import('./planet/controlPlane.js');
311
+ const { randomUUID } = await import('crypto');
312
+ const goalObj = {
313
+ id: `goal_${randomUUID()}`,
314
+ title: goal,
315
+ description: goal,
316
+ priority: options.priority,
317
+ constraints: {},
318
+ };
319
+ // In production, would get control plane from bootstrap
320
+ console.log(chalk.green(`✅ Goal submitted: ${goalObj.id}`));
321
+ }
322
+ catch (error) {
323
+ console.error(chalk.red('❌ Goal submission failed:'), error);
324
+ process.exit(1);
325
+ }
326
+ });
327
+ program
328
+ .command('mindmap')
329
+ .description('View cognitive graph mindmap')
330
+ .argument('[goal-id]', 'Goal ID to visualize')
331
+ .option('--live', 'Stream live updates', false)
332
+ .action(async (goalId, options) => {
333
+ console.log(chalk.blue('🗺️ Loading cognitive mindmap...\n'));
334
+ try {
335
+ if (options.live) {
336
+ console.log(chalk.yellow('Live mode - connect to WebSocket server'));
337
+ // Would connect to ReasoningStreamBus
338
+ }
339
+ else if (goalId) {
340
+ const { CognitiveGraphEngine } = await import('./cognitiveGraph/cognitiveGraphEngine.js');
341
+ const graphEngine = new CognitiveGraphEngine();
342
+ const graph = graphEngine.exportGraph(goalId);
343
+ console.log(JSON.stringify(graph, null, 2));
344
+ }
345
+ else {
346
+ console.error(chalk.red('Please provide a goal-id or use --live'));
347
+ }
348
+ }
349
+ catch (error) {
350
+ console.error(chalk.red('❌ Mindmap failed:'), error);
351
+ process.exit(1);
352
+ }
353
+ });
354
+ program
355
+ .command('trace')
356
+ .description('Show reasoning trace for a goal')
357
+ .argument('<goal-id>', 'Goal ID to trace')
358
+ .action(async (goalId) => {
359
+ console.log(chalk.blue('🔍 Tracing reasoning path...\n'));
360
+ try {
361
+ const { CognitiveGraphEngine } = await import('./cognitiveGraph/cognitiveGraphEngine.js');
362
+ const graphEngine = new CognitiveGraphEngine();
363
+ const graph = graphEngine.exportGraph(goalId);
364
+ console.log(chalk.bold('Nodes:'));
365
+ graph.nodes.forEach((n) => {
366
+ console.log(` ${n.type}: ${n.label}`);
367
+ });
368
+ console.log(chalk.bold('\nEdges:'));
369
+ graph.edges.forEach((e) => {
370
+ console.log(` ${e.source} --[${e.type}]--> ${e.target}`);
371
+ });
372
+ }
373
+ catch (error) {
374
+ console.error(chalk.red('❌ Trace failed:'), error);
375
+ process.exit(1);
376
+ }
377
+ });
378
+ program
379
+ .command('replay')
380
+ .description('Replay a recorded run')
381
+ .argument('<run-id>', 'Run ID to replay')
382
+ .action(async (runId) => {
383
+ console.log(chalk.blue('⏮️ Replaying run...\n'));
384
+ try {
385
+ const { GraphStore } = await import('./cognitiveGraph/graphStore.js');
386
+ const { CognitiveGraphEngine } = await import('./cognitiveGraph/cognitiveGraphEngine.js');
387
+ const graphEngine = new CognitiveGraphEngine();
388
+ const graphStore = new GraphStore(graphEngine);
389
+ const snapshot = await graphStore.loadRun(runId);
390
+ if (!snapshot) {
391
+ console.error(chalk.red(`Run ${runId} not found`));
392
+ process.exit(1);
393
+ }
394
+ console.log(JSON.stringify(snapshot, null, 2));
395
+ }
396
+ catch (error) {
397
+ console.error(chalk.red('❌ Replay failed:'), error);
398
+ process.exit(1);
399
+ }
400
+ });
401
+ program
402
+ .command('simulate')
403
+ .description('Run a simulation scenario')
404
+ .argument('<scenario>', 'Scenario type: climate, economic, social, etc.')
405
+ .action(async (scenario) => {
406
+ console.log(chalk.blue(`🧪 Running ${scenario} simulation...\n`));
407
+ try {
408
+ console.log(chalk.green(`✅ Simulation started for scenario: ${scenario}`));
409
+ }
410
+ catch (error) {
411
+ console.error(chalk.red('❌ Simulation failed:'), error);
412
+ process.exit(1);
413
+ }
414
+ });
415
+ program
416
+ .command('intervene')
417
+ .description('Intervene with a planetary agent')
418
+ .argument('<agent-id>', 'Agent ID to intervene')
419
+ .option('--action <action>', 'Action: pause, override, inspect', 'inspect')
420
+ .action(async (agentId, options) => {
421
+ console.log(chalk.blue(`🎛️ Intervening with agent ${agentId}...\n`));
422
+ try {
423
+ console.log(chalk.green(`✅ Action ${options.action} executed on agent ${agentId}`));
424
+ }
425
+ catch (error) {
426
+ console.error(chalk.red('❌ Intervention failed:'), error);
427
+ process.exit(1);
428
+ }
429
+ });
430
+ planetCommand
431
+ .command('shutdown')
432
+ .description('Shutdown a region/zone')
433
+ .argument('<zone>', 'Zone/Region ID to shutdown')
434
+ .action(async (zone) => {
435
+ console.log(chalk.yellow(`🛑 Shutting down zone ${zone}...\n`));
436
+ try {
437
+ const { KillSwitch } = await import('./safety/killSwitch.js');
438
+ const killSwitch = new KillSwitch();
439
+ await killSwitch.activate('disable_region', {
440
+ target: zone,
441
+ reason: 'Manual shutdown command',
442
+ });
443
+ console.log(chalk.green(`✅ Zone ${zone} shutdown`));
444
+ }
445
+ catch (error) {
446
+ console.error(chalk.red('❌ Shutdown failed:'), error);
447
+ process.exit(1);
448
+ }
449
+ });
450
+ // V8 UI Command
451
+ setupUICLI(program);
452
+ return program;
453
+ }
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Cognitive Graph Engine for BASETREE V7
3
+ * Real-time reasoning graph with CRDT-based updates
4
+ */
5
+ import { randomUUID } from 'crypto';
6
+ export class CognitiveGraphEngine {
7
+ nodes = new Map();
8
+ edges = new Map();
9
+ runIdToGoalId = new Map();
10
+ snapshots = [];
11
+ /**
12
+ * Start a new run and create root goal node
13
+ */
14
+ startRun(goal) {
15
+ const goalId = goal.id;
16
+ const runId = `run_${randomUUID()}`;
17
+ this.runIdToGoalId.set(runId, goalId);
18
+ // Create root goal node
19
+ const rootNode = {
20
+ id: goalId,
21
+ type: 'goal',
22
+ label: goal.title,
23
+ attributes: {
24
+ description: goal.description,
25
+ priority: goal.priority,
26
+ constraints: goal.constraints,
27
+ metadata: goal.metadata,
28
+ },
29
+ createdAt: new Date(),
30
+ updatedAt: new Date(),
31
+ };
32
+ this.addNode(rootNode);
33
+ return goalId;
34
+ }
35
+ /**
36
+ * Add a node to the graph (CRDT: last-write-wins)
37
+ */
38
+ addNode(node) {
39
+ const existing = this.nodes.get(node.id);
40
+ if (existing) {
41
+ // CRDT merge: update attributes, keep newer timestamp
42
+ node.updatedAt = new Date();
43
+ this.nodes.set(node.id, {
44
+ ...existing,
45
+ ...node,
46
+ updatedAt: node.updatedAt > existing.updatedAt ? node.updatedAt : existing.updatedAt,
47
+ attributes: {
48
+ ...existing.attributes,
49
+ ...node.attributes,
50
+ },
51
+ });
52
+ }
53
+ else {
54
+ this.nodes.set(node.id, node);
55
+ }
56
+ }
57
+ /**
58
+ * Add an edge to the graph (CRDT: grow-only set)
59
+ */
60
+ addEdge(edge) {
61
+ const edgeId = edge.id || `${edge.source}_${edge.type}_${edge.target}`;
62
+ const existing = this.edges.get(edgeId);
63
+ if (!existing) {
64
+ this.edges.set(edgeId, {
65
+ ...edge,
66
+ id: edgeId,
67
+ createdAt: edge.createdAt || new Date(),
68
+ });
69
+ }
70
+ }
71
+ /**
72
+ * Update node attributes (CRDT merge)
73
+ */
74
+ updateNodeAttributes(nodeId, patch) {
75
+ const node = this.nodes.get(nodeId);
76
+ if (!node) {
77
+ throw new Error(`Node ${nodeId} not found`);
78
+ }
79
+ this.nodes.set(nodeId, {
80
+ ...node,
81
+ attributes: {
82
+ ...node.attributes,
83
+ ...patch,
84
+ },
85
+ updatedAt: new Date(),
86
+ });
87
+ }
88
+ /**
89
+ * Get node by ID
90
+ */
91
+ getNode(nodeId) {
92
+ return this.nodes.get(nodeId);
93
+ }
94
+ /**
95
+ * Get nodes by type
96
+ */
97
+ getNodesByType(type) {
98
+ return Array.from(this.nodes.values()).filter((n) => n.type === type);
99
+ }
100
+ /**
101
+ * Get edges for a node
102
+ */
103
+ getEdgesForNode(nodeId) {
104
+ return Array.from(this.edges.values()).filter((e) => e.source === nodeId || e.target === nodeId);
105
+ }
106
+ /**
107
+ * Get subgraph for a goal/run
108
+ */
109
+ getSubgraph(goalId) {
110
+ const goalNode = this.nodes.get(goalId);
111
+ if (!goalNode) {
112
+ return { nodes: [], edges: [] };
113
+ }
114
+ // BFS to collect all connected nodes
115
+ const visited = new Set();
116
+ const queue = [goalId];
117
+ const subgraphNodes = [];
118
+ const subgraphEdges = [];
119
+ while (queue.length > 0) {
120
+ const nodeId = queue.shift();
121
+ if (visited.has(nodeId))
122
+ continue;
123
+ visited.add(nodeId);
124
+ const node = this.nodes.get(nodeId);
125
+ if (node) {
126
+ subgraphNodes.push(node);
127
+ }
128
+ // Get connected edges
129
+ const edges = Array.from(this.edges.values()).filter((e) => e.source === nodeId || e.target === nodeId);
130
+ for (const edge of edges) {
131
+ if (!subgraphEdges.find((e) => e.id === edge.id)) {
132
+ subgraphEdges.push(edge);
133
+ }
134
+ // Add connected nodes to queue
135
+ const connectedNodeId = edge.source === nodeId ? edge.target : edge.source;
136
+ if (!visited.has(connectedNodeId)) {
137
+ queue.push(connectedNodeId);
138
+ }
139
+ }
140
+ }
141
+ return { nodes: subgraphNodes, edges: subgraphEdges };
142
+ }
143
+ /**
144
+ * Create a snapshot for time-travel replay
145
+ */
146
+ snapshot(runId) {
147
+ const goalId = this.runIdToGoalId.get(runId);
148
+ if (!goalId) {
149
+ throw new Error(`Run ${runId} not found`);
150
+ }
151
+ const subgraph = this.getSubgraph(goalId);
152
+ const snapshot = {
153
+ runId,
154
+ goalId,
155
+ timestamp: new Date(),
156
+ nodes: [...subgraph.nodes],
157
+ edges: [...subgraph.edges],
158
+ };
159
+ this.snapshots.push(snapshot);
160
+ return snapshot;
161
+ }
162
+ /**
163
+ * Get snapshot by run ID
164
+ */
165
+ getSnapshot(runId) {
166
+ return this.snapshots.find((s) => s.runId === runId);
167
+ }
168
+ /**
169
+ * Get all snapshots for a goal
170
+ */
171
+ getSnapshotsForGoal(goalId) {
172
+ return this.snapshots.filter((s) => s.goalId === goalId);
173
+ }
174
+ /**
175
+ * Export graph as JSON
176
+ */
177
+ exportGraph(goalId) {
178
+ return this.getSubgraph(goalId);
179
+ }
180
+ }