@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,41 @@
1
+ /**
2
+ * Discovery Agent for BASETREE V7
3
+ * Coordinates scientific discovery tasks
4
+ */
5
+ import { getKernel } from '../../kernel/kernel.js';
6
+ export class DiscoveryAgent {
7
+ id = 'discovery-agent';
8
+ name = 'Discovery Agent';
9
+ kernel = getKernel();
10
+ async handleGlobalEvent(event) {
11
+ // Monitor for discovery-related events
12
+ if (event.type.includes('discovery') || event.type.includes('experiment')) {
13
+ await this.processDiscoveryEvent(event);
14
+ }
15
+ }
16
+ async handleGoal(goal) {
17
+ // Accept discovery goals
18
+ if (goal.description.toLowerCase().includes('discover') ||
19
+ goal.description.toLowerCase().includes('research') ||
20
+ goal.description.toLowerCase().includes('hypothesis')) {
21
+ return {
22
+ accepted: true,
23
+ reasoning: 'Discovery goal accepted - will coordinate scientific workflow',
24
+ };
25
+ }
26
+ return {
27
+ accepted: false,
28
+ reasoning: 'Goal does not appear to be discovery-related',
29
+ };
30
+ }
31
+ async processDiscoveryEvent(event) {
32
+ // Process discovery events (hypothesis results, experiment outcomes, etc.)
33
+ // This would integrate with discovery pipeline components
34
+ }
35
+ async initialize() {
36
+ // Initialize discovery workflows
37
+ }
38
+ async shutdown() {
39
+ // Save discovery state
40
+ }
41
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Economic Agent for BASETREE V7
3
+ * Resource allocation across regions/orgs, capital optimization
4
+ */
5
+ import { getKernel } from '../../kernel/kernel.js';
6
+ export class EconomicAgent {
7
+ id = 'economic-agent';
8
+ name = 'Economic Agent';
9
+ kernel = getKernel();
10
+ async handleGlobalEvent(event) {
11
+ // Monitor economic events (resource usage, cost changes)
12
+ if (event.type.includes('resource') || event.type.includes('cost')) {
13
+ await this.updateEconomicModel(event);
14
+ }
15
+ }
16
+ async handleGoal(goal) {
17
+ // Evaluate economic feasibility
18
+ const allocation = await this.allocateResources(goal);
19
+ if (!allocation) {
20
+ return {
21
+ accepted: false,
22
+ reasoning: 'Insufficient resources available',
23
+ };
24
+ }
25
+ // Check cost constraints
26
+ if (goal.constraints.maxCost && allocation.cost > goal.constraints.maxCost) {
27
+ return {
28
+ accepted: false,
29
+ reasoning: `Estimated cost $${allocation.cost} exceeds maximum $${goal.constraints.maxCost}`,
30
+ };
31
+ }
32
+ return {
33
+ accepted: true,
34
+ reasoning: `Resource allocation feasible: $${allocation.cost} cost, ${allocation.carbonCost}kg CO2`,
35
+ };
36
+ }
37
+ async allocateResources(goal) {
38
+ // Simple economic model: estimate resource needs and find optimal region
39
+ // In production, this would use ML models or optimization algorithms
40
+ const estimatedCpu = 100; // Simplified estimation
41
+ const estimatedMemory = 10;
42
+ const estimatedHours = 1;
43
+ // Find cheapest available region (simplified)
44
+ const stateStore = this.kernel.getStateStore();
45
+ // For now, return a default allocation
46
+ return {
47
+ regionId: 'us-east',
48
+ cpuUnits: estimatedCpu,
49
+ memoryGB: estimatedMemory,
50
+ cost: estimatedCpu * estimatedHours * 0.01, // Simplified cost model
51
+ carbonCost: estimatedCpu * estimatedHours * 0.5, // Simplified carbon model
52
+ };
53
+ }
54
+ async updateEconomicModel(event) {
55
+ // Update internal economic models based on observed costs/usage
56
+ // This would feed into future allocation decisions
57
+ }
58
+ async initialize() {
59
+ // Initialize economic models
60
+ }
61
+ async shutdown() {
62
+ // Save economic models
63
+ }
64
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Education Agent for BASETREE V7
3
+ * Designs learning systems, curriculum experiments
4
+ */
5
+ import { getKernel } from '../../kernel/kernel.js';
6
+ export class EducationAgent {
7
+ id = 'education-agent';
8
+ name = 'Education Agent';
9
+ kernel = getKernel();
10
+ async handleGlobalEvent(event) {
11
+ // Monitor education events
12
+ if (event.type.includes('education') || event.type.includes('learning')) {
13
+ await this.processEducationEvent(event);
14
+ }
15
+ }
16
+ async handleGoal(goal) {
17
+ // Accept education-related goals
18
+ const isEducationRelated = goal.description.toLowerCase().includes('education') ||
19
+ goal.description.toLowerCase().includes('learning') ||
20
+ goal.description.toLowerCase().includes('curriculum');
21
+ if (!isEducationRelated) {
22
+ return {
23
+ accepted: false,
24
+ reasoning: 'Goal does not appear to be education-related',
25
+ };
26
+ }
27
+ return {
28
+ accepted: true,
29
+ reasoning: 'Education goal accepted - will design learning system',
30
+ };
31
+ }
32
+ async processEducationEvent(event) {
33
+ // Process education events (learning outcomes, curriculum feedback, etc.)
34
+ }
35
+ async initialize() {
36
+ // Initialize education models
37
+ }
38
+ async shutdown() {
39
+ // Save education state
40
+ }
41
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Governance Council Agent for BASETREE V7
3
+ * Global policy, ethics, safety enforcement
4
+ */
5
+ import { getKernel } from '../../kernel/kernel.js';
6
+ import { KillSwitch } from '../../safety/killSwitch.js';
7
+ export class GovernanceCouncilAgent {
8
+ id = 'governance-council-agent';
9
+ name = 'Governance Council Agent';
10
+ kernel = getKernel();
11
+ killSwitch;
12
+ constructor() {
13
+ this.killSwitch = new KillSwitch();
14
+ }
15
+ async handleGlobalEvent(event) {
16
+ // Monitor global events for policy violations
17
+ if (event.type.includes('risk') || event.type.includes('violation')) {
18
+ await this.evaluatePolicyViolation(event);
19
+ }
20
+ }
21
+ async handleGoal(goal) {
22
+ // Evaluate goal against global policies
23
+ const violations = [];
24
+ // Check priority constraints
25
+ if (goal.priority === 'critical' && !goal.orgId) {
26
+ violations.push('Critical goals require organization approval');
27
+ }
28
+ // Check resource constraints
29
+ if (goal.constraints.maxCost && goal.constraints.maxCost > 1000000) {
30
+ violations.push('Cost exceeds maximum allowed without special approval');
31
+ }
32
+ // Check deadline constraints
33
+ if (goal.constraints.deadline && goal.constraints.deadline < new Date()) {
34
+ violations.push('Deadline is in the past');
35
+ }
36
+ if (violations.length > 0) {
37
+ return {
38
+ accepted: false,
39
+ reasoning: `Policy violations: ${violations.join('; ')}`,
40
+ };
41
+ }
42
+ return {
43
+ accepted: true,
44
+ reasoning: 'Goal complies with global governance policies',
45
+ };
46
+ }
47
+ async evaluatePolicyViolation(event) {
48
+ // Determine severity and escalate if needed
49
+ const severity = this.assessSeverity(event);
50
+ if (severity === 'critical') {
51
+ // Escalate to kill-switch - freeze execution for safety
52
+ await this.killSwitch.activate('freeze_execution', {
53
+ target: 'global',
54
+ reason: 'Critical policy violation detected',
55
+ metadata: { event },
56
+ });
57
+ }
58
+ }
59
+ assessSeverity(event) {
60
+ // Simplified severity assessment
61
+ const payload = event.payload;
62
+ if (payload?.riskLevel === 'critical' || payload?.violationType === 'safety') {
63
+ return 'critical';
64
+ }
65
+ if (payload?.riskLevel === 'high') {
66
+ return 'high';
67
+ }
68
+ return 'medium';
69
+ }
70
+ async initialize() {
71
+ // Register with control plane
72
+ }
73
+ async shutdown() {
74
+ // Cleanup
75
+ }
76
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Healthcare Agent for BASETREE V7
3
+ * Coordinates bio/medical research pipelines
4
+ */
5
+ import { getKernel } from '../../kernel/kernel.js';
6
+ export class HealthcareAgent {
7
+ id = 'healthcare-agent';
8
+ name = 'Healthcare Agent';
9
+ kernel = getKernel();
10
+ async handleGlobalEvent(event) {
11
+ // Monitor healthcare events
12
+ if (event.type.includes('healthcare') || event.type.includes('medical')) {
13
+ await this.processHealthcareEvent(event);
14
+ }
15
+ }
16
+ async handleGoal(goal) {
17
+ // Accept healthcare-related goals with safety checks
18
+ const isHealthcareRelated = goal.description.toLowerCase().includes('health') ||
19
+ goal.description.toLowerCase().includes('medical') ||
20
+ goal.description.toLowerCase().includes('bio');
21
+ if (!isHealthcareRelated) {
22
+ return {
23
+ accepted: false,
24
+ reasoning: 'Goal does not appear to be healthcare-related',
25
+ };
26
+ }
27
+ // Additional safety checks would go here
28
+ return {
29
+ accepted: true,
30
+ reasoning: 'Healthcare goal accepted - will coordinate research pipeline with safety protocols',
31
+ };
32
+ }
33
+ async processHealthcareEvent(event) {
34
+ // Process healthcare events (research results, safety alerts, etc.)
35
+ }
36
+ async initialize() {
37
+ // Initialize healthcare workflows
38
+ }
39
+ async shutdown() {
40
+ // Save healthcare state
41
+ }
42
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Infrastructure Agent for BASETREE V7
3
+ * Manages infra-level tasks: region scaling, deployment decisions, multi-cloud routing
4
+ */
5
+ import { getKernel } from '../../kernel/kernel.js';
6
+ export class InfrastructureAgent {
7
+ id = 'infrastructure-agent';
8
+ name = 'Infrastructure Agent';
9
+ kernel = getKernel();
10
+ async handleGlobalEvent(event) {
11
+ // Monitor infrastructure events
12
+ if (event.type.includes('infrastructure') || event.type.includes('deployment')) {
13
+ await this.processInfrastructureEvent(event);
14
+ }
15
+ }
16
+ async handleGoal(goal) {
17
+ // Evaluate infrastructure requirements
18
+ const infraNeeds = this.assessInfrastructureNeeds(goal);
19
+ if (infraNeeds.requiresNewRegion && !goal.constraints.requiredRegions) {
20
+ return {
21
+ accepted: false,
22
+ reasoning: 'Goal requires new region but none specified',
23
+ };
24
+ }
25
+ return {
26
+ accepted: true,
27
+ reasoning: `Infrastructure needs: ${infraNeeds.summary}`,
28
+ };
29
+ }
30
+ assessInfrastructureNeeds(goal) {
31
+ // Simplified assessment
32
+ const requiresNewRegion = goal.constraints.requiredRegions !== undefined;
33
+ const estimatedCapacity = 100; // Simplified
34
+ return {
35
+ requiresNewRegion,
36
+ estimatedCapacity,
37
+ summary: `Capacity: ${estimatedCapacity} units, Regions: ${goal.constraints.requiredRegions?.length || 0}`,
38
+ };
39
+ }
40
+ async processInfrastructureEvent(event) {
41
+ // Handle infrastructure events (scaling, failures, etc.)
42
+ }
43
+ async initialize() {
44
+ // Initialize infrastructure monitoring
45
+ }
46
+ async shutdown() {
47
+ // Save infrastructure state
48
+ }
49
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Base Planet Agent interface for BASETREE V7
3
+ * All civilization-scale agents implement this interface
4
+ */
5
+ export {};
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Risk & Stability Agent for BASETREE V7
3
+ * Monitors global risk metrics, triggers containment and rollback
4
+ */
5
+ import { getKernel } from '../../kernel/kernel.js';
6
+ import { ContainmentProtocols } from '../../safety/containmentProtocols.js';
7
+ export class RiskStabilityAgent {
8
+ id = 'risk-stability-agent';
9
+ name = 'Risk & Stability Agent';
10
+ kernel = getKernel();
11
+ containmentProtocols;
12
+ riskMetrics = new Map();
13
+ constructor() {
14
+ this.containmentProtocols = new ContainmentProtocols();
15
+ }
16
+ async handleGlobalEvent(event) {
17
+ // Monitor for risk events
18
+ if (event.type.includes('risk') || event.type.includes('failure')) {
19
+ await this.assessRisk(event);
20
+ }
21
+ }
22
+ async handleGoal(goal) {
23
+ // Assess risk level of goal
24
+ const riskScore = await this.calculateRiskScore(goal);
25
+ if (riskScore > 0.8) {
26
+ return {
27
+ accepted: false,
28
+ reasoning: `Risk score ${riskScore.toFixed(2)} exceeds threshold (0.8)`,
29
+ };
30
+ }
31
+ if (riskScore > 0.6) {
32
+ return {
33
+ accepted: true,
34
+ reasoning: `High risk score ${riskScore.toFixed(2)} - will require additional monitoring`,
35
+ };
36
+ }
37
+ return {
38
+ accepted: true,
39
+ reasoning: `Risk score ${riskScore.toFixed(2)} is acceptable`,
40
+ };
41
+ }
42
+ async assessRisk(event) {
43
+ const riskLevel = this.extractRiskLevel(event);
44
+ const regionId = event.source.regionId || 'unknown';
45
+ // Update risk metrics
46
+ const currentRisk = this.riskMetrics.get(regionId) || 0;
47
+ this.riskMetrics.set(regionId, currentRisk + riskLevel);
48
+ // Check if containment is needed
49
+ if (currentRisk + riskLevel > 0.7) {
50
+ await this.containmentProtocols.triggerContainment(regionId, {
51
+ reason: 'Risk threshold exceeded',
52
+ riskLevel: currentRisk + riskLevel,
53
+ });
54
+ }
55
+ }
56
+ extractRiskLevel(event) {
57
+ const payload = event.payload;
58
+ if (payload?.riskLevel === 'critical')
59
+ return 0.5;
60
+ if (payload?.riskLevel === 'high')
61
+ return 0.3;
62
+ if (payload?.riskLevel === 'medium')
63
+ return 0.1;
64
+ return 0.05;
65
+ }
66
+ async calculateRiskScore(goal) {
67
+ // Simplified risk calculation
68
+ let score = 0.2; // Base risk
69
+ if (goal.priority === 'critical')
70
+ score += 0.2;
71
+ if (goal.constraints.maxCost && goal.constraints.maxCost > 100000)
72
+ score += 0.2;
73
+ if (goal.constraints.requiredRegions && goal.constraints.requiredRegions.length > 3) {
74
+ score += 0.2; // Multi-region increases complexity
75
+ }
76
+ return Math.min(score, 1.0);
77
+ }
78
+ async initialize() {
79
+ // Initialize risk monitoring
80
+ }
81
+ async shutdown() {
82
+ // Save risk metrics
83
+ }
84
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Urban Systems Agent for BASETREE V7
3
+ * Orchestrates smart-city simulations, logistics experiments
4
+ */
5
+ import { getKernel } from '../../kernel/kernel.js';
6
+ export class UrbanSystemsAgent {
7
+ id = 'urban-systems-agent';
8
+ name = 'Urban Systems Agent';
9
+ kernel = getKernel();
10
+ async handleGlobalEvent(event) {
11
+ // Monitor urban systems events
12
+ if (event.type.includes('urban') || event.type.includes('city') || event.type.includes('logistics')) {
13
+ await this.processUrbanEvent(event);
14
+ }
15
+ }
16
+ async handleGoal(goal) {
17
+ // Accept urban systems goals
18
+ const isUrbanRelated = goal.description.toLowerCase().includes('city') ||
19
+ goal.description.toLowerCase().includes('urban') ||
20
+ goal.description.toLowerCase().includes('logistics') ||
21
+ goal.description.toLowerCase().includes('transport');
22
+ if (!isUrbanRelated) {
23
+ return {
24
+ accepted: false,
25
+ reasoning: 'Goal does not appear to be urban systems-related',
26
+ };
27
+ }
28
+ return {
29
+ accepted: true,
30
+ reasoning: 'Urban systems goal accepted - will orchestrate smart city simulation',
31
+ };
32
+ }
33
+ async processUrbanEvent(event) {
34
+ // Process urban events (traffic patterns, logistics optimization, etc.)
35
+ }
36
+ async initialize() {
37
+ // Initialize urban systems models
38
+ }
39
+ async shutdown() {
40
+ // Save urban systems state
41
+ }
42
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Policy Agent for BASETREE V5
3
+ * Evaluates proposals against high-level policies
4
+ */
5
+ import { PolicyEngine } from '../safety/policyEngine.js';
6
+ import { getKernel } from '../kernel/kernel.js';
7
+ export class PolicyAgent {
8
+ policyEngine;
9
+ kernel = getKernel();
10
+ constructor() {
11
+ this.policyEngine = new PolicyEngine();
12
+ }
13
+ /**
14
+ * Evaluate proposal against policies
15
+ */
16
+ async evaluate(proposal) {
17
+ return this.policyEngine.evaluate(proposal);
18
+ }
19
+ /**
20
+ * Check if proposal is allowed by policies
21
+ */
22
+ async isAllowed(proposal) {
23
+ return this.policyEngine.isAllowed(proposal);
24
+ }
25
+ /**
26
+ * Get agent ID
27
+ */
28
+ getId() {
29
+ return 'policy-agent';
30
+ }
31
+ }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Prompt Genome Agent for BASETREE V5
3
+ * Manages and evolves a "prompt genome" (prompt templates and parameters) using RL signals
4
+ */
5
+ import { getKernel } from '../kernel/kernel.js';
6
+ import { MetricsCollector } from '../observability/metricsCollector.js';
7
+ export class PromptGenomeAgent {
8
+ kernel = getKernel();
9
+ metricsCollector = new MetricsCollector();
10
+ genome = {
11
+ templates: [],
12
+ mutationRate: 0.1,
13
+ crossoverRate: 0.3,
14
+ };
15
+ /**
16
+ * Register a prompt template
17
+ */
18
+ registerTemplate(template) {
19
+ const fullTemplate = {
20
+ ...template,
21
+ fitness: 0.5, // Initial fitness
22
+ usageCount: 0,
23
+ };
24
+ this.genome.templates.push(fullTemplate);
25
+ }
26
+ /**
27
+ * Get template by ID
28
+ */
29
+ getTemplate(id) {
30
+ return this.genome.templates.find((t) => t.id === id) || null;
31
+ }
32
+ /**
33
+ * Use a template and record outcome for RL
34
+ */
35
+ async useTemplate(templateId, success, reward = 0) {
36
+ const template = this.getTemplate(templateId);
37
+ if (!template) {
38
+ return;
39
+ }
40
+ template.usageCount++;
41
+ // Update fitness using reward signal
42
+ // Simple RL update: fitness = fitness * 0.9 + reward * 0.1
43
+ const learningRate = 0.1;
44
+ const rewardSignal = success ? (reward > 0 ? reward : 0.1) : -0.1;
45
+ template.fitness = template.fitness * (1 - learningRate) + rewardSignal * learningRate;
46
+ template.fitness = Math.max(0, Math.min(1, template.fitness)); // Clamp to [0, 1]
47
+ // Record metrics
48
+ await this.metricsCollector.record({
49
+ name: 'prompt.genome.fitness',
50
+ value: template.fitness,
51
+ tags: {
52
+ templateId,
53
+ success: String(success),
54
+ },
55
+ });
56
+ }
57
+ /**
58
+ * Evolve genome through mutation and crossover
59
+ */
60
+ evolve() {
61
+ // Select best templates (top 50%)
62
+ const sortedTemplates = [...this.genome.templates].sort((a, b) => b.fitness - a.fitness);
63
+ const topTemplates = sortedTemplates.slice(0, Math.ceil(sortedTemplates.length / 2));
64
+ // Mutate templates
65
+ for (const template of topTemplates) {
66
+ if (Math.random() < this.genome.mutationRate) {
67
+ this.mutateTemplate(template);
68
+ }
69
+ }
70
+ // Crossover (create new templates from best)
71
+ if (topTemplates.length >= 2 && Math.random() < this.genome.crossoverRate) {
72
+ const parent1 = topTemplates[0];
73
+ const parent2 = topTemplates[1];
74
+ const child = this.crossoverTemplates(parent1, parent2);
75
+ this.genome.templates.push(child);
76
+ }
77
+ }
78
+ mutateTemplate(template) {
79
+ // Mutate parameters randomly
80
+ for (const key in template.parameters) {
81
+ if (Math.random() < 0.3) {
82
+ // Mutate this parameter
83
+ const value = template.parameters[key];
84
+ if (typeof value === 'number') {
85
+ template.parameters[key] = value * (0.9 + Math.random() * 0.2); // ±10%
86
+ }
87
+ }
88
+ }
89
+ }
90
+ crossoverTemplates(parent1, parent2) {
91
+ // Create child by combining parameters from both parents
92
+ const childParams = {};
93
+ for (const key in parent1.parameters) {
94
+ childParams[key] = Math.random() < 0.5 ? parent1.parameters[key] : parent2.parameters[key];
95
+ }
96
+ return {
97
+ id: `template_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
98
+ name: `Crossover: ${parent1.name} × ${parent2.name}`,
99
+ template: parent1.template, // Use first parent's template
100
+ parameters: childParams,
101
+ fitness: (parent1.fitness + parent2.fitness) / 2,
102
+ usageCount: 0,
103
+ };
104
+ }
105
+ /**
106
+ * Get best template
107
+ */
108
+ getBestTemplate() {
109
+ if (this.genome.templates.length === 0) {
110
+ return null;
111
+ }
112
+ return this.genome.templates.reduce((best, current) => current.fitness > best.fitness ? current : best);
113
+ }
114
+ /**
115
+ * Get agent ID
116
+ */
117
+ getId() {
118
+ return 'prompt-genome-agent';
119
+ }
120
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Reasoning Optimizer Agent for BASETREE V5
3
+ * Adjusts reasoning depth, chain-of-thought strategies, and planning parameters based on performance metrics
4
+ */
5
+ import { getKernel } from '../kernel/kernel.js';
6
+ import { MetricsCollector } from '../observability/metricsCollector.js';
7
+ export class ReasoningOptimizerAgent {
8
+ kernel = getKernel();
9
+ metricsCollector = new MetricsCollector();
10
+ currentConfig = {
11
+ depth: 5,
12
+ useChainOfThought: true,
13
+ planningIterations: 3,
14
+ reflectionEnabled: true,
15
+ };
16
+ /**
17
+ * Optimize reasoning config based on metrics
18
+ */
19
+ async optimize() {
20
+ const stateStore = this.kernel.getStateStore();
21
+ // Get recent success/failure metrics
22
+ const recentMetrics = await stateStore.listMetrics('upgrade.outcome', undefined, 50);
23
+ const successRate = recentMetrics.length > 0
24
+ ? recentMetrics.filter((m) => m.value === 1).length / recentMetrics.length
25
+ : 0.5;
26
+ // Get latency metrics
27
+ const latencyMetrics = await stateStore.listMetrics('latency', undefined, 50);
28
+ const avgLatency = latencyMetrics.length > 0
29
+ ? latencyMetrics.reduce((sum, m) => sum + m.value, 0) / latencyMetrics.length
30
+ : 1000;
31
+ // Adjust config based on performance
32
+ if (successRate < 0.7) {
33
+ // Low success rate - increase depth and reflection
34
+ this.currentConfig.depth = Math.min(this.currentConfig.depth + 1, 10);
35
+ this.currentConfig.reflectionEnabled = true;
36
+ this.currentConfig.planningIterations = Math.min(this.currentConfig.planningIterations + 1, 5);
37
+ }
38
+ else if (successRate > 0.9 && avgLatency > 5000) {
39
+ // High success but slow - reduce depth for speed
40
+ this.currentConfig.depth = Math.max(this.currentConfig.depth - 1, 1);
41
+ this.currentConfig.planningIterations = Math.max(this.currentConfig.planningIterations - 1, 1);
42
+ }
43
+ // Record optimization
44
+ await this.metricsCollector.record({
45
+ name: 'reasoning.optimization',
46
+ value: this.currentConfig.depth,
47
+ tags: {
48
+ depth: String(this.currentConfig.depth),
49
+ chainOfThought: String(this.currentConfig.useChainOfThought),
50
+ },
51
+ });
52
+ return { ...this.currentConfig };
53
+ }
54
+ /**
55
+ * Get current reasoning config
56
+ */
57
+ getConfig() {
58
+ return { ...this.currentConfig };
59
+ }
60
+ /**
61
+ * Set reasoning config
62
+ */
63
+ setConfig(config) {
64
+ this.currentConfig = { ...this.currentConfig, ...config };
65
+ }
66
+ /**
67
+ * Get agent ID
68
+ */
69
+ getId() {
70
+ return 'reasoning-optimizer-agent';
71
+ }
72
+ }