@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,81 @@
1
+ /**
2
+ * Graph Persistence Layer for BASETREE V7
3
+ * Persists graph snapshots and event logs
4
+ */
5
+ import { getKernel } from '../kernel/kernel.js';
6
+ import * as fs from 'fs-extra';
7
+ import * as path from 'path';
8
+ export class GraphStore {
9
+ graphEngine;
10
+ kernel = getKernel();
11
+ storageDir;
12
+ constructor(graphEngine, storageDir = '.basetree-v7/graphs') {
13
+ this.graphEngine = graphEngine;
14
+ this.storageDir = storageDir;
15
+ fs.ensureDirSync(this.storageDir);
16
+ }
17
+ /**
18
+ * Save a snapshot to disk
19
+ */
20
+ async saveSnapshot(snapshot) {
21
+ const filePath = path.join(this.storageDir, `snapshot_${snapshot.runId}.json`);
22
+ await fs.writeJSON(filePath, snapshot, { spaces: 2 });
23
+ }
24
+ /**
25
+ * Load a snapshot from disk
26
+ */
27
+ async loadSnapshot(runId) {
28
+ const filePath = path.join(this.storageDir, `snapshot_${runId}.json`);
29
+ if (await fs.pathExists(filePath)) {
30
+ return await fs.readJSON(filePath);
31
+ }
32
+ return null;
33
+ }
34
+ /**
35
+ * Load all snapshots for a goal
36
+ */
37
+ async loadSnapshotsForGoal(goalId) {
38
+ const files = await fs.readdir(this.storageDir);
39
+ const snapshots = [];
40
+ for (const file of files) {
41
+ if (file.startsWith('snapshot_') && file.endsWith('.json')) {
42
+ const snapshot = await fs.readJSON(path.join(this.storageDir, file));
43
+ if (snapshot.goalId === goalId) {
44
+ snapshots.push(snapshot);
45
+ }
46
+ }
47
+ }
48
+ snapshots.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());
49
+ return snapshots;
50
+ }
51
+ /**
52
+ * Load a run's graph state
53
+ */
54
+ async loadRun(runId) {
55
+ // Try to load from disk first
56
+ const snapshot = await this.loadSnapshot(runId);
57
+ if (snapshot) {
58
+ return snapshot;
59
+ }
60
+ // Fallback to in-memory graph engine
61
+ return this.graphEngine.getSnapshot(runId) || null;
62
+ }
63
+ /**
64
+ * List all stored runs
65
+ */
66
+ async listRuns() {
67
+ const files = await fs.readdir(this.storageDir);
68
+ return files
69
+ .filter((f) => f.startsWith('snapshot_') && f.endsWith('.json'))
70
+ .map((f) => f.replace('snapshot_', '').replace('.json', ''));
71
+ }
72
+ /**
73
+ * Delete a snapshot
74
+ */
75
+ async deleteSnapshot(runId) {
76
+ const filePath = path.join(this.storageDir, `snapshot_${runId}.json`);
77
+ if (await fs.pathExists(filePath)) {
78
+ await fs.remove(filePath);
79
+ }
80
+ }
81
+ }
@@ -0,0 +1,190 @@
1
+ /**
2
+ * Reasoning Stream Bus for BASETREE V7
3
+ * Bridges global events to cognitive graph updates and WebSocket clients
4
+ */
5
+ export class ReasoningStreamBus {
6
+ globalBus;
7
+ graphEngine;
8
+ subscribers = new Set();
9
+ constructor(globalBus, graphEngine) {
10
+ this.globalBus = globalBus;
11
+ this.graphEngine = graphEngine;
12
+ this.setupEventHandlers();
13
+ }
14
+ /**
15
+ * Subscribe to stream updates
16
+ */
17
+ subscribe(handler) {
18
+ this.subscribers.add(handler);
19
+ return () => {
20
+ this.subscribers.delete(handler);
21
+ };
22
+ }
23
+ /**
24
+ * Emit update to all subscribers
25
+ */
26
+ emit(update) {
27
+ for (const handler of this.subscribers) {
28
+ try {
29
+ handler(update);
30
+ }
31
+ catch (error) {
32
+ console.error('Error in stream subscriber:', error);
33
+ }
34
+ }
35
+ }
36
+ /**
37
+ * Setup event handlers to update graph
38
+ */
39
+ setupEventHandlers() {
40
+ // Subscribe to global events
41
+ this.globalBus.subscribe('global.goal', async (payload) => {
42
+ await this.handleGoalEvent(payload);
43
+ });
44
+ this.globalBus.subscribe('global.decision', async (payload) => {
45
+ await this.handleDecisionEvent(payload);
46
+ });
47
+ this.globalBus.subscribe('global.risk', async (payload) => {
48
+ await this.handleRiskEvent(payload);
49
+ });
50
+ this.globalBus.subscribe('region.*', async (payload) => {
51
+ await this.handleRegionalEvent(payload);
52
+ });
53
+ }
54
+ async handleGoalEvent(payload) {
55
+ const event = payload;
56
+ if (event.goal) {
57
+ const goalId = this.graphEngine.startRun(event.goal);
58
+ const node = this.graphEngine.getNode(goalId);
59
+ if (node) {
60
+ this.emit({
61
+ type: 'node_added',
62
+ data: node,
63
+ timestamp: new Date(),
64
+ });
65
+ }
66
+ }
67
+ }
68
+ async handleDecisionEvent(payload) {
69
+ const event = payload;
70
+ if (event.decision && event.goalId) {
71
+ const decisionNode = {
72
+ id: `decision_${Date.now()}`,
73
+ type: 'decision',
74
+ label: event.decision.type || 'Decision',
75
+ attributes: {
76
+ reasoning: event.decision.reasoning,
77
+ outcome: event.decision.outcome,
78
+ },
79
+ createdAt: new Date(),
80
+ updatedAt: new Date(),
81
+ };
82
+ this.graphEngine.addNode(decisionNode);
83
+ // Link to goal
84
+ const edge = {
85
+ id: `${event.goalId}_handled-by_${decisionNode.id}`,
86
+ type: 'handled-by',
87
+ source: event.goalId,
88
+ target: decisionNode.id,
89
+ attributes: {},
90
+ createdAt: new Date(),
91
+ };
92
+ this.graphEngine.addEdge(edge);
93
+ this.emit({
94
+ type: 'node_added',
95
+ data: decisionNode,
96
+ timestamp: new Date(),
97
+ });
98
+ this.emit({
99
+ type: 'edge_added',
100
+ data: edge,
101
+ timestamp: new Date(),
102
+ });
103
+ }
104
+ }
105
+ async handleRiskEvent(payload) {
106
+ const event = payload;
107
+ if (event.risk && event.goalId) {
108
+ const riskNode = {
109
+ id: `risk_${Date.now()}`,
110
+ type: 'risk',
111
+ label: event.risk.level || 'Risk',
112
+ attributes: {
113
+ level: event.risk.level,
114
+ description: event.risk.description,
115
+ },
116
+ createdAt: new Date(),
117
+ updatedAt: new Date(),
118
+ };
119
+ this.graphEngine.addNode(riskNode);
120
+ // Link to goal
121
+ const edge = {
122
+ id: `${event.goalId}_causes_${riskNode.id}`,
123
+ type: 'causes',
124
+ source: event.goalId,
125
+ target: riskNode.id,
126
+ attributes: {},
127
+ createdAt: new Date(),
128
+ };
129
+ this.graphEngine.addEdge(edge);
130
+ this.emit({
131
+ type: 'node_added',
132
+ data: riskNode,
133
+ timestamp: new Date(),
134
+ });
135
+ this.emit({
136
+ type: 'edge_added',
137
+ data: edge,
138
+ timestamp: new Date(),
139
+ });
140
+ }
141
+ }
142
+ async handleRegionalEvent(payload) {
143
+ const event = payload;
144
+ if (event.task && event.goalId) {
145
+ const taskNode = {
146
+ id: event.task.id || `task_${Date.now()}`,
147
+ type: 'task',
148
+ label: event.task.type || 'Task',
149
+ attributes: {
150
+ regionId: event.task.regionId,
151
+ status: event.task.status,
152
+ },
153
+ createdAt: new Date(),
154
+ updatedAt: new Date(),
155
+ };
156
+ this.graphEngine.addNode(taskNode);
157
+ // Link to goal
158
+ const edge = {
159
+ id: `${event.goalId}_depends-on_${taskNode.id}`,
160
+ type: 'depends-on',
161
+ source: event.goalId,
162
+ target: taskNode.id,
163
+ attributes: {},
164
+ createdAt: new Date(),
165
+ };
166
+ this.graphEngine.addEdge(edge);
167
+ this.emit({
168
+ type: 'node_added',
169
+ data: taskNode,
170
+ timestamp: new Date(),
171
+ });
172
+ this.emit({
173
+ type: 'edge_added',
174
+ data: edge,
175
+ timestamp: new Date(),
176
+ });
177
+ }
178
+ }
179
+ /**
180
+ * Create snapshot and emit
181
+ */
182
+ createSnapshot(runId) {
183
+ const snapshot = this.graphEngine.snapshot(runId);
184
+ this.emit({
185
+ type: 'snapshot',
186
+ data: { snapshot },
187
+ timestamp: new Date(),
188
+ });
189
+ }
190
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Configuration loader for BASETREE V5
3
+ * Loads configuration for paths, safety levels, sandbox strategies, thresholds
4
+ */
5
+ import { readFileSync, existsSync } from 'fs';
6
+ import { join } from 'path';
7
+ const DEFAULT_CONFIG = {
8
+ workspaceRoot: process.cwd(),
9
+ srcPath: 'src',
10
+ testPath: 'test',
11
+ stateStorePath: '.basetree-v5',
12
+ safety: {
13
+ kernelGuardEnabled: true,
14
+ protectedPaths: [
15
+ 'src/kernel',
16
+ 'src/safety',
17
+ 'src/config',
18
+ 'src/types',
19
+ ],
20
+ maxRiskLevel: 'medium',
21
+ requireGovernanceApproval: true,
22
+ sandboxStrategy: 'temp_dir',
23
+ rollbackEnabled: true,
24
+ },
25
+ sandbox: {
26
+ strategy: 'temp_dir',
27
+ cleanupOnSuccess: true,
28
+ cleanupOnFailure: false, // keep for debugging
29
+ },
30
+ thresholds: {
31
+ maxComplexity: 50,
32
+ maxBlastRadius: 10,
33
+ maxRiskScore: 0.7,
34
+ minStabilityScore: 0.6,
35
+ minAlignmentScore: 0.7,
36
+ regressionFailureThreshold: 0.1, // 10% max failure rate
37
+ },
38
+ observability: {
39
+ metricsEnabled: true,
40
+ metricsStorePath: '.basetree-v5/metrics',
41
+ enableCognitiveMetrics: true,
42
+ enableFailureSurfaceMapping: true,
43
+ reportFormat: 'both',
44
+ },
45
+ };
46
+ let cachedConfig = null;
47
+ export function loadConfig(configPath) {
48
+ if (cachedConfig) {
49
+ return cachedConfig;
50
+ }
51
+ const configFile = configPath || join(process.cwd(), 'basetree-v5.config.json');
52
+ if (existsSync(configFile)) {
53
+ try {
54
+ const fileContent = readFileSync(configFile, 'utf-8');
55
+ const userConfig = JSON.parse(fileContent);
56
+ cachedConfig = { ...DEFAULT_CONFIG, ...userConfig };
57
+ }
58
+ catch (error) {
59
+ console.warn(`Failed to load config from ${configFile}, using defaults:`, error);
60
+ cachedConfig = DEFAULT_CONFIG;
61
+ }
62
+ }
63
+ else {
64
+ cachedConfig = DEFAULT_CONFIG;
65
+ }
66
+ return cachedConfig;
67
+ }
68
+ export function getConfig() {
69
+ if (!cachedConfig) {
70
+ cachedConfig = loadConfig();
71
+ }
72
+ return cachedConfig;
73
+ }
74
+ export function resetConfig() {
75
+ cachedConfig = null;
76
+ }
@@ -0,0 +1,49 @@
1
+ export class AdaptivePlanner {
2
+ ai;
3
+ memory;
4
+ constructor(ai, memory) {
5
+ this.ai = ai;
6
+ this.memory = memory;
7
+ }
8
+ async createAdaptivePlan(request) {
9
+ const memoryContext = await this.memory.getContextualPatterns(request);
10
+ const prompt = `
11
+ You are the Adaptive Lead Engineer for BASETREE V3.
12
+ Request: "${request}"
13
+
14
+ Historical Context:
15
+ ${memoryContext}
16
+
17
+ GENERATE 2 POSSIBLE SOLUTION PATHS:
18
+ 1. Path A: Most direct/performant.
19
+ 2. Path B: Most robust/safe.
20
+
21
+ For each path, provide a JSON object with steps. Each step MUST include:
22
+ - id: "T1", "T2", etc.
23
+ - description: What to do
24
+ - action: e.g. FILE_WRITE, SHELL_EXEC
25
+ - expectedResult: Success criteria
26
+ - agentRole: Assign to one of [Architect, Backend, Frontend, Infra, Security]
27
+
28
+ Response Format:
29
+ {
30
+ "paths": [
31
+ { "id": "A", "riskScore": 0.3, "reasoning": "...", "steps": [...] },
32
+ { "id": "B", "riskScore": 0.1, "reasoning": "...", "steps": [...] }
33
+ ]
34
+ }
35
+ `;
36
+ const response = await this.ai.generateResponse(prompt);
37
+ try {
38
+ const jsonMatch = response.match(/{[\s\S]*}/);
39
+ const data = JSON.parse(jsonMatch ? jsonMatch[0] : response);
40
+ return data.paths;
41
+ }
42
+ catch (e) {
43
+ return [{ id: "A", riskScore: 0.5, reasoning: "Fallback path", steps: [] }];
44
+ }
45
+ }
46
+ selectBestPath(paths) {
47
+ return paths.sort((a, b) => a.riskScore - b.riskScore)[0];
48
+ }
49
+ }
@@ -0,0 +1,37 @@
1
+ export class AutoFixEngine {
2
+ ai;
3
+ memory;
4
+ constructor(ai, memory) {
5
+ this.ai = ai;
6
+ this.memory = memory;
7
+ }
8
+ async analyzeAndFix(task, output) {
9
+ const historicalFixes = await this.memory.getContextualPatterns("error " + output.slice(0, 100));
10
+ const prompt = `
11
+ You are the Autonomous Debugger for BASETREE V3.
12
+ Task failed: ${task}
13
+ Output/Error: ${output.slice(0, 2000)}
14
+
15
+ Historical context on similar issues:
16
+ ${historicalFixes}
17
+
18
+ 1. Analyze the stack trace / error message.
19
+ 2. Infer the ROOT CAUSE.
20
+ 3. Generate a precise FIX.
21
+
22
+ Response format JSON:
23
+ {
24
+ "rootCause": "...",
25
+ "fix": "FILE_WRITE: ... or SHELL_EXEC: ..."
26
+ }
27
+ `;
28
+ const response = await this.ai.generateResponse(prompt);
29
+ try {
30
+ const jsonMatch = response.match(/{[\s\S]*}/);
31
+ return JSON.parse(jsonMatch ? jsonMatch[0] : response);
32
+ }
33
+ catch (e) {
34
+ return { rootCause: "Unknown", fix: "RETRY_WITH_MORE_LOGGING" };
35
+ }
36
+ }
37
+ }
@@ -0,0 +1,79 @@
1
+ import { FileTools } from "../../tools/FileTools.js";
2
+ import { ShellTools } from "../../tools/ShellTools.js";
3
+ import { AutoFixEngine } from "./AutoFixEngine.js";
4
+ import chalk from "chalk";
5
+ export class ExecutorAgent {
6
+ ai;
7
+ memory;
8
+ constructor(ai, memory) {
9
+ this.ai = ai;
10
+ this.memory = memory;
11
+ }
12
+ async executeStep(description, actionRecommendation) {
13
+ const prompt = `
14
+ You are the Engineering Intelligence Agent (BASETREE V3).
15
+ Action: ${actionRecommendation}
16
+ Task Context: ${description}
17
+
18
+ Execute with precision. If an error occurs, our self-correction loop will trigger.
19
+ `;
20
+ let attempts = 0;
21
+ const maxAttempts = 3;
22
+ let currentAction = actionRecommendation;
23
+ let finalResult = "";
24
+ while (attempts < maxAttempts) {
25
+ process.stdout.write(chalk.gray(` ⚡ Attempt ${attempts + 1}: Executing... `));
26
+ let response = "";
27
+ for await (const chunk of this.ai.streamResponse(prompt, [])) {
28
+ response += chunk;
29
+ }
30
+ process.stdout.write("\n");
31
+ finalResult = await this.processTools(response);
32
+ if (finalResult.includes("STDERR") || finalResult.includes("exitCode: 1")) {
33
+ console.log(chalk.red(` ❌ Execution failed. Initializing Auto-Fix Intelligence...`));
34
+ const autofix = await new AutoFixEngine(this.ai, this.memory).analyzeAndFix(description, finalResult);
35
+ console.log(chalk.yellow(` 💡 Root Cause: ${autofix.rootCause}`));
36
+ console.log(chalk.blue(` 🛠 Applying Fix...`));
37
+ // Execute the fix action
38
+ await this.processTools(autofix.fix);
39
+ attempts++;
40
+ continue;
41
+ }
42
+ break;
43
+ }
44
+ return finalResult;
45
+ }
46
+ async processTools(text) {
47
+ let result = text;
48
+ // Handle FILE_WRITE
49
+ if (text.includes("FILE_WRITE:")) {
50
+ const pathMatch = text.match(/FILE_WRITE:\s*([^\s\n]+)/);
51
+ const contentMatch = text.match(/CONTENT_START\n([\s\S]*?)\nCONTENT_END/);
52
+ if (pathMatch && contentMatch) {
53
+ const filePath = pathMatch[1];
54
+ const content = contentMatch[1];
55
+ await FileTools.writeFile(filePath, content);
56
+ result += `\n${chalk.green(`[System: File written to ${filePath}]`)}`;
57
+ }
58
+ }
59
+ // Handle SHELL_EXEC
60
+ if (text.includes("SHELL_EXEC:")) {
61
+ const cmdMatch = text.match(/SHELL_EXEC:\s*(.+)/);
62
+ if (cmdMatch) {
63
+ const command = cmdMatch[1];
64
+ const shellResult = await ShellTools.execute(command);
65
+ result += `\n${chalk.blue(`[System: Command executed: ${command}]`)}\nSTDOUT: ${shellResult.stdout}\nSTDERR: ${shellResult.stderr}`;
66
+ }
67
+ }
68
+ // Handle FILE_READ
69
+ if (text.includes("FILE_READ:")) {
70
+ const pathMatch = text.match(/FILE_READ:\s*([^\s\n]+)/);
71
+ if (pathMatch) {
72
+ const filePath = pathMatch[1];
73
+ const content = await FileTools.readFile(filePath);
74
+ result += `\n${chalk.yellow(`[System: File read from ${filePath}]`)}\n---CONTENT---\n${content}`;
75
+ }
76
+ }
77
+ return result;
78
+ }
79
+ }
@@ -0,0 +1,67 @@
1
+ import path from "path";
2
+ import fs from "fs-extra";
3
+ export class LearningMemoryAgent {
4
+ ai;
5
+ entries = [];
6
+ memoryPath;
7
+ constructor(ai) {
8
+ this.ai = ai;
9
+ this.memoryPath = path.resolve(process.cwd(), ".basetree/memory.json");
10
+ this.loadMemory();
11
+ }
12
+ async loadMemory() {
13
+ if (await fs.pathExists(this.memoryPath)) {
14
+ this.entries = await fs.readJson(this.memoryPath);
15
+ }
16
+ }
17
+ async saveMemory() {
18
+ await fs.ensureDir(path.dirname(this.memoryPath));
19
+ await fs.writeJson(this.memoryPath, this.entries, { spaces: 2 });
20
+ }
21
+ async learn(type, content, metadata = {}) {
22
+ const embedding = await this.ai.getEmbeddings(content);
23
+ if (!embedding || embedding.length === 0) {
24
+ // If we couldn't obtain an embedding, skip persisting this memory entry.
25
+ return;
26
+ }
27
+ this.entries.push({
28
+ type,
29
+ content,
30
+ embedding,
31
+ metadata,
32
+ timestamp: Date.now(),
33
+ });
34
+ await this.saveMemory();
35
+ }
36
+ async recall(query, limit = 3) {
37
+ const queryEmbedding = await this.ai.getEmbeddings(query);
38
+ if (!queryEmbedding || queryEmbedding.length === 0) {
39
+ return [];
40
+ }
41
+ // Simple cosine similarity search
42
+ const results = this.entries.map(entry => ({
43
+ entry,
44
+ similarity: this.cosineSimilarity(queryEmbedding, entry.embedding)
45
+ }))
46
+ .sort((a, b) => b.similarity - a.similarity)
47
+ .slice(0, limit);
48
+ return results.map(r => r.entry);
49
+ }
50
+ cosineSimilarity(vecA, vecB) {
51
+ if (!vecA.length || !vecB.length || vecA.length !== vecB.length) {
52
+ return 0;
53
+ }
54
+ const dotProduct = vecA.reduce((sum, a, i) => sum + a * vecB[i], 0);
55
+ const magnitudeA = Math.sqrt(vecA.reduce((sum, a) => sum + a * a, 0));
56
+ const magnitudeB = Math.sqrt(vecB.reduce((sum, b) => sum + b * b, 0));
57
+ if (!magnitudeA || !magnitudeB)
58
+ return 0;
59
+ return dotProduct / (magnitudeA * magnitudeB);
60
+ }
61
+ async getContextualPatterns(query) {
62
+ const related = await this.recall(query);
63
+ if (related.length === 0)
64
+ return "No prior patterns found.";
65
+ return related.map(r => `[${r.type.toUpperCase()}] ${r.content}`).join("\n");
66
+ }
67
+ }
@@ -0,0 +1,35 @@
1
+ import { FileTools } from "../../tools/FileTools.js";
2
+ export class MemoryAgent {
3
+ history = [];
4
+ patterns = [];
5
+ addMessage(role, content) {
6
+ this.history.push({ role, content });
7
+ }
8
+ storePattern(key, content) {
9
+ this.patterns.push({ key, content });
10
+ }
11
+ async findRelatedPatterns(query) {
12
+ // Basic implementation: substring/keyword match.
13
+ // In V2.1, this would use Gemini embeddings.
14
+ return this.patterns
15
+ .filter(p => p.key.toLowerCase().includes(query.toLowerCase()) || p.content.toLowerCase().includes(query.toLowerCase()))
16
+ .map(p => p.content);
17
+ }
18
+ getHistory() {
19
+ return this.history;
20
+ }
21
+ async summarizeContext() {
22
+ const files = await FileTools.listFiles();
23
+ const relatedPatterns = await this.findRelatedPatterns("error");
24
+ const refactorPatterns = await this.findRelatedPatterns("refactor");
25
+ const allPatterns = [...relatedPatterns, ...refactorPatterns];
26
+ return `
27
+ Current Workspace: ${process.cwd()}
28
+ Files: ${files.join(", ")}
29
+ Known Patterns: ${allPatterns.length > 0 ? allPatterns.join("\n- ") : "None detected yet."}
30
+ `;
31
+ }
32
+ clear() {
33
+ this.history = [];
34
+ }
35
+ }
@@ -0,0 +1,38 @@
1
+ import chalk from "chalk";
2
+ export class MetaCognitionAgent {
3
+ ai;
4
+ memory;
5
+ constructor(ai, memory) {
6
+ this.ai = ai;
7
+ this.memory = memory;
8
+ }
9
+ async critique(task, result, history) {
10
+ const prompt = `
11
+ You are the Meta-Cognitive Architect for BASETREE. Analyze the task completion.
12
+
13
+ Task: ${task}
14
+ Outcome: ${result.slice(0, 1000)}
15
+
16
+ Questions to answer:
17
+ 1. Did we achieve the goal with minimal hops?
18
+ 2. What patterns led to success or failure?
19
+ 3. How should our future instructions be modified to avoid mistakes made here?
20
+
21
+ Output our "Learning Insight" which will be stored in our long-term memory.
22
+ `;
23
+ const insight = await this.ai.generateResponse(prompt, history);
24
+ console.log(chalk.magenta(`\n🧠 Self-Critique: ${insight.split('\n')[0]}...`));
25
+ // Identify if it was a success or failure for categorization
26
+ const type = result.toLowerCase().includes("error") || result.toLowerCase().includes("failed") ? "bug" : "success";
27
+ await this.memory.learn(type, insight, { task });
28
+ }
29
+ async getOptimizedSystemPrompt(basePrompt) {
30
+ const historyInsights = await this.memory.getContextualPatterns(basePrompt);
31
+ return `
32
+ ${basePrompt}
33
+
34
+ CONSIDER PRIOR LEARNINGS:
35
+ ${historyInsights}
36
+ `;
37
+ }
38
+ }