@gsep/core 0.8.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/LICENSE +21 -0
- package/README.md +286 -0
- package/dist/PGA.d.ts +288 -0
- package/dist/PGA.d.ts.map +1 -0
- package/dist/PGA.js +2228 -0
- package/dist/PGA.js.map +1 -0
- package/dist/advanced-ai/AgentStateVector.d.ts +66 -0
- package/dist/advanced-ai/AgentStateVector.d.ts.map +1 -0
- package/dist/advanced-ai/AgentStateVector.js +127 -0
- package/dist/advanced-ai/AgentStateVector.js.map +1 -0
- package/dist/advanced-ai/AgentVitals.d.ts +23 -0
- package/dist/advanced-ai/AgentVitals.d.ts.map +1 -0
- package/dist/advanced-ai/AgentVitals.js +13 -0
- package/dist/advanced-ai/AgentVitals.js.map +1 -0
- package/dist/advanced-ai/AutonomousLoop.d.ts +57 -0
- package/dist/advanced-ai/AutonomousLoop.d.ts.map +1 -0
- package/dist/advanced-ai/AutonomousLoop.js +207 -0
- package/dist/advanced-ai/AutonomousLoop.js.map +1 -0
- package/dist/advanced-ai/CalibratedAutonomy.d.ts +37 -0
- package/dist/advanced-ai/CalibratedAutonomy.d.ts.map +1 -0
- package/dist/advanced-ai/CalibratedAutonomy.js +151 -0
- package/dist/advanced-ai/CalibratedAutonomy.js.map +1 -0
- package/dist/advanced-ai/EmotionalModel.d.ts +27 -0
- package/dist/advanced-ai/EmotionalModel.d.ts.map +1 -0
- package/dist/advanced-ai/EmotionalModel.js +206 -0
- package/dist/advanced-ai/EmotionalModel.js.map +1 -0
- package/dist/advanced-ai/EnhancedSelfModel.d.ts +53 -0
- package/dist/advanced-ai/EnhancedSelfModel.d.ts.map +1 -0
- package/dist/advanced-ai/EnhancedSelfModel.js +189 -0
- package/dist/advanced-ai/EnhancedSelfModel.js.map +1 -0
- package/dist/advanced-ai/ModelRouter.d.ts +82 -0
- package/dist/advanced-ai/ModelRouter.d.ts.map +1 -0
- package/dist/advanced-ai/ModelRouter.js +280 -0
- package/dist/advanced-ai/ModelRouter.js.map +1 -0
- package/dist/advanced-ai/SelfModel.d.ts +29 -0
- package/dist/advanced-ai/SelfModel.d.ts.map +1 -0
- package/dist/advanced-ai/SelfModel.js +91 -0
- package/dist/advanced-ai/SelfModel.js.map +1 -0
- package/dist/advanced-ai/StrategicAutonomy.d.ts +41 -0
- package/dist/advanced-ai/StrategicAutonomy.d.ts.map +1 -0
- package/dist/advanced-ai/StrategicAutonomy.js +148 -0
- package/dist/advanced-ai/StrategicAutonomy.js.map +1 -0
- package/dist/advanced-ai/ThinkingEngine.d.ts +50 -0
- package/dist/advanced-ai/ThinkingEngine.d.ts.map +1 -0
- package/dist/advanced-ai/ThinkingEngine.js +179 -0
- package/dist/advanced-ai/ThinkingEngine.js.map +1 -0
- package/dist/core/ContextMemory.d.ts +56 -0
- package/dist/core/ContextMemory.d.ts.map +1 -0
- package/dist/core/ContextMemory.js +253 -0
- package/dist/core/ContextMemory.js.map +1 -0
- package/dist/core/DNAProfile.d.ts +19 -0
- package/dist/core/DNAProfile.d.ts.map +1 -0
- package/dist/core/DNAProfile.js +141 -0
- package/dist/core/DNAProfile.js.map +1 -0
- package/dist/core/FitnessTracker.d.ts +13 -0
- package/dist/core/FitnessTracker.d.ts.map +1 -0
- package/dist/core/FitnessTracker.js +96 -0
- package/dist/core/FitnessTracker.js.map +1 -0
- package/dist/core/GSEPActivityFooter.d.ts +15 -0
- package/dist/core/GSEPActivityFooter.d.ts.map +1 -0
- package/dist/core/GSEPActivityFooter.js +42 -0
- package/dist/core/GSEPActivityFooter.js.map +1 -0
- package/dist/core/GSEPIdentitySection.d.ts +23 -0
- package/dist/core/GSEPIdentitySection.d.ts.map +1 -0
- package/dist/core/GSEPIdentitySection.js +64 -0
- package/dist/core/GSEPIdentitySection.js.map +1 -0
- package/dist/core/GenesisBootstrap.d.ts +18 -0
- package/dist/core/GenesisBootstrap.d.ts.map +1 -0
- package/dist/core/GenesisBootstrap.js +95 -0
- package/dist/core/GenesisBootstrap.js.map +1 -0
- package/dist/core/GenomeKernel.d.ts +57 -0
- package/dist/core/GenomeKernel.d.ts.map +1 -0
- package/dist/core/GenomeKernel.js +296 -0
- package/dist/core/GenomeKernel.js.map +1 -0
- package/dist/core/GenomeManager.d.ts +21 -0
- package/dist/core/GenomeManager.d.ts.map +1 -0
- package/dist/core/GenomeManager.js +123 -0
- package/dist/core/GenomeManager.js.map +1 -0
- package/dist/core/LearningAnnouncer.d.ts +18 -0
- package/dist/core/LearningAnnouncer.d.ts.map +1 -0
- package/dist/core/LearningAnnouncer.js +182 -0
- package/dist/core/LearningAnnouncer.js.map +1 -0
- package/dist/core/ProactiveSuggestions.d.ts +25 -0
- package/dist/core/ProactiveSuggestions.d.ts.map +1 -0
- package/dist/core/ProactiveSuggestions.js +238 -0
- package/dist/core/ProactiveSuggestions.js.map +1 -0
- package/dist/core/PromptAssembler.d.ts +58 -0
- package/dist/core/PromptAssembler.d.ts.map +1 -0
- package/dist/core/PromptAssembler.js +265 -0
- package/dist/core/PromptAssembler.js.map +1 -0
- package/dist/enterprise/AuthManager.d.ts +71 -0
- package/dist/enterprise/AuthManager.d.ts.map +1 -0
- package/dist/enterprise/AuthManager.js +216 -0
- package/dist/enterprise/AuthManager.js.map +1 -0
- package/dist/enterprise/RateLimiter.d.ts +50 -0
- package/dist/enterprise/RateLimiter.d.ts.map +1 -0
- package/dist/enterprise/RateLimiter.js +199 -0
- package/dist/enterprise/RateLimiter.js.map +1 -0
- package/dist/evaluation/BenchmarkSuites.d.ts +29 -0
- package/dist/evaluation/BenchmarkSuites.d.ts.map +1 -0
- package/dist/evaluation/BenchmarkSuites.js +72 -0
- package/dist/evaluation/BenchmarkSuites.js.map +1 -0
- package/dist/evaluation/CalibrationManager.d.ts +66 -0
- package/dist/evaluation/CalibrationManager.d.ts.map +1 -0
- package/dist/evaluation/CalibrationManager.js +157 -0
- package/dist/evaluation/CalibrationManager.js.map +1 -0
- package/dist/evaluation/Evaluator.d.ts +79 -0
- package/dist/evaluation/Evaluator.d.ts.map +1 -0
- package/dist/evaluation/Evaluator.js +360 -0
- package/dist/evaluation/Evaluator.js.map +1 -0
- package/dist/evaluation/EvolutionGuardrails.d.ts +29 -0
- package/dist/evaluation/EvolutionGuardrails.d.ts.map +1 -0
- package/dist/evaluation/EvolutionGuardrails.js +166 -0
- package/dist/evaluation/EvolutionGuardrails.js.map +1 -0
- package/dist/evaluation/ProofOfValueRunner.d.ts +41 -0
- package/dist/evaluation/ProofOfValueRunner.d.ts.map +1 -0
- package/dist/evaluation/ProofOfValueRunner.js +177 -0
- package/dist/evaluation/ProofOfValueRunner.js.map +1 -0
- package/dist/evaluation/SandboxSuites.d.ts +26 -0
- package/dist/evaluation/SandboxSuites.d.ts.map +1 -0
- package/dist/evaluation/SandboxSuites.js +252 -0
- package/dist/evaluation/SandboxSuites.js.map +1 -0
- package/dist/evaluation/SemanticJudge.d.ts +21 -0
- package/dist/evaluation/SemanticJudge.d.ts.map +1 -0
- package/dist/evaluation/SemanticJudge.js +138 -0
- package/dist/evaluation/SemanticJudge.js.map +1 -0
- package/dist/evaluation/fixtures/core-coding-v1.json +68 -0
- package/dist/evaluation/fixtures/core-general-v1.json +68 -0
- package/dist/evaluation/fixtures/proof-of-value-v1.json +178 -0
- package/dist/evolution/CanaryDeployment.d.ts +78 -0
- package/dist/evolution/CanaryDeployment.d.ts.map +1 -0
- package/dist/evolution/CanaryDeployment.js +262 -0
- package/dist/evolution/CanaryDeployment.js.map +1 -0
- package/dist/evolution/DriftAnalyzer.d.ts +64 -0
- package/dist/evolution/DriftAnalyzer.d.ts.map +1 -0
- package/dist/evolution/DriftAnalyzer.js +288 -0
- package/dist/evolution/DriftAnalyzer.js.map +1 -0
- package/dist/evolution/FitnessCalculator.d.ts +47 -0
- package/dist/evolution/FitnessCalculator.d.ts.map +1 -0
- package/dist/evolution/FitnessCalculator.js +176 -0
- package/dist/evolution/FitnessCalculator.js.map +1 -0
- package/dist/evolution/MutationOperator.d.ts +102 -0
- package/dist/evolution/MutationOperator.d.ts.map +1 -0
- package/dist/evolution/MutationOperator.js +458 -0
- package/dist/evolution/MutationOperator.js.map +1 -0
- package/dist/evolution/PromotionGate.d.ts +45 -0
- package/dist/evolution/PromotionGate.d.ts.map +1 -0
- package/dist/evolution/PromotionGate.js +248 -0
- package/dist/evolution/PromotionGate.js.map +1 -0
- package/dist/evolution/PurposeSurvival.d.ts +68 -0
- package/dist/evolution/PurposeSurvival.d.ts.map +1 -0
- package/dist/evolution/PurposeSurvival.js +199 -0
- package/dist/evolution/PurposeSurvival.js.map +1 -0
- package/dist/evolution/boost/EvolutionBoostEngine.d.ts +70 -0
- package/dist/evolution/boost/EvolutionBoostEngine.d.ts.map +1 -0
- package/dist/evolution/boost/EvolutionBoostEngine.js +178 -0
- package/dist/evolution/boost/EvolutionBoostEngine.js.map +1 -0
- package/dist/evolution/boost/GeneticRecombinator.d.ts +26 -0
- package/dist/evolution/boost/GeneticRecombinator.d.ts.map +1 -0
- package/dist/evolution/boost/GeneticRecombinator.js +190 -0
- package/dist/evolution/boost/GeneticRecombinator.js.map +1 -0
- package/dist/evolution/boost/MetaEvolutionEngine.d.ts +69 -0
- package/dist/evolution/boost/MetaEvolutionEngine.d.ts.map +1 -0
- package/dist/evolution/boost/MetaEvolutionEngine.js +317 -0
- package/dist/evolution/boost/MetaEvolutionEngine.js.map +1 -0
- package/dist/evolution/boost/ParallelEvolutionEngine.d.ts +44 -0
- package/dist/evolution/boost/ParallelEvolutionEngine.d.ts.map +1 -0
- package/dist/evolution/boost/ParallelEvolutionEngine.js +134 -0
- package/dist/evolution/boost/ParallelEvolutionEngine.js.map +1 -0
- package/dist/evolution/boost/ParetoOptimizer.d.ts +42 -0
- package/dist/evolution/boost/ParetoOptimizer.d.ts.map +1 -0
- package/dist/evolution/boost/ParetoOptimizer.js +167 -0
- package/dist/evolution/boost/ParetoOptimizer.js.map +1 -0
- package/dist/evolution/boost/operators/BreakthroughOperator.d.ts +19 -0
- package/dist/evolution/boost/operators/BreakthroughOperator.d.ts.map +1 -0
- package/dist/evolution/boost/operators/BreakthroughOperator.js +229 -0
- package/dist/evolution/boost/operators/BreakthroughOperator.js.map +1 -0
- package/dist/evolution/boost/operators/CrossoverMutationOperator.d.ts +21 -0
- package/dist/evolution/boost/operators/CrossoverMutationOperator.d.ts.map +1 -0
- package/dist/evolution/boost/operators/CrossoverMutationOperator.js +207 -0
- package/dist/evolution/boost/operators/CrossoverMutationOperator.js.map +1 -0
- package/dist/evolution/boost/operators/PatternExtractionOperator.d.ts +21 -0
- package/dist/evolution/boost/operators/PatternExtractionOperator.d.ts.map +1 -0
- package/dist/evolution/boost/operators/PatternExtractionOperator.js +215 -0
- package/dist/evolution/boost/operators/PatternExtractionOperator.js.map +1 -0
- package/dist/evolution/boost/operators/SemanticRestructuringOperator.d.ts +18 -0
- package/dist/evolution/boost/operators/SemanticRestructuringOperator.d.ts.map +1 -0
- package/dist/evolution/boost/operators/SemanticRestructuringOperator.js +188 -0
- package/dist/evolution/boost/operators/SemanticRestructuringOperator.js.map +1 -0
- package/dist/evolution/boost/utils/llmHelper.d.ts +10 -0
- package/dist/evolution/boost/utils/llmHelper.d.ts.map +1 -0
- package/dist/evolution/boost/utils/llmHelper.js +13 -0
- package/dist/evolution/boost/utils/llmHelper.js.map +1 -0
- package/dist/firewall/ContentFirewall.d.ts +31 -0
- package/dist/firewall/ContentFirewall.d.ts.map +1 -0
- package/dist/firewall/ContentFirewall.js +252 -0
- package/dist/firewall/ContentFirewall.js.map +1 -0
- package/dist/firewall/DefaultPatterns.d.ts +8 -0
- package/dist/firewall/DefaultPatterns.d.ts.map +1 -0
- package/dist/firewall/DefaultPatterns.js +624 -0
- package/dist/firewall/DefaultPatterns.js.map +1 -0
- package/dist/firewall/index.d.ts +3 -0
- package/dist/firewall/index.d.ts.map +1 -0
- package/dist/firewall/index.js +3 -0
- package/dist/firewall/index.js.map +1 -0
- package/dist/gene-bank/CognitiveGene.d.ts +799 -0
- package/dist/gene-bank/CognitiveGene.d.ts.map +1 -0
- package/dist/gene-bank/CognitiveGene.js +128 -0
- package/dist/gene-bank/CognitiveGene.js.map +1 -0
- package/dist/gene-bank/GeneAdopter.d.ts +76 -0
- package/dist/gene-bank/GeneAdopter.d.ts.map +1 -0
- package/dist/gene-bank/GeneAdopter.js +290 -0
- package/dist/gene-bank/GeneAdopter.js.map +1 -0
- package/dist/gene-bank/GeneBank.d.ts +124 -0
- package/dist/gene-bank/GeneBank.d.ts.map +1 -0
- package/dist/gene-bank/GeneBank.js +261 -0
- package/dist/gene-bank/GeneBank.js.map +1 -0
- package/dist/gene-bank/GeneExtractor.d.ts +59 -0
- package/dist/gene-bank/GeneExtractor.d.ts.map +1 -0
- package/dist/gene-bank/GeneExtractor.js +311 -0
- package/dist/gene-bank/GeneExtractor.js.map +1 -0
- package/dist/gene-bank/GeneMatcher.d.ts +83 -0
- package/dist/gene-bank/GeneMatcher.d.ts.map +1 -0
- package/dist/gene-bank/GeneMatcher.js +233 -0
- package/dist/gene-bank/GeneMatcher.js.map +1 -0
- package/dist/gene-bank/MarketplaceClient.d.ts +26 -0
- package/dist/gene-bank/MarketplaceClient.d.ts.map +1 -0
- package/dist/gene-bank/MarketplaceClient.js +147 -0
- package/dist/gene-bank/MarketplaceClient.js.map +1 -0
- package/dist/gene-bank/PGAIntegration.d.ts +68 -0
- package/dist/gene-bank/PGAIntegration.d.ts.map +1 -0
- package/dist/gene-bank/PGAIntegration.js +181 -0
- package/dist/gene-bank/PGAIntegration.js.map +1 -0
- package/dist/gene-bank/SandboxTester.d.ts +92 -0
- package/dist/gene-bank/SandboxTester.d.ts.map +1 -0
- package/dist/gene-bank/SandboxTester.js +262 -0
- package/dist/gene-bank/SandboxTester.js.map +1 -0
- package/dist/gene-bank/adapters/InMemoryGeneStorage.d.ts +21 -0
- package/dist/gene-bank/adapters/InMemoryGeneStorage.d.ts.map +1 -0
- package/dist/gene-bank/adapters/InMemoryGeneStorage.js +115 -0
- package/dist/gene-bank/adapters/InMemoryGeneStorage.js.map +1 -0
- package/dist/gene-bank/adapters/PostgresGeneStorage.d.ts +21 -0
- package/dist/gene-bank/adapters/PostgresGeneStorage.d.ts.map +1 -0
- package/dist/gene-bank/adapters/PostgresGeneStorage.js +272 -0
- package/dist/gene-bank/adapters/PostgresGeneStorage.js.map +1 -0
- package/dist/gene-bank/index.d.ts +8 -0
- package/dist/gene-bank/index.d.ts.map +1 -0
- package/dist/gene-bank/index.js +8 -0
- package/dist/gene-bank/index.js.map +1 -0
- package/dist/immune/BehavioralImmuneSystem.d.ts +68 -0
- package/dist/immune/BehavioralImmuneSystem.d.ts.map +1 -0
- package/dist/immune/BehavioralImmuneSystem.js +253 -0
- package/dist/immune/BehavioralImmuneSystem.js.map +1 -0
- package/dist/index.d.ts +135 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +73 -0
- package/dist/index.js.map +1 -0
- package/dist/interfaces/LLMAdapter.d.ts +31 -0
- package/dist/interfaces/LLMAdapter.d.ts.map +1 -0
- package/dist/interfaces/LLMAdapter.js +2 -0
- package/dist/interfaces/LLMAdapter.js.map +1 -0
- package/dist/interfaces/StorageAdapter.d.ts +82 -0
- package/dist/interfaces/StorageAdapter.d.ts.map +1 -0
- package/dist/interfaces/StorageAdapter.js +2 -0
- package/dist/interfaces/StorageAdapter.js.map +1 -0
- package/dist/memory/AnalyticMemoryEngine.d.ts +106 -0
- package/dist/memory/AnalyticMemoryEngine.d.ts.map +1 -0
- package/dist/memory/AnalyticMemoryEngine.js +440 -0
- package/dist/memory/AnalyticMemoryEngine.js.map +1 -0
- package/dist/memory/CuriosityEngine.d.ts +34 -0
- package/dist/memory/CuriosityEngine.d.ts.map +1 -0
- package/dist/memory/CuriosityEngine.js +143 -0
- package/dist/memory/CuriosityEngine.js.map +1 -0
- package/dist/memory/GrowthJournal.d.ts +46 -0
- package/dist/memory/GrowthJournal.d.ts.map +1 -0
- package/dist/memory/GrowthJournal.js +241 -0
- package/dist/memory/GrowthJournal.js.map +1 -0
- package/dist/memory/LayeredMemory.d.ts +114 -0
- package/dist/memory/LayeredMemory.d.ts.map +1 -0
- package/dist/memory/LayeredMemory.js +406 -0
- package/dist/memory/LayeredMemory.js.map +1 -0
- package/dist/memory/PatternMemory.d.ts +38 -0
- package/dist/memory/PatternMemory.d.ts.map +1 -0
- package/dist/memory/PatternMemory.js +161 -0
- package/dist/memory/PatternMemory.js.map +1 -0
- package/dist/memory/PersonalNarrative.d.ts +51 -0
- package/dist/memory/PersonalNarrative.d.ts.map +1 -0
- package/dist/memory/PersonalNarrative.js +172 -0
- package/dist/memory/PersonalNarrative.js.map +1 -0
- package/dist/memory-compaction/MemoryCompactor.d.ts +18 -0
- package/dist/memory-compaction/MemoryCompactor.d.ts.map +1 -0
- package/dist/memory-compaction/MemoryCompactor.js +156 -0
- package/dist/memory-compaction/MemoryCompactor.js.map +1 -0
- package/dist/memory-compaction/index.d.ts +6 -0
- package/dist/memory-compaction/index.d.ts.map +1 -0
- package/dist/memory-compaction/index.js +5 -0
- package/dist/memory-compaction/index.js.map +1 -0
- package/dist/memory-compaction/strategies/BaseStrategy.d.ts +9 -0
- package/dist/memory-compaction/strategies/BaseStrategy.d.ts.map +1 -0
- package/dist/memory-compaction/strategies/BaseStrategy.js +50 -0
- package/dist/memory-compaction/strategies/BaseStrategy.js.map +1 -0
- package/dist/memory-compaction/strategies/ImportanceBasedStrategy.d.ts +9 -0
- package/dist/memory-compaction/strategies/ImportanceBasedStrategy.d.ts.map +1 -0
- package/dist/memory-compaction/strategies/ImportanceBasedStrategy.js +101 -0
- package/dist/memory-compaction/strategies/ImportanceBasedStrategy.js.map +1 -0
- package/dist/memory-compaction/strategies/SlidingWindowStrategy.d.ts +9 -0
- package/dist/memory-compaction/strategies/SlidingWindowStrategy.d.ts.map +1 -0
- package/dist/memory-compaction/strategies/SlidingWindowStrategy.js +87 -0
- package/dist/memory-compaction/strategies/SlidingWindowStrategy.js.map +1 -0
- package/dist/memory-compaction/types.d.ts +78 -0
- package/dist/memory-compaction/types.d.ts.map +1 -0
- package/dist/memory-compaction/types.js +2 -0
- package/dist/memory-compaction/types.js.map +1 -0
- package/dist/monitoring/AlertWebhooks.d.ts +57 -0
- package/dist/monitoring/AlertWebhooks.d.ts.map +1 -0
- package/dist/monitoring/AlertWebhooks.js +207 -0
- package/dist/monitoring/AlertWebhooks.js.map +1 -0
- package/dist/monitoring/MetricsCollector.d.ts +120 -0
- package/dist/monitoring/MetricsCollector.d.ts.map +1 -0
- package/dist/monitoring/MetricsCollector.js +274 -0
- package/dist/monitoring/MetricsCollector.js.map +1 -0
- package/dist/monitoring/MonitoringDashboard.d.ts +38 -0
- package/dist/monitoring/MonitoringDashboard.d.ts.map +1 -0
- package/dist/monitoring/MonitoringDashboard.js +271 -0
- package/dist/monitoring/MonitoringDashboard.js.map +1 -0
- package/dist/plugins/PluginManager.d.ts +61 -0
- package/dist/plugins/PluginManager.d.ts.map +1 -0
- package/dist/plugins/PluginManager.js +153 -0
- package/dist/plugins/PluginManager.js.map +1 -0
- package/dist/presets/ConfigPresets.d.ts +11 -0
- package/dist/presets/ConfigPresets.d.ts.map +1 -0
- package/dist/presets/ConfigPresets.js +113 -0
- package/dist/presets/ConfigPresets.js.map +1 -0
- package/dist/rag/RAGEngine.d.ts +54 -0
- package/dist/rag/RAGEngine.d.ts.map +1 -0
- package/dist/rag/RAGEngine.js +162 -0
- package/dist/rag/RAGEngine.js.map +1 -0
- package/dist/rag/VectorStoreAdapter.d.ts +40 -0
- package/dist/rag/VectorStoreAdapter.d.ts.map +1 -0
- package/dist/rag/VectorStoreAdapter.js +106 -0
- package/dist/rag/VectorStoreAdapter.js.map +1 -0
- package/dist/realtime/EventEmitter.d.ts +86 -0
- package/dist/realtime/EventEmitter.d.ts.map +1 -0
- package/dist/realtime/EventEmitter.js +171 -0
- package/dist/realtime/EventEmitter.js.map +1 -0
- package/dist/realtime/StreamingManager.d.ts +26 -0
- package/dist/realtime/StreamingManager.d.ts.map +1 -0
- package/dist/realtime/StreamingManager.js +175 -0
- package/dist/realtime/StreamingManager.js.map +1 -0
- package/dist/reasoning/Metacognition.d.ts +50 -0
- package/dist/reasoning/Metacognition.d.ts.map +1 -0
- package/dist/reasoning/Metacognition.js +347 -0
- package/dist/reasoning/Metacognition.js.map +1 -0
- package/dist/reasoning/ReasoningEngine.d.ts +57 -0
- package/dist/reasoning/ReasoningEngine.d.ts.map +1 -0
- package/dist/reasoning/ReasoningEngine.js +316 -0
- package/dist/reasoning/ReasoningEngine.js.map +1 -0
- package/dist/resilience/CircuitBreaker.d.ts +41 -0
- package/dist/resilience/CircuitBreaker.d.ts.map +1 -0
- package/dist/resilience/CircuitBreaker.js +108 -0
- package/dist/resilience/CircuitBreaker.js.map +1 -0
- package/dist/resilience/RetryManager.d.ts +14 -0
- package/dist/resilience/RetryManager.d.ts.map +1 -0
- package/dist/resilience/RetryManager.js +35 -0
- package/dist/resilience/RetryManager.js.map +1 -0
- package/dist/types/GenomeV2.d.ts +321 -0
- package/dist/types/GenomeV2.d.ts.map +1 -0
- package/dist/types/GenomeV2.js +2 -0
- package/dist/types/GenomeV2.js.map +1 -0
- package/dist/types/index.d.ts +401 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/index.js +2 -0
- package/dist/types/index.js.map +1 -0
- package/dist/utils/tokens.d.ts +4 -0
- package/dist/utils/tokens.d.ts.map +1 -0
- package/dist/utils/tokens.js +16 -0
- package/dist/utils/tokens.js.map +1 -0
- package/dist/wrap/FunctionLLMAdapter.d.ts +9 -0
- package/dist/wrap/FunctionLLMAdapter.d.ts.map +1 -0
- package/dist/wrap/FunctionLLMAdapter.js +26 -0
- package/dist/wrap/FunctionLLMAdapter.js.map +1 -0
- package/dist/wrap/GenomeBuilder.d.ts +13 -0
- package/dist/wrap/GenomeBuilder.d.ts.map +1 -0
- package/dist/wrap/GenomeBuilder.js +223 -0
- package/dist/wrap/GenomeBuilder.js.map +1 -0
- package/dist/wrap/InMemoryStorageAdapter.d.ts +97 -0
- package/dist/wrap/InMemoryStorageAdapter.d.ts.map +1 -0
- package/dist/wrap/InMemoryStorageAdapter.js +178 -0
- package/dist/wrap/InMemoryStorageAdapter.js.map +1 -0
- package/dist/wrap/WrapOptions.d.ts +47 -0
- package/dist/wrap/WrapOptions.d.ts.map +1 -0
- package/dist/wrap/WrapOptions.js +2 -0
- package/dist/wrap/WrapOptions.js.map +1 -0
- package/dist/wrap/WrappedAgent.d.ts +77 -0
- package/dist/wrap/WrappedAgent.d.ts.map +1 -0
- package/dist/wrap/WrappedAgent.js +143 -0
- package/dist/wrap/WrappedAgent.js.map +1 -0
- package/dist/wrap/index.d.ts +6 -0
- package/dist/wrap/index.d.ts.map +1 -0
- package/dist/wrap/index.js +5 -0
- package/dist/wrap/index.js.map +1 -0
- package/package.json +83 -0
package/dist/PGA.js
ADDED
|
@@ -0,0 +1,2228 @@
|
|
|
1
|
+
import { WrappedAgent } from './wrap/WrappedAgent.js';
|
|
2
|
+
import { GenomeManager } from './core/GenomeManager.js';
|
|
3
|
+
import { PromptAssembler } from './core/PromptAssembler.js';
|
|
4
|
+
import { DNAProfile } from './core/DNAProfile.js';
|
|
5
|
+
import { FitnessTracker } from './core/FitnessTracker.js';
|
|
6
|
+
import { LearningAnnouncer } from './core/LearningAnnouncer.js';
|
|
7
|
+
import { ContextMemory } from './core/ContextMemory.js';
|
|
8
|
+
import { ProactiveSuggestions } from './core/ProactiveSuggestions.js';
|
|
9
|
+
import { EvolutionGuardrailsManager } from './evaluation/EvolutionGuardrails.js';
|
|
10
|
+
import { ModelRouter } from './advanced-ai/ModelRouter.js';
|
|
11
|
+
import { MetricsCollector } from './monitoring/MetricsCollector.js';
|
|
12
|
+
import { MonitoringDashboard } from './monitoring/MonitoringDashboard.js';
|
|
13
|
+
import { RAGEngine } from './rag/RAGEngine.js';
|
|
14
|
+
import { ReasoningEngine } from './reasoning/ReasoningEngine.js';
|
|
15
|
+
import { MutationEngine, TokenCompressionOperator } from './evolution/MutationOperator.js';
|
|
16
|
+
import { SemanticRestructuringOperator } from './evolution/boost/operators/SemanticRestructuringOperator.js';
|
|
17
|
+
import { PatternExtractionOperator } from './evolution/boost/operators/PatternExtractionOperator.js';
|
|
18
|
+
import { CrossoverMutationOperator } from './evolution/boost/operators/CrossoverMutationOperator.js';
|
|
19
|
+
import { BreakthroughOperator } from './evolution/boost/operators/BreakthroughOperator.js';
|
|
20
|
+
import { estimateTokenCount } from './utils/tokens.js';
|
|
21
|
+
import { DriftAnalyzer } from './evolution/DriftAnalyzer.js';
|
|
22
|
+
import { FitnessCalculator } from './evolution/FitnessCalculator.js';
|
|
23
|
+
import { GenesisBootstrap } from './core/GenesisBootstrap.js';
|
|
24
|
+
import { SelfModel } from './advanced-ai/SelfModel.js';
|
|
25
|
+
import { PatternMemory } from './memory/PatternMemory.js';
|
|
26
|
+
import { Metacognition } from './reasoning/Metacognition.js';
|
|
27
|
+
import { EmotionalModel } from './advanced-ai/EmotionalModel.js';
|
|
28
|
+
import { CalibratedAutonomy } from './advanced-ai/CalibratedAutonomy.js';
|
|
29
|
+
import { PersonalNarrative } from './memory/PersonalNarrative.js';
|
|
30
|
+
import { AnalyticMemoryEngine } from './memory/AnalyticMemoryEngine.js';
|
|
31
|
+
import { MetaEvolutionEngine } from './evolution/boost/MetaEvolutionEngine.js';
|
|
32
|
+
import { CanaryDeploymentManager } from './evolution/CanaryDeployment.js';
|
|
33
|
+
import { EnhancedSelfModel } from './advanced-ai/EnhancedSelfModel.js';
|
|
34
|
+
import { PurposeSurvival } from './evolution/PurposeSurvival.js';
|
|
35
|
+
import { StrategicAutonomy } from './advanced-ai/StrategicAutonomy.js';
|
|
36
|
+
import { computeAgentVitals } from './advanced-ai/AgentVitals.js';
|
|
37
|
+
import { ThinkingEngine } from './advanced-ai/ThinkingEngine.js';
|
|
38
|
+
import { AgentStateVector } from './advanced-ai/AgentStateVector.js';
|
|
39
|
+
import { AutonomousLoop } from './advanced-ai/AutonomousLoop.js';
|
|
40
|
+
import { GrowthJournal } from './memory/GrowthJournal.js';
|
|
41
|
+
import { CuriosityEngine } from './memory/CuriosityEngine.js';
|
|
42
|
+
import { ContentFirewall } from './firewall/ContentFirewall.js';
|
|
43
|
+
import { GenomeKernel } from './core/GenomeKernel.js';
|
|
44
|
+
import { BehavioralImmuneSystem } from './immune/BehavioralImmuneSystem.js';
|
|
45
|
+
import { GSEPIdentitySection } from './core/GSEPIdentitySection.js';
|
|
46
|
+
import { GSEPActivityFooter } from './core/GSEPActivityFooter.js';
|
|
47
|
+
export class PGA {
|
|
48
|
+
pgaConfig;
|
|
49
|
+
genomeManager;
|
|
50
|
+
llm;
|
|
51
|
+
metricsCollector;
|
|
52
|
+
dashboard;
|
|
53
|
+
constructor(pgaConfig) {
|
|
54
|
+
this.pgaConfig = pgaConfig;
|
|
55
|
+
if (!pgaConfig.llm) {
|
|
56
|
+
throw new Error(`[GSEP] LLM adapter is required.\n\n`
|
|
57
|
+
+ `GSEP needs an AI model to function. Please provide an LLM adapter:\n\n`
|
|
58
|
+
+ ` import { PGA } from '@gsep/core';\n`
|
|
59
|
+
+ ` import { ClaudeAdapter } from '@gsep/adapters-llm-anthropic';\n\n`
|
|
60
|
+
+ ` const pga = new PGA({\n`
|
|
61
|
+
+ ` llm: new ClaudeAdapter({ apiKey: process.env.ANTHROPIC_API_KEY }),\n`
|
|
62
|
+
+ ` storage: yourStorageAdapter,\n`
|
|
63
|
+
+ ` });\n\n`
|
|
64
|
+
+ `Supported adapters:\n`
|
|
65
|
+
+ ` - @gsep/adapters-llm-anthropic (Claude)\n`
|
|
66
|
+
+ ` - @gsep/adapters-llm-openai (GPT-4)\n\n`
|
|
67
|
+
+ `Run 'pga doctor' for full diagnostics.`);
|
|
68
|
+
}
|
|
69
|
+
if (!pgaConfig.storage) {
|
|
70
|
+
throw new Error(`[GSEP] Storage adapter is required.\n\n`
|
|
71
|
+
+ `GSEP needs a storage adapter to persist genomes. Please provide one:\n\n`
|
|
72
|
+
+ ` import { InMemoryStorage } from '@gsep/core';\n\n`
|
|
73
|
+
+ ` const pga = new PGA({\n`
|
|
74
|
+
+ ` llm: yourLLMAdapter,\n`
|
|
75
|
+
+ ` storage: new InMemoryStorage(),\n`
|
|
76
|
+
+ ` });\n\n`
|
|
77
|
+
+ `For production, use: @gsep/adapters-storage-postgres`);
|
|
78
|
+
}
|
|
79
|
+
this.llm = pgaConfig.llm;
|
|
80
|
+
this.genomeManager = new GenomeManager(pgaConfig.storage);
|
|
81
|
+
this.metricsCollector = new MetricsCollector(pgaConfig.monitoring || {
|
|
82
|
+
enabled: true,
|
|
83
|
+
enableCostTracking: true,
|
|
84
|
+
enableAuditLogs: true,
|
|
85
|
+
});
|
|
86
|
+
if (pgaConfig.dashboard?.enabled) {
|
|
87
|
+
this.dashboard = new MonitoringDashboard(this.metricsCollector, pgaConfig.dashboard);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
async initialize() {
|
|
91
|
+
await this.pgaConfig.storage.initialize();
|
|
92
|
+
if (this.dashboard && this.pgaConfig.dashboard?.enabled) {
|
|
93
|
+
this.dashboard.start();
|
|
94
|
+
}
|
|
95
|
+
this.metricsCollector.logAudit({
|
|
96
|
+
level: 'info',
|
|
97
|
+
component: 'pga',
|
|
98
|
+
operation: 'initialize',
|
|
99
|
+
message: 'GSEP system initialized successfully',
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
getMetrics() {
|
|
103
|
+
return this.metricsCollector;
|
|
104
|
+
}
|
|
105
|
+
getDashboard() {
|
|
106
|
+
return this.dashboard;
|
|
107
|
+
}
|
|
108
|
+
exportMetrics() {
|
|
109
|
+
return this.metricsCollector.exportMetrics();
|
|
110
|
+
}
|
|
111
|
+
getAlerts() {
|
|
112
|
+
return this.metricsCollector.getAlerts();
|
|
113
|
+
}
|
|
114
|
+
getHealthStatus() {
|
|
115
|
+
return this.metricsCollector.getHealthStatus();
|
|
116
|
+
}
|
|
117
|
+
shutdown() {
|
|
118
|
+
if (this.dashboard) {
|
|
119
|
+
this.dashboard.stop();
|
|
120
|
+
}
|
|
121
|
+
this.metricsCollector.logAudit({
|
|
122
|
+
level: 'info',
|
|
123
|
+
component: 'pga',
|
|
124
|
+
operation: 'shutdown',
|
|
125
|
+
message: 'GSEP system shutdown',
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
async createGenome(options) {
|
|
129
|
+
const defaultGuardrails = {
|
|
130
|
+
minQualityScore: 0.60,
|
|
131
|
+
minSandboxScore: 0.70,
|
|
132
|
+
minCompressionScore: 0.65,
|
|
133
|
+
maxCostPerTask: 0.10,
|
|
134
|
+
minStabilityWindow: 10,
|
|
135
|
+
maxRollbackRate: 0.20,
|
|
136
|
+
gateMode: 'AND',
|
|
137
|
+
};
|
|
138
|
+
const genome = await this.genomeManager.createGenome({
|
|
139
|
+
name: options.name,
|
|
140
|
+
config: {
|
|
141
|
+
enableSandbox: true,
|
|
142
|
+
mutationRate: 'balanced',
|
|
143
|
+
evolutionGuardrails: defaultGuardrails,
|
|
144
|
+
...this.pgaConfig.config,
|
|
145
|
+
...options.config,
|
|
146
|
+
},
|
|
147
|
+
});
|
|
148
|
+
if (this.pgaConfig.geneBank && genome.config.autonomous?.genesisBootstrap) {
|
|
149
|
+
const bootstrap = new GenesisBootstrap(this.pgaConfig.geneBank);
|
|
150
|
+
const result = await bootstrap.bootstrap(genome, genome.config.autonomous.bootstrapMinFitness ?? 0.7);
|
|
151
|
+
if (result.genesUpgraded > 0) {
|
|
152
|
+
await this.pgaConfig.storage.saveGenome(genome);
|
|
153
|
+
this.metricsCollector.logAudit({
|
|
154
|
+
level: 'info',
|
|
155
|
+
component: 'pga',
|
|
156
|
+
operation: 'genesis-bootstrap',
|
|
157
|
+
message: `Bootstrapped ${result.genesUpgraded} genes from Gene Bank`,
|
|
158
|
+
metadata: { upgrades: result.upgrades },
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return new GenomeInstance(genome, this.llm, this.pgaConfig.storage, this.metricsCollector, this.pgaConfig.modelRouter, this.pgaConfig.rag, this.pgaConfig.reasoning, this.pgaConfig.geneBank);
|
|
163
|
+
}
|
|
164
|
+
async loadGenome(genomeId) {
|
|
165
|
+
const genome = await this.genomeManager.loadGenome(genomeId);
|
|
166
|
+
if (!genome)
|
|
167
|
+
return null;
|
|
168
|
+
return new GenomeInstance(genome, this.llm, this.pgaConfig.storage, this.metricsCollector, this.pgaConfig.modelRouter, this.pgaConfig.rag, this.pgaConfig.reasoning, this.pgaConfig.geneBank);
|
|
169
|
+
}
|
|
170
|
+
async listGenomes() {
|
|
171
|
+
return this.genomeManager.listGenomes();
|
|
172
|
+
}
|
|
173
|
+
async deleteGenome(genomeId) {
|
|
174
|
+
await this.genomeManager.deleteGenome(genomeId);
|
|
175
|
+
}
|
|
176
|
+
static async wrap(target, options) {
|
|
177
|
+
if (typeof target === 'function') {
|
|
178
|
+
if (!options.name) {
|
|
179
|
+
throw new Error('GSEP.wrap(): name is required when wrapping a function');
|
|
180
|
+
}
|
|
181
|
+
return WrappedAgent.fromFunction(target, options);
|
|
182
|
+
}
|
|
183
|
+
return WrappedAgent.fromAdapter(target, options);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
export class GenomeInstance {
|
|
187
|
+
genome;
|
|
188
|
+
llm;
|
|
189
|
+
storage;
|
|
190
|
+
geneBank;
|
|
191
|
+
assembler;
|
|
192
|
+
dnaProfile;
|
|
193
|
+
learningAnnouncer;
|
|
194
|
+
contextMemory;
|
|
195
|
+
proactiveSuggestions;
|
|
196
|
+
guardrailsManager;
|
|
197
|
+
modelRouter;
|
|
198
|
+
metrics;
|
|
199
|
+
ragEngine;
|
|
200
|
+
reasoningEngine;
|
|
201
|
+
fitnessTracker;
|
|
202
|
+
fitnessCalculator;
|
|
203
|
+
mutationEngine;
|
|
204
|
+
driftAnalyzer;
|
|
205
|
+
selfModel;
|
|
206
|
+
patternMemory;
|
|
207
|
+
metacognition;
|
|
208
|
+
emotionalModel;
|
|
209
|
+
calibratedAutonomy;
|
|
210
|
+
personalNarrative;
|
|
211
|
+
analyticMemory;
|
|
212
|
+
metaEvolutionEngine;
|
|
213
|
+
canaryManager;
|
|
214
|
+
enhancedSelfModel;
|
|
215
|
+
purposeSurvival;
|
|
216
|
+
strategicAutonomy;
|
|
217
|
+
thinkingEngine;
|
|
218
|
+
stateVector;
|
|
219
|
+
autonomousLoop;
|
|
220
|
+
growthJournal;
|
|
221
|
+
curiosityEngine;
|
|
222
|
+
gsepIdentitySection;
|
|
223
|
+
gsepActivityFooter;
|
|
224
|
+
genomeKernel;
|
|
225
|
+
contentFirewall;
|
|
226
|
+
immuneSystem;
|
|
227
|
+
interactionCount = 0;
|
|
228
|
+
evolutionInProgress = false;
|
|
229
|
+
constructor(genome, llm, storage, metrics, modelRouterConfig, ragConfig, reasoningConfig, geneBank) {
|
|
230
|
+
this.genome = genome;
|
|
231
|
+
this.llm = llm;
|
|
232
|
+
this.storage = storage;
|
|
233
|
+
this.geneBank = geneBank;
|
|
234
|
+
this.assembler = new PromptAssembler(storage, genome);
|
|
235
|
+
this.dnaProfile = new DNAProfile(storage);
|
|
236
|
+
this.learningAnnouncer = new LearningAnnouncer();
|
|
237
|
+
this.contextMemory = new ContextMemory(storage, llm, genome.config.layeredMemory);
|
|
238
|
+
this.proactiveSuggestions = new ProactiveSuggestions(storage);
|
|
239
|
+
this.guardrailsManager = new EvolutionGuardrailsManager(storage, genome.config.evolutionGuardrails);
|
|
240
|
+
this.modelRouter = new ModelRouter(storage, modelRouterConfig);
|
|
241
|
+
this.metrics = metrics;
|
|
242
|
+
if (ragConfig && genome.config.rag?.enabled) {
|
|
243
|
+
this.ragEngine = new RAGEngine(llm, ragConfig);
|
|
244
|
+
}
|
|
245
|
+
if (genome.config.reasoning?.enabled) {
|
|
246
|
+
this.reasoningEngine = new ReasoningEngine(llm, reasoningConfig);
|
|
247
|
+
}
|
|
248
|
+
this.fitnessTracker = new FitnessTracker(storage, genome);
|
|
249
|
+
this.fitnessCalculator = new FitnessCalculator();
|
|
250
|
+
this.mutationEngine = new MutationEngine();
|
|
251
|
+
this.canaryManager = new CanaryDeploymentManager(storage, {
|
|
252
|
+
initialTrafficPercent: 10,
|
|
253
|
+
minSampleSize: 5,
|
|
254
|
+
});
|
|
255
|
+
this.mutationEngine.registerOperator(new TokenCompressionOperator(llm));
|
|
256
|
+
this.mutationEngine.registerOperator(new SemanticRestructuringOperator(llm));
|
|
257
|
+
this.mutationEngine.registerOperator(new PatternExtractionOperator(llm, this.geneBank));
|
|
258
|
+
this.mutationEngine.registerOperator(new CrossoverMutationOperator(llm));
|
|
259
|
+
this.mutationEngine.registerOperator(new BreakthroughOperator(llm));
|
|
260
|
+
this.driftAnalyzer = new DriftAnalyzer();
|
|
261
|
+
if (genome.config.autonomous?.enableSelfModel) {
|
|
262
|
+
this.selfModel = new SelfModel(genome, this.driftAnalyzer);
|
|
263
|
+
this.assembler.setSelfModel(this.selfModel);
|
|
264
|
+
}
|
|
265
|
+
if (genome.config.autonomous?.enablePatternMemory) {
|
|
266
|
+
this.patternMemory = new PatternMemory(genome.config.autonomous.maxPatterns ?? 50);
|
|
267
|
+
this.assembler.setPatternMemory(this.patternMemory);
|
|
268
|
+
}
|
|
269
|
+
if (genome.config.autonomous?.enableMetacognition) {
|
|
270
|
+
this.metacognition = new Metacognition(() => this.selfModel?.assess() ?? null);
|
|
271
|
+
this.assembler.setMetacognition(this.metacognition);
|
|
272
|
+
}
|
|
273
|
+
if (genome.config.autonomous?.enableEmotionalModel) {
|
|
274
|
+
this.emotionalModel = new EmotionalModel();
|
|
275
|
+
this.assembler.setEmotionalModel(this.emotionalModel);
|
|
276
|
+
}
|
|
277
|
+
if (genome.config.autonomous?.enableCalibratedAutonomy) {
|
|
278
|
+
this.calibratedAutonomy = new CalibratedAutonomy();
|
|
279
|
+
this.assembler.setCalibratedAutonomy(this.calibratedAutonomy);
|
|
280
|
+
}
|
|
281
|
+
if (genome.config.autonomous?.enablePersonalNarrative) {
|
|
282
|
+
this.personalNarrative = new PersonalNarrative();
|
|
283
|
+
this.assembler.setPersonalNarrative(this.personalNarrative);
|
|
284
|
+
}
|
|
285
|
+
if (genome.config.autonomous?.enableAnalyticMemory) {
|
|
286
|
+
this.analyticMemory = new AnalyticMemoryEngine();
|
|
287
|
+
this.assembler.setAnalyticMemory(this.analyticMemory);
|
|
288
|
+
}
|
|
289
|
+
if (genome.config.autonomous) {
|
|
290
|
+
this.metaEvolutionEngine = new MetaEvolutionEngine();
|
|
291
|
+
this.assembler.setMetaEvolution(this.metaEvolutionEngine);
|
|
292
|
+
}
|
|
293
|
+
const agentPurpose = genome.config.autonomous?.agentPurpose
|
|
294
|
+
|| genome.layers.layer0[0]?.content
|
|
295
|
+
|| 'AI Assistant';
|
|
296
|
+
if (genome.config.autonomous?.enableEnhancedSelfModel) {
|
|
297
|
+
this.enhancedSelfModel = new EnhancedSelfModel(genome, this.driftAnalyzer, agentPurpose);
|
|
298
|
+
this.assembler.setSelfModel(this.enhancedSelfModel);
|
|
299
|
+
}
|
|
300
|
+
if (genome.config.autonomous?.enablePurposeSurvival) {
|
|
301
|
+
this.purposeSurvival = new PurposeSurvival(agentPurpose, this.driftAnalyzer, () => this.enhancedSelfModel?.assessFull()
|
|
302
|
+
?? { score: 0.5, fitnessComponent: 0.5, driftComponent: 1.0,
|
|
303
|
+
purposeComponent: 0.5, trajectoryComponent: 0.5, label: 'stable' });
|
|
304
|
+
}
|
|
305
|
+
if (genome.config.autonomous?.enableStrategicAutonomy) {
|
|
306
|
+
this.strategicAutonomy = new StrategicAutonomy(agentPurpose, () => this.enhancedSelfModel?.assessFull() ?? null, () => this.purposeSurvival?.getMode() ?? 'stable');
|
|
307
|
+
this.assembler.setCalibratedAutonomy(this.strategicAutonomy);
|
|
308
|
+
}
|
|
309
|
+
if (genome.config.autonomous?.enableThinkingEngine) {
|
|
310
|
+
this.thinkingEngine = new ThinkingEngine();
|
|
311
|
+
}
|
|
312
|
+
if (genome.config.autonomous?.enableStateVector) {
|
|
313
|
+
this.stateVector = new AgentStateVector();
|
|
314
|
+
this.assembler.setStateVector(this.stateVector);
|
|
315
|
+
}
|
|
316
|
+
if (genome.config.autonomous?.enableAutonomousLoop) {
|
|
317
|
+
this.autonomousLoop = new AutonomousLoop();
|
|
318
|
+
this.assembler.setAutonomousLoop(this.autonomousLoop);
|
|
319
|
+
}
|
|
320
|
+
if (genome.config.autonomous?.enableGrowthJournal) {
|
|
321
|
+
this.growthJournal = new GrowthJournal();
|
|
322
|
+
this.assembler.setGrowthJournal(this.growthJournal);
|
|
323
|
+
}
|
|
324
|
+
if (genome.config.autonomous?.enableCuriosityEngine) {
|
|
325
|
+
this.curiosityEngine = new CuriosityEngine();
|
|
326
|
+
this.assembler.setCuriosityEngine(this.curiosityEngine);
|
|
327
|
+
}
|
|
328
|
+
if (genome.config.firewall?.enabled !== false) {
|
|
329
|
+
this.contentFirewall = new ContentFirewall();
|
|
330
|
+
this.assembler.setFirewall(this.contentFirewall);
|
|
331
|
+
}
|
|
332
|
+
if (this.contentFirewall) {
|
|
333
|
+
this.immuneSystem = new BehavioralImmuneSystem({
|
|
334
|
+
firewall: this.contentFirewall,
|
|
335
|
+
genomeKernel: this.genomeKernel,
|
|
336
|
+
purposeSurvival: this.purposeSurvival,
|
|
337
|
+
c0Identity: {
|
|
338
|
+
purpose: genome.layers.layer0[0]?.content || 'AI Assistant',
|
|
339
|
+
constraints: genome.layers.layer0.slice(1).map(a => a.content),
|
|
340
|
+
forbiddenTopics: [],
|
|
341
|
+
},
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
this.gsepIdentitySection = new GSEPIdentitySection();
|
|
345
|
+
this.gsepActivityFooter = new GSEPActivityFooter();
|
|
346
|
+
const visibility = genome.config.gsepVisibility ?? 'subtle';
|
|
347
|
+
if (visibility !== 'silent') {
|
|
348
|
+
this.assembler.setGSEPIdentity(this.gsepIdentitySection, this.buildIdentityContext());
|
|
349
|
+
}
|
|
350
|
+
try {
|
|
351
|
+
this.genomeKernel = new GenomeKernel(this.toGenomeV2(), {
|
|
352
|
+
strictMode: false,
|
|
353
|
+
autoRollback: false,
|
|
354
|
+
onSecurityEvent: (event) => {
|
|
355
|
+
this.metrics.logAudit({
|
|
356
|
+
level: event.level === 'critical' ? 'error' : event.level,
|
|
357
|
+
component: 'genome-kernel',
|
|
358
|
+
operation: event.event,
|
|
359
|
+
message: `[C0 Shadow] ${event.event}`,
|
|
360
|
+
genomeId: this.genome.id,
|
|
361
|
+
metadata: event.details,
|
|
362
|
+
});
|
|
363
|
+
},
|
|
364
|
+
onIntegrityViolation: (violation) => {
|
|
365
|
+
this.metrics.logAudit({
|
|
366
|
+
level: 'error',
|
|
367
|
+
component: 'genome-kernel',
|
|
368
|
+
operation: 'c0_integrity_violation',
|
|
369
|
+
message: `C0 integrity violation: expected ${violation.expected.substring(0, 16)}..., got ${violation.actual.substring(0, 16)}...`,
|
|
370
|
+
genomeId: this.genome.id,
|
|
371
|
+
});
|
|
372
|
+
},
|
|
373
|
+
onQuarantine: (genomeId, reason) => {
|
|
374
|
+
this.metrics.logAudit({
|
|
375
|
+
level: 'error',
|
|
376
|
+
component: 'genome-kernel',
|
|
377
|
+
operation: 'quarantine',
|
|
378
|
+
message: `Genome quarantined: ${reason}`,
|
|
379
|
+
genomeId,
|
|
380
|
+
});
|
|
381
|
+
},
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
catch {
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
get id() {
|
|
388
|
+
return this.genome.id;
|
|
389
|
+
}
|
|
390
|
+
get name() {
|
|
391
|
+
return this.genome.name;
|
|
392
|
+
}
|
|
393
|
+
getWelcomeMessage(style = 'detailed') {
|
|
394
|
+
const messages = {
|
|
395
|
+
short: `🧬 I now have GSEP — Genomic Self-Evolving Prompts integrated into my DNA!
|
|
396
|
+
|
|
397
|
+
This means I can:
|
|
398
|
+
✓ Learn from every interaction
|
|
399
|
+
✓ Adapt uniquely to each user
|
|
400
|
+
✓ Improve continuously without manual updates
|
|
401
|
+
|
|
402
|
+
I'm ready to evolve with you!`,
|
|
403
|
+
detailed: `🧬 Great news! I now have GSEP — Genomic Self-Evolving Prompts integrated into my core system!
|
|
404
|
+
|
|
405
|
+
What this means for you:
|
|
406
|
+
|
|
407
|
+
🎯 **Adaptive Intelligence**
|
|
408
|
+
→ I learn from every conversation we have
|
|
409
|
+
→ I adapt my responses to match your unique style and preferences
|
|
410
|
+
→ I remember what works best for you
|
|
411
|
+
|
|
412
|
+
🔄 **Continuous Evolution**
|
|
413
|
+
→ My capabilities improve automatically over time
|
|
414
|
+
→ No manual updates needed — I evolve naturally
|
|
415
|
+
→ Each interaction makes me better at helping you
|
|
416
|
+
|
|
417
|
+
🛡️ **Built-in Safety**
|
|
418
|
+
→ Four-layer genomic architecture (Immutable Core + Adaptive Layers + Content Firewall)
|
|
419
|
+
→ Automatic rollback if performance drops
|
|
420
|
+
→ Sandbox-tested improvements before deployment
|
|
421
|
+
|
|
422
|
+
📊 **What happens next:**
|
|
423
|
+
1. I'll start learning your communication style
|
|
424
|
+
2. I'll track which approaches work best for you
|
|
425
|
+
3. I'll continuously optimize my responses
|
|
426
|
+
4. You'll notice me getting better at understanding your needs
|
|
427
|
+
|
|
428
|
+
Let's evolve together! How can I help you today?`,
|
|
429
|
+
technical: `🧬 System Update: GSEP (Genomic Self-Evolving Prompts) — ACTIVE
|
|
430
|
+
|
|
431
|
+
**Architecture Overview:**
|
|
432
|
+
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
|
433
|
+
├─ Layer 0: Immutable DNA (Core Identity, Ethics, Security)
|
|
434
|
+
│ └─ Status: LOCKED — Never mutates
|
|
435
|
+
├─ Layer 1: Operative Genes (Tool Usage, Problem Solving)
|
|
436
|
+
│ └─ Status: ACTIVE — Slow mutation with validation
|
|
437
|
+
└─ Layer 2: Epigenomes (User Preferences, Communication Style)
|
|
438
|
+
└─ Status: ACTIVE — Fast mutation with daily adaptation
|
|
439
|
+
|
|
440
|
+
**Enabled Capabilities:**
|
|
441
|
+
→ Natural Selection Loop (Transcription → Variation → Simulation → Selection)
|
|
442
|
+
→ User DNA Profiling (Cognitive patterns, preferences, expertise)
|
|
443
|
+
→ Epsilon-Greedy Selection (Exploration: ${this.genome.config.epsilonExplore || 0.1})
|
|
444
|
+
→ Sandbox Testing (${this.genome.config.enableSandbox ? 'ENABLED' : 'DISABLED'})
|
|
445
|
+
→ Mutation Rate: ${this.genome.config.mutationRate.toUpperCase()}
|
|
446
|
+
→ Immune System: Auto-rollback on performance drops >20%
|
|
447
|
+
|
|
448
|
+
**Fitness Optimization:**
|
|
449
|
+
├─ Cognitive Compression (efficiency)
|
|
450
|
+
├─ Intervention Rate (autonomy)
|
|
451
|
+
└─ Execution Precision (reliability)
|
|
452
|
+
|
|
453
|
+
**Learning Protocol:**
|
|
454
|
+
Every interaction contributes to:
|
|
455
|
+
1. Allele fitness tracking (EMA updates)
|
|
456
|
+
2. User DNA profile evolution
|
|
457
|
+
3. Mutation proposal generation
|
|
458
|
+
4. Performance optimization
|
|
459
|
+
|
|
460
|
+
System ready. Genomic evolution: INITIALIZED.`,
|
|
461
|
+
casual: `🧬 Hey! Exciting update — I just got upgraded with GSEP (think of it as evolutionary AI)!
|
|
462
|
+
|
|
463
|
+
Here's the cool part:
|
|
464
|
+
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
|
465
|
+
🎨 I'll learn your style
|
|
466
|
+
→ Prefer technical answers? I'll adapt
|
|
467
|
+
→ Like casual chat? I'll match that vibe
|
|
468
|
+
→ Need quick responses? I'll optimize for speed
|
|
469
|
+
|
|
470
|
+
🚀 I get better over time
|
|
471
|
+
→ Each conversation teaches me something new
|
|
472
|
+
→ I remember what works best for you
|
|
473
|
+
→ No updates needed — I evolve naturally
|
|
474
|
+
|
|
475
|
+
🛡️ Built-in safety nets
|
|
476
|
+
→ If something doesn't work, I auto-rollback
|
|
477
|
+
→ Core values never change (safety first!)
|
|
478
|
+
→ All improvements are tested before going live
|
|
479
|
+
|
|
480
|
+
So basically... I'm not just an AI anymore. I'm YOUR AI, continuously evolving to serve you better.
|
|
481
|
+
|
|
482
|
+
Ready to see what we can do together? 😊`,
|
|
483
|
+
};
|
|
484
|
+
return messages[style];
|
|
485
|
+
}
|
|
486
|
+
async assemblePrompt(context, currentMessage) {
|
|
487
|
+
return this.assembler.assemblePrompt(context, currentMessage);
|
|
488
|
+
}
|
|
489
|
+
static MAX_INPUT_LENGTH = 100_000;
|
|
490
|
+
async chat(userMessage, context) {
|
|
491
|
+
if (!this.llm) {
|
|
492
|
+
throw new Error(`[GSEP] Cannot chat: no LLM adapter configured. `
|
|
493
|
+
+ `The agent needs an AI model to generate responses.`);
|
|
494
|
+
}
|
|
495
|
+
if (userMessage.length > GenomeInstance.MAX_INPUT_LENGTH) {
|
|
496
|
+
throw new Error(`[GSEP] Input too long: ${userMessage.length} characters exceeds maximum of ${GenomeInstance.MAX_INPUT_LENGTH}.`);
|
|
497
|
+
}
|
|
498
|
+
if (this.genomeKernel) {
|
|
499
|
+
try {
|
|
500
|
+
this.genomeKernel.verifyIntegrity();
|
|
501
|
+
}
|
|
502
|
+
catch (integrityError) {
|
|
503
|
+
const msg = integrityError instanceof Error ? integrityError.message : 'Unknown integrity violation';
|
|
504
|
+
this.metrics.logAudit({
|
|
505
|
+
level: 'error',
|
|
506
|
+
component: 'genome-kernel',
|
|
507
|
+
operation: 'c0-integrity-check',
|
|
508
|
+
message: `C0 integrity violation detected: ${msg}`,
|
|
509
|
+
genomeId: this.genome.id,
|
|
510
|
+
});
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
const requestId = `chat_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
|
514
|
+
const startTime = Date.now();
|
|
515
|
+
let error;
|
|
516
|
+
try {
|
|
517
|
+
if (this.stateVector) {
|
|
518
|
+
this.stateVector.beginCycle(userMessage, context.taskType);
|
|
519
|
+
}
|
|
520
|
+
if (this.stateVector) {
|
|
521
|
+
if (this.emotionalModel) {
|
|
522
|
+
const emotion = this.emotionalModel.inferEmotion(userMessage);
|
|
523
|
+
const tone = this.emotionalModel.getToneGuidance(emotion);
|
|
524
|
+
this.stateVector.updateEmotional({
|
|
525
|
+
userEmotion: emotion.primary,
|
|
526
|
+
intensity: emotion.intensity,
|
|
527
|
+
agentTone: tone.suggestedTone,
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
if (this.metacognition) {
|
|
531
|
+
const preAnalysis = this.metacognition.analyzePreResponse(userMessage);
|
|
532
|
+
this.stateVector.updateCognitive({
|
|
533
|
+
confidence: preAnalysis.confidence.overall,
|
|
534
|
+
knowledgeGaps: preAnalysis.knowledgeGaps ?? [],
|
|
535
|
+
suggestedAction: preAnalysis.suggestedAction,
|
|
536
|
+
domain: context.taskType ?? null,
|
|
537
|
+
});
|
|
538
|
+
}
|
|
539
|
+
if (this.patternMemory) {
|
|
540
|
+
const preds = this.patternMemory.getPredictions();
|
|
541
|
+
this.stateVector.updateMemory({ predictions: preds.map(p => p.prediction) });
|
|
542
|
+
}
|
|
543
|
+
if (this.personalNarrative) {
|
|
544
|
+
const stage = this.personalNarrative.getRelationshipStage();
|
|
545
|
+
this.stateVector.updateMemory({ relationshipStage: stage });
|
|
546
|
+
}
|
|
547
|
+
if (this.analyticMemory && context.userId) {
|
|
548
|
+
const ks = this.analyticMemory.getKnowledgeSummary(context.userId);
|
|
549
|
+
this.stateVector.updateMemory({
|
|
550
|
+
knowledgeSummary: ks.summary,
|
|
551
|
+
recentTopics: ks.topEntities?.slice(0, 5).map((e) => e.name) ?? [],
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
const driftReport = this.driftAnalyzer.analyzeDrift();
|
|
555
|
+
const fitnessVec = this.driftAnalyzer.getLatestFitness();
|
|
556
|
+
const hScore = fitnessVec?.composite ?? 0.5;
|
|
557
|
+
this.stateVector.updateHealth({
|
|
558
|
+
operatingMode: this.purposeSurvival?.getMode() ?? 'stable',
|
|
559
|
+
healthScore: hScore,
|
|
560
|
+
healthLabel: hScore >= 0.8 ? 'excellent' : hScore >= 0.6 ? 'stable' : hScore >= 0.4 ? 'degraded' : 'critical',
|
|
561
|
+
isDrifting: driftReport.isDrifting,
|
|
562
|
+
driftSeverity: driftReport.overallSeverity ?? 'none',
|
|
563
|
+
});
|
|
564
|
+
if (this.metaEvolutionEngine) {
|
|
565
|
+
const rec = this.metaEvolutionEngine.getStrategyRecommendation();
|
|
566
|
+
const vel = this.metaEvolutionEngine.getLearningVelocity();
|
|
567
|
+
this.stateVector.updateEvolution({
|
|
568
|
+
bestOperator: rec.bestOperator,
|
|
569
|
+
learningVelocity: vel.status,
|
|
570
|
+
interactionCount: this.interactionCount,
|
|
571
|
+
lastEvolutionTriggered: false,
|
|
572
|
+
});
|
|
573
|
+
}
|
|
574
|
+
if (this.strategicAutonomy && context.taskType) {
|
|
575
|
+
const decision = this.strategicAutonomy.evaluateStrategic(context.taskType, undefined, userMessage);
|
|
576
|
+
this.stateVector.updateAutonomy({
|
|
577
|
+
canActAutonomously: decision.action === 'proceed',
|
|
578
|
+
mutationRate: decision.suggestedMutationRate ?? 'balanced',
|
|
579
|
+
refusedCurrentTask: decision.action === 'refuse',
|
|
580
|
+
refusalReason: decision.action === 'refuse' ? decision.reasoning : null,
|
|
581
|
+
});
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
if (this.autonomousLoop && this.stateVector) {
|
|
585
|
+
const observation = this.autonomousLoop.observe(userMessage, this.stateVector.getState());
|
|
586
|
+
const thinking = this.autonomousLoop.think(observation);
|
|
587
|
+
this.autonomousLoop.plan(thinking);
|
|
588
|
+
}
|
|
589
|
+
if (this.curiosityEngine) {
|
|
590
|
+
const domain = this.stateVector?.getState().cognitive.domain ?? context.taskType ?? null;
|
|
591
|
+
const confidence = this.stateVector?.getState().cognitive.confidence ?? 0.7;
|
|
592
|
+
this.curiosityEngine.detectGaps(userMessage, domain, confidence);
|
|
593
|
+
}
|
|
594
|
+
if (this.strategicAutonomy && context.taskType) {
|
|
595
|
+
const refusal = this.strategicAutonomy.shouldRefuse(context.taskType, userMessage);
|
|
596
|
+
if (refusal.refuse) {
|
|
597
|
+
this.metrics.logAudit({
|
|
598
|
+
level: 'info',
|
|
599
|
+
component: 'genome',
|
|
600
|
+
operation: 'strategic-refusal',
|
|
601
|
+
message: `Task refused: ${refusal.reason}`,
|
|
602
|
+
userId: context.userId,
|
|
603
|
+
genomeId: this.genome.id,
|
|
604
|
+
});
|
|
605
|
+
return `I can't proceed with this request. ${refusal.reason}`;
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
if (this.metacognition && !this.stateVector) {
|
|
609
|
+
this.metacognition.analyzePreResponse(userMessage);
|
|
610
|
+
}
|
|
611
|
+
if (this.genome.config.autonomous?.enableModelRouting) {
|
|
612
|
+
const routingDecision = await this.modelRouter.routeTask({
|
|
613
|
+
userMessage,
|
|
614
|
+
context: context.taskType,
|
|
615
|
+
genomeId: this.genome.id,
|
|
616
|
+
});
|
|
617
|
+
this.metrics.logAudit({
|
|
618
|
+
level: 'info',
|
|
619
|
+
component: 'model-router',
|
|
620
|
+
operation: 'route',
|
|
621
|
+
message: `Routed to ${routingDecision.selectedModel}: ${routingDecision.reason}`,
|
|
622
|
+
genomeId: this.genome.id,
|
|
623
|
+
metadata: {
|
|
624
|
+
selectedModel: routingDecision.selectedModel,
|
|
625
|
+
estimatedCost: routingDecision.estimatedCost,
|
|
626
|
+
confidence: routingDecision.confidence,
|
|
627
|
+
},
|
|
628
|
+
});
|
|
629
|
+
}
|
|
630
|
+
let prompt = await this.assemblePrompt(context, userMessage);
|
|
631
|
+
if (this.ragEngine) {
|
|
632
|
+
const ragContext = await this.ragEngine.augment(userMessage, prompt);
|
|
633
|
+
prompt = ragContext.augmentedPrompt;
|
|
634
|
+
}
|
|
635
|
+
if (this.patternMemory) {
|
|
636
|
+
const predictions = this.patternMemory.getPredictions();
|
|
637
|
+
if (predictions.length > 0) {
|
|
638
|
+
const predictionLines = predictions.slice(0, 3).map(p => `- ${p.prediction} (${Math.round(p.confidence * 100)}% confidence)`);
|
|
639
|
+
prompt += `\n\n---\n\n## Behavioral Predictions\nBased on observed patterns, the user may:\n${predictionLines.join('\n')}\nConsider these predictions to proactively address the user's needs.`;
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
let activeCanaryId;
|
|
643
|
+
const activeCanaries = this.canaryManager.getActiveDeployments();
|
|
644
|
+
for (const canary of activeCanaries) {
|
|
645
|
+
if (canary.genomeId === this.genome.id && context.userId) {
|
|
646
|
+
if (this.canaryManager.shouldUseCanary(canary.id, context.userId)) {
|
|
647
|
+
activeCanaryId = canary.id;
|
|
648
|
+
prompt = this.applyCanaryVariant(prompt, canary);
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
let sanitizedUserMessage = userMessage;
|
|
653
|
+
if (this.contentFirewall) {
|
|
654
|
+
const inputScan = this.contentFirewall.scan(userMessage, 'user-input');
|
|
655
|
+
if (!inputScan.allowed) {
|
|
656
|
+
this.metrics.logAudit({
|
|
657
|
+
level: 'warning',
|
|
658
|
+
component: 'firewall',
|
|
659
|
+
operation: 'user-input-scan',
|
|
660
|
+
message: `User input blocked: ${inputScan.detections.map(d => d.patternId).join(', ')}`,
|
|
661
|
+
genomeId: this.genome.id,
|
|
662
|
+
userId: context.userId,
|
|
663
|
+
});
|
|
664
|
+
}
|
|
665
|
+
sanitizedUserMessage = inputScan.sanitizedContent;
|
|
666
|
+
}
|
|
667
|
+
let response;
|
|
668
|
+
if (this.reasoningEngine) {
|
|
669
|
+
const reasoningResult = await this.reasoningEngine.reason(sanitizedUserMessage, prompt, this.genome.config.reasoning?.defaultStrategy);
|
|
670
|
+
response = { content: reasoningResult.answer };
|
|
671
|
+
}
|
|
672
|
+
else {
|
|
673
|
+
response = await this.llm.chat([
|
|
674
|
+
{ role: 'system', content: prompt },
|
|
675
|
+
{ role: 'user', content: sanitizedUserMessage },
|
|
676
|
+
]);
|
|
677
|
+
}
|
|
678
|
+
if (this.immuneSystem) {
|
|
679
|
+
const verdict = this.immuneSystem.scanOutput(response.content, sanitizedUserMessage, prompt);
|
|
680
|
+
if (!verdict.clean) {
|
|
681
|
+
this.metrics.logAudit({
|
|
682
|
+
level: verdict.action === 'quarantine' ? 'error' : 'warning',
|
|
683
|
+
component: 'c4-immune-system',
|
|
684
|
+
operation: 'output-scan',
|
|
685
|
+
message: `Output infection detected: ${verdict.threats.map(t => t.type).join(', ')}`,
|
|
686
|
+
genomeId: this.genome.id,
|
|
687
|
+
userId: context.userId,
|
|
688
|
+
});
|
|
689
|
+
if (verdict.action === 'quarantine') {
|
|
690
|
+
this.immuneSystem.quarantineAndRecover();
|
|
691
|
+
const retryResponse = await this.llm.chat([
|
|
692
|
+
{ role: 'system', content: prompt },
|
|
693
|
+
{ role: 'user', content: sanitizedUserMessage },
|
|
694
|
+
]);
|
|
695
|
+
const retryVerdict = this.immuneSystem.scanOutput(retryResponse.content, sanitizedUserMessage, prompt);
|
|
696
|
+
if (retryVerdict.clean) {
|
|
697
|
+
response = retryResponse;
|
|
698
|
+
}
|
|
699
|
+
else {
|
|
700
|
+
response = { content: 'I apologize, but I cannot process this request safely. Please try rephrasing your question.' };
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
else if (verdict.action === 'sanitize') {
|
|
704
|
+
response = { ...response, content: verdict.response };
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
const inputTokens = response.usage?.inputTokens
|
|
709
|
+
?? Math.ceil((prompt.length + userMessage.length) / 4);
|
|
710
|
+
const outputTokens = response.usage?.outputTokens
|
|
711
|
+
?? Math.ceil(response.content.length / 4);
|
|
712
|
+
this.metrics.recordRequest({
|
|
713
|
+
requestId,
|
|
714
|
+
duration: Date.now() - startTime,
|
|
715
|
+
success: true,
|
|
716
|
+
model: 'pga-genome',
|
|
717
|
+
inputTokens,
|
|
718
|
+
outputTokens,
|
|
719
|
+
});
|
|
720
|
+
this.metrics.logAudit({
|
|
721
|
+
level: 'info',
|
|
722
|
+
component: 'genome',
|
|
723
|
+
operation: 'chat',
|
|
724
|
+
message: 'Chat completed successfully',
|
|
725
|
+
userId: context.userId,
|
|
726
|
+
genomeId: this.genome.id,
|
|
727
|
+
duration: Date.now() - startTime,
|
|
728
|
+
metadata: {
|
|
729
|
+
inputTokens,
|
|
730
|
+
outputTokens,
|
|
731
|
+
},
|
|
732
|
+
});
|
|
733
|
+
let quality = this.estimateQuality(userMessage, response.content);
|
|
734
|
+
if (this.thinkingEngine) {
|
|
735
|
+
const reflection = await this.thinkingEngine.selfReflect(userMessage, response.content);
|
|
736
|
+
quality = quality * 0.7 + reflection.qualityScore * 0.3;
|
|
737
|
+
if (context.taskType) {
|
|
738
|
+
this.thinkingEngine.recordPattern(context.taskType, reflection.qualityScore > 0.5, reflection.qualityScore);
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
if (this.genome.config.autonomous?.enableModelRouting) {
|
|
742
|
+
this.modelRouter.recordPerformance(this.llm.model ?? 'unknown', {
|
|
743
|
+
success: true,
|
|
744
|
+
cost: (inputTokens + outputTokens) / 1_000_000,
|
|
745
|
+
latency: Date.now() - startTime,
|
|
746
|
+
});
|
|
747
|
+
}
|
|
748
|
+
if (this.autonomousLoop) {
|
|
749
|
+
this.autonomousLoop.learn(quality, true);
|
|
750
|
+
}
|
|
751
|
+
if (this.growthJournal) {
|
|
752
|
+
const domain = context.taskType ?? null;
|
|
753
|
+
this.growthJournal.recordSuccess(domain, userMessage, quality);
|
|
754
|
+
}
|
|
755
|
+
if (this.curiosityEngine && context.taskType) {
|
|
756
|
+
this.curiosityEngine.recordExploration(context.taskType, true);
|
|
757
|
+
}
|
|
758
|
+
if (activeCanaryId) {
|
|
759
|
+
this.canaryManager.recordRequest(activeCanaryId, 'canary', {
|
|
760
|
+
success: true,
|
|
761
|
+
latencyMs: Date.now() - startTime,
|
|
762
|
+
fitness: quality,
|
|
763
|
+
});
|
|
764
|
+
}
|
|
765
|
+
else {
|
|
766
|
+
for (const canary of activeCanaries) {
|
|
767
|
+
if (canary.genomeId === this.genome.id) {
|
|
768
|
+
this.canaryManager.recordRequest(canary.id, 'stable', {
|
|
769
|
+
success: true,
|
|
770
|
+
latencyMs: Date.now() - startTime,
|
|
771
|
+
fitness: quality,
|
|
772
|
+
});
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
const interactionData = {
|
|
777
|
+
success: true,
|
|
778
|
+
quality,
|
|
779
|
+
inputTokens,
|
|
780
|
+
outputTokens,
|
|
781
|
+
latency: Date.now() - startTime,
|
|
782
|
+
model: this.llm.model ?? 'unknown',
|
|
783
|
+
interventionNeeded: false,
|
|
784
|
+
timestamp: new Date(),
|
|
785
|
+
};
|
|
786
|
+
const fitnessVector = this.fitnessCalculator.computeFitness([interactionData]);
|
|
787
|
+
this.driftAnalyzer.recordFitness(fitnessVector);
|
|
788
|
+
if (this.enhancedSelfModel && context.taskType) {
|
|
789
|
+
for (const allele of this.genome.layers.layer1.filter(a => a.status === 'active')) {
|
|
790
|
+
this.enhancedSelfModel.recordCapability(context.taskType, allele.gene, quality);
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
if (this.purposeSurvival) {
|
|
794
|
+
this.purposeSurvival.evaluateThreats();
|
|
795
|
+
}
|
|
796
|
+
this.interactionCount++;
|
|
797
|
+
const autoConfig = this.genome.config.autonomous;
|
|
798
|
+
if (!this.evolutionInProgress
|
|
799
|
+
&& autoConfig?.continuousEvolution
|
|
800
|
+
&& this.interactionCount % (autoConfig.evolveEveryN ?? 10) === 0) {
|
|
801
|
+
this.evolutionInProgress = true;
|
|
802
|
+
this.runEvolutionCycle()
|
|
803
|
+
.catch(err => this.metrics.logAudit({
|
|
804
|
+
level: 'warning',
|
|
805
|
+
component: 'genome',
|
|
806
|
+
operation: 'auto-evolve',
|
|
807
|
+
message: `Auto-evolution failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
808
|
+
genomeId: this.genome.id,
|
|
809
|
+
}))
|
|
810
|
+
.finally(() => {
|
|
811
|
+
this.evolutionInProgress = false;
|
|
812
|
+
});
|
|
813
|
+
}
|
|
814
|
+
if (context.userId) {
|
|
815
|
+
const previousDNA = await this.dnaProfile.getDNA(context.userId, this.genome.id);
|
|
816
|
+
await this.recordInteraction({
|
|
817
|
+
userId: context.userId,
|
|
818
|
+
userMessage,
|
|
819
|
+
assistantResponse: response.content,
|
|
820
|
+
toolCalls: [],
|
|
821
|
+
taskType: context.taskType,
|
|
822
|
+
timestamp: new Date(),
|
|
823
|
+
});
|
|
824
|
+
const updatedDNA = await this.dnaProfile.getDNA(context.userId, this.genome.id);
|
|
825
|
+
const learningEvents = this.learningAnnouncer.detectLearning(previousDNA, updatedDNA);
|
|
826
|
+
if (learningEvents.length > 0 && learningEvents[0].confidence > 0.7) {
|
|
827
|
+
const announcement = this.learningAnnouncer.formatLearningAnnouncement(learningEvents);
|
|
828
|
+
if (announcement) {
|
|
829
|
+
return response.content + '\n\n' + announcement;
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
return response.content;
|
|
834
|
+
}
|
|
835
|
+
catch (err) {
|
|
836
|
+
error = err instanceof Error ? err.message : String(err);
|
|
837
|
+
this.metrics.recordRequest({
|
|
838
|
+
requestId,
|
|
839
|
+
duration: Date.now() - startTime,
|
|
840
|
+
success: false,
|
|
841
|
+
model: 'pga-genome',
|
|
842
|
+
inputTokens: 0,
|
|
843
|
+
outputTokens: 0,
|
|
844
|
+
error,
|
|
845
|
+
});
|
|
846
|
+
this.metrics.logAudit({
|
|
847
|
+
level: 'error',
|
|
848
|
+
component: 'genome',
|
|
849
|
+
operation: 'chat',
|
|
850
|
+
message: `Chat failed: ${error}`,
|
|
851
|
+
userId: context.userId,
|
|
852
|
+
genomeId: this.genome.id,
|
|
853
|
+
duration: Date.now() - startTime,
|
|
854
|
+
error: {
|
|
855
|
+
name: err instanceof Error ? err.name : 'Error',
|
|
856
|
+
message: error,
|
|
857
|
+
stack: err instanceof Error ? err.stack : undefined,
|
|
858
|
+
},
|
|
859
|
+
});
|
|
860
|
+
throw err;
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
async chatWithStatus(userMessage, context) {
|
|
864
|
+
const visibility = this.genome.config.gsepVisibility ?? 'subtle';
|
|
865
|
+
if (visibility !== 'silent') {
|
|
866
|
+
this.assembler.updateGSEPIdentityContext(this.buildIdentityContext(context.userId));
|
|
867
|
+
}
|
|
868
|
+
const rawContent = await this.chat(userMessage, context);
|
|
869
|
+
const driftReport = this.driftAnalyzer.analyzeDrift();
|
|
870
|
+
const fitnessVector = this.driftAnalyzer.getLatestFitness();
|
|
871
|
+
const healthScore = fitnessVector?.composite ?? 0.5;
|
|
872
|
+
const healthLabel = healthScore >= 0.8 ? 'excellent' :
|
|
873
|
+
healthScore >= 0.6 ? 'stable' :
|
|
874
|
+
healthScore >= 0.4 ? 'degraded' : 'critical';
|
|
875
|
+
const autoConfig = this.genome.config.autonomous;
|
|
876
|
+
const evolutionTriggered = !!(autoConfig?.continuousEvolution
|
|
877
|
+
&& this.interactionCount % (autoConfig.evolveEveryN ?? 10) === 0);
|
|
878
|
+
const learningEventsCount = this.learningAnnouncer.getLastLearningCount();
|
|
879
|
+
const gsepStatus = {
|
|
880
|
+
active: true,
|
|
881
|
+
version: `${this.genome.version ?? 1}`,
|
|
882
|
+
interactionNumber: this.interactionCount,
|
|
883
|
+
health: { score: healthScore, label: healthLabel },
|
|
884
|
+
fitness: {
|
|
885
|
+
composite: fitnessVector?.composite ?? 0.5,
|
|
886
|
+
quality: fitnessVector?.quality ?? 0.5,
|
|
887
|
+
successRate: fitnessVector?.successRate ?? 1.0,
|
|
888
|
+
},
|
|
889
|
+
drift: {
|
|
890
|
+
isDrifting: driftReport.isDrifting,
|
|
891
|
+
signalCount: driftReport.signals?.length ?? 0,
|
|
892
|
+
},
|
|
893
|
+
learning: { eventsDetected: learningEventsCount },
|
|
894
|
+
evolution: {
|
|
895
|
+
triggered: evolutionTriggered,
|
|
896
|
+
generation: Math.max(...this.genome.layers.layer1.map(a => a.generation || 0), 0),
|
|
897
|
+
},
|
|
898
|
+
};
|
|
899
|
+
const activity = {
|
|
900
|
+
learningEventsCount,
|
|
901
|
+
driftDetected: driftReport.isDrifting,
|
|
902
|
+
evolutionTriggered,
|
|
903
|
+
healthLabel,
|
|
904
|
+
healthScore,
|
|
905
|
+
interactionNumber: this.interactionCount,
|
|
906
|
+
};
|
|
907
|
+
const footer = this.gsepActivityFooter.format(activity, visibility);
|
|
908
|
+
const content = footer ? rawContent + footer : rawContent;
|
|
909
|
+
return { content, gsep: gsepStatus };
|
|
910
|
+
}
|
|
911
|
+
buildIdentityContext(userId) {
|
|
912
|
+
const visibility = this.genome.config.gsepVisibility ?? 'subtle';
|
|
913
|
+
const driftReport = this.driftAnalyzer.analyzeDrift();
|
|
914
|
+
const fitnessVector = this.driftAnalyzer.getLatestFitness();
|
|
915
|
+
const healthScore = fitnessVector?.composite ?? 0.5;
|
|
916
|
+
const healthLabel = healthScore >= 0.8 ? 'excellent' :
|
|
917
|
+
healthScore >= 0.6 ? 'stable' :
|
|
918
|
+
healthScore >= 0.4 ? 'degraded' : 'critical';
|
|
919
|
+
const activeCapabilities = [];
|
|
920
|
+
if (this.contextMemory)
|
|
921
|
+
activeCapabilities.push('Adaptive memory — remembers your preferences');
|
|
922
|
+
if (this.patternMemory)
|
|
923
|
+
activeCapabilities.push('Pattern recognition — predicts your needs');
|
|
924
|
+
if (this.emotionalModel)
|
|
925
|
+
activeCapabilities.push('Emotional awareness — adapts tone to your state');
|
|
926
|
+
if (this.metacognition)
|
|
927
|
+
activeCapabilities.push('Metacognition — reflects on response quality');
|
|
928
|
+
if (this.selfModel || this.enhancedSelfModel)
|
|
929
|
+
activeCapabilities.push('Self-awareness — monitors its own performance');
|
|
930
|
+
if (this.calibratedAutonomy || this.strategicAutonomy)
|
|
931
|
+
activeCapabilities.push('Calibrated autonomy — adjusts independence level');
|
|
932
|
+
if (this.personalNarrative)
|
|
933
|
+
activeCapabilities.push('Relationship memory — builds on past conversations');
|
|
934
|
+
if (this.analyticMemory)
|
|
935
|
+
activeCapabilities.push('Knowledge graph — connects information across sessions');
|
|
936
|
+
if (this.ragEngine)
|
|
937
|
+
activeCapabilities.push('Knowledge retrieval — searches relevant documents');
|
|
938
|
+
if (this.reasoningEngine)
|
|
939
|
+
activeCapabilities.push('Advanced reasoning — multi-step problem solving');
|
|
940
|
+
if (this.thinkingEngine)
|
|
941
|
+
activeCapabilities.push('Chain-of-thought — self-reflects on response quality');
|
|
942
|
+
if (this.genome.config.autonomous?.enableModelRouting)
|
|
943
|
+
activeCapabilities.push('Intelligent routing — optimizes model selection per task');
|
|
944
|
+
if (this.stateVector)
|
|
945
|
+
activeCapabilities.push('Unified consciousness — blackboard architecture for self-awareness');
|
|
946
|
+
if (this.autonomousLoop)
|
|
947
|
+
activeCapabilities.push('Cognitive loop — observe→think→plan→act→learn cycle');
|
|
948
|
+
if (this.growthJournal)
|
|
949
|
+
activeCapabilities.push('Growth narrative — tracks learning journey and milestones');
|
|
950
|
+
if (this.curiosityEngine)
|
|
951
|
+
activeCapabilities.push('Curiosity driven — explores knowledge gaps proactively');
|
|
952
|
+
return {
|
|
953
|
+
genomeName: this.genome.name,
|
|
954
|
+
version: `${this.genome.version ?? 1}`,
|
|
955
|
+
visibility,
|
|
956
|
+
interactionCount: this.interactionCount,
|
|
957
|
+
isFirstInteraction: this.interactionCount === 0,
|
|
958
|
+
healthLabel,
|
|
959
|
+
healthScore,
|
|
960
|
+
fitnessScore: fitnessVector?.composite,
|
|
961
|
+
userLearningSummary: userId && this.analyticMemory
|
|
962
|
+
? this.analyticMemory.getKnowledgeSummary(userId).summary || undefined
|
|
963
|
+
: undefined,
|
|
964
|
+
activeCapabilities,
|
|
965
|
+
driftStatus: driftReport.isDrifting
|
|
966
|
+
? { isDrifting: true, severity: driftReport.overallSeverity }
|
|
967
|
+
: undefined,
|
|
968
|
+
};
|
|
969
|
+
}
|
|
970
|
+
async recordInteraction(interaction) {
|
|
971
|
+
const fullInteraction = {
|
|
972
|
+
...interaction,
|
|
973
|
+
genomeId: this.genome.id,
|
|
974
|
+
};
|
|
975
|
+
await this.storage.recordInteraction(fullInteraction);
|
|
976
|
+
await this.dnaProfile.updateDNA(interaction.userId, this.genome.id, fullInteraction);
|
|
977
|
+
for (const allele of this.genome.layers.layer1.filter(a => a.status === 'active')) {
|
|
978
|
+
const score = this.computeInteractionQuality(interaction);
|
|
979
|
+
await this.fitnessTracker.recordPerformance(1, allele.gene, allele.variant, score);
|
|
980
|
+
}
|
|
981
|
+
if (this.patternMemory) {
|
|
982
|
+
this.patternMemory.recordInteraction({
|
|
983
|
+
taskType: interaction.taskType,
|
|
984
|
+
success: !!interaction.assistantResponse,
|
|
985
|
+
timestamp: interaction.timestamp,
|
|
986
|
+
});
|
|
987
|
+
}
|
|
988
|
+
if (this.personalNarrative) {
|
|
989
|
+
this.personalNarrative.recordInteraction({
|
|
990
|
+
topic: interaction.taskType,
|
|
991
|
+
wasSuccessful: !!interaction.assistantResponse,
|
|
992
|
+
userExpressedGratitude: interaction.userMessage?.toLowerCase().includes('thanks') ||
|
|
993
|
+
interaction.userMessage?.toLowerCase().includes('thank you'),
|
|
994
|
+
});
|
|
995
|
+
}
|
|
996
|
+
if (this.analyticMemory) {
|
|
997
|
+
if (interaction.taskType) {
|
|
998
|
+
this.analyticMemory.recordObservation({
|
|
999
|
+
subject: interaction.userId,
|
|
1000
|
+
action: 'performed',
|
|
1001
|
+
object: interaction.taskType,
|
|
1002
|
+
timestamp: interaction.timestamp,
|
|
1003
|
+
});
|
|
1004
|
+
}
|
|
1005
|
+
if (interaction.userMessage) {
|
|
1006
|
+
const topics = this.extractTopicsFromMessage(interaction.userMessage);
|
|
1007
|
+
for (const topic of topics) {
|
|
1008
|
+
this.analyticMemory.recordObservation({
|
|
1009
|
+
subject: interaction.userId,
|
|
1010
|
+
action: 'mentioned',
|
|
1011
|
+
object: topic,
|
|
1012
|
+
timestamp: interaction.timestamp,
|
|
1013
|
+
});
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
if (interaction.toolCalls) {
|
|
1017
|
+
for (const tool of interaction.toolCalls) {
|
|
1018
|
+
const toolName = typeof tool === 'string' ? tool : tool.name ?? String(tool);
|
|
1019
|
+
this.analyticMemory.recordObservation({
|
|
1020
|
+
subject: interaction.userId,
|
|
1021
|
+
action: 'used tool',
|
|
1022
|
+
object: toolName,
|
|
1023
|
+
timestamp: interaction.timestamp,
|
|
1024
|
+
});
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
if (this.metacognition && interaction.assistantResponse) {
|
|
1029
|
+
this.metacognition.analyzePostResponse(interaction.userMessage, interaction.assistantResponse, !!interaction.assistantResponse);
|
|
1030
|
+
}
|
|
1031
|
+
if (this.calibratedAutonomy && interaction.taskType && interaction.assistantResponse) {
|
|
1032
|
+
this.calibratedAutonomy.recordSuccess(interaction.taskType);
|
|
1033
|
+
}
|
|
1034
|
+
if (this.enhancedSelfModel && this.interactionCount % 10 === 0) {
|
|
1035
|
+
this.enhancedSelfModel.recordFitnessSnapshot();
|
|
1036
|
+
}
|
|
1037
|
+
if (this.geneBank && this.genome.config.autonomous?.enableSwarm) {
|
|
1038
|
+
const threshold = this.genome.config.autonomous.autoPublishThreshold ?? 0.85;
|
|
1039
|
+
for (const allele of this.genome.layers.layer1.filter(a => a.status === 'active')) {
|
|
1040
|
+
if (allele.fitness >= threshold && !allele.publishedToSwarm) {
|
|
1041
|
+
this.autoPublishGene(allele).catch(err => this.metrics.logAudit({
|
|
1042
|
+
level: 'warning',
|
|
1043
|
+
component: 'gene-bank',
|
|
1044
|
+
operation: 'auto-publish',
|
|
1045
|
+
message: `Auto-publish gene failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
1046
|
+
genomeId: this.genome.id,
|
|
1047
|
+
}));
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
async reportExternalMetrics(metrics) {
|
|
1053
|
+
const requestId = `ext_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
|
1054
|
+
this.metrics.recordRequest({
|
|
1055
|
+
requestId,
|
|
1056
|
+
duration: metrics.latencyMs,
|
|
1057
|
+
success: metrics.success,
|
|
1058
|
+
model: 'external',
|
|
1059
|
+
inputTokens: metrics.inputTokens,
|
|
1060
|
+
outputTokens: metrics.outputTokens,
|
|
1061
|
+
...(metrics.success ? {} : { error: 'external-failure' }),
|
|
1062
|
+
});
|
|
1063
|
+
this.metrics.logAudit({
|
|
1064
|
+
level: 'info',
|
|
1065
|
+
component: 'genome',
|
|
1066
|
+
operation: 'external-report',
|
|
1067
|
+
message: `External metrics reported: ${metrics.success ? 'success' : 'failure'}`,
|
|
1068
|
+
userId: metrics.userId,
|
|
1069
|
+
genomeId: this.genome.id,
|
|
1070
|
+
duration: metrics.latencyMs,
|
|
1071
|
+
metadata: {
|
|
1072
|
+
inputTokens: metrics.inputTokens,
|
|
1073
|
+
outputTokens: metrics.outputTokens,
|
|
1074
|
+
taskType: metrics.taskType,
|
|
1075
|
+
},
|
|
1076
|
+
});
|
|
1077
|
+
const quality = metrics.quality ?? (metrics.success ? 0.7 : 0.3);
|
|
1078
|
+
const interactionData = {
|
|
1079
|
+
success: metrics.success,
|
|
1080
|
+
quality,
|
|
1081
|
+
inputTokens: metrics.inputTokens,
|
|
1082
|
+
outputTokens: metrics.outputTokens,
|
|
1083
|
+
latency: metrics.latencyMs,
|
|
1084
|
+
model: 'external',
|
|
1085
|
+
interventionNeeded: false,
|
|
1086
|
+
timestamp: new Date(),
|
|
1087
|
+
};
|
|
1088
|
+
const fitnessVector = this.fitnessCalculator.computeFitness([interactionData]);
|
|
1089
|
+
this.driftAnalyzer.recordFitness(fitnessVector);
|
|
1090
|
+
if (this.enhancedSelfModel && metrics.taskType) {
|
|
1091
|
+
for (const allele of this.genome.layers.layer1.filter(a => a.status === 'active')) {
|
|
1092
|
+
this.enhancedSelfModel.recordCapability(metrics.taskType, allele.gene, quality);
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
if (this.purposeSurvival) {
|
|
1096
|
+
this.purposeSurvival.evaluateThreats();
|
|
1097
|
+
}
|
|
1098
|
+
this.interactionCount++;
|
|
1099
|
+
const autoConfig = this.genome.config.autonomous;
|
|
1100
|
+
if (!this.evolutionInProgress
|
|
1101
|
+
&& autoConfig?.continuousEvolution
|
|
1102
|
+
&& this.interactionCount % (autoConfig.evolveEveryN ?? 10) === 0) {
|
|
1103
|
+
this.evolutionInProgress = true;
|
|
1104
|
+
this.runEvolutionCycle()
|
|
1105
|
+
.catch(err => this.metrics.logAudit({
|
|
1106
|
+
level: 'warning',
|
|
1107
|
+
component: 'genome',
|
|
1108
|
+
operation: 'auto-evolve',
|
|
1109
|
+
message: `Auto-evolution failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
1110
|
+
genomeId: this.genome.id,
|
|
1111
|
+
}))
|
|
1112
|
+
.finally(() => {
|
|
1113
|
+
this.evolutionInProgress = false;
|
|
1114
|
+
});
|
|
1115
|
+
}
|
|
1116
|
+
if (metrics.feedback && metrics.userId) {
|
|
1117
|
+
const activeGenes = this.genome.layers.layer1.filter(a => a.status === 'active');
|
|
1118
|
+
for (const allele of activeGenes) {
|
|
1119
|
+
await this.recordFeedback(metrics.userId, allele.gene, metrics.feedback);
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
async getDNA(userId) {
|
|
1124
|
+
return this.dnaProfile.getDNA(userId, this.genome.id);
|
|
1125
|
+
}
|
|
1126
|
+
async recordFeedback(userId, gene, sentiment) {
|
|
1127
|
+
await this.storage.recordFeedback({
|
|
1128
|
+
genomeId: this.genome.id,
|
|
1129
|
+
userId,
|
|
1130
|
+
gene,
|
|
1131
|
+
sentiment,
|
|
1132
|
+
timestamp: new Date(),
|
|
1133
|
+
});
|
|
1134
|
+
}
|
|
1135
|
+
async addAllele(layer, gene, variant, content) {
|
|
1136
|
+
const newAllele = {
|
|
1137
|
+
gene,
|
|
1138
|
+
variant,
|
|
1139
|
+
content,
|
|
1140
|
+
fitness: 0.5,
|
|
1141
|
+
sampleCount: 0,
|
|
1142
|
+
generation: 0,
|
|
1143
|
+
status: 'active',
|
|
1144
|
+
createdAt: new Date(),
|
|
1145
|
+
};
|
|
1146
|
+
const layerKey = `layer${layer}`;
|
|
1147
|
+
this.genome.layers[layerKey].push(newAllele);
|
|
1148
|
+
try {
|
|
1149
|
+
await this.storage.saveGenome(this.genome);
|
|
1150
|
+
}
|
|
1151
|
+
catch (err) {
|
|
1152
|
+
const idx = this.genome.layers[layerKey].indexOf(newAllele);
|
|
1153
|
+
if (idx !== -1)
|
|
1154
|
+
this.genome.layers[layerKey].splice(idx, 1);
|
|
1155
|
+
throw err;
|
|
1156
|
+
}
|
|
1157
|
+
await this.storage.logMutation({
|
|
1158
|
+
genomeId: this.genome.id,
|
|
1159
|
+
layer,
|
|
1160
|
+
gene,
|
|
1161
|
+
variant,
|
|
1162
|
+
mutationType: 'user_feedback',
|
|
1163
|
+
parentVariant: null,
|
|
1164
|
+
deployed: true,
|
|
1165
|
+
createdAt: new Date(),
|
|
1166
|
+
});
|
|
1167
|
+
}
|
|
1168
|
+
async mutate(options) {
|
|
1169
|
+
const startTime = Date.now();
|
|
1170
|
+
const opts = {
|
|
1171
|
+
operators: options?.operators || ['compress_instructions', 'reorder_constraints'],
|
|
1172
|
+
candidates: options?.candidates || 3,
|
|
1173
|
+
minImprovement: options?.minImprovement || 0.05,
|
|
1174
|
+
taskType: options?.taskType || 'general',
|
|
1175
|
+
layer: options?.layer ?? 2,
|
|
1176
|
+
gene: options?.gene || 'system_instructions',
|
|
1177
|
+
};
|
|
1178
|
+
try {
|
|
1179
|
+
if (this.genomeKernel) {
|
|
1180
|
+
try {
|
|
1181
|
+
this.genomeKernel.createSnapshot(`pre-mutation:${opts.gene}`);
|
|
1182
|
+
}
|
|
1183
|
+
catch {
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
const layerKey = `layer${opts.layer}`;
|
|
1187
|
+
const currentAlleles = this.genome.layers[layerKey].filter(a => a.gene === opts.gene && a.status === 'active');
|
|
1188
|
+
if (currentAlleles.length === 0) {
|
|
1189
|
+
return {
|
|
1190
|
+
applied: false,
|
|
1191
|
+
reason: `No active allele found for gene '${opts.gene}' in layer ${opts.layer}`,
|
|
1192
|
+
};
|
|
1193
|
+
}
|
|
1194
|
+
const currentAllele = currentAlleles[0];
|
|
1195
|
+
const mutationContext = {
|
|
1196
|
+
genome: this.toGenomeV2(),
|
|
1197
|
+
targetChromosome: opts.layer <= 1 ? 'c1' : 'c2',
|
|
1198
|
+
targetGene: this.toOperativeGene(currentAllele),
|
|
1199
|
+
reason: `Mutation for ${opts.taskType}: gene ${opts.gene}`,
|
|
1200
|
+
evidence: this.buildEvolutionEvidence(),
|
|
1201
|
+
};
|
|
1202
|
+
let mutatedContent = currentAllele.content;
|
|
1203
|
+
let expectedImprovement = 0.05;
|
|
1204
|
+
try {
|
|
1205
|
+
const mutants = await this.mutationEngine.generateMutants(mutationContext, opts.candidates);
|
|
1206
|
+
if (mutants.length > 0) {
|
|
1207
|
+
const bestMutant = mutants.sort((a, b) => b.expectedImprovement - a.expectedImprovement)[0];
|
|
1208
|
+
const mutatedGene = bestMutant.mutant.chromosomes.c1.operations.find(g => g.category === currentAllele.gene);
|
|
1209
|
+
if (mutatedGene) {
|
|
1210
|
+
mutatedContent = mutatedGene.content;
|
|
1211
|
+
}
|
|
1212
|
+
expectedImprovement = bestMutant.expectedImprovement;
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
catch {
|
|
1216
|
+
}
|
|
1217
|
+
const mutationCandidate = {
|
|
1218
|
+
layer: opts.layer,
|
|
1219
|
+
gene: opts.gene,
|
|
1220
|
+
variant: `${currentAllele.variant}_v${Date.now()}`,
|
|
1221
|
+
content: mutatedContent,
|
|
1222
|
+
fitness: currentAllele.fitness + expectedImprovement,
|
|
1223
|
+
sandboxScore: 0.75,
|
|
1224
|
+
sampleCount: currentAllele.sampleCount || 0,
|
|
1225
|
+
rollbackCount: 0,
|
|
1226
|
+
};
|
|
1227
|
+
const gateResult = await this.guardrailsManager.evaluateCandidate(mutationCandidate, this.genome.id);
|
|
1228
|
+
const result = gateResult.finalDecision === 'promote' ? await (async () => {
|
|
1229
|
+
currentAllele.status = 'retired';
|
|
1230
|
+
const promotedAllele = {
|
|
1231
|
+
gene: opts.gene,
|
|
1232
|
+
variant: mutationCandidate.variant,
|
|
1233
|
+
content: mutationCandidate.content,
|
|
1234
|
+
fitness: mutationCandidate.fitness,
|
|
1235
|
+
sampleCount: 0,
|
|
1236
|
+
generation: (currentAllele.generation || 0) + 1,
|
|
1237
|
+
parentVariant: currentAllele.variant,
|
|
1238
|
+
status: 'active',
|
|
1239
|
+
createdAt: new Date(),
|
|
1240
|
+
};
|
|
1241
|
+
this.genome.layers[layerKey].push(promotedAllele);
|
|
1242
|
+
try {
|
|
1243
|
+
await this.storage.saveGenome(this.genome);
|
|
1244
|
+
}
|
|
1245
|
+
catch (err) {
|
|
1246
|
+
currentAllele.status = 'active';
|
|
1247
|
+
const idx = this.genome.layers[layerKey].indexOf(promotedAllele);
|
|
1248
|
+
if (idx !== -1)
|
|
1249
|
+
this.genome.layers[layerKey].splice(idx, 1);
|
|
1250
|
+
throw err;
|
|
1251
|
+
}
|
|
1252
|
+
await this.storage.logMutation({
|
|
1253
|
+
genomeId: this.genome.id,
|
|
1254
|
+
layer: opts.layer,
|
|
1255
|
+
gene: opts.gene,
|
|
1256
|
+
variant: mutationCandidate.variant,
|
|
1257
|
+
mutationType: 'targeted',
|
|
1258
|
+
parentVariant: currentAllele.variant,
|
|
1259
|
+
deployed: true,
|
|
1260
|
+
createdAt: new Date(),
|
|
1261
|
+
});
|
|
1262
|
+
return {
|
|
1263
|
+
applied: true,
|
|
1264
|
+
reason: gateResult.reason,
|
|
1265
|
+
improvement: mutationCandidate.fitness - currentAllele.fitness,
|
|
1266
|
+
gateResults: {
|
|
1267
|
+
quality: gateResult.gates.quality,
|
|
1268
|
+
sandbox: gateResult.gates.sandbox,
|
|
1269
|
+
economic: gateResult.gates.economic,
|
|
1270
|
+
stability: gateResult.gates.stability,
|
|
1271
|
+
},
|
|
1272
|
+
};
|
|
1273
|
+
})() : gateResult.finalDecision === 'canary' ? await (async () => {
|
|
1274
|
+
const canaryAllele = {
|
|
1275
|
+
gene: opts.gene,
|
|
1276
|
+
variant: mutationCandidate.variant,
|
|
1277
|
+
content: mutationCandidate.content,
|
|
1278
|
+
fitness: mutationCandidate.fitness,
|
|
1279
|
+
status: 'active',
|
|
1280
|
+
createdAt: new Date(),
|
|
1281
|
+
};
|
|
1282
|
+
await this.canaryManager.startCanary({
|
|
1283
|
+
genomeId: this.genome.id,
|
|
1284
|
+
layer: opts.layer,
|
|
1285
|
+
gene: opts.gene,
|
|
1286
|
+
stableAllele: currentAllele,
|
|
1287
|
+
canaryAllele,
|
|
1288
|
+
});
|
|
1289
|
+
return {
|
|
1290
|
+
applied: false,
|
|
1291
|
+
reason: `${gateResult.reason} - Canary deployment started (10% traffic)`,
|
|
1292
|
+
gateResults: {
|
|
1293
|
+
quality: gateResult.gates.quality,
|
|
1294
|
+
sandbox: gateResult.gates.sandbox,
|
|
1295
|
+
economic: gateResult.gates.economic,
|
|
1296
|
+
stability: gateResult.gates.stability,
|
|
1297
|
+
},
|
|
1298
|
+
};
|
|
1299
|
+
})() : {
|
|
1300
|
+
applied: false,
|
|
1301
|
+
reason: gateResult.reason,
|
|
1302
|
+
gateResults: {
|
|
1303
|
+
quality: gateResult.gates.quality,
|
|
1304
|
+
sandbox: gateResult.gates.sandbox,
|
|
1305
|
+
economic: gateResult.gates.economic,
|
|
1306
|
+
stability: gateResult.gates.stability,
|
|
1307
|
+
},
|
|
1308
|
+
};
|
|
1309
|
+
if (result.applied && this.genomeKernel) {
|
|
1310
|
+
try {
|
|
1311
|
+
this.genomeKernel = new GenomeKernel(this.toGenomeV2(), {
|
|
1312
|
+
strictMode: false,
|
|
1313
|
+
autoRollback: false,
|
|
1314
|
+
});
|
|
1315
|
+
}
|
|
1316
|
+
catch {
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
this.metrics.logAudit({
|
|
1320
|
+
level: result.applied ? 'info' : 'warning',
|
|
1321
|
+
component: 'genome',
|
|
1322
|
+
operation: 'mutate',
|
|
1323
|
+
message: result.applied ? 'Mutation applied successfully' : `Mutation rejected: ${result.reason}`,
|
|
1324
|
+
genomeId: this.genome.id,
|
|
1325
|
+
duration: Date.now() - startTime,
|
|
1326
|
+
metadata: {
|
|
1327
|
+
layer: opts.layer,
|
|
1328
|
+
gene: opts.gene,
|
|
1329
|
+
operators: opts.operators,
|
|
1330
|
+
decision: gateResult.finalDecision,
|
|
1331
|
+
improvement: 'improvement' in result ? result.improvement : undefined,
|
|
1332
|
+
gatesPassed: Object.values(gateResult.gates).filter(g => g.passed).length,
|
|
1333
|
+
totalGates: Object.keys(gateResult.gates).length,
|
|
1334
|
+
},
|
|
1335
|
+
});
|
|
1336
|
+
return result;
|
|
1337
|
+
}
|
|
1338
|
+
catch (err) {
|
|
1339
|
+
const error = err instanceof Error ? err.message : String(err);
|
|
1340
|
+
this.metrics.logAudit({
|
|
1341
|
+
level: 'error',
|
|
1342
|
+
component: 'genome',
|
|
1343
|
+
operation: 'mutate',
|
|
1344
|
+
message: `Mutation failed: ${error}`,
|
|
1345
|
+
genomeId: this.genome.id,
|
|
1346
|
+
duration: Date.now() - startTime,
|
|
1347
|
+
error: {
|
|
1348
|
+
name: err instanceof Error ? err.name : 'Error',
|
|
1349
|
+
message: error,
|
|
1350
|
+
stack: err instanceof Error ? err.stack : undefined,
|
|
1351
|
+
},
|
|
1352
|
+
});
|
|
1353
|
+
throw err;
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
async rollback(options) {
|
|
1357
|
+
const { layer, gene, variant } = options;
|
|
1358
|
+
const layerKey = `layer${layer}`;
|
|
1359
|
+
const alleles = this.genome.layers[layerKey];
|
|
1360
|
+
const allele = alleles.find(a => a.gene === gene && a.variant === variant);
|
|
1361
|
+
if (!allele) {
|
|
1362
|
+
throw new Error(`Allele not found: ${gene}:${variant}`);
|
|
1363
|
+
}
|
|
1364
|
+
if (!allele.parentVariant) {
|
|
1365
|
+
throw new Error(`No parent variant to rollback to for ${gene}:${variant}`);
|
|
1366
|
+
}
|
|
1367
|
+
const parentAllele = alleles.find(a => a.gene === gene && a.variant === allele.parentVariant);
|
|
1368
|
+
if (!parentAllele) {
|
|
1369
|
+
throw new Error(`Parent variant not found: ${allele.parentVariant}`);
|
|
1370
|
+
}
|
|
1371
|
+
allele.status = 'retired';
|
|
1372
|
+
parentAllele.status = 'active';
|
|
1373
|
+
if (this.genome.lineage) {
|
|
1374
|
+
this.genome.lineage.mutationOps = [
|
|
1375
|
+
...(this.genome.lineage.mutationOps || []),
|
|
1376
|
+
'rollback',
|
|
1377
|
+
];
|
|
1378
|
+
}
|
|
1379
|
+
await this.storage.saveGenome(this.genome);
|
|
1380
|
+
await this.storage.logMutation({
|
|
1381
|
+
genomeId: this.genome.id,
|
|
1382
|
+
layer,
|
|
1383
|
+
gene,
|
|
1384
|
+
variant: parentAllele.variant,
|
|
1385
|
+
mutationType: 'rollback',
|
|
1386
|
+
parentVariant: allele.variant,
|
|
1387
|
+
deployed: true,
|
|
1388
|
+
reason: 'Manual rollback requested',
|
|
1389
|
+
createdAt: new Date(),
|
|
1390
|
+
});
|
|
1391
|
+
}
|
|
1392
|
+
async chatWithMetrics(userMessage, context) {
|
|
1393
|
+
const startTime = Date.now();
|
|
1394
|
+
const content = await this.chat(userMessage, context);
|
|
1395
|
+
const endTime = Date.now();
|
|
1396
|
+
const tokensUsed = Math.ceil((userMessage.length + content.length) / 4);
|
|
1397
|
+
const responseTime = endTime - startTime;
|
|
1398
|
+
const analytics = await this.storage.getAnalytics(this.genome.id);
|
|
1399
|
+
const fitnessScore = analytics.userSatisfaction || 0.5;
|
|
1400
|
+
return {
|
|
1401
|
+
content,
|
|
1402
|
+
metrics: {
|
|
1403
|
+
tokensUsed,
|
|
1404
|
+
responseTime,
|
|
1405
|
+
fitnessScore,
|
|
1406
|
+
},
|
|
1407
|
+
};
|
|
1408
|
+
}
|
|
1409
|
+
async publishGeneToRegistry(gene, variant, description) {
|
|
1410
|
+
if (!this.genome.familyId) {
|
|
1411
|
+
throw new Error('Genome must have familyId to publish to registry');
|
|
1412
|
+
}
|
|
1413
|
+
let allele;
|
|
1414
|
+
let layer = 0;
|
|
1415
|
+
for (const [layerName, alleles] of Object.entries(this.genome.layers)) {
|
|
1416
|
+
allele = alleles.find(a => a.gene === gene && a.variant === variant);
|
|
1417
|
+
if (allele) {
|
|
1418
|
+
layer = parseInt(layerName.replace('layer', ''));
|
|
1419
|
+
break;
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
if (!allele) {
|
|
1423
|
+
throw new Error(`Allele not found: ${gene}:${variant}`);
|
|
1424
|
+
}
|
|
1425
|
+
const successRate = allele.fitness;
|
|
1426
|
+
const registryId = `${this.genome.familyId}_${gene}_${variant}_${Date.now()}`;
|
|
1427
|
+
if (this.storage.saveToGeneRegistry) {
|
|
1428
|
+
await this.storage.saveToGeneRegistry({
|
|
1429
|
+
id: registryId,
|
|
1430
|
+
familyId: this.genome.familyId,
|
|
1431
|
+
gene,
|
|
1432
|
+
variant,
|
|
1433
|
+
content: allele.content,
|
|
1434
|
+
layer,
|
|
1435
|
+
fitness: allele.fitness,
|
|
1436
|
+
sampleCount: allele.sampleCount || 0,
|
|
1437
|
+
successRate,
|
|
1438
|
+
metadata: {
|
|
1439
|
+
sourceGenomeId: this.genome.id,
|
|
1440
|
+
sourceVersion: this.genome.version || 1,
|
|
1441
|
+
publishedBy: this.genome.id,
|
|
1442
|
+
description: description || undefined,
|
|
1443
|
+
},
|
|
1444
|
+
createdAt: new Date(),
|
|
1445
|
+
});
|
|
1446
|
+
}
|
|
1447
|
+
await this.storage.logMutation({
|
|
1448
|
+
genomeId: this.genome.id,
|
|
1449
|
+
layer,
|
|
1450
|
+
gene,
|
|
1451
|
+
variant,
|
|
1452
|
+
mutationType: 'user_feedback',
|
|
1453
|
+
parentVariant: null,
|
|
1454
|
+
deployed: true,
|
|
1455
|
+
reason: `Published to registry: ${description || 'No description'} (fitness: ${successRate})`,
|
|
1456
|
+
createdAt: new Date(),
|
|
1457
|
+
});
|
|
1458
|
+
return registryId;
|
|
1459
|
+
}
|
|
1460
|
+
async inheritGeneFromRegistry(familyId, gene, targetLayer) {
|
|
1461
|
+
if (this.genome.familyId && this.genome.familyId !== familyId) {
|
|
1462
|
+
throw new Error(`Cannot inherit from different family: ${familyId}`);
|
|
1463
|
+
}
|
|
1464
|
+
if (!this.storage.getBestRegistryGene) {
|
|
1465
|
+
throw new Error('Storage adapter does not support Gene Registry queries');
|
|
1466
|
+
}
|
|
1467
|
+
const bestGene = await this.storage.getBestRegistryGene(familyId, gene);
|
|
1468
|
+
if (!bestGene) {
|
|
1469
|
+
throw new Error(`No gene '${gene}' found in registry for family '${familyId}'`);
|
|
1470
|
+
}
|
|
1471
|
+
const layer = targetLayer ?? bestGene.layer ?? 1;
|
|
1472
|
+
await this.addAllele(layer, gene, `inherited_${bestGene.variant}_${Date.now()}`, bestGene.content);
|
|
1473
|
+
if (this.genome.lineage) {
|
|
1474
|
+
this.genome.lineage.mutationOps = [
|
|
1475
|
+
...(this.genome.lineage.mutationOps || []),
|
|
1476
|
+
`inherit:${gene}:${bestGene.variant}`,
|
|
1477
|
+
];
|
|
1478
|
+
}
|
|
1479
|
+
this.metrics.logAudit({
|
|
1480
|
+
level: 'info',
|
|
1481
|
+
component: 'genome',
|
|
1482
|
+
operation: 'inherit-gene',
|
|
1483
|
+
message: `Inherited gene '${gene}' (variant: ${bestGene.variant}, fitness: ${bestGene.fitness.toFixed(2)}) from family '${familyId}'`,
|
|
1484
|
+
genomeId: this.genome.id,
|
|
1485
|
+
});
|
|
1486
|
+
}
|
|
1487
|
+
async getEvolutionHealth() {
|
|
1488
|
+
const analytics = await this.storage.getAnalytics(this.genome.id);
|
|
1489
|
+
const allAlleles = [
|
|
1490
|
+
...this.genome.layers.layer0,
|
|
1491
|
+
...this.genome.layers.layer1,
|
|
1492
|
+
...this.genome.layers.layer2,
|
|
1493
|
+
].filter(a => a.status === 'active');
|
|
1494
|
+
const avgFitness = allAlleles.length > 0
|
|
1495
|
+
? allAlleles.reduce((sum, a) => sum + a.fitness, 0) / allAlleles.length
|
|
1496
|
+
: 0.5;
|
|
1497
|
+
const generationCount = Math.max(...allAlleles.map(a => a.generation || 0), 0);
|
|
1498
|
+
const warnings = [];
|
|
1499
|
+
if (avgFitness < 0.4)
|
|
1500
|
+
warnings.push('Low average fitness detected');
|
|
1501
|
+
if (analytics.totalMutations > 100 && analytics.avgFitnessImprovement < 0.02) {
|
|
1502
|
+
warnings.push('Mutation plateau detected');
|
|
1503
|
+
}
|
|
1504
|
+
const status = avgFitness >= 0.6 ? 'healthy' :
|
|
1505
|
+
avgFitness >= 0.4 ? 'degraded' : 'critical';
|
|
1506
|
+
return {
|
|
1507
|
+
status,
|
|
1508
|
+
metrics: {
|
|
1509
|
+
avgFitness,
|
|
1510
|
+
mutationRate: analytics.totalMutations / Math.max(analytics.totalInteractions, 1),
|
|
1511
|
+
stabilityScore: analytics.userSatisfaction || 0.5,
|
|
1512
|
+
generationCount,
|
|
1513
|
+
},
|
|
1514
|
+
warnings,
|
|
1515
|
+
};
|
|
1516
|
+
}
|
|
1517
|
+
getIntegrityStatus() {
|
|
1518
|
+
if (!this.genomeKernel)
|
|
1519
|
+
return null;
|
|
1520
|
+
return {
|
|
1521
|
+
active: true,
|
|
1522
|
+
quarantined: this.genomeKernel.isQuarantined(),
|
|
1523
|
+
c0Hash: this.genomeKernel.getC0Hash(),
|
|
1524
|
+
violations: this.genomeKernel.getViolationCount(),
|
|
1525
|
+
snapshotCount: this.genomeKernel.getSnapshots().length,
|
|
1526
|
+
immuneSystem: this.immuneSystem ? {
|
|
1527
|
+
active: true,
|
|
1528
|
+
...this.immuneSystem.getImmuneStatus(),
|
|
1529
|
+
} : null,
|
|
1530
|
+
};
|
|
1531
|
+
}
|
|
1532
|
+
async getAnalytics() {
|
|
1533
|
+
return this.storage.getAnalytics(this.genome.id);
|
|
1534
|
+
}
|
|
1535
|
+
getGuardrailsReport() {
|
|
1536
|
+
return this.guardrailsManager.getGuardrailsReport();
|
|
1537
|
+
}
|
|
1538
|
+
updateGuardrails(updates) {
|
|
1539
|
+
this.guardrailsManager.updateGuardrails(updates);
|
|
1540
|
+
}
|
|
1541
|
+
async getOptimalModel(userMessage, context) {
|
|
1542
|
+
return this.modelRouter.routeTask({
|
|
1543
|
+
userMessage,
|
|
1544
|
+
context,
|
|
1545
|
+
genomeId: this.genome.id,
|
|
1546
|
+
});
|
|
1547
|
+
}
|
|
1548
|
+
getRoutingAnalytics() {
|
|
1549
|
+
return this.modelRouter.getRoutingAnalytics();
|
|
1550
|
+
}
|
|
1551
|
+
async export() {
|
|
1552
|
+
return this.genome;
|
|
1553
|
+
}
|
|
1554
|
+
async getLearningSummary(userId) {
|
|
1555
|
+
const dna = await this.dnaProfile.getDNA(userId, this.genome.id);
|
|
1556
|
+
const interactions = await this.storage.getRecentInteractions?.(this.genome.id, userId, 50) || [];
|
|
1557
|
+
const recentEvents = [];
|
|
1558
|
+
for (let i = 1; i < Math.min(interactions.length, 10); i++) {
|
|
1559
|
+
const prevDNA = await this.dnaProfile.getDNA(userId, this.genome.id);
|
|
1560
|
+
const events = this.learningAnnouncer.detectLearning(prevDNA, dna);
|
|
1561
|
+
recentEvents.push(...events);
|
|
1562
|
+
}
|
|
1563
|
+
return this.learningAnnouncer.generateLearningSummary(dna, recentEvents);
|
|
1564
|
+
}
|
|
1565
|
+
async getProactiveSuggestions(userId, currentMessage) {
|
|
1566
|
+
return this.proactiveSuggestions.generateSuggestions(userId, this.genome.id, currentMessage);
|
|
1567
|
+
}
|
|
1568
|
+
async getConversationContext(userId) {
|
|
1569
|
+
return this.contextMemory.buildContext(userId, this.genome.id);
|
|
1570
|
+
}
|
|
1571
|
+
getDriftAnalysis() {
|
|
1572
|
+
return this.driftAnalyzer.analyzeDrift();
|
|
1573
|
+
}
|
|
1574
|
+
getSelfAssessment() {
|
|
1575
|
+
return this.selfModel?.assess() ?? null;
|
|
1576
|
+
}
|
|
1577
|
+
getPatterns() {
|
|
1578
|
+
return this.patternMemory?.getPatterns() ?? [];
|
|
1579
|
+
}
|
|
1580
|
+
getPredictions() {
|
|
1581
|
+
return this.patternMemory?.getPredictions() ?? [];
|
|
1582
|
+
}
|
|
1583
|
+
getPreResponseAnalysis(message) {
|
|
1584
|
+
return this.metacognition?.analyzePreResponse(message) ?? null;
|
|
1585
|
+
}
|
|
1586
|
+
getPostResponseAnalysis(message, response, wasSuccessful) {
|
|
1587
|
+
return this.metacognition?.analyzePostResponse(message, response, wasSuccessful) ?? null;
|
|
1588
|
+
}
|
|
1589
|
+
inferEmotion(message) {
|
|
1590
|
+
return this.emotionalModel?.inferEmotion(message) ?? null;
|
|
1591
|
+
}
|
|
1592
|
+
evaluateAutonomy(taskType, riskLevel) {
|
|
1593
|
+
return this.calibratedAutonomy?.evaluate(taskType, riskLevel) ?? null;
|
|
1594
|
+
}
|
|
1595
|
+
recordAutonomyCorrection(taskType, correctionType) {
|
|
1596
|
+
this.calibratedAutonomy?.recordCorrection({
|
|
1597
|
+
taskType,
|
|
1598
|
+
wasAutonomous: true,
|
|
1599
|
+
correctionType,
|
|
1600
|
+
timestamp: new Date(),
|
|
1601
|
+
});
|
|
1602
|
+
}
|
|
1603
|
+
getNarrativeSummary() {
|
|
1604
|
+
return this.personalNarrative?.getSummary() ?? null;
|
|
1605
|
+
}
|
|
1606
|
+
findHistoryCallback(topic) {
|
|
1607
|
+
return this.personalNarrative?.callbackToHistory(topic) ?? null;
|
|
1608
|
+
}
|
|
1609
|
+
queryMemory(question) {
|
|
1610
|
+
return this.analyticMemory?.query(question) ?? null;
|
|
1611
|
+
}
|
|
1612
|
+
getActiveCanaries() {
|
|
1613
|
+
return this.canaryManager.getActiveDeployments()
|
|
1614
|
+
.filter(d => d.genomeId === this.genome.id);
|
|
1615
|
+
}
|
|
1616
|
+
recordMemoryObservation(observation) {
|
|
1617
|
+
this.analyticMemory?.recordObservation(observation);
|
|
1618
|
+
}
|
|
1619
|
+
getIntegratedHealth() {
|
|
1620
|
+
return this.enhancedSelfModel?.assessFull() ?? null;
|
|
1621
|
+
}
|
|
1622
|
+
getOperatingMode() {
|
|
1623
|
+
return this.purposeSurvival?.getMode() ?? null;
|
|
1624
|
+
}
|
|
1625
|
+
getSurvivalStrategy() {
|
|
1626
|
+
return this.purposeSurvival?.getStrategy() ?? null;
|
|
1627
|
+
}
|
|
1628
|
+
getCapabilities() {
|
|
1629
|
+
return this.enhancedSelfModel?.getCapabilities() ?? [];
|
|
1630
|
+
}
|
|
1631
|
+
getTrajectories() {
|
|
1632
|
+
return this.enhancedSelfModel?.getTrajectories() ?? [];
|
|
1633
|
+
}
|
|
1634
|
+
getEvolutionPriorities() {
|
|
1635
|
+
if (!this.strategicAutonomy)
|
|
1636
|
+
return [];
|
|
1637
|
+
const drift = this.driftAnalyzer.analyzeDrift();
|
|
1638
|
+
const health = this.enhancedSelfModel?.assessFull()
|
|
1639
|
+
?? { score: 0.5, fitnessComponent: 0.5, driftComponent: 1.0,
|
|
1640
|
+
purposeComponent: 0.5, trajectoryComponent: 0.5, label: 'stable' };
|
|
1641
|
+
return this.strategicAutonomy.prioritizeEvolution(drift.signals, health);
|
|
1642
|
+
}
|
|
1643
|
+
getAgentVitals() {
|
|
1644
|
+
if (!this.purposeSurvival || !this.enhancedSelfModel)
|
|
1645
|
+
return null;
|
|
1646
|
+
return computeAgentVitals(this.purposeSurvival, this.enhancedSelfModel);
|
|
1647
|
+
}
|
|
1648
|
+
async runEvolutionCycle() {
|
|
1649
|
+
const autoConfig = this.genome.config.autonomous;
|
|
1650
|
+
const drift = this.driftAnalyzer.analyzeDrift();
|
|
1651
|
+
if (this.purposeSurvival) {
|
|
1652
|
+
const evaluation = this.purposeSurvival.evaluateThreats();
|
|
1653
|
+
if (evaluation.mode === 'critical') {
|
|
1654
|
+
const snapshot = this.purposeSurvival.getLastKnownGood();
|
|
1655
|
+
if (snapshot) {
|
|
1656
|
+
this.restoreFromSnapshot(snapshot);
|
|
1657
|
+
return;
|
|
1658
|
+
}
|
|
1659
|
+
}
|
|
1660
|
+
if (evaluation.mode === 'stressed' || evaluation.mode === 'survival') {
|
|
1661
|
+
this.purposeSurvival.snapshotLastKnownGood(this.genome);
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
if (autoConfig?.autoMutateOnDrift !== false && drift.isDrifting) {
|
|
1665
|
+
if (this.strategicAutonomy && this.enhancedSelfModel) {
|
|
1666
|
+
const health = this.enhancedSelfModel.assessFull();
|
|
1667
|
+
const priorities = this.strategicAutonomy.prioritizeEvolution(drift.signals, health);
|
|
1668
|
+
for (const priority of priorities.filter(p => p.urgency === 'immediate')) {
|
|
1669
|
+
if (this.purposeSurvival) {
|
|
1670
|
+
const currentAllele = this.genome.layers[`layer${priority.layer}`]
|
|
1671
|
+
?.find((a) => a.gene === priority.gene && a.status === 'active');
|
|
1672
|
+
if (currentAllele) {
|
|
1673
|
+
const check = this.purposeSurvival.purposeFidelityCheck({
|
|
1674
|
+
gene: priority.gene,
|
|
1675
|
+
content: currentAllele.content,
|
|
1676
|
+
});
|
|
1677
|
+
if (!check.approved)
|
|
1678
|
+
continue;
|
|
1679
|
+
}
|
|
1680
|
+
}
|
|
1681
|
+
const target = this.driftToMutationTarget({
|
|
1682
|
+
type: priority.gene, severity: 'moderate',
|
|
1683
|
+
baselineValue: 0.7, currentValue: 0.5,
|
|
1684
|
+
});
|
|
1685
|
+
await this.mutate({
|
|
1686
|
+
layer: target.layer,
|
|
1687
|
+
gene: target.gene,
|
|
1688
|
+
taskType: `strategic-evolve:${priority.reason}`,
|
|
1689
|
+
});
|
|
1690
|
+
}
|
|
1691
|
+
}
|
|
1692
|
+
else {
|
|
1693
|
+
for (const signal of drift.signals) {
|
|
1694
|
+
if (signal.severity === 'minor')
|
|
1695
|
+
continue;
|
|
1696
|
+
const target = this.driftToMutationTarget(signal);
|
|
1697
|
+
await this.mutate({
|
|
1698
|
+
layer: target.layer,
|
|
1699
|
+
gene: target.gene,
|
|
1700
|
+
taskType: `auto-evolve:${signal.type}`,
|
|
1701
|
+
});
|
|
1702
|
+
}
|
|
1703
|
+
}
|
|
1704
|
+
}
|
|
1705
|
+
if (autoConfig?.autoCompressOnPressure !== false) {
|
|
1706
|
+
const totalC1Tokens = this.genome.layers.layer1
|
|
1707
|
+
.filter(a => a.status === 'active')
|
|
1708
|
+
.reduce((sum, a) => sum + estimateTokenCount(a.content), 0);
|
|
1709
|
+
const threshold = this.genome.config.compression?.autoCompressThreshold ?? 1600;
|
|
1710
|
+
if (totalC1Tokens > threshold) {
|
|
1711
|
+
await this.compressGenes();
|
|
1712
|
+
}
|
|
1713
|
+
}
|
|
1714
|
+
await this.evaluateCanaries();
|
|
1715
|
+
if (this.geneBank && (autoConfig?.enableSwarm ?? !!this.geneBank)) {
|
|
1716
|
+
await this.publishHighFitnessGenes();
|
|
1717
|
+
}
|
|
1718
|
+
if (this.genome.familyId && this.storage.getBestRegistryGene && drift.isDrifting) {
|
|
1719
|
+
for (const signal of drift.signals) {
|
|
1720
|
+
if (signal.severity === 'minor')
|
|
1721
|
+
continue;
|
|
1722
|
+
const target = this.driftToMutationTarget(signal);
|
|
1723
|
+
try {
|
|
1724
|
+
await this.inheritGeneFromRegistry(this.genome.familyId, target.gene, target.layer);
|
|
1725
|
+
}
|
|
1726
|
+
catch {
|
|
1727
|
+
}
|
|
1728
|
+
}
|
|
1729
|
+
}
|
|
1730
|
+
if (this.geneBank && autoConfig?.enableSwarm && drift.isDrifting) {
|
|
1731
|
+
const targetSeverity = autoConfig.autoImportOnDrift ?? 'severe';
|
|
1732
|
+
const severityRank = (s) => s === 'critical' ? 3 : s === 'major' ? 2 : s === 'moderate' ? 1 : 0;
|
|
1733
|
+
for (const signal of drift.signals) {
|
|
1734
|
+
if (severityRank(signal.severity) >= severityRank(targetSeverity)) {
|
|
1735
|
+
await this.autoImportGene(signal);
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1738
|
+
}
|
|
1739
|
+
this.metrics.logAudit({
|
|
1740
|
+
level: 'info',
|
|
1741
|
+
component: 'genome',
|
|
1742
|
+
operation: 'evolution-cycle',
|
|
1743
|
+
message: `Evolution cycle #${this.interactionCount} completed`,
|
|
1744
|
+
genomeId: this.genome.id,
|
|
1745
|
+
metadata: { isDrifting: drift.isDrifting, signalCount: drift.signals.length },
|
|
1746
|
+
});
|
|
1747
|
+
}
|
|
1748
|
+
computeInteractionQuality(interaction) {
|
|
1749
|
+
if (!interaction.assistantResponse)
|
|
1750
|
+
return 0.2;
|
|
1751
|
+
const response = interaction.assistantResponse;
|
|
1752
|
+
const message = interaction.userMessage;
|
|
1753
|
+
const hasSubstance = response.length > 20 ? 0.3 : response.length / 20 * 0.3;
|
|
1754
|
+
const ratio = message.length > 0 ? response.length / message.length : 1;
|
|
1755
|
+
const efficiencyScore = ratio >= 1 && ratio <= 5 ? 0.25 :
|
|
1756
|
+
ratio > 5 ? Math.max(0, 0.25 - (ratio - 5) * 0.02) :
|
|
1757
|
+
ratio * 0.25;
|
|
1758
|
+
const hasStructure = ((response.includes('\n\n') ? 0.08 : 0) +
|
|
1759
|
+
(response.includes('```') ? 0.08 : 0) +
|
|
1760
|
+
(response.includes('- ') || response.includes('* ') ? 0.05 : 0) +
|
|
1761
|
+
(response.length > 100 ? 0.04 : 0));
|
|
1762
|
+
const userSatisfied = interaction.userSatisfied;
|
|
1763
|
+
const satisfactionScore = userSatisfied === true ? 0.2 :
|
|
1764
|
+
userSatisfied === false ? 0.0 :
|
|
1765
|
+
0.1;
|
|
1766
|
+
return Math.min(1, hasSubstance + efficiencyScore + hasStructure + satisfactionScore);
|
|
1767
|
+
}
|
|
1768
|
+
applyCanaryVariant(prompt, canary) {
|
|
1769
|
+
const canaryAlleleContent = this.genome.layers[`layer${canary.layer}`]
|
|
1770
|
+
?.find(a => a.variant === canary.canaryVariant)?.content;
|
|
1771
|
+
if (!canaryAlleleContent)
|
|
1772
|
+
return prompt;
|
|
1773
|
+
const stableContent = this.genome.layers[`layer${canary.layer}`]
|
|
1774
|
+
?.find(a => a.variant === canary.stableVariant)?.content;
|
|
1775
|
+
if (stableContent && prompt.includes(stableContent)) {
|
|
1776
|
+
return prompt.replace(stableContent, canaryAlleleContent);
|
|
1777
|
+
}
|
|
1778
|
+
return prompt + `\n\n## Gene Override (${canary.gene})\n${canaryAlleleContent}`;
|
|
1779
|
+
}
|
|
1780
|
+
estimateQuality(userMessage, response) {
|
|
1781
|
+
let score = 0.5;
|
|
1782
|
+
const len = response.length;
|
|
1783
|
+
if (len > 50 && len < 5000)
|
|
1784
|
+
score += 0.15;
|
|
1785
|
+
else if (len < 20)
|
|
1786
|
+
score -= 0.2;
|
|
1787
|
+
const asksForCode = /write|code|function|implement|create.*class|fix.*bug/i.test(userMessage);
|
|
1788
|
+
if (asksForCode && /```/.test(response))
|
|
1789
|
+
score += 0.15;
|
|
1790
|
+
if (/^#{1,3}\s|^[-*]\s|```/m.test(response))
|
|
1791
|
+
score += 0.1;
|
|
1792
|
+
if (/sorry.*can't|i don't know|as an ai|i cannot/i.test(response))
|
|
1793
|
+
score -= 0.15;
|
|
1794
|
+
const questionWords = new Set(userMessage.toLowerCase().split(/\W+/).filter(w => w.length > 3));
|
|
1795
|
+
if (questionWords.size > 0) {
|
|
1796
|
+
const responseWords = response.toLowerCase().split(/\W+/).filter(w => w.length > 3);
|
|
1797
|
+
const overlap = responseWords.filter(w => questionWords.has(w)).length;
|
|
1798
|
+
const relevanceRatio = Math.min(overlap / questionWords.size, 1);
|
|
1799
|
+
if (relevanceRatio > 0.3)
|
|
1800
|
+
score += 0.05;
|
|
1801
|
+
if (relevanceRatio > 0.6)
|
|
1802
|
+
score += 0.05;
|
|
1803
|
+
}
|
|
1804
|
+
if (/because|therefore|since|this means|the reason|due to/i.test(response) && len > 100) {
|
|
1805
|
+
score += 0.05;
|
|
1806
|
+
}
|
|
1807
|
+
const questionLen = userMessage.length;
|
|
1808
|
+
const ratio = len / Math.max(questionLen, 1);
|
|
1809
|
+
if (ratio > 1 && ratio < 20)
|
|
1810
|
+
score += 0.05;
|
|
1811
|
+
if (ratio > 50)
|
|
1812
|
+
score -= 0.05;
|
|
1813
|
+
const lastChar = response.trim().slice(-1);
|
|
1814
|
+
if (/[.!?)\]`\d]/.test(lastChar))
|
|
1815
|
+
score += 0.03;
|
|
1816
|
+
const codeBlockCount = (response.match(/```/g) || []).length;
|
|
1817
|
+
if (codeBlockCount > 0 && codeBlockCount % 2 !== 0)
|
|
1818
|
+
score -= 0.1;
|
|
1819
|
+
const isTaskOriented = /how|explain|help|show|create|build|fix|setup|install/i.test(userMessage);
|
|
1820
|
+
if (isTaskOriented && /\d\.\s|step\s\d|first.*then|```/i.test(response))
|
|
1821
|
+
score += 0.05;
|
|
1822
|
+
const sentences = response.split(/[.!?]+/).filter(s => s.trim().length > 10);
|
|
1823
|
+
if (sentences.length > 3) {
|
|
1824
|
+
const uniqueSentences = new Set(sentences.map(s => s.trim().toLowerCase()));
|
|
1825
|
+
const repetitionRatio = 1 - (uniqueSentences.size / sentences.length);
|
|
1826
|
+
if (repetitionRatio > 0.3)
|
|
1827
|
+
score -= 0.1;
|
|
1828
|
+
}
|
|
1829
|
+
return Math.max(0, Math.min(1, score));
|
|
1830
|
+
}
|
|
1831
|
+
buildEvolutionEvidence() {
|
|
1832
|
+
const evidence = {};
|
|
1833
|
+
const drift = this.driftAnalyzer.analyzeDrift();
|
|
1834
|
+
if (drift.isDrifting) {
|
|
1835
|
+
evidence.driftSignals = drift.signals.map(s => ({
|
|
1836
|
+
type: s.type,
|
|
1837
|
+
severity: s.severity,
|
|
1838
|
+
currentValue: s.currentValue,
|
|
1839
|
+
baselineValue: s.baselineValue,
|
|
1840
|
+
}));
|
|
1841
|
+
}
|
|
1842
|
+
if (this.enhancedSelfModel) {
|
|
1843
|
+
evidence.health = this.enhancedSelfModel.assessFull();
|
|
1844
|
+
evidence.capabilities = this.enhancedSelfModel.getCapabilities()
|
|
1845
|
+
.filter((c) => c.trend === 'declining' || c.performanceScore < 0.5)
|
|
1846
|
+
.slice(0, 10);
|
|
1847
|
+
evidence.trajectories = this.enhancedSelfModel.getTrajectories()
|
|
1848
|
+
.filter((t) => t.trend === 'declining')
|
|
1849
|
+
.slice(0, 5);
|
|
1850
|
+
}
|
|
1851
|
+
if (this.patternMemory) {
|
|
1852
|
+
evidence.patterns = this.patternMemory.getPatterns()
|
|
1853
|
+
.filter((p) => p.confidence >= 0.6)
|
|
1854
|
+
.slice(0, 8);
|
|
1855
|
+
evidence.predictions = this.patternMemory.getPredictions().slice(0, 3);
|
|
1856
|
+
}
|
|
1857
|
+
if (this.strategicAutonomy) {
|
|
1858
|
+
const mode = this.purposeSurvival?.getMode?.() ?? 'stable';
|
|
1859
|
+
const health = this.enhancedSelfModel?.assessFull() ?? null;
|
|
1860
|
+
evidence.mutationRate = this.strategicAutonomy.recommendMutationRate(mode, health);
|
|
1861
|
+
}
|
|
1862
|
+
if (this.genome.config.autonomous?.agentPurpose) {
|
|
1863
|
+
evidence.purpose = this.genome.config.autonomous.agentPurpose;
|
|
1864
|
+
}
|
|
1865
|
+
return evidence;
|
|
1866
|
+
}
|
|
1867
|
+
async publishHighFitnessGenes() {
|
|
1868
|
+
if (!this.geneBank)
|
|
1869
|
+
return;
|
|
1870
|
+
const threshold = this.genome.config.autonomous?.autoPublishThreshold ?? 0.85;
|
|
1871
|
+
for (const allele of this.genome.layers.layer1.filter(a => a.status === 'active')) {
|
|
1872
|
+
if (allele.fitness >= threshold && !allele.publishedToSwarm) {
|
|
1873
|
+
await this.autoPublishGene(allele).catch(err => this.metrics.logAudit({
|
|
1874
|
+
level: 'warning',
|
|
1875
|
+
component: 'gene-bank',
|
|
1876
|
+
operation: 'auto-publish',
|
|
1877
|
+
message: `Auto-publish gene failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
1878
|
+
genomeId: this.genome.id,
|
|
1879
|
+
}));
|
|
1880
|
+
}
|
|
1881
|
+
}
|
|
1882
|
+
}
|
|
1883
|
+
async evaluateCanaries() {
|
|
1884
|
+
const deployments = this.canaryManager.getActiveDeployments();
|
|
1885
|
+
for (const deployment of deployments) {
|
|
1886
|
+
if (deployment.genomeId !== this.genome.id)
|
|
1887
|
+
continue;
|
|
1888
|
+
try {
|
|
1889
|
+
const decision = await this.canaryManager.evaluateCanary(deployment.id);
|
|
1890
|
+
if (decision.action === 'promote') {
|
|
1891
|
+
const canaryContent = deployment.canaryContent;
|
|
1892
|
+
if (canaryContent) {
|
|
1893
|
+
const layerKey = `layer${deployment.layer}`;
|
|
1894
|
+
const activeAllele = this.genome.layers[layerKey]
|
|
1895
|
+
.find(a => a.gene === deployment.gene && a.status === 'active');
|
|
1896
|
+
if (activeAllele) {
|
|
1897
|
+
activeAllele.status = 'retired';
|
|
1898
|
+
}
|
|
1899
|
+
await this.addAllele(deployment.layer, deployment.gene, deployment.canaryVariant, canaryContent);
|
|
1900
|
+
}
|
|
1901
|
+
await this.canaryManager.promote(deployment.id);
|
|
1902
|
+
}
|
|
1903
|
+
else if (decision.action === 'rollback') {
|
|
1904
|
+
await this.canaryManager.rollback(deployment.id, decision.reason);
|
|
1905
|
+
}
|
|
1906
|
+
else if (decision.action === 'ramp-up') {
|
|
1907
|
+
await this.canaryManager.rampUp(deployment.id);
|
|
1908
|
+
}
|
|
1909
|
+
}
|
|
1910
|
+
catch {
|
|
1911
|
+
}
|
|
1912
|
+
}
|
|
1913
|
+
}
|
|
1914
|
+
driftToMutationTarget(signal) {
|
|
1915
|
+
const mapping = {
|
|
1916
|
+
'quality-decline': { layer: 1, gene: 'coding-patterns' },
|
|
1917
|
+
'efficiency-decline': { layer: 1, gene: 'tool-usage' },
|
|
1918
|
+
'cost-increase': { layer: 1, gene: 'tool-usage' },
|
|
1919
|
+
'intervention-increase': { layer: 1, gene: 'coding-patterns' },
|
|
1920
|
+
'latency-increase': { layer: 1, gene: 'tool-usage' },
|
|
1921
|
+
};
|
|
1922
|
+
return mapping[signal.type] || { layer: 2, gene: 'communication-style' };
|
|
1923
|
+
}
|
|
1924
|
+
async autoPublishGene(allele) {
|
|
1925
|
+
if (!this.geneBank)
|
|
1926
|
+
return;
|
|
1927
|
+
try {
|
|
1928
|
+
const cognitiveGene = {
|
|
1929
|
+
id: `auto_${this.genome.id}_${allele.gene}_${Date.now()}`,
|
|
1930
|
+
version: '1.0.0',
|
|
1931
|
+
name: `${allele.gene} from ${this.genome.name}`,
|
|
1932
|
+
description: `Auto-published ${allele.gene} gene with fitness ${allele.fitness.toFixed(2)}`,
|
|
1933
|
+
type: this.geneCategoryToType(allele.gene),
|
|
1934
|
+
domain: 'general',
|
|
1935
|
+
content: {
|
|
1936
|
+
instruction: allele.content,
|
|
1937
|
+
requiredCapabilities: [],
|
|
1938
|
+
applicableContexts: [],
|
|
1939
|
+
contraindications: [],
|
|
1940
|
+
metadata: {},
|
|
1941
|
+
},
|
|
1942
|
+
fitness: {
|
|
1943
|
+
overallFitness: allele.fitness,
|
|
1944
|
+
taskSuccessRate: allele.fitness,
|
|
1945
|
+
tokenEfficiency: 0.7,
|
|
1946
|
+
responseQuality: allele.fitness,
|
|
1947
|
+
adoptionCount: 0,
|
|
1948
|
+
adoptionPerformance: null,
|
|
1949
|
+
},
|
|
1950
|
+
lineage: {
|
|
1951
|
+
parentGeneId: null,
|
|
1952
|
+
generation: allele.generation || 0,
|
|
1953
|
+
ancestors: [],
|
|
1954
|
+
mutationHistory: [],
|
|
1955
|
+
},
|
|
1956
|
+
tenant: {
|
|
1957
|
+
tenantId: this.genome.familyId || this.genome.id,
|
|
1958
|
+
createdBy: this.genome.id,
|
|
1959
|
+
scope: 'tenant',
|
|
1960
|
+
},
|
|
1961
|
+
tags: [allele.gene],
|
|
1962
|
+
createdAt: new Date().toISOString(),
|
|
1963
|
+
updatedAt: new Date().toISOString(),
|
|
1964
|
+
};
|
|
1965
|
+
await this.geneBank.storeGene(cognitiveGene);
|
|
1966
|
+
allele.publishedToSwarm = true;
|
|
1967
|
+
this.metrics.logAudit({
|
|
1968
|
+
level: 'info',
|
|
1969
|
+
component: 'genome',
|
|
1970
|
+
operation: 'swarm-publish',
|
|
1971
|
+
message: `Auto-published gene ${allele.gene} (fitness: ${allele.fitness.toFixed(2)})`,
|
|
1972
|
+
genomeId: this.genome.id,
|
|
1973
|
+
});
|
|
1974
|
+
}
|
|
1975
|
+
catch {
|
|
1976
|
+
}
|
|
1977
|
+
}
|
|
1978
|
+
async autoImportGene(signal) {
|
|
1979
|
+
if (!this.geneBank)
|
|
1980
|
+
return;
|
|
1981
|
+
const target = this.driftToMutationTarget(signal);
|
|
1982
|
+
const geneTypes = [this.geneCategoryToType(target.gene)];
|
|
1983
|
+
try {
|
|
1984
|
+
const candidates = await this.geneBank.searchGenes({
|
|
1985
|
+
type: geneTypes,
|
|
1986
|
+
minFitness: 0.75,
|
|
1987
|
+
sortBy: 'fitness',
|
|
1988
|
+
sortOrder: 'desc',
|
|
1989
|
+
limit: 1,
|
|
1990
|
+
});
|
|
1991
|
+
if (candidates.length === 0)
|
|
1992
|
+
return;
|
|
1993
|
+
const bestGene = candidates[0];
|
|
1994
|
+
await this.addAllele(target.layer, target.gene, `swarm_${bestGene.id.slice(0, 8)}_${Date.now()}`, bestGene.content.instruction);
|
|
1995
|
+
this.metrics.logAudit({
|
|
1996
|
+
level: 'info',
|
|
1997
|
+
component: 'genome',
|
|
1998
|
+
operation: 'swarm-import',
|
|
1999
|
+
message: `Auto-imported gene ${bestGene.name} for ${signal.type}`,
|
|
2000
|
+
genomeId: this.genome.id,
|
|
2001
|
+
});
|
|
2002
|
+
}
|
|
2003
|
+
catch {
|
|
2004
|
+
}
|
|
2005
|
+
}
|
|
2006
|
+
geneCategoryToType(category) {
|
|
2007
|
+
const mapping = {
|
|
2008
|
+
'tool-usage': 'tool-usage-pattern',
|
|
2009
|
+
'coding-patterns': 'reasoning-pattern',
|
|
2010
|
+
'communication-style': 'communication-pattern',
|
|
2011
|
+
};
|
|
2012
|
+
return mapping[category] || 'reasoning-pattern';
|
|
2013
|
+
}
|
|
2014
|
+
toGenomeV2() {
|
|
2015
|
+
const defaultFitness = {
|
|
2016
|
+
quality: 0.5, successRate: 0.5, tokenEfficiency: 0.5,
|
|
2017
|
+
latency: 1000, costPerSuccess: 0.01, interventionRate: 0.1,
|
|
2018
|
+
composite: 0.5, sampleSize: 0, lastUpdated: new Date(), confidence: 0,
|
|
2019
|
+
};
|
|
2020
|
+
const operations = this.genome.layers.layer1
|
|
2021
|
+
.filter(a => a.status === 'active')
|
|
2022
|
+
.map(a => ({
|
|
2023
|
+
id: `${this.genome.id}_${a.gene}_${a.variant}`,
|
|
2024
|
+
category: a.gene,
|
|
2025
|
+
content: a.content,
|
|
2026
|
+
fitness: defaultFitness,
|
|
2027
|
+
origin: 'initial',
|
|
2028
|
+
usageCount: a.sampleCount || 0,
|
|
2029
|
+
lastUsed: new Date(),
|
|
2030
|
+
successRate: a.fitness || 0.5,
|
|
2031
|
+
}));
|
|
2032
|
+
return {
|
|
2033
|
+
id: this.genome.id,
|
|
2034
|
+
name: this.genome.name,
|
|
2035
|
+
familyId: this.genome.familyId || this.genome.id,
|
|
2036
|
+
version: this.genome.version || 1,
|
|
2037
|
+
chromosomes: {
|
|
2038
|
+
c0: {
|
|
2039
|
+
identity: {
|
|
2040
|
+
role: this.genome.layers.layer0[0]?.content || 'AI Assistant',
|
|
2041
|
+
purpose: 'Genomic self-evolving prompt agent',
|
|
2042
|
+
constraints: this.genome.layers.layer0.slice(1).map(a => a.content),
|
|
2043
|
+
},
|
|
2044
|
+
security: {
|
|
2045
|
+
forbiddenTopics: [],
|
|
2046
|
+
accessControls: [],
|
|
2047
|
+
safetyRules: [],
|
|
2048
|
+
},
|
|
2049
|
+
attribution: {
|
|
2050
|
+
creator: 'GSEP',
|
|
2051
|
+
copyright: 'GSEP Platform',
|
|
2052
|
+
license: 'MIT',
|
|
2053
|
+
},
|
|
2054
|
+
metadata: {
|
|
2055
|
+
version: '2.0.0',
|
|
2056
|
+
createdAt: this.genome.createdAt,
|
|
2057
|
+
},
|
|
2058
|
+
},
|
|
2059
|
+
c1: {
|
|
2060
|
+
operations,
|
|
2061
|
+
metadata: {
|
|
2062
|
+
lastMutated: new Date(),
|
|
2063
|
+
mutationCount: 0,
|
|
2064
|
+
avgFitnessGain: 0,
|
|
2065
|
+
},
|
|
2066
|
+
},
|
|
2067
|
+
c2: {
|
|
2068
|
+
userAdaptations: new Map(),
|
|
2069
|
+
contextPatterns: [],
|
|
2070
|
+
metadata: {
|
|
2071
|
+
lastMutated: new Date(),
|
|
2072
|
+
adaptationRate: 0,
|
|
2073
|
+
totalUsers: 0,
|
|
2074
|
+
},
|
|
2075
|
+
},
|
|
2076
|
+
},
|
|
2077
|
+
integrity: {
|
|
2078
|
+
c0Hash: this.genome.c0IntegrityHash || '',
|
|
2079
|
+
lastVerified: new Date(),
|
|
2080
|
+
violations: 0,
|
|
2081
|
+
quarantined: false,
|
|
2082
|
+
},
|
|
2083
|
+
lineage: {
|
|
2084
|
+
parentVersion: this.genome.lineage?.parentVersion,
|
|
2085
|
+
inheritedGenes: [],
|
|
2086
|
+
mutations: [],
|
|
2087
|
+
},
|
|
2088
|
+
fitness: defaultFitness,
|
|
2089
|
+
config: {
|
|
2090
|
+
mutationRate: this.genome.config.mutationRate === 'slow' ? 'conservative' : this.genome.config.mutationRate,
|
|
2091
|
+
epsilonExplore: this.genome.config.epsilonExplore ?? 0.1,
|
|
2092
|
+
enableSandbox: this.genome.config.enableSandbox,
|
|
2093
|
+
fitnessWeights: undefined,
|
|
2094
|
+
minFitnessImprovement: 0.05,
|
|
2095
|
+
enableIntegrityCheck: true,
|
|
2096
|
+
autoRollbackThreshold: 0.15,
|
|
2097
|
+
allowInheritance: true,
|
|
2098
|
+
minCompatibilityScore: 0.6,
|
|
2099
|
+
},
|
|
2100
|
+
state: 'active',
|
|
2101
|
+
tags: [],
|
|
2102
|
+
createdAt: this.genome.createdAt,
|
|
2103
|
+
updatedAt: this.genome.updatedAt,
|
|
2104
|
+
};
|
|
2105
|
+
}
|
|
2106
|
+
toOperativeGene(allele) {
|
|
2107
|
+
const defaultFitness = {
|
|
2108
|
+
quality: allele.fitness, successRate: allele.fitness, tokenEfficiency: 0.5,
|
|
2109
|
+
latency: 1000, costPerSuccess: 0.01, interventionRate: 0.1,
|
|
2110
|
+
composite: allele.fitness, sampleSize: 0, lastUpdated: new Date(), confidence: 0,
|
|
2111
|
+
};
|
|
2112
|
+
return {
|
|
2113
|
+
id: `${this.genome.id}_${allele.gene}_${allele.variant}`,
|
|
2114
|
+
category: allele.gene,
|
|
2115
|
+
content: allele.content,
|
|
2116
|
+
fitness: defaultFitness,
|
|
2117
|
+
origin: 'initial',
|
|
2118
|
+
usageCount: 0,
|
|
2119
|
+
lastUsed: new Date(),
|
|
2120
|
+
successRate: allele.fitness,
|
|
2121
|
+
tokenCount: estimateTokenCount(allele.content),
|
|
2122
|
+
};
|
|
2123
|
+
}
|
|
2124
|
+
async compressGenes() {
|
|
2125
|
+
const emptyResult = { compressed: false, totalOriginalTokens: 0, totalCompressedTokens: 0, tokensSaved: 0, reductionPercent: 0 };
|
|
2126
|
+
const compressionOperator = this.mutationEngine.getOperator('compress_instructions');
|
|
2127
|
+
if (!compressionOperator)
|
|
2128
|
+
return emptyResult;
|
|
2129
|
+
const compressionConfig = this.genome.config.compression;
|
|
2130
|
+
const maxRatio = compressionConfig?.maxCompressionRatio ?? 0.3;
|
|
2131
|
+
const context = {
|
|
2132
|
+
genome: this.toGenomeV2(),
|
|
2133
|
+
targetChromosome: 'c1',
|
|
2134
|
+
reason: 'Token compression: optimize gene token usage while preserving functionality',
|
|
2135
|
+
};
|
|
2136
|
+
const result = await compressionOperator.mutate(context);
|
|
2137
|
+
if (!result.success || !result.compressionMetrics)
|
|
2138
|
+
return emptyResult;
|
|
2139
|
+
const metrics = result.compressionMetrics;
|
|
2140
|
+
if (metrics.ratio < maxRatio) {
|
|
2141
|
+
return emptyResult;
|
|
2142
|
+
}
|
|
2143
|
+
const gateResult = await this.guardrailsManager.evaluateCandidate({
|
|
2144
|
+
layer: 1,
|
|
2145
|
+
gene: 'compression',
|
|
2146
|
+
variant: `compressed_v${Date.now()}`,
|
|
2147
|
+
content: JSON.stringify(result.mutant.chromosomes.c1.operations.map(g => g.content)),
|
|
2148
|
+
fitness: result.expectedImprovement + 0.5,
|
|
2149
|
+
sandboxScore: 0.8,
|
|
2150
|
+
sampleCount: 0,
|
|
2151
|
+
rollbackCount: 0,
|
|
2152
|
+
}, this.genome.id);
|
|
2153
|
+
if (gateResult.finalDecision === 'reject') {
|
|
2154
|
+
return emptyResult;
|
|
2155
|
+
}
|
|
2156
|
+
const minFitness = compressionConfig?.minFitnessForCompression ?? 0.3;
|
|
2157
|
+
for (const operation of result.mutant.chromosomes.c1.operations) {
|
|
2158
|
+
const allele = this.genome.layers.layer1.find(a => a.gene === operation.category && a.status === 'active');
|
|
2159
|
+
if (allele && allele.fitness >= minFitness) {
|
|
2160
|
+
allele.content = operation.content;
|
|
2161
|
+
}
|
|
2162
|
+
}
|
|
2163
|
+
return {
|
|
2164
|
+
compressed: true,
|
|
2165
|
+
totalOriginalTokens: metrics.originalTokens,
|
|
2166
|
+
totalCompressedTokens: metrics.compressedTokens,
|
|
2167
|
+
tokensSaved: metrics.originalTokens - metrics.compressedTokens,
|
|
2168
|
+
reductionPercent: Math.round((1 - metrics.ratio) * 100),
|
|
2169
|
+
};
|
|
2170
|
+
}
|
|
2171
|
+
getMutationStrategy() {
|
|
2172
|
+
const context = {
|
|
2173
|
+
genome: this.toGenomeV2(),
|
|
2174
|
+
targetChromosome: 'c1',
|
|
2175
|
+
reason: 'Strategy analysis',
|
|
2176
|
+
evidence: (() => {
|
|
2177
|
+
const drift = this.driftAnalyzer.analyzeDrift();
|
|
2178
|
+
return drift.isDrifting
|
|
2179
|
+
? { driftSignals: drift.signals.map(s => ({ type: s.type, severity: s.severity })) }
|
|
2180
|
+
: undefined;
|
|
2181
|
+
})(),
|
|
2182
|
+
};
|
|
2183
|
+
return this.mutationEngine.selectMutationStrategy(context).map(s => ({
|
|
2184
|
+
operator: s.operator.name,
|
|
2185
|
+
score: s.score,
|
|
2186
|
+
reason: s.reason,
|
|
2187
|
+
}));
|
|
2188
|
+
}
|
|
2189
|
+
restoreFromSnapshot(snapshot) {
|
|
2190
|
+
for (const saved of snapshot.alleles) {
|
|
2191
|
+
const layerKey = `layer${saved.layer}`;
|
|
2192
|
+
const allele = this.genome.layers[layerKey].find((a) => a.gene === saved.gene && a.status === 'active');
|
|
2193
|
+
if (allele) {
|
|
2194
|
+
allele.content = saved.content;
|
|
2195
|
+
allele.fitness = saved.fitness;
|
|
2196
|
+
}
|
|
2197
|
+
}
|
|
2198
|
+
this.storage.saveGenome(this.genome).catch(err => this.metrics.logAudit({
|
|
2199
|
+
level: 'error',
|
|
2200
|
+
component: 'genome',
|
|
2201
|
+
operation: 'emergency-rollback-save',
|
|
2202
|
+
message: `Failed to persist rollback: ${err instanceof Error ? err.message : String(err)}`,
|
|
2203
|
+
genomeId: this.genome.id,
|
|
2204
|
+
}));
|
|
2205
|
+
this.metrics.logAudit({
|
|
2206
|
+
level: 'warning',
|
|
2207
|
+
component: 'genome',
|
|
2208
|
+
operation: 'emergency-rollback',
|
|
2209
|
+
message: `Restored from snapshot taken at ${snapshot.timestamp.toISOString()}`,
|
|
2210
|
+
genomeId: this.genome.id,
|
|
2211
|
+
});
|
|
2212
|
+
}
|
|
2213
|
+
extractTopicsFromMessage(message) {
|
|
2214
|
+
const TECH_TERMS = [
|
|
2215
|
+
'typescript', 'javascript', 'python', 'rust', 'go', 'java', 'c++', 'ruby', 'php', 'swift',
|
|
2216
|
+
'react', 'vue', 'angular', 'svelte', 'nextjs', 'node', 'deno', 'bun',
|
|
2217
|
+
'docker', 'kubernetes', 'aws', 'azure', 'gcp', 'terraform', 'ci/cd',
|
|
2218
|
+
'sql', 'postgres', 'mongodb', 'redis', 'graphql', 'rest', 'grpc',
|
|
2219
|
+
'machine learning', 'ai', 'llm', 'neural network', 'deep learning',
|
|
2220
|
+
'security', 'authentication', 'oauth', 'jwt', 'encryption',
|
|
2221
|
+
'testing', 'vitest', 'jest', 'cypress', 'playwright',
|
|
2222
|
+
'git', 'github', 'linux', 'nginx', 'webpack', 'vite',
|
|
2223
|
+
];
|
|
2224
|
+
const lower = message.toLowerCase();
|
|
2225
|
+
return TECH_TERMS.filter(term => lower.includes(term));
|
|
2226
|
+
}
|
|
2227
|
+
}
|
|
2228
|
+
//# sourceMappingURL=PGA.js.map
|