@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
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Report Renderer for BASETREE V5
3
+ * Renders human-readable reports (CLI tables, JSON, optionally web-friendly JSON)
4
+ */
5
+ import chalk from 'chalk';
6
+ export class ReportRenderer {
7
+ /**
8
+ * Render introspection report
9
+ */
10
+ renderIntrospection(report, format = 'both') {
11
+ if (format === 'json' || format === 'both') {
12
+ console.log(JSON.stringify(report, null, 2));
13
+ }
14
+ if (format === 'cli' || format === 'both') {
15
+ console.log(chalk.blue('\n📊 Introspection Report\n'));
16
+ console.log(`Modules: ${report.metrics.totalModules}`);
17
+ console.log(`LOC: ${report.metrics.totalLinesOfCode}`);
18
+ console.log(`Avg Complexity: ${report.metrics.averageComplexity.toFixed(2)}`);
19
+ console.log(`Bottlenecks: ${report.bottlenecks.length}`);
20
+ console.log(`Proposals: ${report.upgradeProposals.length}\n`);
21
+ }
22
+ }
23
+ /**
24
+ * Render cognitive metrics
25
+ */
26
+ renderCognitiveMetrics(drift, entropy, velocity, format = 'both') {
27
+ if (format === 'json' || format === 'both') {
28
+ console.log(JSON.stringify({
29
+ drift,
30
+ entropy,
31
+ velocity,
32
+ }, null, 2));
33
+ }
34
+ if (format === 'cli' || format === 'both') {
35
+ console.log(chalk.blue('\n🧠 Cognitive Metrics\n'));
36
+ console.log(chalk.yellow('Cognitive Drift:'));
37
+ console.log(` Score: ${(drift.driftScore * 100).toFixed(1)}%`);
38
+ console.log(` Complexity Change: ${(drift.factors.complexityChange * 100).toFixed(1)}%`);
39
+ console.log(` Coupling Change: ${(drift.factors.couplingChange * 100).toFixed(1)}%\n`);
40
+ console.log(chalk.yellow('Architectural Entropy:'));
41
+ console.log(` Entropy: ${entropy.entropy.toFixed(2)}`);
42
+ console.log(` Normalized: ${(entropy.normalizedEntropy * 100).toFixed(1)}%`);
43
+ console.log(` Dependency Complexity: ${(entropy.factors.dependencyComplexity * 100).toFixed(1)}%\n`);
44
+ console.log(chalk.yellow('Learning Velocity:'));
45
+ console.log(` Velocity: ${velocity.velocity.toFixed(2)} improvements/day`);
46
+ console.log(` Trend: ${velocity.trend}`);
47
+ console.log(` Success Rate: ${(velocity.metrics.successRate * 100).toFixed(1)}%\n`);
48
+ }
49
+ }
50
+ /**
51
+ * Render failure surface
52
+ */
53
+ renderFailureSurface(surface, format = 'both') {
54
+ if (format === 'json' || format === 'both') {
55
+ console.log(JSON.stringify(surface, null, 2));
56
+ }
57
+ if (format === 'cli' || format === 'both') {
58
+ console.log(chalk.blue('\n🛡️ Failure Surface Map\n'));
59
+ if (surface.hotspots.length > 0) {
60
+ console.log(chalk.yellow('Hotspots:'));
61
+ for (const hotspot of surface.hotspots.slice(0, 5)) {
62
+ console.log(` ${hotspot.location}: ${hotspot.failureCount} failures (risk: ${(hotspot.riskScore * 100).toFixed(0)}%)`);
63
+ }
64
+ console.log('');
65
+ }
66
+ if (surface.patterns.length > 0) {
67
+ console.log(chalk.yellow('Common Patterns:'));
68
+ for (const pattern of surface.patterns.slice(0, 5)) {
69
+ console.log(` ${pattern.pattern}: ${pattern.frequency} occurrences`);
70
+ }
71
+ console.log('');
72
+ }
73
+ }
74
+ }
75
+ /**
76
+ * Render metrics dashboard
77
+ */
78
+ renderMetrics(metrics, format = 'both') {
79
+ if (format === 'json' || format === 'both') {
80
+ console.log(JSON.stringify(metrics, null, 2));
81
+ }
82
+ if (format === 'cli' || format === 'both') {
83
+ console.log(chalk.blue('\n📈 Metrics Dashboard\n'));
84
+ // Group by name
85
+ const grouped = new Map();
86
+ for (const metric of metrics) {
87
+ if (!grouped.has(metric.name)) {
88
+ grouped.set(metric.name, []);
89
+ }
90
+ grouped.get(metric.name).push(metric);
91
+ }
92
+ for (const [name, values] of grouped.entries()) {
93
+ const avg = values.reduce((sum, m) => sum + m.value, 0) / values.length;
94
+ const unit = values[0].unit || '';
95
+ console.log(`${name}: ${avg.toFixed(2)} ${unit} (${values.length} samples)`);
96
+ }
97
+ console.log('');
98
+ }
99
+ }
100
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Memory Profiler for BASETREE V5
3
+ * Tracks memory usage, leaks, and high-allocation paths
4
+ */
5
+ import { performance } from 'perf_hooks';
6
+ export class MemoryProfiler {
7
+ snapshots = [];
8
+ intervalId = null;
9
+ maxSnapshots = 1000;
10
+ /**
11
+ * Take a memory snapshot
12
+ */
13
+ snapshot() {
14
+ const memUsage = process.memoryUsage();
15
+ const snapshot = {
16
+ timestamp: performance.now(),
17
+ heapUsed: memUsage.heapUsed,
18
+ heapTotal: memUsage.heapTotal,
19
+ external: memUsage.external,
20
+ rss: memUsage.rss,
21
+ };
22
+ this.snapshots.push(snapshot);
23
+ if (this.snapshots.length > this.maxSnapshots) {
24
+ this.snapshots.shift();
25
+ }
26
+ return snapshot;
27
+ }
28
+ /**
29
+ * Start continuous monitoring
30
+ */
31
+ startMonitoring(intervalMs = 1000) {
32
+ if (this.intervalId) {
33
+ this.stopMonitoring();
34
+ }
35
+ this.intervalId = setInterval(() => {
36
+ this.snapshot();
37
+ }, intervalMs);
38
+ }
39
+ /**
40
+ * Stop continuous monitoring
41
+ */
42
+ stopMonitoring() {
43
+ if (this.intervalId) {
44
+ clearInterval(this.intervalId);
45
+ this.intervalId = null;
46
+ }
47
+ }
48
+ /**
49
+ * Get current memory usage
50
+ */
51
+ getCurrentMemory() {
52
+ return this.snapshot();
53
+ }
54
+ /**
55
+ * Detect potential memory leaks
56
+ */
57
+ detectLeaks(thresholdBytesPerSecond = 1024 * 1024) {
58
+ if (this.snapshots.length < 2) {
59
+ return {
60
+ detected: false,
61
+ growthRate: 0,
62
+ threshold: thresholdBytesPerSecond,
63
+ snapshots: [],
64
+ };
65
+ }
66
+ const recent = this.snapshots.slice(-10); // Last 10 snapshots
67
+ const first = recent[0];
68
+ const last = recent[recent.length - 1];
69
+ const timeDelta = (last.timestamp - first.timestamp) / 1000; // seconds
70
+ const memoryDelta = last.heapUsed - first.heapUsed;
71
+ const growthRate = timeDelta > 0 ? memoryDelta / timeDelta : 0;
72
+ return {
73
+ detected: growthRate > thresholdBytesPerSecond,
74
+ growthRate,
75
+ threshold: thresholdBytesPerSecond,
76
+ snapshots: recent,
77
+ };
78
+ }
79
+ /**
80
+ * Get memory statistics
81
+ */
82
+ getStatistics() {
83
+ const current = this.getCurrentMemory();
84
+ const peak = this.snapshots.reduce((max, snap) => (snap.heapUsed > max.heapUsed ? snap : max), this.snapshots[0] || current);
85
+ const averages = this.snapshots.reduce((acc, snap) => ({
86
+ heapUsed: acc.heapUsed + snap.heapUsed,
87
+ heapTotal: acc.heapTotal + snap.heapTotal,
88
+ rss: acc.rss + snap.rss,
89
+ }), { heapUsed: 0, heapTotal: 0, rss: 0 });
90
+ const count = this.snapshots.length || 1;
91
+ return {
92
+ current,
93
+ peak: this.snapshots.length > 0 ? peak : null,
94
+ average: {
95
+ heapUsed: averages.heapUsed / count,
96
+ heapTotal: averages.heapTotal / count,
97
+ rss: averages.rss / count,
98
+ },
99
+ };
100
+ }
101
+ /**
102
+ * Clear snapshots
103
+ */
104
+ clear() {
105
+ this.snapshots = [];
106
+ }
107
+ }
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Performance Profiler for BASETREE V5
3
+ * Hooks into Node performance APIs to measure runtime hotspots
4
+ */
5
+ import { performance, PerformanceObserver } from 'perf_hooks';
6
+ export class Profiler {
7
+ measurements = new Map();
8
+ observer = null;
9
+ constructor() {
10
+ this.setupObserver();
11
+ }
12
+ setupObserver() {
13
+ this.observer = new PerformanceObserver((list) => {
14
+ for (const entry of list.getEntries()) {
15
+ const name = entry.name;
16
+ const duration = entry.duration;
17
+ const startTime = entry.startTime;
18
+ if (!this.measurements.has(name)) {
19
+ this.measurements.set(name, []);
20
+ }
21
+ this.measurements.get(name).push({
22
+ name,
23
+ duration,
24
+ startTime,
25
+ endTime: startTime + duration,
26
+ });
27
+ }
28
+ });
29
+ this.observer.observe({ entryTypes: ['measure', 'function'] });
30
+ }
31
+ /**
32
+ * Start a performance mark
33
+ */
34
+ mark(name) {
35
+ performance.mark(`${name}-start`);
36
+ }
37
+ /**
38
+ * End a performance mark and measure
39
+ */
40
+ measure(name, details) {
41
+ const startMark = `${name}-start`;
42
+ const endMark = `${name}-end`;
43
+ performance.mark(endMark);
44
+ performance.measure(name, startMark, endMark);
45
+ const entries = performance.getEntriesByName(name, 'measure');
46
+ const entry = entries[entries.length - 1];
47
+ const measurement = {
48
+ name,
49
+ duration: entry.duration,
50
+ startTime: entry.startTime,
51
+ endTime: entry.startTime + entry.duration,
52
+ details,
53
+ };
54
+ if (!this.measurements.has(name)) {
55
+ this.measurements.set(name, []);
56
+ }
57
+ this.measurements.get(name).push(measurement);
58
+ // Cleanup marks
59
+ performance.clearMarks(startMark);
60
+ performance.clearMarks(endMark);
61
+ performance.clearMeasures(name);
62
+ return measurement;
63
+ }
64
+ /**
65
+ * Measure async function execution
66
+ */
67
+ async measureAsync(name, fn, details) {
68
+ this.mark(name);
69
+ try {
70
+ const result = await fn();
71
+ this.measure(name, details);
72
+ return result;
73
+ }
74
+ catch (error) {
75
+ this.measure(name, { ...details, error: String(error) });
76
+ throw error;
77
+ }
78
+ }
79
+ /**
80
+ * Get measurements for a specific name
81
+ */
82
+ getMeasurements(name) {
83
+ return this.measurements.get(name) || [];
84
+ }
85
+ /**
86
+ * Get all measurements
87
+ */
88
+ getAllMeasurements() {
89
+ return new Map(this.measurements);
90
+ }
91
+ /**
92
+ * Get statistics for a measurement name
93
+ */
94
+ getStatistics(name) {
95
+ const measurements = this.getMeasurements(name);
96
+ if (measurements.length === 0) {
97
+ return null;
98
+ }
99
+ const durations = measurements.map((m) => m.duration);
100
+ const total = durations.reduce((sum, d) => sum + d, 0);
101
+ const average = total / durations.length;
102
+ const min = Math.min(...durations);
103
+ const max = Math.max(...durations);
104
+ return {
105
+ count: measurements.length,
106
+ total,
107
+ average,
108
+ min,
109
+ max,
110
+ };
111
+ }
112
+ /**
113
+ * Clear all measurements
114
+ */
115
+ clear() {
116
+ this.measurements.clear();
117
+ performance.clearMarks();
118
+ performance.clearMeasures();
119
+ }
120
+ /**
121
+ * Cleanup
122
+ */
123
+ destroy() {
124
+ if (this.observer) {
125
+ this.observer.disconnect();
126
+ this.observer = null;
127
+ }
128
+ this.clear();
129
+ }
130
+ }
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Evolve Pipeline for BASETREE V5
3
+ * Orchestrates the full self-evolution cycle
4
+ */
5
+ import { getKernel } from '../kernel/kernel.js';
6
+ import { SystemIntrospectionAgent } from '../agents/systemIntrospectionAgent.js';
7
+ import { UpgradePlannerAgent } from '../agents/upgradePlannerAgent.js';
8
+ import { GovernanceOrchestrator } from '../agents/governanceOrchestrator.js';
9
+ import { UpgradeExecutorAgent } from '../agents/upgradeExecutorAgent.js';
10
+ import { RegressionAgent } from '../agents/regressionAgent.js';
11
+ import { RollbackAgent } from '../agents/rollbackAgent.js';
12
+ import { Snapshotter } from '../state/snapshotter.js';
13
+ import { Sandbox } from '../safety/sandbox.js';
14
+ import { MetricsCollector } from '../observability/metricsCollector.js';
15
+ import { getConfig } from '../config/config.js';
16
+ import chalk from 'chalk';
17
+ import ora from 'ora';
18
+ export class EvolvePipeline {
19
+ kernel = getKernel();
20
+ config = getConfig();
21
+ introspectionAgent = new SystemIntrospectionAgent();
22
+ plannerAgent = new UpgradePlannerAgent();
23
+ governanceOrchestrator = new GovernanceOrchestrator();
24
+ executorAgent = new UpgradeExecutorAgent();
25
+ regressionAgent = new RegressionAgent();
26
+ rollbackAgent = new RollbackAgent();
27
+ snapshotter = new Snapshotter();
28
+ metricsCollector = new MetricsCollector();
29
+ async run(options = {}) {
30
+ const startTime = Date.now();
31
+ try {
32
+ // Step 1: Snapshot current system state
33
+ const snapshotSpinner = ora('Creating system snapshot...').start();
34
+ const baselineSnapshot = await this.snapshotter.createSnapshot();
35
+ snapshotSpinner.succeed('System snapshot created');
36
+ // Step 2: Run System Introspection Agent
37
+ const introspectSpinner = ora('Running system introspection...').start();
38
+ const introspectionReport = await this.introspectionAgent.introspect();
39
+ introspectSpinner.succeed(`Introspection complete: ${introspectionReport.bottlenecks.length} bottlenecks found`);
40
+ // Step 3: Generate upgrade proposals
41
+ const planSpinner = ora('Generating upgrade proposals...').start();
42
+ let proposals = await this.plannerAgent.planUpgrades(introspectionReport);
43
+ planSpinner.succeed(`Generated ${proposals.length} upgrade proposal(s)`);
44
+ // Filter by proposalId if specified
45
+ if (options.proposalId) {
46
+ proposals = proposals.filter((p) => p.id === options.proposalId);
47
+ if (proposals.length === 0) {
48
+ console.error(chalk.red(`Proposal ${options.proposalId} not found`));
49
+ return;
50
+ }
51
+ }
52
+ if (proposals.length === 0) {
53
+ console.log(chalk.yellow('No upgrade proposals generated'));
54
+ return;
55
+ }
56
+ // Step 4: Governance review for each proposal
57
+ const approvedProposals = [];
58
+ for (const proposal of proposals) {
59
+ const governSpinner = ora(`Evaluating proposal: ${proposal.title}...`).start();
60
+ const verdict = await this.governanceOrchestrator.evaluate(proposal);
61
+ // Save proposal with governance decision
62
+ await this.kernel.getStateStore().saveProposal({
63
+ ...proposal,
64
+ governanceDecision: verdict.decision,
65
+ governanceRationale: verdict.rationale,
66
+ });
67
+ if (verdict.decision === 'approve') {
68
+ governSpinner.succeed(`Proposal approved: ${proposal.title}`);
69
+ approvedProposals.push(proposal);
70
+ }
71
+ else {
72
+ governSpinner.fail(`Proposal ${verdict.decision}: ${proposal.title} - ${verdict.rationale}`);
73
+ }
74
+ }
75
+ if (approvedProposals.length === 0) {
76
+ console.log(chalk.yellow('No proposals approved by governance'));
77
+ return;
78
+ }
79
+ if (options.dryRun) {
80
+ console.log(chalk.blue('\n🔍 DRY RUN MODE - No changes will be applied\n'));
81
+ for (const proposal of approvedProposals) {
82
+ console.log(chalk.green(`Would apply: ${proposal.title}`));
83
+ console.log(` Changes: ${proposal.changes.length} file(s)`);
84
+ }
85
+ return;
86
+ }
87
+ // Step 5: Execute approved proposals in sandbox
88
+ for (const proposal of approvedProposals) {
89
+ const sandbox = new Sandbox();
90
+ try {
91
+ const sandboxSpinner = ora('Creating sandbox...').start();
92
+ const sandboxPath = await sandbox.create();
93
+ sandboxSpinner.succeed('Sandbox created');
94
+ // Execute upgrade
95
+ const execSpinner = ora(`Applying upgrade: ${proposal.title}...`).start();
96
+ const execResult = await this.executorAgent.execute(proposal, sandboxPath);
97
+ if (execResult.success) {
98
+ execSpinner.succeed(`Upgrade applied: ${execResult.changesApplied} change(s)`);
99
+ }
100
+ else {
101
+ execSpinner.fail(`Upgrade failed: ${execResult.errors.join('; ')}`);
102
+ await sandbox.cleanupOnFailure();
103
+ continue;
104
+ }
105
+ // Step 6: Run regression tests
106
+ const regressionSpinner = ora('Running regression tests...').start();
107
+ const regressionResult = await this.regressionAgent.runRegression(sandboxPath, baselineSnapshot);
108
+ if (!regressionResult.passed) {
109
+ regressionSpinner.fail('Regression tests failed');
110
+ console.log(chalk.red(`Test failures: ${regressionResult.testResults.failed}`));
111
+ await sandbox.cleanupOnFailure();
112
+ continue;
113
+ }
114
+ regressionSpinner.succeed('Regression tests passed');
115
+ // Step 7: Apply upgrade to main workspace
116
+ const applySpinner = ora('Applying upgrade to main workspace...').start();
117
+ const mainResult = await this.executorAgent.execute(proposal, this.config.workspaceRoot);
118
+ if (mainResult.success) {
119
+ applySpinner.succeed('Upgrade applied successfully');
120
+ }
121
+ else {
122
+ applySpinner.fail(`Failed to apply: ${mainResult.errors.join('; ')}`);
123
+ // Trigger rollback
124
+ const rollbackPoint = this.rollbackAgent.getLatestRollbackPoint();
125
+ if (rollbackPoint) {
126
+ await this.rollbackAgent.rollback(rollbackPoint.id, 'Application to main workspace failed');
127
+ }
128
+ await sandbox.cleanupOnFailure();
129
+ continue;
130
+ }
131
+ // Cleanup sandbox
132
+ await sandbox.cleanupOnSuccess();
133
+ // Record metrics
134
+ const duration = Date.now() - startTime;
135
+ await this.metricsCollector.recordUpgradeOutcome(proposal.id, true, duration);
136
+ }
137
+ catch (error) {
138
+ console.error(chalk.red(`Error processing proposal ${proposal.id}:`), error);
139
+ await sandbox.cleanupOnFailure();
140
+ }
141
+ }
142
+ const totalDuration = Date.now() - startTime;
143
+ console.log(chalk.green(`\n✅ Evolution complete in ${totalDuration}ms`));
144
+ }
145
+ catch (error) {
146
+ console.error(chalk.red('Evolution pipeline failed:'), error);
147
+ throw error;
148
+ }
149
+ }
150
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Governance Review Pipeline for BASETREE V5
3
+ * Review queued proposals, generate governance decisions, output rationales
4
+ */
5
+ import { GovernanceOrchestrator } from '../agents/governanceOrchestrator.js';
6
+ import { getKernel } from '../kernel/kernel.js';
7
+ import chalk from 'chalk';
8
+ export class GovernanceReviewPipeline {
9
+ kernel = getKernel();
10
+ governanceOrchestrator = new GovernanceOrchestrator();
11
+ async run(options = {}) {
12
+ const stateStore = this.kernel.getStateStore();
13
+ let proposals;
14
+ if (options.proposalId) {
15
+ const proposal = await stateStore.getProposal(options.proposalId);
16
+ if (!proposal) {
17
+ console.error(chalk.red(`Proposal ${options.proposalId} not found`));
18
+ return;
19
+ }
20
+ proposals = [proposal];
21
+ }
22
+ else if (options.allPending) {
23
+ proposals = await stateStore.listProposals('pending');
24
+ }
25
+ else {
26
+ // Get latest pending proposals
27
+ proposals = await stateStore.listProposals('pending', 10);
28
+ }
29
+ if (proposals.length === 0) {
30
+ console.log(chalk.yellow('No proposals to review'));
31
+ return;
32
+ }
33
+ console.log(chalk.blue(`\n⚖️ Reviewing ${proposals.length} proposal(s)\n`));
34
+ for (const proposal of proposals) {
35
+ console.log(chalk.cyan(`Proposal: ${proposal.title}`));
36
+ console.log(chalk.gray(` ID: ${proposal.id}`));
37
+ console.log(chalk.gray(` Risk Level: ${proposal.riskLevel}`));
38
+ console.log(chalk.gray(` Changes: ${proposal.changes.length} file(s)\n`));
39
+ const verdict = await this.governanceOrchestrator.evaluate(proposal);
40
+ // Update proposal
41
+ await stateStore.updateProposal(proposal.id, {
42
+ governanceDecision: verdict.decision,
43
+ governanceRationale: verdict.rationale,
44
+ });
45
+ // Display decision
46
+ const decisionColor = verdict.decision === 'approve'
47
+ ? chalk.green
48
+ : verdict.decision === 'reject'
49
+ ? chalk.red
50
+ : chalk.yellow;
51
+ console.log(decisionColor(`Decision: ${verdict.decision.toUpperCase()}`));
52
+ console.log(chalk.gray(`Rationale: ${verdict.rationale}\n`));
53
+ if (verdict.conditions && verdict.conditions.length > 0) {
54
+ console.log(chalk.yellow('Conditions:'));
55
+ for (const condition of verdict.conditions) {
56
+ console.log(` - ${condition}`);
57
+ }
58
+ console.log('');
59
+ }
60
+ // Display agent decisions
61
+ console.log(chalk.gray('Agent Evaluations:'));
62
+ console.log(` Policy: ${verdict.agentDecisions.policy.filter((e) => e.passed).length}/${verdict.agentDecisions.policy.length} passed`);
63
+ console.log(` Stability: ${(verdict.agentDecisions.stability.stabilityScore * 100).toFixed(0)}%`);
64
+ console.log(` Alignment: ${(verdict.agentDecisions.alignment.alignmentScore * 100).toFixed(0)}%`);
65
+ console.log(` Risk: ${verdict.agentDecisions.risk.riskLevel}\n`);
66
+ }
67
+ }
68
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Introspect Pipeline for BASETREE V5
3
+ * Run introspection alone and print/save report
4
+ */
5
+ import { SystemIntrospectionAgent } from '../agents/systemIntrospectionAgent.js';
6
+ import { getKernel } from '../kernel/kernel.js';
7
+ import chalk from 'chalk';
8
+ export class IntrospectPipeline {
9
+ kernel = getKernel();
10
+ introspectionAgent = new SystemIntrospectionAgent();
11
+ async run(options = {}) {
12
+ const outputFormat = options.output || 'both';
13
+ const save = options.save || false;
14
+ try {
15
+ const report = await this.introspectionAgent.introspect();
16
+ if (save) {
17
+ // Save report to state store (simplified - would need report storage)
18
+ console.log(chalk.green('Report generated'));
19
+ }
20
+ if (outputFormat === 'json' || outputFormat === 'both') {
21
+ console.log(JSON.stringify(report, null, 2));
22
+ }
23
+ if (outputFormat === 'cli' || outputFormat === 'both') {
24
+ this.renderCLIReport(report);
25
+ }
26
+ }
27
+ catch (error) {
28
+ console.error(chalk.red('Introspection failed:'), error);
29
+ throw error;
30
+ }
31
+ }
32
+ renderCLIReport(report) {
33
+ console.log(chalk.blue('\n📊 System Introspection Report\n'));
34
+ console.log(chalk.gray(`Generated: ${report.timestamp.toISOString()}\n`));
35
+ // Metrics
36
+ console.log(chalk.yellow('Metrics:'));
37
+ console.log(` Total Modules: ${report.metrics.totalModules}`);
38
+ console.log(` Total LOC: ${report.metrics.totalLinesOfCode}`);
39
+ console.log(` Avg Complexity: ${report.metrics.averageComplexity.toFixed(2)}`);
40
+ console.log(` Max Complexity: ${report.metrics.maxComplexity}`);
41
+ console.log(` Coupling Score: ${report.metrics.couplingScore.toFixed(2)}`);
42
+ console.log(` Cohesion Score: ${report.metrics.cohesionScore.toFixed(2)}\n`);
43
+ // Bottlenecks
44
+ if (report.bottlenecks.length > 0) {
45
+ console.log(chalk.yellow(`Bottlenecks (${report.bottlenecks.length}):`));
46
+ for (const bottleneck of report.bottlenecks.slice(0, 10)) {
47
+ const severityColor = bottleneck.severity === 'critical'
48
+ ? chalk.red
49
+ : bottleneck.severity === 'high'
50
+ ? chalk.yellow
51
+ : chalk.gray;
52
+ console.log(` ${severityColor(bottleneck.severity.toUpperCase())} ${bottleneck.type}: ${bottleneck.location.module}`);
53
+ console.log(` ${bottleneck.description}`);
54
+ }
55
+ if (report.bottlenecks.length > 10) {
56
+ console.log(chalk.gray(` ... and ${report.bottlenecks.length - 10} more`));
57
+ }
58
+ console.log('');
59
+ }
60
+ // Upgrade Proposals
61
+ if (report.upgradeProposals.length > 0) {
62
+ console.log(chalk.yellow(`Upgrade Proposals (${report.upgradeProposals.length}):`));
63
+ for (const proposal of report.upgradeProposals.slice(0, 5)) {
64
+ console.log(` ${proposal.title}`);
65
+ console.log(` Risk: ${proposal.riskLevel}`);
66
+ console.log(` Changes: ${proposal.changes.length} file(s)`);
67
+ }
68
+ if (report.upgradeProposals.length > 5) {
69
+ console.log(chalk.gray(` ... and ${report.upgradeProposals.length - 5} more`));
70
+ }
71
+ }
72
+ }
73
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Grow Pipeline for BASETREE V6
3
+ * Orchestrates growth experiments and optimization
4
+ */
5
+ import { getKernel } from '../../kernel/kernel.js';
6
+ import { GrowthAgent } from '../../agents/venture/growthAgent.js';
7
+ import { ExperimentationEngine } from '../../experiments/experimentationEngine.js';
8
+ import { GeminiProvider } from '../../core/ai/GeminiProvider.js';
9
+ import chalk from 'chalk';
10
+ import ora from 'ora';
11
+ export class GrowPipeline {
12
+ kernel = getKernel();
13
+ ai = new GeminiProvider();
14
+ growthAgent = new GrowthAgent(this.ai);
15
+ experimentationEngine = new ExperimentationEngine();
16
+ async run(ventureId) {
17
+ const spinner = ora(`Growing venture ${ventureId}...`).start();
18
+ try {
19
+ const venture = await this.kernel.getStateStore().getVenture(ventureId);
20
+ if (!venture) {
21
+ throw new Error(`Venture ${ventureId} not found`);
22
+ }
23
+ // Design growth strategy
24
+ spinner.text = 'Designing growth strategy...';
25
+ const growthStrategy = await this.growthAgent.designGrowthStrategy(venture);
26
+ spinner.succeed('Growth strategy designed');
27
+ // Create growth experiments
28
+ spinner.text = 'Creating growth experiments...';
29
+ const seoKeywords = growthStrategy.seo.map((s) => s.keyword);
30
+ const landingExperiment = await this.experimentationEngine.createLandingPageExperiment(venture, seoKeywords.slice(0, 3));
31
+ spinner.succeed('Growth experiments created');
32
+ // Update venture stage
33
+ await this.kernel.getStateStore().updateVenture(ventureId, {
34
+ stage: 'growing',
35
+ experimentIds: [...venture.experimentIds, landingExperiment.id],
36
+ });
37
+ spinner.succeed('Growth pipeline initiated!');
38
+ console.log(chalk.green(`\nGrowth strategy for "${venture.idea}"`));
39
+ console.log(chalk.blue(`\nSEO Keywords: ${seoKeywords.slice(0, 5).join(', ')}`));
40
+ console.log(chalk.blue(`Funnels: ${growthStrategy.funnels.length}`));
41
+ console.log(chalk.blue(`Virality mechanisms: ${growthStrategy.virality.join(', ')}`));
42
+ console.log(chalk.blue(`\nNext steps:`));
43
+ console.log(chalk.blue(`1. Monitor growth metrics`));
44
+ console.log(chalk.blue(`2. Run: basetree monetize ${ventureId}`));
45
+ }
46
+ catch (error) {
47
+ spinner.fail(`Growth pipeline failed: ${error.message}`);
48
+ throw error;
49
+ }
50
+ }
51
+ }