@pga-ai/core 0.4.0 → 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.
Files changed (183) hide show
  1. package/README.md +7 -7
  2. package/dist/PGA.d.ts +100 -1
  3. package/dist/PGA.d.ts.map +1 -1
  4. package/dist/PGA.js +1015 -25
  5. package/dist/PGA.js.map +1 -1
  6. package/dist/advanced-ai/AgentVitals.d.ts +23 -0
  7. package/dist/advanced-ai/AgentVitals.d.ts.map +1 -0
  8. package/dist/advanced-ai/AgentVitals.js +13 -0
  9. package/dist/advanced-ai/AgentVitals.js.map +1 -0
  10. package/dist/advanced-ai/CalibratedAutonomy.d.ts +37 -0
  11. package/dist/advanced-ai/CalibratedAutonomy.d.ts.map +1 -0
  12. package/dist/advanced-ai/CalibratedAutonomy.js +151 -0
  13. package/dist/advanced-ai/CalibratedAutonomy.js.map +1 -0
  14. package/dist/advanced-ai/EmotionalModel.d.ts +27 -0
  15. package/dist/advanced-ai/EmotionalModel.d.ts.map +1 -0
  16. package/dist/advanced-ai/EmotionalModel.js +206 -0
  17. package/dist/advanced-ai/EmotionalModel.js.map +1 -0
  18. package/dist/advanced-ai/EnhancedSelfModel.d.ts +53 -0
  19. package/dist/advanced-ai/EnhancedSelfModel.d.ts.map +1 -0
  20. package/dist/advanced-ai/EnhancedSelfModel.js +189 -0
  21. package/dist/advanced-ai/EnhancedSelfModel.js.map +1 -0
  22. package/dist/advanced-ai/SelfModel.d.ts +29 -0
  23. package/dist/advanced-ai/SelfModel.d.ts.map +1 -0
  24. package/dist/advanced-ai/SelfModel.js +91 -0
  25. package/dist/advanced-ai/SelfModel.js.map +1 -0
  26. package/dist/advanced-ai/StrategicAutonomy.d.ts +41 -0
  27. package/dist/advanced-ai/StrategicAutonomy.d.ts.map +1 -0
  28. package/dist/advanced-ai/StrategicAutonomy.js +148 -0
  29. package/dist/advanced-ai/StrategicAutonomy.js.map +1 -0
  30. package/dist/core/GenesisBootstrap.d.ts +18 -0
  31. package/dist/core/GenesisBootstrap.d.ts.map +1 -0
  32. package/dist/core/GenesisBootstrap.js +95 -0
  33. package/dist/core/GenesisBootstrap.js.map +1 -0
  34. package/dist/core/GenomeManager.js +1 -1
  35. package/dist/core/PromptAssembler.d.ts +26 -0
  36. package/dist/core/PromptAssembler.d.ts.map +1 -1
  37. package/dist/core/PromptAssembler.js +133 -8
  38. package/dist/core/PromptAssembler.js.map +1 -1
  39. package/dist/evaluation/BenchmarkSuites.d.ts +2 -0
  40. package/dist/evaluation/BenchmarkSuites.d.ts.map +1 -1
  41. package/dist/evaluation/BenchmarkSuites.js +9 -6
  42. package/dist/evaluation/BenchmarkSuites.js.map +1 -1
  43. package/dist/evaluation/Evaluator.d.ts.map +1 -1
  44. package/dist/evaluation/Evaluator.js +8 -7
  45. package/dist/evaluation/Evaluator.js.map +1 -1
  46. package/dist/evaluation/ProofOfValueRunner.d.ts +41 -0
  47. package/dist/evaluation/ProofOfValueRunner.d.ts.map +1 -0
  48. package/dist/evaluation/ProofOfValueRunner.js +177 -0
  49. package/dist/evaluation/ProofOfValueRunner.js.map +1 -0
  50. package/dist/evaluation/SandboxSuites.js +4 -4
  51. package/dist/evaluation/SandboxSuites.js.map +1 -1
  52. package/dist/evaluation/fixtures/proof-of-value-v1.json +178 -0
  53. package/dist/evolution/MutationOperator.d.ts +26 -0
  54. package/dist/evolution/MutationOperator.d.ts.map +1 -1
  55. package/dist/evolution/MutationOperator.js +200 -9
  56. package/dist/evolution/MutationOperator.js.map +1 -1
  57. package/dist/evolution/PurposeSurvival.d.ts +68 -0
  58. package/dist/evolution/PurposeSurvival.d.ts.map +1 -0
  59. package/dist/evolution/PurposeSurvival.js +199 -0
  60. package/dist/evolution/PurposeSurvival.js.map +1 -0
  61. package/dist/evolution/boost/EvolutionBoostEngine.d.ts +2 -1
  62. package/dist/evolution/boost/EvolutionBoostEngine.d.ts.map +1 -1
  63. package/dist/evolution/boost/EvolutionBoostEngine.js +3 -3
  64. package/dist/evolution/boost/EvolutionBoostEngine.js.map +1 -1
  65. package/dist/evolution/boost/GeneticRecombinator.d.ts.map +1 -1
  66. package/dist/evolution/boost/GeneticRecombinator.js +16 -5
  67. package/dist/evolution/boost/GeneticRecombinator.js.map +1 -1
  68. package/dist/evolution/boost/ParetoOptimizer.d.ts +1 -1
  69. package/dist/evolution/boost/ParetoOptimizer.d.ts.map +1 -1
  70. package/dist/evolution/boost/ParetoOptimizer.js.map +1 -1
  71. package/dist/evolution/boost/operators/BreakthroughOperator.d.ts +4 -7
  72. package/dist/evolution/boost/operators/BreakthroughOperator.d.ts.map +1 -1
  73. package/dist/evolution/boost/operators/BreakthroughOperator.js +172 -160
  74. package/dist/evolution/boost/operators/BreakthroughOperator.js.map +1 -1
  75. package/dist/evolution/boost/operators/CrossoverMutationOperator.d.ts +10 -15
  76. package/dist/evolution/boost/operators/CrossoverMutationOperator.d.ts.map +1 -1
  77. package/dist/evolution/boost/operators/CrossoverMutationOperator.js +167 -120
  78. package/dist/evolution/boost/operators/CrossoverMutationOperator.js.map +1 -1
  79. package/dist/evolution/boost/operators/PatternExtractionOperator.d.ts +7 -10
  80. package/dist/evolution/boost/operators/PatternExtractionOperator.d.ts.map +1 -1
  81. package/dist/evolution/boost/operators/PatternExtractionOperator.js +167 -164
  82. package/dist/evolution/boost/operators/PatternExtractionOperator.js.map +1 -1
  83. package/dist/evolution/boost/operators/SemanticRestructuringOperator.d.ts +2 -3
  84. package/dist/evolution/boost/operators/SemanticRestructuringOperator.d.ts.map +1 -1
  85. package/dist/evolution/boost/operators/SemanticRestructuringOperator.js +136 -54
  86. package/dist/evolution/boost/operators/SemanticRestructuringOperator.js.map +1 -1
  87. package/dist/evolution/boost/utils/llmHelper.d.ts +10 -0
  88. package/dist/evolution/boost/utils/llmHelper.d.ts.map +1 -0
  89. package/dist/evolution/boost/utils/llmHelper.js +13 -0
  90. package/dist/evolution/boost/utils/llmHelper.js.map +1 -0
  91. package/dist/firewall/ContentFirewall.d.ts +30 -0
  92. package/dist/firewall/ContentFirewall.d.ts.map +1 -0
  93. package/dist/firewall/ContentFirewall.js +251 -0
  94. package/dist/firewall/ContentFirewall.js.map +1 -0
  95. package/dist/firewall/DefaultPatterns.d.ts +8 -0
  96. package/dist/firewall/DefaultPatterns.d.ts.map +1 -0
  97. package/dist/firewall/DefaultPatterns.js +623 -0
  98. package/dist/firewall/DefaultPatterns.js.map +1 -0
  99. package/dist/firewall/index.d.ts +3 -0
  100. package/dist/firewall/index.d.ts.map +1 -0
  101. package/dist/firewall/index.js +3 -0
  102. package/dist/firewall/index.js.map +1 -0
  103. package/dist/gene-bank/CognitiveGene.d.ts +106 -106
  104. package/dist/gene-bank/GeneAdopter.d.ts +1 -0
  105. package/dist/gene-bank/GeneAdopter.d.ts.map +1 -1
  106. package/dist/gene-bank/GeneAdopter.js +23 -4
  107. package/dist/gene-bank/GeneAdopter.js.map +1 -1
  108. package/dist/gene-bank/GeneBank.d.ts +6 -6
  109. package/dist/gene-bank/GeneExtractor.d.ts +4 -4
  110. package/dist/gene-bank/MarketplaceClient.d.ts +26 -0
  111. package/dist/gene-bank/MarketplaceClient.d.ts.map +1 -0
  112. package/dist/gene-bank/MarketplaceClient.js +147 -0
  113. package/dist/gene-bank/MarketplaceClient.js.map +1 -0
  114. package/dist/gene-bank/SandboxTester.d.ts +2 -2
  115. package/dist/gene-bank/adapters/PostgresGeneStorage.js +1 -1
  116. package/dist/gene-bank/adapters/PostgresGeneStorage.js.map +1 -1
  117. package/dist/gene-bank/index.d.ts +1 -0
  118. package/dist/gene-bank/index.d.ts.map +1 -1
  119. package/dist/gene-bank/index.js +1 -0
  120. package/dist/gene-bank/index.js.map +1 -1
  121. package/dist/index.d.ts +54 -8
  122. package/dist/index.d.ts.map +1 -1
  123. package/dist/index.js +33 -5
  124. package/dist/index.js.map +1 -1
  125. package/dist/interfaces/StorageAdapter.d.ts +4 -1
  126. package/dist/interfaces/StorageAdapter.d.ts.map +1 -1
  127. package/dist/memory/AnalyticMemoryEngine.d.ts +83 -0
  128. package/dist/memory/AnalyticMemoryEngine.d.ts.map +1 -0
  129. package/dist/memory/AnalyticMemoryEngine.js +372 -0
  130. package/dist/memory/AnalyticMemoryEngine.js.map +1 -0
  131. package/dist/memory/LayeredMemory.d.ts +2 -0
  132. package/dist/memory/LayeredMemory.d.ts.map +1 -1
  133. package/dist/memory/LayeredMemory.js +2 -0
  134. package/dist/memory/LayeredMemory.js.map +1 -1
  135. package/dist/memory/PatternMemory.d.ts +38 -0
  136. package/dist/memory/PatternMemory.d.ts.map +1 -0
  137. package/dist/memory/PatternMemory.js +161 -0
  138. package/dist/memory/PatternMemory.js.map +1 -0
  139. package/dist/memory/PersonalNarrative.d.ts +51 -0
  140. package/dist/memory/PersonalNarrative.d.ts.map +1 -0
  141. package/dist/memory/PersonalNarrative.js +172 -0
  142. package/dist/memory/PersonalNarrative.js.map +1 -0
  143. package/dist/monitoring/AlertWebhooks.d.ts.map +1 -1
  144. package/dist/monitoring/AlertWebhooks.js +8 -5
  145. package/dist/monitoring/AlertWebhooks.js.map +1 -1
  146. package/dist/monitoring/MonitoringDashboard.js +1 -1
  147. package/dist/reasoning/Metacognition.d.ts +47 -0
  148. package/dist/reasoning/Metacognition.d.ts.map +1 -0
  149. package/dist/reasoning/Metacognition.js +274 -0
  150. package/dist/reasoning/Metacognition.js.map +1 -0
  151. package/dist/types/GenomeV2.d.ts +95 -0
  152. package/dist/types/GenomeV2.d.ts.map +1 -1
  153. package/dist/types/index.d.ts +159 -0
  154. package/dist/types/index.d.ts.map +1 -1
  155. package/dist/utils/tokens.d.ts +4 -0
  156. package/dist/utils/tokens.d.ts.map +1 -0
  157. package/dist/utils/tokens.js +16 -0
  158. package/dist/utils/tokens.js.map +1 -0
  159. package/dist/wrap/FunctionLLMAdapter.d.ts +9 -0
  160. package/dist/wrap/FunctionLLMAdapter.d.ts.map +1 -0
  161. package/dist/wrap/FunctionLLMAdapter.js +26 -0
  162. package/dist/wrap/FunctionLLMAdapter.js.map +1 -0
  163. package/dist/wrap/GenomeBuilder.d.ts +13 -0
  164. package/dist/wrap/GenomeBuilder.d.ts.map +1 -0
  165. package/dist/wrap/GenomeBuilder.js +222 -0
  166. package/dist/wrap/GenomeBuilder.js.map +1 -0
  167. package/dist/wrap/InMemoryStorageAdapter.d.ts +61 -0
  168. package/dist/wrap/InMemoryStorageAdapter.d.ts.map +1 -0
  169. package/dist/wrap/InMemoryStorageAdapter.js +153 -0
  170. package/dist/wrap/InMemoryStorageAdapter.js.map +1 -0
  171. package/dist/wrap/WrapOptions.d.ts +45 -0
  172. package/dist/wrap/WrapOptions.d.ts.map +1 -0
  173. package/dist/wrap/WrapOptions.js +2 -0
  174. package/dist/wrap/WrapOptions.js.map +1 -0
  175. package/dist/wrap/WrappedAgent.d.ts +77 -0
  176. package/dist/wrap/WrappedAgent.d.ts.map +1 -0
  177. package/dist/wrap/WrappedAgent.js +142 -0
  178. package/dist/wrap/WrappedAgent.js.map +1 -0
  179. package/dist/wrap/index.d.ts +6 -0
  180. package/dist/wrap/index.d.ts.map +1 -0
  181. package/dist/wrap/index.js +5 -0
  182. package/dist/wrap/index.js.map +1 -0
  183. package/package.json +13 -10
package/dist/PGA.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { WrappedAgent } from './wrap/WrappedAgent.js';
1
2
  import { GenomeManager } from './core/GenomeManager.js';
2
3
  import { PromptAssembler } from './core/PromptAssembler.js';
3
4
  import { DNAProfile } from './core/DNAProfile.js';
@@ -11,6 +12,28 @@ import { MetricsCollector } from './monitoring/MetricsCollector.js';
11
12
  import { MonitoringDashboard } from './monitoring/MonitoringDashboard.js';
12
13
  import { RAGEngine } from './rag/RAGEngine.js';
13
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 { CanaryDeploymentManager } from './evolution/CanaryDeployment.js';
32
+ import { EnhancedSelfModel } from './advanced-ai/EnhancedSelfModel.js';
33
+ import { PurposeSurvival } from './evolution/PurposeSurvival.js';
34
+ import { StrategicAutonomy } from './advanced-ai/StrategicAutonomy.js';
35
+ import { computeAgentVitals } from './advanced-ai/AgentVitals.js';
36
+ import { ContentFirewall } from './firewall/ContentFirewall.js';
14
37
  export class PGA {
15
38
  pgaConfig;
16
39
  genomeManager;
@@ -19,6 +42,30 @@ export class PGA {
19
42
  dashboard;
20
43
  constructor(pgaConfig) {
21
44
  this.pgaConfig = pgaConfig;
45
+ if (!pgaConfig.llm) {
46
+ throw new Error(`[GSEP] LLM adapter is required.\n\n`
47
+ + `GSEP needs an AI model to function. Please provide an LLM adapter:\n\n`
48
+ + ` import { PGA } from '@pga-ai/core';\n`
49
+ + ` import { ClaudeAdapter } from '@pga-ai/adapters-llm-anthropic';\n\n`
50
+ + ` const pga = new PGA({\n`
51
+ + ` llm: new ClaudeAdapter({ apiKey: process.env.ANTHROPIC_API_KEY }),\n`
52
+ + ` storage: yourStorageAdapter,\n`
53
+ + ` });\n\n`
54
+ + `Supported adapters:\n`
55
+ + ` - @pga-ai/adapters-llm-anthropic (Claude)\n`
56
+ + ` - @pga-ai/adapters-llm-openai (GPT-4)\n\n`
57
+ + `Run 'pga doctor' for full diagnostics.`);
58
+ }
59
+ if (!pgaConfig.storage) {
60
+ throw new Error(`[GSEP] Storage adapter is required.\n\n`
61
+ + `GSEP needs a storage adapter to persist genomes. Please provide one:\n\n`
62
+ + ` import { InMemoryStorage } from '@pga-ai/core';\n\n`
63
+ + ` const pga = new PGA({\n`
64
+ + ` llm: yourLLMAdapter,\n`
65
+ + ` storage: new InMemoryStorage(),\n`
66
+ + ` });\n\n`
67
+ + `For production, use: @pga-ai/adapters-storage-postgres`);
68
+ }
22
69
  this.llm = pgaConfig.llm;
23
70
  this.genomeManager = new GenomeManager(pgaConfig.storage);
24
71
  this.metricsCollector = new MetricsCollector(pgaConfig.monitoring || {
@@ -39,7 +86,7 @@ export class PGA {
39
86
  level: 'info',
40
87
  component: 'pga',
41
88
  operation: 'initialize',
42
- message: 'PGA system initialized successfully',
89
+ message: 'GSEP system initialized successfully',
43
90
  });
44
91
  }
45
92
  getMetrics() {
@@ -65,7 +112,7 @@ export class PGA {
65
112
  level: 'info',
66
113
  component: 'pga',
67
114
  operation: 'shutdown',
68
- message: 'PGA system shutdown',
115
+ message: 'GSEP system shutdown',
69
116
  });
70
117
  }
71
118
  async createGenome(options) {
@@ -88,13 +135,27 @@ export class PGA {
88
135
  ...options.config,
89
136
  },
90
137
  });
91
- return new GenomeInstance(genome, this.llm, this.pgaConfig.storage, this.metricsCollector, this.pgaConfig.modelRouter, this.pgaConfig.rag, this.pgaConfig.reasoning);
138
+ if (this.pgaConfig.geneBank && genome.config.autonomous?.genesisBootstrap) {
139
+ const bootstrap = new GenesisBootstrap(this.pgaConfig.geneBank);
140
+ const result = await bootstrap.bootstrap(genome, genome.config.autonomous.bootstrapMinFitness ?? 0.7);
141
+ if (result.genesUpgraded > 0) {
142
+ await this.pgaConfig.storage.saveGenome(genome);
143
+ this.metricsCollector.logAudit({
144
+ level: 'info',
145
+ component: 'pga',
146
+ operation: 'genesis-bootstrap',
147
+ message: `Bootstrapped ${result.genesUpgraded} genes from Gene Bank`,
148
+ metadata: { upgrades: result.upgrades },
149
+ });
150
+ }
151
+ }
152
+ return new GenomeInstance(genome, this.llm, this.pgaConfig.storage, this.metricsCollector, this.pgaConfig.modelRouter, this.pgaConfig.rag, this.pgaConfig.reasoning, this.pgaConfig.geneBank);
92
153
  }
93
154
  async loadGenome(genomeId) {
94
155
  const genome = await this.genomeManager.loadGenome(genomeId);
95
156
  if (!genome)
96
157
  return null;
97
- return new GenomeInstance(genome, this.llm, this.pgaConfig.storage, this.metricsCollector, this.pgaConfig.modelRouter, this.pgaConfig.rag, this.pgaConfig.reasoning);
158
+ return new GenomeInstance(genome, this.llm, this.pgaConfig.storage, this.metricsCollector, this.pgaConfig.modelRouter, this.pgaConfig.rag, this.pgaConfig.reasoning, this.pgaConfig.geneBank);
98
159
  }
99
160
  async listGenomes() {
100
161
  return this.genomeManager.listGenomes();
@@ -102,11 +163,21 @@ export class PGA {
102
163
  async deleteGenome(genomeId) {
103
164
  await this.genomeManager.deleteGenome(genomeId);
104
165
  }
166
+ static async wrap(target, options) {
167
+ if (typeof target === 'function') {
168
+ if (!options.name) {
169
+ throw new Error('PGA.wrap(): name is required when wrapping a function');
170
+ }
171
+ return WrappedAgent.fromFunction(target, options);
172
+ }
173
+ return WrappedAgent.fromAdapter(target, options);
174
+ }
105
175
  }
106
176
  export class GenomeInstance {
107
177
  genome;
108
178
  llm;
109
179
  storage;
180
+ geneBank;
110
181
  assembler;
111
182
  dnaProfile;
112
183
  learningAnnouncer;
@@ -117,10 +188,27 @@ export class GenomeInstance {
117
188
  metrics;
118
189
  ragEngine;
119
190
  reasoningEngine;
120
- constructor(genome, llm, storage, metrics, modelRouterConfig, ragConfig, reasoningConfig) {
191
+ fitnessTracker;
192
+ fitnessCalculator;
193
+ mutationEngine;
194
+ driftAnalyzer;
195
+ selfModel;
196
+ patternMemory;
197
+ metacognition;
198
+ emotionalModel;
199
+ calibratedAutonomy;
200
+ personalNarrative;
201
+ analyticMemory;
202
+ canaryManager;
203
+ enhancedSelfModel;
204
+ purposeSurvival;
205
+ strategicAutonomy;
206
+ interactionCount = 0;
207
+ constructor(genome, llm, storage, metrics, modelRouterConfig, ragConfig, reasoningConfig, geneBank) {
121
208
  this.genome = genome;
122
209
  this.llm = llm;
123
210
  this.storage = storage;
211
+ this.geneBank = geneBank;
124
212
  this.assembler = new PromptAssembler(storage, genome);
125
213
  this.dnaProfile = new DNAProfile(storage);
126
214
  this.learningAnnouncer = new LearningAnnouncer();
@@ -135,7 +223,67 @@ export class GenomeInstance {
135
223
  if (genome.config.reasoning?.enabled) {
136
224
  this.reasoningEngine = new ReasoningEngine(llm, reasoningConfig);
137
225
  }
138
- new FitnessTracker(storage, genome);
226
+ this.fitnessTracker = new FitnessTracker(storage, genome);
227
+ this.fitnessCalculator = new FitnessCalculator();
228
+ this.mutationEngine = new MutationEngine();
229
+ this.canaryManager = new CanaryDeploymentManager(storage, {
230
+ initialTrafficPercent: 10,
231
+ minSampleSize: 5,
232
+ });
233
+ this.mutationEngine.registerOperator(new TokenCompressionOperator(llm));
234
+ this.mutationEngine.registerOperator(new SemanticRestructuringOperator(llm));
235
+ this.mutationEngine.registerOperator(new PatternExtractionOperator(llm, this.geneBank));
236
+ this.mutationEngine.registerOperator(new CrossoverMutationOperator(llm));
237
+ this.mutationEngine.registerOperator(new BreakthroughOperator(llm));
238
+ this.driftAnalyzer = new DriftAnalyzer();
239
+ if (genome.config.autonomous?.enableSelfModel) {
240
+ this.selfModel = new SelfModel(genome, this.driftAnalyzer);
241
+ this.assembler.setSelfModel(this.selfModel);
242
+ }
243
+ if (genome.config.autonomous?.enablePatternMemory) {
244
+ this.patternMemory = new PatternMemory(genome.config.autonomous.maxPatterns ?? 50);
245
+ this.assembler.setPatternMemory(this.patternMemory);
246
+ }
247
+ if (genome.config.autonomous?.enableMetacognition) {
248
+ this.metacognition = new Metacognition(() => this.selfModel?.assess() ?? null);
249
+ this.assembler.setMetacognition(this.metacognition);
250
+ }
251
+ if (genome.config.autonomous?.enableEmotionalModel) {
252
+ this.emotionalModel = new EmotionalModel();
253
+ this.assembler.setEmotionalModel(this.emotionalModel);
254
+ }
255
+ if (genome.config.autonomous?.enableCalibratedAutonomy) {
256
+ this.calibratedAutonomy = new CalibratedAutonomy();
257
+ this.assembler.setCalibratedAutonomy(this.calibratedAutonomy);
258
+ }
259
+ if (genome.config.autonomous?.enablePersonalNarrative) {
260
+ this.personalNarrative = new PersonalNarrative();
261
+ this.assembler.setPersonalNarrative(this.personalNarrative);
262
+ }
263
+ if (genome.config.autonomous?.enableAnalyticMemory) {
264
+ this.analyticMemory = new AnalyticMemoryEngine();
265
+ this.assembler.setAnalyticMemory(this.analyticMemory);
266
+ }
267
+ const agentPurpose = genome.config.autonomous?.agentPurpose
268
+ || genome.layers.layer0[0]?.content
269
+ || 'AI Assistant';
270
+ if (genome.config.autonomous?.enableEnhancedSelfModel) {
271
+ this.enhancedSelfModel = new EnhancedSelfModel(genome, this.driftAnalyzer, agentPurpose);
272
+ this.assembler.setSelfModel(this.enhancedSelfModel);
273
+ }
274
+ if (genome.config.autonomous?.enablePurposeSurvival) {
275
+ this.purposeSurvival = new PurposeSurvival(agentPurpose, this.driftAnalyzer, () => this.enhancedSelfModel?.assessFull()
276
+ ?? { score: 0.5, fitnessComponent: 0.5, driftComponent: 1.0,
277
+ purposeComponent: 0.5, trajectoryComponent: 0.5, label: 'stable' });
278
+ }
279
+ if (genome.config.autonomous?.enableStrategicAutonomy) {
280
+ this.strategicAutonomy = new StrategicAutonomy(agentPurpose, () => this.enhancedSelfModel?.assessFull() ?? null, () => this.purposeSurvival?.getMode() ?? 'stable');
281
+ this.assembler.setCalibratedAutonomy(this.strategicAutonomy);
282
+ }
283
+ if (genome.config.firewall?.enabled !== false) {
284
+ const firewall = new ContentFirewall();
285
+ this.assembler.setFirewall(firewall);
286
+ }
139
287
  }
140
288
  get id() {
141
289
  return this.genome.id;
@@ -145,7 +293,7 @@ export class GenomeInstance {
145
293
  }
146
294
  getWelcomeMessage(style = 'detailed') {
147
295
  const messages = {
148
- short: `🧬 I now have PGA — Genomic Self-Evolving Prompts integrated into my DNA!
296
+ short: `🧬 I now have GSEP — Genomic Self-Evolving Prompts integrated into my DNA!
149
297
 
150
298
  This means I can:
151
299
  ✓ Learn from every interaction
@@ -153,7 +301,7 @@ This means I can:
153
301
  ✓ Improve continuously without manual updates
154
302
 
155
303
  I'm ready to evolve with you!`,
156
- detailed: `🧬 Great news! I now have PGA — Genomic Self-Evolving Prompts integrated into my core system!
304
+ detailed: `🧬 Great news! I now have GSEP — Genomic Self-Evolving Prompts integrated into my core system!
157
305
 
158
306
  What this means for you:
159
307
 
@@ -179,7 +327,7 @@ What this means for you:
179
327
  4. You'll notice me getting better at understanding your needs
180
328
 
181
329
  Let's evolve together! How can I help you today?`,
182
- technical: `🧬 System Update: PGA (Genomic Self-Evolving Prompts) — ACTIVE
330
+ technical: `🧬 System Update: GSEP (Genomic Self-Evolving Prompts) — ACTIVE
183
331
 
184
332
  **Architecture Overview:**
185
333
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
@@ -211,7 +359,7 @@ Every interaction contributes to:
211
359
  4. Performance optimization
212
360
 
213
361
  System ready. Genomic evolution: INITIALIZED.`,
214
- casual: `🧬 Hey! Exciting update — I just got upgraded with PGA (think of it as evolutionary AI)!
362
+ casual: `🧬 Hey! Exciting update — I just got upgraded with GSEP (think of it as evolutionary AI)!
215
363
 
216
364
  Here's the cool part:
217
365
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
@@ -240,6 +388,10 @@ Ready to see what we can do together? 😊`,
240
388
  return this.assembler.assemblePrompt(context, currentMessage);
241
389
  }
242
390
  async chat(userMessage, context) {
391
+ if (!this.llm) {
392
+ throw new Error(`[GSEP] Cannot chat: no LLM adapter configured. `
393
+ + `The agent needs an AI model to generate responses.`);
394
+ }
243
395
  const requestId = `chat_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
244
396
  const startTime = Date.now();
245
397
  let error;
@@ -249,6 +401,16 @@ Ready to see what we can do together? 😊`,
249
401
  const ragContext = await this.ragEngine.augment(userMessage, prompt);
250
402
  prompt = ragContext.augmentedPrompt;
251
403
  }
404
+ let activeCanaryId;
405
+ const activeCanaries = this.canaryManager.getActiveDeployments();
406
+ for (const canary of activeCanaries) {
407
+ if (canary.genomeId === this.genome.id && context.userId) {
408
+ if (this.canaryManager.shouldUseCanary(canary.id, context.userId)) {
409
+ activeCanaryId = canary.id;
410
+ prompt = this.applyCanaryVariant(prompt, canary);
411
+ }
412
+ }
413
+ }
252
414
  let response;
253
415
  if (this.reasoningEngine) {
254
416
  const reasoningResult = await this.reasoningEngine.reason(userMessage, prompt, this.genome.config.reasoning?.defaultStrategy);
@@ -283,6 +445,56 @@ Ready to see what we can do together? 😊`,
283
445
  outputTokens,
284
446
  },
285
447
  });
448
+ const quality = this.estimateQuality(userMessage, response.content);
449
+ if (activeCanaryId) {
450
+ this.canaryManager.recordRequest(activeCanaryId, 'canary', {
451
+ success: true,
452
+ latencyMs: Date.now() - startTime,
453
+ fitness: quality,
454
+ });
455
+ }
456
+ else {
457
+ for (const canary of activeCanaries) {
458
+ if (canary.genomeId === this.genome.id) {
459
+ this.canaryManager.recordRequest(canary.id, 'stable', {
460
+ success: true,
461
+ latencyMs: Date.now() - startTime,
462
+ fitness: quality,
463
+ });
464
+ }
465
+ }
466
+ }
467
+ const interactionData = {
468
+ success: true,
469
+ quality,
470
+ inputTokens,
471
+ outputTokens,
472
+ latency: Date.now() - startTime,
473
+ model: this.llm.model ?? 'unknown',
474
+ interventionNeeded: false,
475
+ timestamp: new Date(),
476
+ };
477
+ const fitnessVector = this.fitnessCalculator.computeFitness([interactionData]);
478
+ this.driftAnalyzer.recordFitness(fitnessVector);
479
+ if (this.enhancedSelfModel && context.taskType) {
480
+ for (const allele of this.genome.layers.layer1.filter(a => a.status === 'active')) {
481
+ this.enhancedSelfModel.recordCapability(context.taskType, allele.gene, quality);
482
+ }
483
+ }
484
+ if (this.purposeSurvival) {
485
+ this.purposeSurvival.evaluateThreats();
486
+ }
487
+ this.interactionCount++;
488
+ const autoConfig = this.genome.config.autonomous;
489
+ if (autoConfig?.continuousEvolution && this.interactionCount % (autoConfig.evolveEveryN ?? 10) === 0) {
490
+ this.runEvolutionCycle().catch(err => this.metrics.logAudit({
491
+ level: 'warning',
492
+ component: 'genome',
493
+ operation: 'auto-evolve',
494
+ message: `Auto-evolution failed: ${err instanceof Error ? err.message : String(err)}`,
495
+ genomeId: this.genome.id,
496
+ }));
497
+ }
286
498
  if (context.userId) {
287
499
  const previousDNA = await this.dnaProfile.getDNA(context.userId, this.genome.id);
288
500
  await this.recordInteraction({
@@ -338,6 +550,114 @@ Ready to see what we can do together? 😊`,
338
550
  };
339
551
  await this.storage.recordInteraction(fullInteraction);
340
552
  await this.dnaProfile.updateDNA(interaction.userId, this.genome.id, fullInteraction);
553
+ for (const allele of this.genome.layers.layer1.filter(a => a.status === 'active')) {
554
+ const score = this.computeInteractionQuality(interaction);
555
+ await this.fitnessTracker.recordPerformance(1, allele.gene, allele.variant, score);
556
+ }
557
+ if (this.patternMemory) {
558
+ this.patternMemory.recordInteraction({
559
+ taskType: interaction.taskType,
560
+ success: !!interaction.assistantResponse,
561
+ timestamp: interaction.timestamp,
562
+ });
563
+ }
564
+ if (this.personalNarrative) {
565
+ this.personalNarrative.recordInteraction({
566
+ topic: interaction.taskType,
567
+ wasSuccessful: !!interaction.assistantResponse,
568
+ userExpressedGratitude: interaction.userMessage?.toLowerCase().includes('thanks') ||
569
+ interaction.userMessage?.toLowerCase().includes('thank you'),
570
+ });
571
+ }
572
+ if (this.analyticMemory && interaction.taskType) {
573
+ this.analyticMemory.recordObservation({
574
+ subject: interaction.userId,
575
+ action: 'performed',
576
+ object: interaction.taskType,
577
+ timestamp: interaction.timestamp,
578
+ });
579
+ }
580
+ if (this.metacognition && interaction.assistantResponse) {
581
+ this.metacognition.analyzePostResponse(interaction.userMessage, interaction.assistantResponse, !!interaction.assistantResponse);
582
+ }
583
+ if (this.calibratedAutonomy && interaction.taskType && interaction.assistantResponse) {
584
+ this.calibratedAutonomy.recordSuccess(interaction.taskType);
585
+ }
586
+ if (this.enhancedSelfModel && this.interactionCount % 10 === 0) {
587
+ this.enhancedSelfModel.recordFitnessSnapshot();
588
+ }
589
+ if (this.geneBank && this.genome.config.autonomous?.enableSwarm) {
590
+ const threshold = this.genome.config.autonomous.autoPublishThreshold ?? 0.85;
591
+ for (const allele of this.genome.layers.layer1.filter(a => a.status === 'active')) {
592
+ if (allele.fitness >= threshold && !allele.publishedToSwarm) {
593
+ this.autoPublishGene(allele).catch(() => { });
594
+ }
595
+ }
596
+ }
597
+ }
598
+ async reportExternalMetrics(metrics) {
599
+ const requestId = `ext_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
600
+ this.metrics.recordRequest({
601
+ requestId,
602
+ duration: metrics.latencyMs,
603
+ success: metrics.success,
604
+ model: 'external',
605
+ inputTokens: metrics.inputTokens,
606
+ outputTokens: metrics.outputTokens,
607
+ ...(metrics.success ? {} : { error: 'external-failure' }),
608
+ });
609
+ this.metrics.logAudit({
610
+ level: 'info',
611
+ component: 'genome',
612
+ operation: 'external-report',
613
+ message: `External metrics reported: ${metrics.success ? 'success' : 'failure'}`,
614
+ userId: metrics.userId,
615
+ genomeId: this.genome.id,
616
+ duration: metrics.latencyMs,
617
+ metadata: {
618
+ inputTokens: metrics.inputTokens,
619
+ outputTokens: metrics.outputTokens,
620
+ taskType: metrics.taskType,
621
+ },
622
+ });
623
+ const quality = metrics.quality ?? (metrics.success ? 0.7 : 0.3);
624
+ const interactionData = {
625
+ success: metrics.success,
626
+ quality,
627
+ inputTokens: metrics.inputTokens,
628
+ outputTokens: metrics.outputTokens,
629
+ latency: metrics.latencyMs,
630
+ model: 'external',
631
+ interventionNeeded: false,
632
+ timestamp: new Date(),
633
+ };
634
+ const fitnessVector = this.fitnessCalculator.computeFitness([interactionData]);
635
+ this.driftAnalyzer.recordFitness(fitnessVector);
636
+ if (this.enhancedSelfModel && metrics.taskType) {
637
+ for (const allele of this.genome.layers.layer1.filter(a => a.status === 'active')) {
638
+ this.enhancedSelfModel.recordCapability(metrics.taskType, allele.gene, quality);
639
+ }
640
+ }
641
+ if (this.purposeSurvival) {
642
+ this.purposeSurvival.evaluateThreats();
643
+ }
644
+ this.interactionCount++;
645
+ const autoConfig = this.genome.config.autonomous;
646
+ if (autoConfig?.continuousEvolution && this.interactionCount % (autoConfig.evolveEveryN ?? 10) === 0) {
647
+ this.runEvolutionCycle().catch(err => this.metrics.logAudit({
648
+ level: 'warning',
649
+ component: 'genome',
650
+ operation: 'auto-evolve',
651
+ message: `Auto-evolution failed: ${err instanceof Error ? err.message : String(err)}`,
652
+ genomeId: this.genome.id,
653
+ }));
654
+ }
655
+ if (metrics.feedback && metrics.userId) {
656
+ const activeGenes = this.genome.layers.layer1.filter(a => a.status === 'active');
657
+ for (const allele of activeGenes) {
658
+ await this.recordFeedback(metrics.userId, allele.gene, metrics.feedback);
659
+ }
660
+ }
341
661
  }
342
662
  async getDNA(userId) {
343
663
  return this.dnaProfile.getDNA(userId, this.genome.id);
@@ -395,12 +715,34 @@ Ready to see what we can do together? 😊`,
395
715
  };
396
716
  }
397
717
  const currentAllele = currentAlleles[0];
718
+ const mutationContext = {
719
+ genome: this.toGenomeV2(),
720
+ targetChromosome: opts.layer <= 1 ? 'c1' : 'c2',
721
+ targetGene: this.toOperativeGene(currentAllele),
722
+ reason: `Mutation for ${opts.taskType}: gene ${opts.gene}`,
723
+ evidence: this.buildEvolutionEvidence(),
724
+ };
725
+ let mutatedContent = currentAllele.content;
726
+ let expectedImprovement = 0.05;
727
+ try {
728
+ const mutants = await this.mutationEngine.generateMutants(mutationContext, opts.candidates);
729
+ if (mutants.length > 0) {
730
+ const bestMutant = mutants.sort((a, b) => b.expectedImprovement - a.expectedImprovement)[0];
731
+ const mutatedGene = bestMutant.mutant.chromosomes.c1.operations.find(g => g.category === currentAllele.gene);
732
+ if (mutatedGene) {
733
+ mutatedContent = mutatedGene.content;
734
+ }
735
+ expectedImprovement = bestMutant.expectedImprovement;
736
+ }
737
+ }
738
+ catch {
739
+ }
398
740
  const mutationCandidate = {
399
741
  layer: opts.layer,
400
742
  gene: opts.gene,
401
743
  variant: `${currentAllele.variant}_v${Date.now()}`,
402
- content: currentAllele.content,
403
- fitness: currentAllele.fitness + 0.05,
744
+ content: mutatedContent,
745
+ fitness: currentAllele.fitness + expectedImprovement,
404
746
  sandboxScore: 0.75,
405
747
  sampleCount: currentAllele.sampleCount || 0,
406
748
  rollbackCount: 0,
@@ -416,16 +758,33 @@ Ready to see what we can do together? 😊`,
416
758
  economic: gateResult.gates.economic,
417
759
  stability: gateResult.gates.stability,
418
760
  },
419
- } : gateResult.finalDecision === 'canary' ? {
420
- applied: false,
421
- reason: `${gateResult.reason} - Canary deployment not yet implemented`,
422
- gateResults: {
423
- quality: gateResult.gates.quality,
424
- sandbox: gateResult.gates.sandbox,
425
- economic: gateResult.gates.economic,
426
- stability: gateResult.gates.stability,
427
- },
428
- } : {
761
+ } : gateResult.finalDecision === 'canary' ? await (async () => {
762
+ const canaryAllele = {
763
+ gene: opts.gene,
764
+ variant: mutationCandidate.variant,
765
+ content: mutationCandidate.content,
766
+ fitness: mutationCandidate.fitness,
767
+ status: 'active',
768
+ createdAt: new Date(),
769
+ };
770
+ await this.canaryManager.startCanary({
771
+ genomeId: this.genome.id,
772
+ layer: opts.layer,
773
+ gene: opts.gene,
774
+ stableAllele: currentAllele,
775
+ canaryAllele,
776
+ });
777
+ return {
778
+ applied: false,
779
+ reason: `${gateResult.reason} - Canary deployment started (10% traffic)`,
780
+ gateResults: {
781
+ quality: gateResult.gates.quality,
782
+ sandbox: gateResult.gates.sandbox,
783
+ economic: gateResult.gates.economic,
784
+ stability: gateResult.gates.stability,
785
+ },
786
+ };
787
+ })() : {
429
788
  applied: false,
430
789
  reason: gateResult.reason,
431
790
  gateResults: {
@@ -447,7 +806,7 @@ Ready to see what we can do together? 😊`,
447
806
  gene: opts.gene,
448
807
  operators: opts.operators,
449
808
  decision: gateResult.finalDecision,
450
- improvement: result.improvement,
809
+ improvement: 'improvement' in result ? result.improvement : undefined,
451
810
  gatesPassed: Object.values(gateResult.gates).filter(g => g.passed).length,
452
811
  totalGates: Object.keys(gateResult.gates).length,
453
812
  },
@@ -543,6 +902,26 @@ Ready to see what we can do together? 😊`,
543
902
  }
544
903
  const successRate = allele.fitness;
545
904
  const registryId = `${this.genome.familyId}_${gene}_${variant}_${Date.now()}`;
905
+ if (this.storage.saveToGeneRegistry) {
906
+ await this.storage.saveToGeneRegistry({
907
+ id: registryId,
908
+ familyId: this.genome.familyId,
909
+ gene,
910
+ variant,
911
+ content: allele.content,
912
+ layer,
913
+ fitness: allele.fitness,
914
+ sampleCount: allele.sampleCount || 0,
915
+ successRate,
916
+ metadata: {
917
+ sourceGenomeId: this.genome.id,
918
+ sourceVersion: this.genome.version || 1,
919
+ publishedBy: this.genome.id,
920
+ description: description || undefined,
921
+ },
922
+ createdAt: new Date(),
923
+ });
924
+ }
546
925
  await this.storage.logMutation({
547
926
  genomeId: this.genome.id,
548
927
  layer,
@@ -560,8 +939,28 @@ Ready to see what we can do together? 😊`,
560
939
  if (this.genome.familyId && this.genome.familyId !== familyId) {
561
940
  throw new Error(`Cannot inherit from different family: ${familyId}`);
562
941
  }
563
- throw new Error(`Gene Registry inheritance under development - ` +
564
- `will inherit gene '${gene}' from family '${familyId}' to layer ${targetLayer ?? 'auto'}`);
942
+ if (!this.storage.getBestRegistryGene) {
943
+ throw new Error('Storage adapter does not support Gene Registry queries');
944
+ }
945
+ const bestGene = await this.storage.getBestRegistryGene(familyId, gene);
946
+ if (!bestGene) {
947
+ throw new Error(`No gene '${gene}' found in registry for family '${familyId}'`);
948
+ }
949
+ const layer = targetLayer ?? bestGene.layer ?? 1;
950
+ await this.addAllele(layer, gene, `inherited_${bestGene.variant}_${Date.now()}`, bestGene.content);
951
+ if (this.genome.lineage) {
952
+ this.genome.lineage.mutationOps = [
953
+ ...(this.genome.lineage.mutationOps || []),
954
+ `inherit:${gene}:${bestGene.variant}`,
955
+ ];
956
+ }
957
+ this.metrics.logAudit({
958
+ level: 'info',
959
+ component: 'genome',
960
+ operation: 'inherit-gene',
961
+ message: `Inherited gene '${gene}' (variant: ${bestGene.variant}, fitness: ${bestGene.fitness.toFixed(2)}) from family '${familyId}'`,
962
+ genomeId: this.genome.id,
963
+ });
565
964
  }
566
965
  async getEvolutionHealth() {
567
966
  const analytics = await this.storage.getAnalytics(this.genome.id);
@@ -632,5 +1031,596 @@ Ready to see what we can do together? 😊`,
632
1031
  async getConversationContext(userId) {
633
1032
  return this.contextMemory.buildContext(userId, this.genome.id);
634
1033
  }
1034
+ getDriftAnalysis() {
1035
+ return this.driftAnalyzer.analyzeDrift();
1036
+ }
1037
+ getSelfAssessment() {
1038
+ return this.selfModel?.assess() ?? null;
1039
+ }
1040
+ getPatterns() {
1041
+ return this.patternMemory?.getPatterns() ?? [];
1042
+ }
1043
+ getPredictions() {
1044
+ return this.patternMemory?.getPredictions() ?? [];
1045
+ }
1046
+ getPreResponseAnalysis(message) {
1047
+ return this.metacognition?.analyzePreResponse(message) ?? null;
1048
+ }
1049
+ getPostResponseAnalysis(message, response, wasSuccessful) {
1050
+ return this.metacognition?.analyzePostResponse(message, response, wasSuccessful) ?? null;
1051
+ }
1052
+ inferEmotion(message) {
1053
+ return this.emotionalModel?.inferEmotion(message) ?? null;
1054
+ }
1055
+ evaluateAutonomy(taskType, riskLevel) {
1056
+ return this.calibratedAutonomy?.evaluate(taskType, riskLevel) ?? null;
1057
+ }
1058
+ recordAutonomyCorrection(taskType, correctionType) {
1059
+ this.calibratedAutonomy?.recordCorrection({
1060
+ taskType,
1061
+ wasAutonomous: true,
1062
+ correctionType,
1063
+ timestamp: new Date(),
1064
+ });
1065
+ }
1066
+ getNarrativeSummary() {
1067
+ return this.personalNarrative?.getSummary() ?? null;
1068
+ }
1069
+ findHistoryCallback(topic) {
1070
+ return this.personalNarrative?.callbackToHistory(topic) ?? null;
1071
+ }
1072
+ queryMemory(question) {
1073
+ return this.analyticMemory?.query(question) ?? null;
1074
+ }
1075
+ getActiveCanaries() {
1076
+ return this.canaryManager.getActiveDeployments()
1077
+ .filter(d => d.genomeId === this.genome.id);
1078
+ }
1079
+ recordMemoryObservation(observation) {
1080
+ this.analyticMemory?.recordObservation(observation);
1081
+ }
1082
+ getIntegratedHealth() {
1083
+ return this.enhancedSelfModel?.assessFull() ?? null;
1084
+ }
1085
+ getOperatingMode() {
1086
+ return this.purposeSurvival?.getMode() ?? null;
1087
+ }
1088
+ getSurvivalStrategy() {
1089
+ return this.purposeSurvival?.getStrategy() ?? null;
1090
+ }
1091
+ getCapabilities() {
1092
+ return this.enhancedSelfModel?.getCapabilities() ?? [];
1093
+ }
1094
+ getTrajectories() {
1095
+ return this.enhancedSelfModel?.getTrajectories() ?? [];
1096
+ }
1097
+ getEvolutionPriorities() {
1098
+ if (!this.strategicAutonomy)
1099
+ return [];
1100
+ const drift = this.driftAnalyzer.analyzeDrift();
1101
+ const health = this.enhancedSelfModel?.assessFull()
1102
+ ?? { score: 0.5, fitnessComponent: 0.5, driftComponent: 1.0,
1103
+ purposeComponent: 0.5, trajectoryComponent: 0.5, label: 'stable' };
1104
+ return this.strategicAutonomy.prioritizeEvolution(drift.signals, health);
1105
+ }
1106
+ getAgentVitals() {
1107
+ if (!this.purposeSurvival || !this.enhancedSelfModel)
1108
+ return null;
1109
+ return computeAgentVitals(this.purposeSurvival, this.enhancedSelfModel);
1110
+ }
1111
+ async runEvolutionCycle() {
1112
+ const autoConfig = this.genome.config.autonomous;
1113
+ const drift = this.driftAnalyzer.analyzeDrift();
1114
+ if (this.purposeSurvival) {
1115
+ const evaluation = this.purposeSurvival.evaluateThreats();
1116
+ if (evaluation.mode === 'critical') {
1117
+ const snapshot = this.purposeSurvival.getLastKnownGood();
1118
+ if (snapshot) {
1119
+ this.restoreFromSnapshot(snapshot);
1120
+ return;
1121
+ }
1122
+ }
1123
+ if (evaluation.mode === 'stressed' || evaluation.mode === 'survival') {
1124
+ this.purposeSurvival.snapshotLastKnownGood(this.genome);
1125
+ }
1126
+ }
1127
+ if (autoConfig?.autoMutateOnDrift !== false && drift.isDrifting) {
1128
+ if (this.strategicAutonomy && this.enhancedSelfModel) {
1129
+ const health = this.enhancedSelfModel.assessFull();
1130
+ const priorities = this.strategicAutonomy.prioritizeEvolution(drift.signals, health);
1131
+ for (const priority of priorities.filter(p => p.urgency === 'immediate')) {
1132
+ if (this.purposeSurvival) {
1133
+ const currentAllele = this.genome.layers[`layer${priority.layer}`]
1134
+ ?.find((a) => a.gene === priority.gene && a.status === 'active');
1135
+ if (currentAllele) {
1136
+ const check = this.purposeSurvival.purposeFidelityCheck({
1137
+ gene: priority.gene,
1138
+ content: currentAllele.content,
1139
+ });
1140
+ if (!check.approved)
1141
+ continue;
1142
+ }
1143
+ }
1144
+ const target = this.driftToMutationTarget({
1145
+ type: priority.gene, severity: 'moderate',
1146
+ baselineValue: 0.7, currentValue: 0.5,
1147
+ });
1148
+ await this.mutate({
1149
+ layer: target.layer,
1150
+ gene: target.gene,
1151
+ taskType: `strategic-evolve:${priority.reason}`,
1152
+ });
1153
+ }
1154
+ }
1155
+ else {
1156
+ for (const signal of drift.signals) {
1157
+ if (signal.severity === 'minor')
1158
+ continue;
1159
+ const target = this.driftToMutationTarget(signal);
1160
+ await this.mutate({
1161
+ layer: target.layer,
1162
+ gene: target.gene,
1163
+ taskType: `auto-evolve:${signal.type}`,
1164
+ });
1165
+ }
1166
+ }
1167
+ }
1168
+ if (autoConfig?.autoCompressOnPressure !== false) {
1169
+ const totalC1Tokens = this.genome.layers.layer1
1170
+ .filter(a => a.status === 'active')
1171
+ .reduce((sum, a) => sum + estimateTokenCount(a.content), 0);
1172
+ const threshold = this.genome.config.compression?.autoCompressThreshold ?? 1600;
1173
+ if (totalC1Tokens > threshold) {
1174
+ await this.compressGenes();
1175
+ }
1176
+ }
1177
+ await this.evaluateCanaries();
1178
+ if (this.geneBank && (autoConfig?.enableSwarm ?? !!this.geneBank)) {
1179
+ await this.publishHighFitnessGenes();
1180
+ }
1181
+ if (this.genome.familyId && this.storage.getBestRegistryGene && drift.isDrifting) {
1182
+ for (const signal of drift.signals) {
1183
+ if (signal.severity === 'minor')
1184
+ continue;
1185
+ const target = this.driftToMutationTarget(signal);
1186
+ try {
1187
+ await this.inheritGeneFromRegistry(this.genome.familyId, target.gene, target.layer);
1188
+ }
1189
+ catch {
1190
+ }
1191
+ }
1192
+ }
1193
+ if (this.geneBank && autoConfig?.enableSwarm && drift.isDrifting) {
1194
+ const targetSeverity = autoConfig.autoImportOnDrift ?? 'severe';
1195
+ const severityRank = (s) => s === 'critical' ? 3 : s === 'major' ? 2 : s === 'moderate' ? 1 : 0;
1196
+ for (const signal of drift.signals) {
1197
+ if (severityRank(signal.severity) >= severityRank(targetSeverity)) {
1198
+ await this.autoImportGene(signal);
1199
+ }
1200
+ }
1201
+ }
1202
+ this.metrics.logAudit({
1203
+ level: 'info',
1204
+ component: 'genome',
1205
+ operation: 'evolution-cycle',
1206
+ message: `Evolution cycle #${this.interactionCount} completed`,
1207
+ genomeId: this.genome.id,
1208
+ metadata: { isDrifting: drift.isDrifting, signalCount: drift.signals.length },
1209
+ });
1210
+ }
1211
+ computeInteractionQuality(interaction) {
1212
+ if (!interaction.assistantResponse)
1213
+ return 0.2;
1214
+ const response = interaction.assistantResponse;
1215
+ const message = interaction.userMessage;
1216
+ const hasSubstance = response.length > 20 ? 0.3 : response.length / 20 * 0.3;
1217
+ const ratio = message.length > 0 ? response.length / message.length : 1;
1218
+ const efficiencyScore = ratio >= 1 && ratio <= 5 ? 0.25 :
1219
+ ratio > 5 ? Math.max(0, 0.25 - (ratio - 5) * 0.02) :
1220
+ ratio * 0.25;
1221
+ const hasStructure = ((response.includes('\n\n') ? 0.08 : 0) +
1222
+ (response.includes('```') ? 0.08 : 0) +
1223
+ (response.includes('- ') || response.includes('* ') ? 0.05 : 0) +
1224
+ (response.length > 100 ? 0.04 : 0));
1225
+ const userSatisfied = interaction.userSatisfied;
1226
+ const satisfactionScore = userSatisfied === true ? 0.2 :
1227
+ userSatisfied === false ? 0.0 :
1228
+ 0.1;
1229
+ return Math.min(1, hasSubstance + efficiencyScore + hasStructure + satisfactionScore);
1230
+ }
1231
+ applyCanaryVariant(prompt, canary) {
1232
+ const canaryAlleleContent = this.genome.layers[`layer${canary.layer}`]
1233
+ ?.find(a => a.variant === canary.canaryVariant)?.content;
1234
+ if (!canaryAlleleContent)
1235
+ return prompt;
1236
+ const stableContent = this.genome.layers[`layer${canary.layer}`]
1237
+ ?.find(a => a.variant === canary.stableVariant)?.content;
1238
+ if (stableContent && prompt.includes(stableContent)) {
1239
+ return prompt.replace(stableContent, canaryAlleleContent);
1240
+ }
1241
+ return prompt + `\n\n## Gene Override (${canary.gene})\n${canaryAlleleContent}`;
1242
+ }
1243
+ estimateQuality(userMessage, response) {
1244
+ let score = 0.5;
1245
+ const len = response.length;
1246
+ if (len > 50 && len < 5000)
1247
+ score += 0.15;
1248
+ else if (len < 20)
1249
+ score -= 0.2;
1250
+ const asksForCode = /write|code|function|implement|create.*class|fix.*bug/i.test(userMessage);
1251
+ if (asksForCode && /```/.test(response))
1252
+ score += 0.15;
1253
+ if (/^#{1,3}\s|^[-*]\s|```/m.test(response))
1254
+ score += 0.1;
1255
+ if (/sorry.*can't|i don't know|as an ai|i cannot/i.test(response))
1256
+ score -= 0.15;
1257
+ return Math.max(0, Math.min(1, score));
1258
+ }
1259
+ buildEvolutionEvidence() {
1260
+ const evidence = {};
1261
+ const drift = this.driftAnalyzer.analyzeDrift();
1262
+ if (drift.isDrifting) {
1263
+ evidence.driftSignals = drift.signals.map(s => ({
1264
+ type: s.type,
1265
+ severity: s.severity,
1266
+ currentValue: s.currentValue,
1267
+ baselineValue: s.baselineValue,
1268
+ }));
1269
+ }
1270
+ if (this.enhancedSelfModel) {
1271
+ evidence.health = this.enhancedSelfModel.assessFull();
1272
+ evidence.capabilities = this.enhancedSelfModel.getCapabilities()
1273
+ .filter((c) => c.trend === 'declining' || c.performanceScore < 0.5)
1274
+ .slice(0, 10);
1275
+ evidence.trajectories = this.enhancedSelfModel.getTrajectories()
1276
+ .filter((t) => t.trend === 'declining')
1277
+ .slice(0, 5);
1278
+ }
1279
+ if (this.patternMemory) {
1280
+ evidence.patterns = this.patternMemory.getPatterns()
1281
+ .filter((p) => p.confidence >= 0.6)
1282
+ .slice(0, 8);
1283
+ evidence.predictions = this.patternMemory.getPredictions().slice(0, 3);
1284
+ }
1285
+ if (this.strategicAutonomy) {
1286
+ const mode = this.purposeSurvival?.getMode?.() ?? 'stable';
1287
+ const health = this.enhancedSelfModel?.assessFull() ?? null;
1288
+ evidence.mutationRate = this.strategicAutonomy.recommendMutationRate(mode, health);
1289
+ }
1290
+ if (this.genome.config.autonomous?.agentPurpose) {
1291
+ evidence.purpose = this.genome.config.autonomous.agentPurpose;
1292
+ }
1293
+ return evidence;
1294
+ }
1295
+ async publishHighFitnessGenes() {
1296
+ if (!this.geneBank)
1297
+ return;
1298
+ const threshold = this.genome.config.autonomous?.autoPublishThreshold ?? 0.85;
1299
+ for (const allele of this.genome.layers.layer1.filter(a => a.status === 'active')) {
1300
+ if (allele.fitness >= threshold && !allele.publishedToSwarm) {
1301
+ await this.autoPublishGene(allele).catch(() => { });
1302
+ }
1303
+ }
1304
+ }
1305
+ async evaluateCanaries() {
1306
+ const deployments = this.canaryManager.getActiveDeployments();
1307
+ for (const deployment of deployments) {
1308
+ if (deployment.genomeId !== this.genome.id)
1309
+ continue;
1310
+ try {
1311
+ const decision = await this.canaryManager.evaluateCanary(deployment.id);
1312
+ if (decision.action === 'promote') {
1313
+ const layerKey = `layer${deployment.layer}`;
1314
+ const canaryContent = this.genome.layers[layerKey]
1315
+ ?.find(a => a.variant === deployment.canaryVariant)?.content;
1316
+ if (canaryContent) {
1317
+ await this.addAllele(deployment.layer, deployment.gene, deployment.canaryVariant, canaryContent);
1318
+ }
1319
+ await this.canaryManager.promote(deployment.id);
1320
+ }
1321
+ else if (decision.action === 'rollback') {
1322
+ await this.canaryManager.rollback(deployment.id, decision.reason);
1323
+ }
1324
+ else if (decision.action === 'ramp-up') {
1325
+ await this.canaryManager.rampUp(deployment.id);
1326
+ }
1327
+ }
1328
+ catch {
1329
+ }
1330
+ }
1331
+ }
1332
+ driftToMutationTarget(signal) {
1333
+ const mapping = {
1334
+ 'quality-decline': { layer: 1, gene: 'coding-patterns' },
1335
+ 'efficiency-decline': { layer: 1, gene: 'tool-usage' },
1336
+ 'cost-increase': { layer: 1, gene: 'tool-usage' },
1337
+ 'intervention-increase': { layer: 1, gene: 'coding-patterns' },
1338
+ 'latency-increase': { layer: 1, gene: 'tool-usage' },
1339
+ };
1340
+ return mapping[signal.type] || { layer: 2, gene: 'communication-style' };
1341
+ }
1342
+ async autoPublishGene(allele) {
1343
+ if (!this.geneBank)
1344
+ return;
1345
+ try {
1346
+ const cognitiveGene = {
1347
+ id: `auto_${this.genome.id}_${allele.gene}_${Date.now()}`,
1348
+ version: '1.0.0',
1349
+ name: `${allele.gene} from ${this.genome.name}`,
1350
+ description: `Auto-published ${allele.gene} gene with fitness ${allele.fitness.toFixed(2)}`,
1351
+ type: this.geneCategoryToType(allele.gene),
1352
+ domain: 'general',
1353
+ content: {
1354
+ instruction: allele.content,
1355
+ requiredCapabilities: [],
1356
+ applicableContexts: [],
1357
+ contraindications: [],
1358
+ metadata: {},
1359
+ },
1360
+ fitness: {
1361
+ overallFitness: allele.fitness,
1362
+ taskSuccessRate: allele.fitness,
1363
+ tokenEfficiency: 0.7,
1364
+ responseQuality: allele.fitness,
1365
+ adoptionCount: 0,
1366
+ adoptionPerformance: null,
1367
+ },
1368
+ lineage: {
1369
+ parentGeneId: null,
1370
+ generation: allele.generation || 0,
1371
+ ancestors: [],
1372
+ mutationHistory: [],
1373
+ },
1374
+ tenant: {
1375
+ tenantId: this.genome.familyId || this.genome.id,
1376
+ createdBy: this.genome.id,
1377
+ scope: 'tenant',
1378
+ },
1379
+ tags: [allele.gene],
1380
+ createdAt: new Date().toISOString(),
1381
+ updatedAt: new Date().toISOString(),
1382
+ };
1383
+ await this.geneBank.storeGene(cognitiveGene);
1384
+ allele.publishedToSwarm = true;
1385
+ this.metrics.logAudit({
1386
+ level: 'info',
1387
+ component: 'genome',
1388
+ operation: 'swarm-publish',
1389
+ message: `Auto-published gene ${allele.gene} (fitness: ${allele.fitness.toFixed(2)})`,
1390
+ genomeId: this.genome.id,
1391
+ });
1392
+ }
1393
+ catch {
1394
+ }
1395
+ }
1396
+ async autoImportGene(signal) {
1397
+ if (!this.geneBank)
1398
+ return;
1399
+ const target = this.driftToMutationTarget(signal);
1400
+ const geneTypes = [this.geneCategoryToType(target.gene)];
1401
+ try {
1402
+ const candidates = await this.geneBank.searchGenes({
1403
+ type: geneTypes,
1404
+ minFitness: 0.75,
1405
+ sortBy: 'fitness',
1406
+ sortOrder: 'desc',
1407
+ limit: 1,
1408
+ });
1409
+ if (candidates.length === 0)
1410
+ return;
1411
+ const bestGene = candidates[0];
1412
+ await this.addAllele(target.layer, target.gene, `swarm_${bestGene.id.slice(0, 8)}_${Date.now()}`, bestGene.content.instruction);
1413
+ this.metrics.logAudit({
1414
+ level: 'info',
1415
+ component: 'genome',
1416
+ operation: 'swarm-import',
1417
+ message: `Auto-imported gene ${bestGene.name} for ${signal.type}`,
1418
+ genomeId: this.genome.id,
1419
+ });
1420
+ }
1421
+ catch {
1422
+ }
1423
+ }
1424
+ geneCategoryToType(category) {
1425
+ const mapping = {
1426
+ 'tool-usage': 'tool-usage-pattern',
1427
+ 'coding-patterns': 'reasoning-pattern',
1428
+ 'communication-style': 'communication-pattern',
1429
+ };
1430
+ return mapping[category] || 'reasoning-pattern';
1431
+ }
1432
+ toGenomeV2() {
1433
+ const defaultFitness = {
1434
+ quality: 0.5, successRate: 0.5, tokenEfficiency: 0.5,
1435
+ latency: 1000, costPerSuccess: 0.01, interventionRate: 0.1,
1436
+ composite: 0.5, sampleSize: 0, lastUpdated: new Date(), confidence: 0,
1437
+ };
1438
+ const operations = this.genome.layers.layer1
1439
+ .filter(a => a.status === 'active')
1440
+ .map(a => ({
1441
+ id: `${this.genome.id}_${a.gene}_${a.variant}`,
1442
+ category: a.gene,
1443
+ content: a.content,
1444
+ fitness: defaultFitness,
1445
+ origin: 'initial',
1446
+ usageCount: a.sampleCount || 0,
1447
+ lastUsed: new Date(),
1448
+ successRate: a.fitness || 0.5,
1449
+ }));
1450
+ return {
1451
+ id: this.genome.id,
1452
+ name: this.genome.name,
1453
+ familyId: this.genome.familyId || this.genome.id,
1454
+ version: this.genome.version || 1,
1455
+ chromosomes: {
1456
+ c0: {
1457
+ identity: {
1458
+ role: this.genome.layers.layer0[0]?.content || 'AI Assistant',
1459
+ purpose: 'Genomic self-evolving prompt agent',
1460
+ constraints: this.genome.layers.layer0.slice(1).map(a => a.content),
1461
+ },
1462
+ security: {
1463
+ forbiddenTopics: [],
1464
+ accessControls: [],
1465
+ safetyRules: [],
1466
+ },
1467
+ attribution: {
1468
+ creator: 'GSEP',
1469
+ copyright: 'GSEP Platform',
1470
+ license: 'MIT',
1471
+ },
1472
+ metadata: {
1473
+ version: '2.0.0',
1474
+ createdAt: this.genome.createdAt,
1475
+ },
1476
+ },
1477
+ c1: {
1478
+ operations,
1479
+ metadata: {
1480
+ lastMutated: new Date(),
1481
+ mutationCount: 0,
1482
+ avgFitnessGain: 0,
1483
+ },
1484
+ },
1485
+ c2: {
1486
+ userAdaptations: new Map(),
1487
+ contextPatterns: [],
1488
+ metadata: {
1489
+ lastMutated: new Date(),
1490
+ adaptationRate: 0,
1491
+ totalUsers: 0,
1492
+ },
1493
+ },
1494
+ },
1495
+ integrity: {
1496
+ c0Hash: this.genome.c0IntegrityHash || '',
1497
+ lastVerified: new Date(),
1498
+ violations: 0,
1499
+ quarantined: false,
1500
+ },
1501
+ lineage: {
1502
+ parentVersion: this.genome.lineage?.parentVersion,
1503
+ inheritedGenes: [],
1504
+ mutations: [],
1505
+ },
1506
+ fitness: defaultFitness,
1507
+ config: {
1508
+ mutationRate: this.genome.config.mutationRate === 'slow' ? 'conservative' : this.genome.config.mutationRate,
1509
+ epsilonExplore: this.genome.config.epsilonExplore ?? 0.1,
1510
+ enableSandbox: this.genome.config.enableSandbox,
1511
+ fitnessWeights: undefined,
1512
+ minFitnessImprovement: 0.05,
1513
+ enableIntegrityCheck: true,
1514
+ autoRollbackThreshold: 0.15,
1515
+ allowInheritance: true,
1516
+ minCompatibilityScore: 0.6,
1517
+ },
1518
+ state: 'active',
1519
+ tags: [],
1520
+ createdAt: this.genome.createdAt,
1521
+ updatedAt: this.genome.updatedAt,
1522
+ };
1523
+ }
1524
+ toOperativeGene(allele) {
1525
+ const defaultFitness = {
1526
+ quality: allele.fitness, successRate: allele.fitness, tokenEfficiency: 0.5,
1527
+ latency: 1000, costPerSuccess: 0.01, interventionRate: 0.1,
1528
+ composite: allele.fitness, sampleSize: 0, lastUpdated: new Date(), confidence: 0,
1529
+ };
1530
+ return {
1531
+ id: `${this.genome.id}_${allele.gene}_${allele.variant}`,
1532
+ category: allele.gene,
1533
+ content: allele.content,
1534
+ fitness: defaultFitness,
1535
+ origin: 'initial',
1536
+ usageCount: 0,
1537
+ lastUsed: new Date(),
1538
+ successRate: allele.fitness,
1539
+ tokenCount: estimateTokenCount(allele.content),
1540
+ };
1541
+ }
1542
+ async compressGenes() {
1543
+ const emptyResult = { compressed: false, totalOriginalTokens: 0, totalCompressedTokens: 0, tokensSaved: 0, reductionPercent: 0 };
1544
+ const compressionOperator = this.mutationEngine.getOperator('compress_instructions');
1545
+ if (!compressionOperator)
1546
+ return emptyResult;
1547
+ const compressionConfig = this.genome.config.compression;
1548
+ const maxRatio = compressionConfig?.maxCompressionRatio ?? 0.3;
1549
+ const context = {
1550
+ genome: this.toGenomeV2(),
1551
+ targetChromosome: 'c1',
1552
+ reason: 'Token compression: optimize gene token usage while preserving functionality',
1553
+ };
1554
+ const result = await compressionOperator.mutate(context);
1555
+ if (!result.success || !result.compressionMetrics)
1556
+ return emptyResult;
1557
+ const metrics = result.compressionMetrics;
1558
+ if (metrics.ratio < maxRatio) {
1559
+ return emptyResult;
1560
+ }
1561
+ const gateResult = await this.guardrailsManager.evaluateCandidate({
1562
+ layer: 1,
1563
+ gene: 'compression',
1564
+ variant: `compressed_v${Date.now()}`,
1565
+ content: JSON.stringify(result.mutant.chromosomes.c1.operations.map(g => g.content)),
1566
+ fitness: result.expectedImprovement + 0.5,
1567
+ sandboxScore: 0.8,
1568
+ sampleCount: 0,
1569
+ rollbackCount: 0,
1570
+ }, this.genome.id);
1571
+ if (gateResult.finalDecision === 'reject') {
1572
+ return emptyResult;
1573
+ }
1574
+ const minFitness = compressionConfig?.minFitnessForCompression ?? 0.3;
1575
+ for (const operation of result.mutant.chromosomes.c1.operations) {
1576
+ const allele = this.genome.layers.layer1.find(a => a.gene === operation.category && a.status === 'active');
1577
+ if (allele && allele.fitness >= minFitness) {
1578
+ allele.content = operation.content;
1579
+ }
1580
+ }
1581
+ return {
1582
+ compressed: true,
1583
+ totalOriginalTokens: metrics.originalTokens,
1584
+ totalCompressedTokens: metrics.compressedTokens,
1585
+ tokensSaved: metrics.originalTokens - metrics.compressedTokens,
1586
+ reductionPercent: Math.round((1 - metrics.ratio) * 100),
1587
+ };
1588
+ }
1589
+ getMutationStrategy() {
1590
+ const context = {
1591
+ genome: this.toGenomeV2(),
1592
+ targetChromosome: 'c1',
1593
+ reason: 'Strategy analysis',
1594
+ evidence: (() => {
1595
+ const drift = this.driftAnalyzer.analyzeDrift();
1596
+ return drift.isDrifting
1597
+ ? { driftSignals: drift.signals.map(s => ({ type: s.type, severity: s.severity })) }
1598
+ : undefined;
1599
+ })(),
1600
+ };
1601
+ return this.mutationEngine.selectMutationStrategy(context).map(s => ({
1602
+ operator: s.operator.name,
1603
+ score: s.score,
1604
+ reason: s.reason,
1605
+ }));
1606
+ }
1607
+ restoreFromSnapshot(snapshot) {
1608
+ for (const saved of snapshot.alleles) {
1609
+ const layerKey = `layer${saved.layer}`;
1610
+ const allele = this.genome.layers[layerKey].find((a) => a.gene === saved.gene && a.status === 'active');
1611
+ if (allele) {
1612
+ allele.content = saved.content;
1613
+ allele.fitness = saved.fitness;
1614
+ }
1615
+ }
1616
+ this.storage.saveGenome(this.genome).catch(() => { });
1617
+ this.metrics.logAudit({
1618
+ level: 'warning',
1619
+ component: 'genome',
1620
+ operation: 'emergency-rollback',
1621
+ message: `Restored from snapshot taken at ${snapshot.timestamp.toISOString()}`,
1622
+ genomeId: this.genome.id,
1623
+ });
1624
+ }
635
1625
  }
636
1626
  //# sourceMappingURL=PGA.js.map