@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.
- package/.env.example +10 -0
- package/README.md +369 -0
- package/dist/agents/alignmentAgent.js +68 -0
- package/dist/agents/governanceOrchestrator.js +152 -0
- package/dist/agents/planet/climateAgent.js +39 -0
- package/dist/agents/planet/diplomacyAgent.js +52 -0
- package/dist/agents/planet/discoveryAgent.js +41 -0
- package/dist/agents/planet/economicAgent.js +64 -0
- package/dist/agents/planet/educationAgent.js +41 -0
- package/dist/agents/planet/governanceCouncilAgent.js +76 -0
- package/dist/agents/planet/healthcareAgent.js +42 -0
- package/dist/agents/planet/infrastructureAgent.js +49 -0
- package/dist/agents/planet/planetAgent.js +5 -0
- package/dist/agents/planet/riskStabilityAgent.js +84 -0
- package/dist/agents/planet/urbanSystemsAgent.js +42 -0
- package/dist/agents/policyAgent.js +31 -0
- package/dist/agents/promptGenomeAgent.js +120 -0
- package/dist/agents/reasoningOptimizerAgent.js +72 -0
- package/dist/agents/regressionAgent.js +162 -0
- package/dist/agents/reinforcementLearnerAgent.js +108 -0
- package/dist/agents/riskEvaluationAgent.js +131 -0
- package/dist/agents/rollbackAgent.js +53 -0
- package/dist/agents/stabilityAgent.js +90 -0
- package/dist/agents/strategyMutationAgent.js +74 -0
- package/dist/agents/systemIntrospectionAgent.js +274 -0
- package/dist/agents/upgradeExecutorAgent.js +146 -0
- package/dist/agents/upgradePlannerAgent.js +80 -0
- package/dist/agents/venture/businessModelAgent.js +81 -0
- package/dist/agents/venture/growthAgent.js +82 -0
- package/dist/agents/venture/ideationAgent.js +89 -0
- package/dist/agents/venture/investorAgent.js +90 -0
- package/dist/agents/venture/legalAgent.js +112 -0
- package/dist/agents/venture/marketResearchAgent.js +80 -0
- package/dist/agents/venture/productAgent.js +96 -0
- package/dist/agents/venture/revenueAgent.js +63 -0
- package/dist/agents/venture/validationAgent.js +189 -0
- package/dist/bootstrap.js +200 -0
- package/dist/cli.js +453 -0
- package/dist/cognitiveGraph/cognitiveGraphEngine.js +180 -0
- package/dist/cognitiveGraph/graphStore.js +81 -0
- package/dist/cognitiveGraph/reasoningStreamBus.js +190 -0
- package/dist/config/config.js +76 -0
- package/dist/core/agent/AdaptivePlanner.js +49 -0
- package/dist/core/agent/AutoFixEngine.js +37 -0
- package/dist/core/agent/ExecutorAgent.js +79 -0
- package/dist/core/agent/LearningMemoryAgent.js +67 -0
- package/dist/core/agent/MemoryAgent.js +35 -0
- package/dist/core/agent/MetaCognitionAgent.js +38 -0
- package/dist/core/agent/PlannerAgent.js +59 -0
- package/dist/core/agent/ReflectionLoop.js +34 -0
- package/dist/core/agent/ReviewerAgent.js +34 -0
- package/dist/core/agent/VerificationAgent.js +20 -0
- package/dist/core/agent/specialists/SpecializedAgents.js +43 -0
- package/dist/core/ai/GeminiProvider.js +113 -0
- package/dist/core/ai/listModels.js +73 -0
- package/dist/core/monitor/PerformanceMonitor.js +18 -0
- package/dist/core/swarm/AgentSwarm.js +56 -0
- package/dist/core/swarm/ReasoningBus.js +26 -0
- package/dist/core/swarm/SwarmOrchestrator.js +36 -0
- package/dist/discovery/experimentOrchestrator.js +75 -0
- package/dist/discovery/hypothesisEngine.js +79 -0
- package/dist/discovery/knowledgeSynthesizer.js +83 -0
- package/dist/discovery/simulationPipeline.js +57 -0
- package/dist/experiments/experimentationEngine.js +174 -0
- package/dist/index.js +67 -0
- package/dist/kernel/eventBus.js +89 -0
- package/dist/kernel/kernel.js +146 -0
- package/dist/llm/tokenEfficiencyOptimizer.js +91 -0
- package/dist/memory/civilizationMemory.js +147 -0
- package/dist/memory/globalVectorMemory.js +87 -0
- package/dist/mesh/crossOrgProtocol.js +110 -0
- package/dist/mesh/globalReasoningBus.js +99 -0
- package/dist/observability/businessDashboard.js +103 -0
- package/dist/observability/businessMetrics.js +105 -0
- package/dist/observability/cognitiveMetrics.js +119 -0
- package/dist/observability/failureSurfaceMapper.js +135 -0
- package/dist/observability/metricsCollector.js +94 -0
- package/dist/observability/planetaryDashboard.js +97 -0
- package/dist/observability/planetaryMetrics.js +127 -0
- package/dist/observability/reportRenderer.js +100 -0
- package/dist/performance/memoryProfiler.js +107 -0
- package/dist/performance/profiler.js +130 -0
- package/dist/pipelines/evolvePipeline.js +150 -0
- package/dist/pipelines/governanceReviewPipeline.js +68 -0
- package/dist/pipelines/introspectPipeline.js +73 -0
- package/dist/pipelines/venture/growPipeline.js +51 -0
- package/dist/pipelines/venture/launchPipeline.js +55 -0
- package/dist/pipelines/venture/monetizePipeline.js +46 -0
- package/dist/pipelines/venture/shutdownPipeline.js +40 -0
- package/dist/pipelines/venture/startupPipeline.js +145 -0
- package/dist/pipelines/venture/validatePipeline.js +40 -0
- package/dist/planet/controlPlane.js +131 -0
- package/dist/planet/executionEngine.js +142 -0
- package/dist/planet/globalTypes.js +5 -0
- package/dist/planet/regionManager.js +114 -0
- package/dist/quality/codeQualityAuditor.js +161 -0
- package/dist/safety/containmentProtocols.js +87 -0
- package/dist/safety/integrityChecker.js +110 -0
- package/dist/safety/kernelGuard.js +57 -0
- package/dist/safety/killSwitch.js +100 -0
- package/dist/safety/planetaryKernel.js +92 -0
- package/dist/safety/policyEngine.js +129 -0
- package/dist/safety/rollbackManager.js +141 -0
- package/dist/safety/sandbox.js +143 -0
- package/dist/server/mindmapServer.js +102 -0
- package/dist/state/distributedState.js +241 -0
- package/dist/state/fileStateStore.js +264 -0
- package/dist/state/snapshotter.js +96 -0
- package/dist/state/stateStore.js +5 -0
- package/dist/tools/FileTools.js +25 -0
- package/dist/tools/GitTools.js +16 -0
- package/dist/tools/ShellTools.js +24 -0
- package/dist/types/architecture.js +5 -0
- package/dist/types/core.js +35 -0
- package/dist/types/governance.js +5 -0
- package/dist/types/venture.js +5 -0
- package/dist/ui/App.js +32 -0
- package/dist/ui/animation/AnimationEngine.js +117 -0
- package/dist/ui/animation/Easing.js +61 -0
- package/dist/ui/cli.js +50 -0
- package/dist/ui/command/ActionPreview.js +47 -0
- package/dist/ui/command/CommandPalette.js +55 -0
- package/dist/ui/command/NaturalLanguageBar.js +77 -0
- package/dist/ui/emotion/AnimationSequences.js +59 -0
- package/dist/ui/emotion/EmotionalUXEngine.js +86 -0
- package/dist/ui/integration/BackendAdapter.js +50 -0
- package/dist/ui/integration/WebSocketAdapter.js +90 -0
- package/dist/ui/intelligence/AdaptiveUIEngine.js +75 -0
- package/dist/ui/intelligence/UserBehaviorTracker.js +88 -0
- package/dist/ui/layout/LayoutEngine.js +115 -0
- package/dist/ui/mindmap/CognitiveMindmapRenderer.js +53 -0
- package/dist/ui/mindmap/EdgeRenderer.js +35 -0
- package/dist/ui/mindmap/GraphLayout.js +137 -0
- package/dist/ui/mindmap/MindmapControls.js +53 -0
- package/dist/ui/mindmap/NodeRenderer.js +53 -0
- package/dist/ui/modes/CognitiveMode.js +31 -0
- package/dist/ui/modes/CommandMode.js +6 -0
- package/dist/ui/modes/GovernanceMode.js +6 -0
- package/dist/ui/modes/MissionControlMode.js +6 -0
- package/dist/ui/modes/ModeManager.js +67 -0
- package/dist/ui/modes/ObservatoryMode.js +10 -0
- package/dist/ui/modes/TimelineMode.js +27 -0
- package/dist/ui/terminalOS.js +180 -0
- package/dist/ui/theme/ThemeEngine.js +164 -0
- package/dist/ui/visual/ColorGradient.js +91 -0
- package/dist/ui/visual/Typography.js +128 -0
- package/dist/ui/visual/UnicodeRenderer.js +86 -0
- package/dist/venture/ventureMemory.js +62 -0
- package/package.json +70 -0
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Token Efficiency Optimizer for BASETREE V5
|
|
3
|
+
* Analyzes prompt/response lengths, compression strategies, and summarization heuristics
|
|
4
|
+
*/
|
|
5
|
+
export class TokenEfficiencyOptimizer {
|
|
6
|
+
usageHistory = [];
|
|
7
|
+
maxHistory = 1000;
|
|
8
|
+
/**
|
|
9
|
+
* Record token usage
|
|
10
|
+
*/
|
|
11
|
+
recordUsage(usage) {
|
|
12
|
+
this.usageHistory.push({
|
|
13
|
+
...usage,
|
|
14
|
+
timestamp: new Date(),
|
|
15
|
+
});
|
|
16
|
+
if (this.usageHistory.length > this.maxHistory) {
|
|
17
|
+
this.usageHistory.shift();
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Estimate token count (rough approximation)
|
|
22
|
+
*/
|
|
23
|
+
estimateTokens(text) {
|
|
24
|
+
// Rough approximation: ~4 characters per token
|
|
25
|
+
return Math.ceil(text.length / 4);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Analyze efficiency metrics
|
|
29
|
+
*/
|
|
30
|
+
analyzeEfficiency(operation) {
|
|
31
|
+
const relevant = operation
|
|
32
|
+
? this.usageHistory.filter((u) => u.operation === operation)
|
|
33
|
+
: this.usageHistory;
|
|
34
|
+
if (relevant.length === 0) {
|
|
35
|
+
return {
|
|
36
|
+
averagePromptLength: 0,
|
|
37
|
+
averageResponseLength: 0,
|
|
38
|
+
compressionRatio: 1,
|
|
39
|
+
efficiencyScore: 0,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
const avgPrompt = relevant.reduce((sum, u) => sum + u.promptTokens, 0) / relevant.length;
|
|
43
|
+
const avgResponse = relevant.reduce((sum, u) => sum + u.responseTokens, 0) / relevant.length;
|
|
44
|
+
const avgTotal = relevant.reduce((sum, u) => sum + u.totalTokens, 0) / relevant.length;
|
|
45
|
+
// Compression ratio: how much response vs prompt
|
|
46
|
+
const compressionRatio = avgPrompt > 0 ? avgResponse / avgPrompt : 1;
|
|
47
|
+
// Efficiency score: inverse of total tokens (normalized)
|
|
48
|
+
// Lower total tokens = higher efficiency
|
|
49
|
+
const maxObserved = Math.max(...relevant.map((u) => u.totalTokens));
|
|
50
|
+
const efficiencyScore = maxObserved > 0 ? 1 - avgTotal / maxObserved : 1;
|
|
51
|
+
return {
|
|
52
|
+
averagePromptLength: avgPrompt,
|
|
53
|
+
averageResponseLength: avgResponse,
|
|
54
|
+
compressionRatio,
|
|
55
|
+
efficiencyScore,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Suggest optimizations
|
|
60
|
+
*/
|
|
61
|
+
suggestOptimizations(operation) {
|
|
62
|
+
const metrics = this.analyzeEfficiency(operation);
|
|
63
|
+
const suggestions = [];
|
|
64
|
+
if (metrics.averagePromptLength > 10000) {
|
|
65
|
+
suggestions.push('Consider summarizing or chunking prompts to reduce token usage');
|
|
66
|
+
}
|
|
67
|
+
if (metrics.compressionRatio > 2) {
|
|
68
|
+
suggestions.push('Response length is significantly longer than prompts - consider response summarization');
|
|
69
|
+
}
|
|
70
|
+
if (metrics.efficiencyScore < 0.5) {
|
|
71
|
+
suggestions.push('Token efficiency is low - review prompt engineering strategies');
|
|
72
|
+
}
|
|
73
|
+
return suggestions;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Get usage history
|
|
77
|
+
*/
|
|
78
|
+
getHistory(operation, limit) {
|
|
79
|
+
let history = operation
|
|
80
|
+
? this.usageHistory.filter((u) => u.operation === operation)
|
|
81
|
+
: [...this.usageHistory];
|
|
82
|
+
history.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime());
|
|
83
|
+
return limit ? history.slice(0, limit) : history;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Clear history
|
|
87
|
+
*/
|
|
88
|
+
clear() {
|
|
89
|
+
this.usageHistory = [];
|
|
90
|
+
}
|
|
91
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Civilization Memory for BASETREE V7
|
|
3
|
+
* Cross-agent, cross-region long-term memory for civilization-level learning
|
|
4
|
+
*/
|
|
5
|
+
import { getKernel } from '../kernel/kernel.js';
|
|
6
|
+
import { GlobalVectorMemory } from './globalVectorMemory.js';
|
|
7
|
+
import { GeminiProvider } from '../core/ai/GeminiProvider.js';
|
|
8
|
+
import { randomUUID } from 'crypto';
|
|
9
|
+
export class CivilizationMemory {
|
|
10
|
+
kernel = getKernel();
|
|
11
|
+
vectorMemory;
|
|
12
|
+
ai;
|
|
13
|
+
constructor(vectorMemory) {
|
|
14
|
+
this.vectorMemory = vectorMemory || new GlobalVectorMemory();
|
|
15
|
+
this.ai = new GeminiProvider();
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Record a civilization-level memory
|
|
19
|
+
*/
|
|
20
|
+
async record(kind, title, content, options = {}) {
|
|
21
|
+
const record = {
|
|
22
|
+
id: randomUUID(),
|
|
23
|
+
kind,
|
|
24
|
+
title,
|
|
25
|
+
content,
|
|
26
|
+
agentId: options.agentId,
|
|
27
|
+
goalId: options.goalId,
|
|
28
|
+
regionId: options.regionId,
|
|
29
|
+
tags: options.tags || [],
|
|
30
|
+
createdAt: new Date(),
|
|
31
|
+
};
|
|
32
|
+
// Generate embedding for semantic search
|
|
33
|
+
try {
|
|
34
|
+
const embedding = await this.ai.getEmbeddings(`${title}\n${content}`);
|
|
35
|
+
record.embedding = embedding;
|
|
36
|
+
await this.vectorMemory.storeEmbedding(embedding, {
|
|
37
|
+
id: record.id,
|
|
38
|
+
text: content,
|
|
39
|
+
agentId: options.agentId,
|
|
40
|
+
goalId: options.goalId,
|
|
41
|
+
regionId: options.regionId,
|
|
42
|
+
tags: options.tags || [],
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
console.warn('Failed to generate embedding:', error);
|
|
47
|
+
}
|
|
48
|
+
// Also save to state store (for structured queries)
|
|
49
|
+
await this.kernel.getStateStore().saveVentureMemory({
|
|
50
|
+
id: record.id,
|
|
51
|
+
ventureId: options.goalId,
|
|
52
|
+
kind: kind,
|
|
53
|
+
title,
|
|
54
|
+
details: content,
|
|
55
|
+
tags: options.tags || [],
|
|
56
|
+
createdAt: record.createdAt,
|
|
57
|
+
});
|
|
58
|
+
return record;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Search for similar memories
|
|
62
|
+
*/
|
|
63
|
+
async search(query, kind, topK = 10) {
|
|
64
|
+
try {
|
|
65
|
+
// Generate query embedding
|
|
66
|
+
const queryEmbedding = await this.ai.getEmbeddings(query);
|
|
67
|
+
// Search vector memory
|
|
68
|
+
const filters = {};
|
|
69
|
+
if (kind) {
|
|
70
|
+
// Filter by kind via tags
|
|
71
|
+
filters.tags = kind;
|
|
72
|
+
}
|
|
73
|
+
const results = await this.vectorMemory.search(queryEmbedding, topK, filters);
|
|
74
|
+
// Convert to CivilizationMemoryRecord format
|
|
75
|
+
return results.map((r) => ({
|
|
76
|
+
id: r.metadata.id,
|
|
77
|
+
kind: r.metadata.tags?.[0] || 'culture_pattern',
|
|
78
|
+
title: r.metadata.text?.substring(0, 100) || 'Untitled',
|
|
79
|
+
content: r.metadata.text || '',
|
|
80
|
+
agentId: r.metadata.agentId,
|
|
81
|
+
goalId: r.metadata.goalId,
|
|
82
|
+
regionId: r.metadata.regionId,
|
|
83
|
+
tags: r.metadata.tags || [],
|
|
84
|
+
embedding: r.vector,
|
|
85
|
+
createdAt: r.metadata.timestamp,
|
|
86
|
+
}));
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
console.warn('Vector search failed, falling back to text search:', error);
|
|
90
|
+
// Fallback to text-based search via state store
|
|
91
|
+
const records = await this.kernel.getStateStore().listVentureMemory({
|
|
92
|
+
kind: kind,
|
|
93
|
+
limit: topK,
|
|
94
|
+
});
|
|
95
|
+
return records.map((r) => ({
|
|
96
|
+
id: r.id,
|
|
97
|
+
kind: r.kind,
|
|
98
|
+
title: r.title,
|
|
99
|
+
content: r.details,
|
|
100
|
+
tags: r.tags,
|
|
101
|
+
createdAt: r.createdAt,
|
|
102
|
+
}));
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Record culture pattern
|
|
107
|
+
*/
|
|
108
|
+
async recordCulturePattern(title, content, tags = []) {
|
|
109
|
+
return this.record('culture_pattern', title, content, { tags });
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Record ethical decision
|
|
113
|
+
*/
|
|
114
|
+
async recordEthicalDecision(title, content, agentId) {
|
|
115
|
+
return this.record('ethical_decision', title, content, {
|
|
116
|
+
agentId,
|
|
117
|
+
tags: ['ethics', 'governance'],
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Record policy change
|
|
122
|
+
*/
|
|
123
|
+
async recordPolicyChange(title, content, agentId) {
|
|
124
|
+
return this.record('policy_change', title, content, {
|
|
125
|
+
agentId,
|
|
126
|
+
tags: ['policy', 'governance'],
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Record scientific discovery
|
|
131
|
+
*/
|
|
132
|
+
async recordScientificDiscovery(title, content, goalId) {
|
|
133
|
+
return this.record('scientific_discovery', title, content, {
|
|
134
|
+
goalId,
|
|
135
|
+
tags: ['science', 'discovery'],
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Record incident report
|
|
140
|
+
*/
|
|
141
|
+
async recordIncident(title, content, regionId) {
|
|
142
|
+
return this.record('incident_report', title, content, {
|
|
143
|
+
regionId,
|
|
144
|
+
tags: ['incident', 'safety'],
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Global Vector Memory for BASETREE V7
|
|
3
|
+
* Planet-scale vector memory abstraction for embeddings
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* In-memory vector store (for dev)
|
|
7
|
+
* In production, would use Pinecone, FAISS, Qdrant, etc.
|
|
8
|
+
*/
|
|
9
|
+
export class InMemoryVectorStore {
|
|
10
|
+
vectors = new Map();
|
|
11
|
+
async store(vector, metadata) {
|
|
12
|
+
this.vectors.set(metadata.id, { vector, metadata });
|
|
13
|
+
}
|
|
14
|
+
async search(queryVector, topK, filters) {
|
|
15
|
+
const results = [];
|
|
16
|
+
for (const [id, { vector, metadata }] of this.vectors.entries()) {
|
|
17
|
+
// Apply filters
|
|
18
|
+
if (filters) {
|
|
19
|
+
let matches = true;
|
|
20
|
+
for (const [key, value] of Object.entries(filters)) {
|
|
21
|
+
if (metadata[key] !== value) {
|
|
22
|
+
matches = false;
|
|
23
|
+
break;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
if (!matches)
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
// Calculate cosine similarity
|
|
30
|
+
const similarity = this.cosineSimilarity(queryVector, vector);
|
|
31
|
+
results.push({
|
|
32
|
+
vector,
|
|
33
|
+
metadata,
|
|
34
|
+
similarity,
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
// Sort by similarity and return top K
|
|
38
|
+
results.sort((a, b) => b.similarity - a.similarity);
|
|
39
|
+
return results.slice(0, topK);
|
|
40
|
+
}
|
|
41
|
+
async delete(id) {
|
|
42
|
+
this.vectors.delete(id);
|
|
43
|
+
}
|
|
44
|
+
cosineSimilarity(a, b) {
|
|
45
|
+
if (a.length !== b.length) {
|
|
46
|
+
return 0;
|
|
47
|
+
}
|
|
48
|
+
let dotProduct = 0;
|
|
49
|
+
let normA = 0;
|
|
50
|
+
let normB = 0;
|
|
51
|
+
for (let i = 0; i < a.length; i++) {
|
|
52
|
+
dotProduct += a[i] * b[i];
|
|
53
|
+
normA += a[i] * a[i];
|
|
54
|
+
normB += b[i] * b[i];
|
|
55
|
+
}
|
|
56
|
+
const denominator = Math.sqrt(normA) * Math.sqrt(normB);
|
|
57
|
+
return denominator > 0 ? dotProduct / denominator : 0;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
export class GlobalVectorMemory {
|
|
61
|
+
store;
|
|
62
|
+
constructor(store) {
|
|
63
|
+
this.store = store || new InMemoryVectorStore();
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Store an embedding with metadata
|
|
67
|
+
*/
|
|
68
|
+
async storeEmbedding(vector, metadata) {
|
|
69
|
+
const fullMetadata = {
|
|
70
|
+
...metadata,
|
|
71
|
+
timestamp: new Date(),
|
|
72
|
+
};
|
|
73
|
+
await this.store.store(vector, fullMetadata);
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Search for similar embeddings
|
|
77
|
+
*/
|
|
78
|
+
async search(queryVector, topK = 10, filters) {
|
|
79
|
+
return this.store.search(queryVector, topK, filters);
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Delete an embedding
|
|
83
|
+
*/
|
|
84
|
+
async delete(id) {
|
|
85
|
+
await this.store.delete(id);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cross-Organization Protocol for BASETREE V7
|
|
3
|
+
* Coordination protocol for cross-organization collaboration
|
|
4
|
+
*/
|
|
5
|
+
export class CrossOrgProtocol {
|
|
6
|
+
proposals = new Map();
|
|
7
|
+
offers = new Map();
|
|
8
|
+
agreements = new Map();
|
|
9
|
+
disputes = new Map();
|
|
10
|
+
/**
|
|
11
|
+
* Create a proposal
|
|
12
|
+
*/
|
|
13
|
+
createProposal(proposal) {
|
|
14
|
+
const id = `proposal_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
|
15
|
+
const fullProposal = {
|
|
16
|
+
...proposal,
|
|
17
|
+
id,
|
|
18
|
+
createdAt: new Date(),
|
|
19
|
+
};
|
|
20
|
+
this.proposals.set(id, fullProposal);
|
|
21
|
+
return fullProposal;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Create an offer in response to a proposal
|
|
25
|
+
*/
|
|
26
|
+
createOffer(offer) {
|
|
27
|
+
const id = `offer_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
|
28
|
+
const fullOffer = {
|
|
29
|
+
...offer,
|
|
30
|
+
id,
|
|
31
|
+
createdAt: new Date(),
|
|
32
|
+
};
|
|
33
|
+
this.offers.set(id, fullOffer);
|
|
34
|
+
return fullOffer;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Create an agreement from proposal/offer
|
|
38
|
+
*/
|
|
39
|
+
createAgreement(agreement) {
|
|
40
|
+
const id = `agreement_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
|
41
|
+
const fullAgreement = {
|
|
42
|
+
...agreement,
|
|
43
|
+
id,
|
|
44
|
+
status: 'pending',
|
|
45
|
+
createdAt: new Date(),
|
|
46
|
+
};
|
|
47
|
+
this.agreements.set(id, fullAgreement);
|
|
48
|
+
return fullAgreement;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Activate an agreement (CRDT-like: all parties must agree)
|
|
52
|
+
*/
|
|
53
|
+
activateAgreement(agreementId, activatedBy) {
|
|
54
|
+
const agreement = this.agreements.get(agreementId);
|
|
55
|
+
if (!agreement) {
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
// Simple consensus: if all parties have activated (simplified)
|
|
59
|
+
if (agreement.status === 'pending') {
|
|
60
|
+
agreement.status = 'active';
|
|
61
|
+
agreement.activatedAt = new Date();
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Raise a dispute
|
|
68
|
+
*/
|
|
69
|
+
raiseDispute(dispute) {
|
|
70
|
+
const id = `dispute_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
|
71
|
+
const fullDispute = {
|
|
72
|
+
...dispute,
|
|
73
|
+
id,
|
|
74
|
+
createdAt: new Date(),
|
|
75
|
+
};
|
|
76
|
+
this.disputes.set(id, fullDispute);
|
|
77
|
+
// Mark agreement as disputed
|
|
78
|
+
const agreement = this.agreements.get(dispute.agreementId);
|
|
79
|
+
if (agreement) {
|
|
80
|
+
agreement.status = 'disputed';
|
|
81
|
+
}
|
|
82
|
+
return fullDispute;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Resolve a dispute
|
|
86
|
+
*/
|
|
87
|
+
resolveDispute(disputeId, resolution) {
|
|
88
|
+
const dispute = this.disputes.get(disputeId);
|
|
89
|
+
if (dispute) {
|
|
90
|
+
dispute.resolution = resolution;
|
|
91
|
+
// Update agreement status based on resolution
|
|
92
|
+
const agreement = this.agreements.get(dispute.agreementId);
|
|
93
|
+
if (agreement) {
|
|
94
|
+
agreement.status = resolution.includes('cancel') ? 'cancelled' : 'active';
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Get proposals for an org
|
|
100
|
+
*/
|
|
101
|
+
getProposalsForOrg(orgId) {
|
|
102
|
+
return Array.from(this.proposals.values()).filter((p) => p.toOrg === orgId || p.fromOrg === orgId);
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Get agreements for an org
|
|
106
|
+
*/
|
|
107
|
+
getAgreementsForOrg(orgId) {
|
|
108
|
+
return Array.from(this.agreements.values()).filter((a) => a.parties.includes(orgId));
|
|
109
|
+
}
|
|
110
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Global Reasoning Bus for BASETREE V7
|
|
3
|
+
* Multi-region reasoning mesh connecting regional buses
|
|
4
|
+
*/
|
|
5
|
+
import { ReasoningBus } from '../core/swarm/ReasoningBus.js';
|
|
6
|
+
import { getEventBus } from '../kernel/eventBus.js';
|
|
7
|
+
/**
|
|
8
|
+
* In-process message broker (for dev/K8s-ready)
|
|
9
|
+
*/
|
|
10
|
+
class InProcessMessageBroker {
|
|
11
|
+
subscriptions = new Map();
|
|
12
|
+
async publish(topic, payload) {
|
|
13
|
+
const handlers = this.subscriptions.get(topic);
|
|
14
|
+
if (handlers) {
|
|
15
|
+
for (const handler of handlers) {
|
|
16
|
+
try {
|
|
17
|
+
await Promise.resolve(handler(payload));
|
|
18
|
+
}
|
|
19
|
+
catch (error) {
|
|
20
|
+
console.error(`Error in handler for topic ${topic}:`, error);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
// Also publish to wildcard subscribers
|
|
25
|
+
const wildcardHandlers = this.subscriptions.get('*');
|
|
26
|
+
if (wildcardHandlers) {
|
|
27
|
+
for (const handler of wildcardHandlers) {
|
|
28
|
+
try {
|
|
29
|
+
await Promise.resolve(handler({ topic, payload }));
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
console.error(`Error in wildcard handler:`, error);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
subscribe(topic, handler) {
|
|
38
|
+
if (!this.subscriptions.has(topic)) {
|
|
39
|
+
this.subscriptions.set(topic, new Set());
|
|
40
|
+
}
|
|
41
|
+
this.subscriptions.get(topic).add(handler);
|
|
42
|
+
return () => {
|
|
43
|
+
const handlers = this.subscriptions.get(topic);
|
|
44
|
+
if (handlers) {
|
|
45
|
+
handlers.delete(handler);
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
export class GlobalReasoningBus {
|
|
51
|
+
broker;
|
|
52
|
+
regionalBus;
|
|
53
|
+
eventBus = getEventBus();
|
|
54
|
+
constructor(broker) {
|
|
55
|
+
this.broker = broker || new InProcessMessageBroker();
|
|
56
|
+
this.regionalBus = ReasoningBus.getInstance();
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Publish to global topic
|
|
60
|
+
*/
|
|
61
|
+
async publish(topic, payload) {
|
|
62
|
+
// Publish to broker
|
|
63
|
+
await this.broker.publish(topic, payload);
|
|
64
|
+
// Also emit to local event bus
|
|
65
|
+
await this.eventBus.emit({
|
|
66
|
+
type: 'ProposalCreated', // Generic event type
|
|
67
|
+
timestamp: new Date(),
|
|
68
|
+
metadata: { topic, payload },
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Subscribe to global topic
|
|
73
|
+
*/
|
|
74
|
+
subscribe(topic, handler) {
|
|
75
|
+
return this.broker.subscribe(topic, handler);
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Subscribe to regional events and forward to global mesh
|
|
79
|
+
*/
|
|
80
|
+
connectRegionalBus() {
|
|
81
|
+
this.regionalBus.subscribe((event) => {
|
|
82
|
+
// Forward regional events to global topics
|
|
83
|
+
const topic = `region.${event.role || 'unknown'}`;
|
|
84
|
+
this.publish(topic, event).catch(console.error);
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Initialize and connect regional bus
|
|
89
|
+
*/
|
|
90
|
+
async initialize() {
|
|
91
|
+
this.connectRegionalBus();
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Get underlying broker (for extensibility)
|
|
95
|
+
*/
|
|
96
|
+
getBroker() {
|
|
97
|
+
return this.broker;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Business Dashboard for BASETREE V6
|
|
3
|
+
* Renders business metrics in CLI format
|
|
4
|
+
*/
|
|
5
|
+
import chalk from 'chalk';
|
|
6
|
+
import { BusinessMetricsCalculator } from './businessMetrics.js';
|
|
7
|
+
import { getKernel } from '../kernel/kernel.js';
|
|
8
|
+
export class BusinessDashboard {
|
|
9
|
+
metricsCalculator = new BusinessMetricsCalculator();
|
|
10
|
+
kernel = getKernel();
|
|
11
|
+
async render(ventureId) {
|
|
12
|
+
if (ventureId) {
|
|
13
|
+
await this.renderVentureDashboard(ventureId);
|
|
14
|
+
}
|
|
15
|
+
else {
|
|
16
|
+
await this.renderOverview();
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
async renderVentureDashboard(ventureId) {
|
|
20
|
+
const venture = await this.kernel.getStateStore().getVenture(ventureId);
|
|
21
|
+
if (!venture) {
|
|
22
|
+
console.log(chalk.red(`Venture ${ventureId} not found`));
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
console.log(chalk.blue(`\n๐ Business Dashboard: ${venture.idea}\n`));
|
|
26
|
+
console.log(chalk.gray(`Venture ID: ${venture.id}`));
|
|
27
|
+
console.log(chalk.gray(`Stage: ${venture.stage}`));
|
|
28
|
+
console.log(chalk.gray(`Created: ${venture.createdAt.toLocaleDateString()}\n`));
|
|
29
|
+
// MRR
|
|
30
|
+
const mrr = await this.metricsCalculator.calculateMRR(ventureId);
|
|
31
|
+
console.log(chalk.yellow('๐ฐ Revenue Metrics:'));
|
|
32
|
+
console.log(` MRR: $${mrr.toLocaleString()}`);
|
|
33
|
+
// CAC/LTV
|
|
34
|
+
const { cac, ltv, ratio } = await this.metricsCalculator.calculateCACLTV(ventureId);
|
|
35
|
+
console.log(` CAC: $${cac.toLocaleString()}`);
|
|
36
|
+
console.log(` LTV: $${ltv.toLocaleString()}`);
|
|
37
|
+
console.log(` LTV/CAC Ratio: ${ratio.toFixed(2)}`);
|
|
38
|
+
if (ratio >= 3) {
|
|
39
|
+
console.log(chalk.green(' โ
Healthy ratio (โฅ3)'));
|
|
40
|
+
}
|
|
41
|
+
else if (ratio >= 1) {
|
|
42
|
+
console.log(chalk.yellow(' โ ๏ธ Ratio below ideal (โฅ3 recommended)'));
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
console.log(chalk.red(' โ Unhealthy ratio (<1)'));
|
|
46
|
+
}
|
|
47
|
+
// Retention
|
|
48
|
+
const retention = await this.metricsCalculator.calculateRetention(ventureId);
|
|
49
|
+
console.log(`\n${chalk.yellow('๐ฅ User Metrics:')}`);
|
|
50
|
+
console.log(` Retention Rate: ${(retention * 100).toFixed(1)}%`);
|
|
51
|
+
console.log(` Activation Rate: ${(venture.metrics.activationRate * 100).toFixed(1)}%`);
|
|
52
|
+
// Growth
|
|
53
|
+
const growthVelocity = await this.metricsCalculator.calculateGrowthVelocity(ventureId);
|
|
54
|
+
console.log(`\n${chalk.yellow('๐ Growth Metrics:')}`);
|
|
55
|
+
console.log(` Growth Rate: ${(growthVelocity * 100).toFixed(1)}%`);
|
|
56
|
+
// Activation Funnel
|
|
57
|
+
const funnel = await this.metricsCalculator.analyzeActivationFunnel(ventureId);
|
|
58
|
+
console.log(`\n${chalk.yellow('๐ Activation Funnel:')}`);
|
|
59
|
+
console.log(` Visitors: ${funnel.visitors.toLocaleString()}`);
|
|
60
|
+
console.log(` Signups: ${funnel.signups.toLocaleString()} (${funnel.visitors > 0 ? ((funnel.signups / funnel.visitors) * 100).toFixed(1) : 0}%)`);
|
|
61
|
+
console.log(` Conversions: ${funnel.conversions.toLocaleString()} (${funnel.signups > 0 ? ((funnel.conversions / funnel.signups) * 100).toFixed(1) : 0}%)`);
|
|
62
|
+
console.log(` Activated: ${funnel.activated.toLocaleString()}`);
|
|
63
|
+
// Experiments
|
|
64
|
+
const experimentStats = await this.metricsCalculator.calculateExperimentSuccessRate(ventureId);
|
|
65
|
+
console.log(`\n${chalk.yellow('๐งช Experiments:')}`);
|
|
66
|
+
console.log(` Total: ${experimentStats.total}`);
|
|
67
|
+
console.log(` Completed: ${experimentStats.completed}`);
|
|
68
|
+
console.log(` Success Rate: ${(experimentStats.successRate * 100).toFixed(1)}%`);
|
|
69
|
+
if (experimentStats.winners.length > 0) {
|
|
70
|
+
console.log(`\n Winners:`);
|
|
71
|
+
for (const winner of experimentStats.winners.slice(0, 5)) {
|
|
72
|
+
console.log(` - ${winner.experimentId}: ${winner.winner}`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
console.log('');
|
|
76
|
+
}
|
|
77
|
+
async renderOverview() {
|
|
78
|
+
const ventures = await this.kernel.getStateStore().listVentures();
|
|
79
|
+
console.log(chalk.blue(`\n๐ Business Overview\n`));
|
|
80
|
+
console.log(chalk.gray(`Total Ventures: ${ventures.length}\n`));
|
|
81
|
+
if (ventures.length === 0) {
|
|
82
|
+
console.log(chalk.yellow('No ventures found. Create one with: basetree startup <idea>'));
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
// Group by stage
|
|
86
|
+
const byStage = {};
|
|
87
|
+
let totalMRR = 0;
|
|
88
|
+
for (const venture of ventures) {
|
|
89
|
+
byStage[venture.stage] = (byStage[venture.stage] || 0) + 1;
|
|
90
|
+
totalMRR += venture.metrics.mrr;
|
|
91
|
+
}
|
|
92
|
+
console.log(chalk.yellow('By Stage:'));
|
|
93
|
+
for (const [stage, count] of Object.entries(byStage)) {
|
|
94
|
+
console.log(` ${stage}: ${count}`);
|
|
95
|
+
}
|
|
96
|
+
console.log(`\n${chalk.yellow('Total MRR:')} $${totalMRR.toLocaleString()}`);
|
|
97
|
+
console.log(`\n${chalk.yellow('Recent Ventures:')}`);
|
|
98
|
+
for (const venture of ventures.slice(0, 5)) {
|
|
99
|
+
console.log(` ${venture.idea} (${venture.stage}) - MRR: $${venture.metrics.mrr.toLocaleString()}`);
|
|
100
|
+
}
|
|
101
|
+
console.log('');
|
|
102
|
+
}
|
|
103
|
+
}
|