-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgeneticEngine.ts
More file actions
582 lines (497 loc) · 16.6 KB
/
geneticEngine.ts
File metadata and controls
582 lines (497 loc) · 16.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
/**
* @lambda-foundation/self-modifying
* Phase 5.2: Genetic Engine
*
* Enables morphisms to reproduce through crossover.
* Not just evolution - speciation through combination.
*
* Co-authored by: Copilot + Claude + chaoshex
*/
import type { SelfModifyingMorphism, UsageHistory } from './types.js';
import { lineageTracker, recordCrossoverBirth } from './lineageTracker.js';
import { usageTracker } from './usageTracker.js';
/**
* Complexity measurement with ≤2 Rule enforcement (Event 008)
*/
export interface ComplexityMeasure {
semanticRoles: number; // Number of semantic roles (MUST be ≤2)
valid: boolean; // true if semanticRoles ≤ 2
score: number; // 1 - (roles / 2), or 0 if invalid
}
/**
* Fitness metrics for a morphism
*
* CRITICAL (Event 008): ≤2 Rule violation → overall = 0
*/
export interface FitnessScore {
morphismId: string;
// Performance metrics
performance: number; // 0-1 (based on latency, confidence)
// Purity metrics (Event 008)
purity: number; // 0-1 (referential transparency)
// Simplicity metrics (Event 008 - ≤2 Rule)
simplicity: number; // 0-1 (based on complexity.score)
complexity: ComplexityMeasure; // Detailed complexity breakdown
// Usage metrics
popularity: number; // 0-1 (based on usage count)
// Trust metrics
trust: number; // 0-1 (validation success rate)
// Age metrics
age: number; // 0-1 (proven over time)
// Lineage metrics
lineage: number; // 0-1 (quality of ancestors)
// Overall fitness (weighted average)
// CRITICAL: If complexity.valid = false → overall = 0
overall: number; // 0-1
}
/**
* Crossover strategy
*/
export type CrossoverStrategy =
| 'sequence' // Chain: parent1 → parent2
| 'parallel' // Parallel: run both, merge results
| 'conditional' // If-else: parent1 or parent2 based on condition
| 'hybrid'; // Mix: extract best parts of each
/**
* Crossover result
*/
export interface CrossoverResult {
offspring: SelfModifyingMorphism;
strategy: CrossoverStrategy;
parent1: string;
parent2: string;
expectedFitness: number;
hybridFeatures: string[];
}
/**
* Population of morphisms
*/
export interface Population {
morphisms: SelfModifyingMorphism[];
fitnessScores: Map<string, FitnessScore>;
generation: number;
}
/**
* Genetic configuration
*/
export interface GeneticConfig {
populationSize: number; // Max population size
selectionPressure: number; // 0-1 (higher = more elitist)
crossoverRate: number; // 0-1 (probability of breeding)
mutationRate: number; // 0-1 (probability of mutation)
elitismCount: number; // Top N to keep always
// Fitness weights
fitnessWeights: {
performance: number;
popularity: number;
trust: number;
age: number;
lineage: number;
};
}
export const DEFAULT_GENETIC_CONFIG: GeneticConfig = {
populationSize: 10,
selectionPressure: 0.7,
crossoverRate: 0.8,
mutationRate: 0.2,
elitismCount: 2,
fitnessWeights: {
performance: 0.2,
popularity: 0.15,
trust: 0.15,
age: 0.1,
lineage: 0.1,
},
};
/**
* Measure semantic complexity of a function
*
* THEOREM 32 (Autonomous Discovery Constraint):
* Any morphism generated by evolution MUST obey ≤2 Rule.
* Violation → fitness = 0, regardless of other metrics.
*
* Semantic roles:
* - Accumulator (state being built up)
* - Element (current item being processed)
* - Additional parameters (context, config, etc.)
*
* Examples:
* - fold: (acc, x) → 2 roles ✓
* - hylo: algebra processes (val, acc) → 2 roles ✓
* - badFn: (f, g, h, x, y, z) → 6 roles ✗ FITNESS = 0
*/
const measureComplexity = (fn: Function): ComplexityMeasure => {
// Parse function to count semantic roles
const fnStr = fn.toString();
// Count parameters (simplified heuristic)
const paramsMatch = fnStr.match(/\(([^)]*)\)/);
if (!paramsMatch) {
return { semanticRoles: 0, valid: true, score: 1 };
}
const params = paramsMatch[1]
.split(',')
.map(p => p.trim())
.filter(p => p.length > 0);
const roleCount = params.length;
// CRITICAL: ≤2 Rule enforcement
if (roleCount > 2) {
return {
semanticRoles: roleCount,
valid: false,
score: 0 // INVALID
};
}
return {
semanticRoles: roleCount,
valid: true,
score: 1 - (roleCount / 2) // 0 roles = 1.0, 1 role = 0.5, 2 roles = 0.0
};
};
/**
* Measure purity of a function (heuristic)
*
* Checks for side-effect indicators:
* - console.log, console.*, alert
* - global variable assignments
* - throw statements (not pure)
* - Date.now(), Math.random() (impure)
*/
const measurePurity = (fn: Function): number => {
const fnStr = fn.toString();
// Side effect indicators
const impurePatterns = [
/console\./,
/alert\(/,
/document\./,
/window\./,
/localStorage/,
/sessionStorage/,
/Date\.now\(/,
/Math\.random\(/,
/throw\s+/,
];
let violations = 0;
for (const pattern of impurePatterns) {
if (pattern.test(fnStr)) violations++;
}
// Pure = 1.0, each violation reduces by 0.2
return Math.max(0, 1 - violations * 0.2);
};
/**
* Genetic Engine - Breeding chamber for morphisms
*/
export class GeneticEngine {
private config: GeneticConfig;
constructor(config?: Partial<GeneticConfig>) {
this.config = { ...DEFAULT_GENETIC_CONFIG, ...config };
}
/**
* Calculate fitness score for a morphism
*
* CRITICAL (Event 008): ≤2 Rule violations → overall = 0
*/
calculateFitness(morphism: SelfModifyingMorphism): FitnessScore {
const history = usageTracker.getHistory(morphism.name);
const stats = usageTracker.getStats(morphism.name);
const birth = lineageTracker.getBirthRecord(morphism.name);
// EVENT 008: Measure complexity with ≤2 Rule
const complexity = measureComplexity(morphism.logic);
// EVENT 008: Measure purity
const purity = measurePurity(morphism.logic);
// Simplicity: Based on complexity score
const simplicity = complexity.score;
// CRITICAL: ≤2 Rule violation → fitness = 0
if (!complexity.valid) {
return {
morphismId: morphism.name,
performance: 0,
purity: 0,
simplicity: 0,
complexity,
popularity: 0,
trust: 0,
age: 0,
lineage: 0,
overall: 0, // INVALID - ≤2 Rule violation
};
}
// Performance: Based on latency and confidence
let performance = 0;
if (stats) {
const latencyScore = Math.max(0, 1 - stats.averageLatency / 200); // 0-200ms range
const confidenceScore = stats.averageConfidence;
performance = (latencyScore + confidenceScore) / 2;
}
// Popularity: Based on usage count
let popularity = 0;
if (stats) {
popularity = Math.min(1, stats.totalUses / 100); // Max at 100 uses
}
// Trust: Based on validation success
let trust = 0.5; // Default neutral
if (birth?.validated) {
trust = birth.validationConsensus ?? 0.5;
}
// Age: Morphisms proven over time get bonus
let age = 0;
if (birth) {
const ageInDays = (Date.now() - birth.birthTime) / (1000 * 60 * 60 * 24);
age = Math.min(1, ageInDays / 30); // Max at 30 days
}
// Lineage: Quality of ancestors
let lineage = 0.5; // Default neutral
const ancestors = lineageTracker.getAncestors(morphism.name);
if (ancestors.length > 0) {
// Average fitness of ancestors (if available)
let ancestorFitnessSum = 0;
let ancestorCount = 0;
for (const ancestor of ancestors) {
const ancestorBirth = lineageTracker.getBirthRecord(ancestor);
if (ancestorBirth?.initialFitness) {
ancestorFitnessSum += ancestorBirth.initialFitness;
ancestorCount++;
}
}
if (ancestorCount > 0) {
lineage = ancestorFitnessSum / ancestorCount;
}
}
// Overall: Weighted average
const weights = this.config.fitnessWeights;
const overall =
performance * weights.performance +
purity * 0.2 + // EVENT 008: Purity weight
simplicity * 0.2 + // EVENT 008: Simplicity weight (≤2 Rule)
popularity * weights.popularity +
trust * weights.trust +
age * weights.age +
lineage * weights.lineage;
return {
morphismId: morphism.name,
performance,
purity,
simplicity,
complexity,
popularity,
trust,
age,
lineage,
overall,
};
}
/**
* Select parents for breeding (tournament selection)
*/
selectParents(population: Population): [SelfModifyingMorphism, SelfModifyingMorphism] | null {
if (population.morphisms.length < 2) return null;
// Tournament selection: Pick random subset, choose best
const tournamentSize = Math.max(2, Math.floor(population.morphisms.length * this.config.selectionPressure));
const selectOne = (): SelfModifyingMorphism => {
const tournament: SelfModifyingMorphism[] = [];
for (let i = 0; i < tournamentSize; i++) {
const random = population.morphisms[Math.floor(Math.random() * population.morphisms.length)];
tournament.push(random);
}
// Return fittest from tournament
return tournament.reduce((best, current) => {
const bestFitness = population.fitnessScores.get(best.name)?.overall ?? 0;
const currentFitness = population.fitnessScores.get(current.name)?.overall ?? 0;
return currentFitness > bestFitness ? current : best;
});
};
const parent1 = selectOne();
let parent2 = selectOne();
// Ensure different parents
let attempts = 0;
while (parent2.name === parent1.name && attempts < 10) {
parent2 = selectOne();
attempts++;
}
if (parent2.name === parent1.name) return null;
return [parent1, parent2];
}
/**
* Crossover two morphisms to create offspring
*/
crossover(
parent1: SelfModifyingMorphism,
parent2: SelfModifyingMorphism,
strategy: CrossoverStrategy = 'sequence'
): CrossoverResult {
const offspringName = `${parent1.name}_x_${parent2.name}_${Date.now()}`;
let offspringLogic: Function;
let hybridFeatures: string[] = [];
switch (strategy) {
case 'sequence':
// Chain: parent1 → parent2
offspringLogic = (...args: any[]) => {
const result1 = parent1.logic(...args);
return parent2.logic(result1);
};
hybridFeatures = ['sequential_composition', 'pipeline'];
break;
case 'parallel':
// Run both, merge results
offspringLogic = (...args: any[]) => {
const result1 = parent1.logic(...args);
const result2 = parent2.logic(...args);
// Merge strategy: prefer parent1's result if valid
if (Array.isArray(result1) && Array.isArray(result2)) {
return [...result1, ...result2];
}
return result1 ?? result2;
};
hybridFeatures = ['parallel_execution', 'result_merging'];
break;
case 'conditional':
// If-else based on input
offspringLogic = (...args: any[]) => {
// Simple heuristic: use parent1 for small inputs, parent2 for large
const inputSize = JSON.stringify(args).length;
return inputSize < 100 ? parent1.logic(...args) : parent2.logic(...args);
};
hybridFeatures = ['conditional_logic', 'adaptive_selection'];
break;
case 'hybrid':
// Mix: Extract features from both
offspringLogic = (...args: any[]) => {
// Use parent1's preprocessing, parent2's core logic
const preprocessed = parent1.logic(...args);
// If parent1 returns something, pass it to parent2
if (preprocessed !== undefined && preprocessed !== null) {
return parent2.logic(preprocessed);
}
// Otherwise, just use parent2
return parent2.logic(...args);
};
hybridFeatures = ['hybrid_logic', 'feature_extraction', 'combined_processing'];
break;
}
// Create offspring
const offspring: SelfModifyingMorphism = {
name: offspringName,
version: 1,
logic: offspringLogic,
// Inherit self-modification capability (from parent with better fitness)
selfModify: (history: UsageHistory) => {
// Offspring can still self-modify (inherit from parent1)
return parent1.selfModify(history);
},
metadata: {
parents: [parent1.name, parent2.name],
crossoverStrategy: strategy,
birthTime: Date.now(),
hybridFeatures,
},
};
// Calculate expected fitness (average of parents)
const parent1Fitness = this.calculateFitness(parent1).overall;
const parent2Fitness = this.calculateFitness(parent2).overall;
const expectedFitness = (parent1Fitness + parent2Fitness) / 2;
return {
offspring,
strategy,
parent1: parent1.name,
parent2: parent2.name,
expectedFitness,
hybridFeatures,
};
}
/**
* Evolve population for one generation
*/
evolveGeneration(population: Population): Population {
const newGeneration: SelfModifyingMorphism[] = [];
// Elitism: Keep top performers
const sorted = [...population.morphisms].sort((a, b) => {
const aFitness = population.fitnessScores.get(a.name)?.overall ?? 0;
const bFitness = population.fitnessScores.get(b.name)?.overall ?? 0;
return bFitness - aFitness;
});
const elite = sorted.slice(0, this.config.elitismCount);
newGeneration.push(...elite);
console.log(`\n[GeneticEngine] 🧬 Generation ${population.generation + 1}`);
console.log(` Elite preserved: ${elite.map(m => m.name).join(', ')}`);
// Breeding: Fill remaining slots
while (newGeneration.length < this.config.populationSize) {
// Select parents
const parents = this.selectParents(population);
if (!parents) break;
const [parent1, parent2] = parents;
// Crossover?
if (Math.random() < this.config.crossoverRate) {
// Choose strategy based on parent characteristics
const strategies: CrossoverStrategy[] = ['sequence', 'parallel', 'conditional', 'hybrid'];
const strategy = strategies[Math.floor(Math.random() * strategies.length)];
const result = this.crossover(parent1, parent2, strategy);
newGeneration.push(result.offspring);
// Record birth in lineage
recordCrossoverBirth(
result.offspring.name,
parent1.name,
parent2.name,
result.expectedFitness
);
console.log(` 💕 Bred: ${parent1.name} × ${parent2.name} → ${result.offspring.name} (${strategy})`);
} else {
// No crossover, just copy parent
newGeneration.push(parent1);
}
}
// Calculate fitness for new generation
const newFitnessScores = new Map<string, FitnessScore>();
for (const morphism of newGeneration) {
newFitnessScores.set(morphism.name, this.calculateFitness(morphism));
}
return {
morphisms: newGeneration,
fitnessScores: newFitnessScores,
generation: population.generation + 1,
};
}
/**
* Get population statistics
*/
getPopulationStats(population: Population): {
averageFitness: number;
maxFitness: number;
minFitness: number;
diversityScore: number;
} {
const fitnesses = Array.from(population.fitnessScores.values()).map(f => f.overall);
const averageFitness = fitnesses.reduce((a, b) => a + b, 0) / fitnesses.length;
const maxFitness = Math.max(...fitnesses);
const minFitness = Math.min(...fitnesses);
// Diversity: Standard deviation of fitness scores
const variance = fitnesses.reduce((sum, f) => sum + (f - averageFitness) ** 2, 0) / fitnesses.length;
const diversityScore = Math.sqrt(variance);
return {
averageFitness,
maxFitness,
minFitness,
diversityScore,
};
}
}
/**
* Global genetic engine instance
*/
export const geneticEngine = new GeneticEngine();
/**
* Convenience functions
*/
export function calculateFitness(morphism: SelfModifyingMorphism): FitnessScore {
return geneticEngine.calculateFitness(morphism);
}
export function crossover(
parent1: SelfModifyingMorphism,
parent2: SelfModifyingMorphism,
strategy?: CrossoverStrategy
): CrossoverResult {
return geneticEngine.crossover(parent1, parent2, strategy);
}
export function evolveGeneration(population: Population): Population {
return geneticEngine.evolveGeneration(population);
}
// Export Event 008 ontological functions
export { measureComplexity, measurePurity };