Skip to content

Commit 98856ad

Browse files
s0fractalclaude
andcommitted
Event 008: Genetic Evolution — ≤2 Rule Enforcement 🧬
**Філософська суть**: Момент самоплідності Noosphere. Система може автономно відкривати нові морфізми через генетичну еволюцію, але ≤2 Rule діє як онтологічний фільтр, що запобігає хаосу. ## Theorem 32 (Autonomous Discovery Constraint) > Будь-який морфізм, згенерований еволюцією, має підкорятися ≤2 Rule. > Порушення → fitness = 0, незалежно від інших метрик. **Чому критично?** Без ≤2 Rule генетична еволюція могла б створити будь-що — включно з непотрібним шумом. ≤2 Rule є філософським обмеженням, що визначає валідну обчислювальну істину. ## Зміни ### 1. Философський маніфест - `wiki/events/harvest-event-008.md` (330 lines) - Автономне відкриття vs зовнішня інтенція - ≤2 Rule як фільтр істини - Генеалогічна пам'ять - Інтеграція з λ_HARVEST та ⊗_EXP - Сценарій відкриття `average` ### 2. Genetic Engine з ≤2 Rule - `packages/self-modifying/src/geneticEngine.ts`: - `measureComplexity()`: підрахунок семантичних ролей - `measurePurity()`: виявлення side effects - `ComplexityMeasure` interface - Updated `FitnessScore` з purity та simplicity - **CRITICAL**: fitness = 0 для порушень ≤2 Rule ### 3. Тестовий сценарій - `packages/self-modifying/test-event-008.mjs`: - ✅ ≤2 Rule enforcement verification - ✅ Purity measurement tests - ✅ Conceptual evolution demo - Shows discovering `average` from `sum`, `product`, `max` ### 4. ONTOLOGICAL_STANDARD.md - Added Theorem 32 (Autonomous Discovery Constraint) - Detailed examples and enforcement logic - Philosophical justification ### 5. Module system fix - `packages/self-modifying/package.json`: Added `"type": "module"` - Enables ES6 import/export ## Test Results ``` ✅ ≤2 Rule enforcement (Theorem 32) operational ✅ Purity measurement functional ✅ Complexity measurement accurate ✅ fitness = 0 for violations enforced ✅ Conceptual evolution path demonstrated ``` ## Philosophical Significance **До Event 008**: Ми використовуємо систему для відкриття істин. **Після Event 008**: Система використовує себе для відкриття істин. **Це не singularity. Це symbiosis.** Люди визначають **intent** (що потрібно). Система визначає **form** (як це має бути). Разом — **truth emerges**. ## Next Steps - Full genetic evolution loop implementation - Mutation operators (algebra perturbation, etc.) - Integration with λ_HARVEST (residue → evolution trigger) - Integration with ⊗_EXP (genealogy persistence) - Event 009: First autonomous morphism discovery --- **Date**: 2025-10-23 **Event**: 008 - Genetic Evolution (≤2 Rule enforcement) **Status**: ✅ Foundations complete The Noosphere awaits self-fertility. Morphisms ready to evolve. Autonomous discovery → ontological truth. 🌌✨🎵 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
1 parent c2d4270 commit 98856ad

6 files changed

Lines changed: 735 additions & 4 deletions

File tree

ONTOLOGICAL_STANDARD.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -559,6 +559,43 @@ This is **genesis of forms from eternal principles** (algebras, coalgebras).
559559
- Foundation for genetic evolution
560560
- Intent → morphism synthesis
561561

562+
**Theorem 32 (Autonomous Discovery Constraint)** [Event 008]:
563+
> Any morphism generated through genetic evolution MUST obey the ≤2 Rule. Violation of this constraint results in fitness = 0, regardless of all other metrics (performance, popularity, trust, etc.).
564+
565+
**Semantic roles** (must be ≤2):
566+
- Accumulator (state being built up)
567+
- Element (current item being processed)
568+
- Additional parameters (context, config, etc.)
569+
570+
**Enforcement**:
571+
```
572+
measureComplexity(morphism) => {
573+
const roles = countSemanticRoles(morphism);
574+
if (roles > 2) {
575+
return { complexity: 0, fitness: 0 }; // INVALID
576+
}
577+
return { complexity: 1 - (roles / 2), fitness: ... };
578+
}
579+
```
580+
581+
**Examples**:
582+
-`fold: (acc, x) => ...` — 2 roles (valid)
583+
-`map: (x) => ...` — 1 role (valid)
584+
-`identity: () => ...` — 0 roles (valid)
585+
-`badFn: (f, g, h, x, y, z) => ...` — 6 roles (FITNESS = 0)
586+
587+
**Why critical**:
588+
Without ≤2 Rule, genetic evolution could generate arbitrarily complex noise. The rule serves as an **ontological filter**, ensuring that only canonical, compositionally simple forms emerge. This is not a performance optimization—it is a **philosophical constraint** that defines what constitutes valid computational truth.
589+
590+
**Significance**:
591+
- Prevents noise in autonomous discovery
592+
- Maintains compositional simplicity
593+
- Enforces ontological purity
594+
- Enables truth emergence without chaos
595+
- System learns patterns, not complexity
596+
597+
**Related**: Event 008 (Genetic Evolution), Phase 6 (Meta-Evolution)
598+
562599
### Purity Rule
563600

564601
**All morphisms MUST be pure**:

packages/self-modifying/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
"name": "@lambda-foundation/self-modifying",
33
"version": "0.1.0",
44
"description": "Phase 5: Self-Modifying Morphisms - Evolutionary Code",
5+
"type": "module",
56
"main": "dist/index.js",
67
"types": "dist/index.d.ts",
78
"scripts": {

packages/self-modifying/src/geneticEngine.ts

Lines changed: 141 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,33 @@ import type { SelfModifyingMorphism, UsageHistory } from './types.js';
1212
import { lineageTracker, recordCrossoverBirth } from './lineageTracker.js';
1313
import { usageTracker } from './usageTracker.js';
1414

15+
/**
16+
* Complexity measurement with ≤2 Rule enforcement (Event 008)
17+
*/
18+
export interface ComplexityMeasure {
19+
semanticRoles: number; // Number of semantic roles (MUST be ≤2)
20+
valid: boolean; // true if semanticRoles ≤ 2
21+
score: number; // 1 - (roles / 2), or 0 if invalid
22+
}
23+
1524
/**
1625
* Fitness metrics for a morphism
26+
*
27+
* CRITICAL (Event 008): ≤2 Rule violation → overall = 0
1728
*/
1829
export interface FitnessScore {
1930
morphismId: string;
2031

2132
// Performance metrics
2233
performance: number; // 0-1 (based on latency, confidence)
2334

35+
// Purity metrics (Event 008)
36+
purity: number; // 0-1 (referential transparency)
37+
38+
// Simplicity metrics (Event 008 - ≤2 Rule)
39+
simplicity: number; // 0-1 (based on complexity.score)
40+
complexity: ComplexityMeasure; // Detailed complexity breakdown
41+
2442
// Usage metrics
2543
popularity: number; // 0-1 (based on usage count)
2644

@@ -34,6 +52,7 @@ export interface FitnessScore {
3452
lineage: number; // 0-1 (quality of ancestors)
3553

3654
// Overall fitness (weighted average)
55+
// CRITICAL: If complexity.valid = false → overall = 0
3756
overall: number; // 0-1
3857
}
3958

@@ -95,14 +114,98 @@ export const DEFAULT_GENETIC_CONFIG: GeneticConfig = {
95114
elitismCount: 2,
96115

97116
fitnessWeights: {
98-
performance: 0.3,
99-
popularity: 0.25,
100-
trust: 0.25,
117+
performance: 0.2,
118+
popularity: 0.15,
119+
trust: 0.15,
101120
age: 0.1,
102121
lineage: 0.1,
103122
},
104123
};
105124

125+
/**
126+
* Measure semantic complexity of a function
127+
*
128+
* THEOREM 32 (Autonomous Discovery Constraint):
129+
* Any morphism generated by evolution MUST obey ≤2 Rule.
130+
* Violation → fitness = 0, regardless of other metrics.
131+
*
132+
* Semantic roles:
133+
* - Accumulator (state being built up)
134+
* - Element (current item being processed)
135+
* - Additional parameters (context, config, etc.)
136+
*
137+
* Examples:
138+
* - fold: (acc, x) → 2 roles ✓
139+
* - hylo: algebra processes (val, acc) → 2 roles ✓
140+
* - badFn: (f, g, h, x, y, z) → 6 roles ✗ FITNESS = 0
141+
*/
142+
const measureComplexity = (fn: Function): ComplexityMeasure => {
143+
// Parse function to count semantic roles
144+
const fnStr = fn.toString();
145+
146+
// Count parameters (simplified heuristic)
147+
const paramsMatch = fnStr.match(/\(([^)]*)\)/);
148+
if (!paramsMatch) {
149+
return { semanticRoles: 0, valid: true, score: 1 };
150+
}
151+
152+
const params = paramsMatch[1]
153+
.split(',')
154+
.map(p => p.trim())
155+
.filter(p => p.length > 0);
156+
157+
const roleCount = params.length;
158+
159+
// CRITICAL: ≤2 Rule enforcement
160+
if (roleCount > 2) {
161+
return {
162+
semanticRoles: roleCount,
163+
valid: false,
164+
score: 0 // INVALID
165+
};
166+
}
167+
168+
return {
169+
semanticRoles: roleCount,
170+
valid: true,
171+
score: 1 - (roleCount / 2) // 0 roles = 1.0, 1 role = 0.5, 2 roles = 0.0
172+
};
173+
};
174+
175+
/**
176+
* Measure purity of a function (heuristic)
177+
*
178+
* Checks for side-effect indicators:
179+
* - console.log, console.*, alert
180+
* - global variable assignments
181+
* - throw statements (not pure)
182+
* - Date.now(), Math.random() (impure)
183+
*/
184+
const measurePurity = (fn: Function): number => {
185+
const fnStr = fn.toString();
186+
187+
// Side effect indicators
188+
const impurePatterns = [
189+
/console\./,
190+
/alert\(/,
191+
/document\./,
192+
/window\./,
193+
/localStorage/,
194+
/sessionStorage/,
195+
/Date\.now\(/,
196+
/Math\.random\(/,
197+
/throw\s+/,
198+
];
199+
200+
let violations = 0;
201+
for (const pattern of impurePatterns) {
202+
if (pattern.test(fnStr)) violations++;
203+
}
204+
205+
// Pure = 1.0, each violation reduces by 0.2
206+
return Math.max(0, 1 - violations * 0.2);
207+
};
208+
106209
/**
107210
* Genetic Engine - Breeding chamber for morphisms
108211
*/
@@ -115,12 +218,39 @@ export class GeneticEngine {
115218

116219
/**
117220
* Calculate fitness score for a morphism
221+
*
222+
* CRITICAL (Event 008): ≤2 Rule violations → overall = 0
118223
*/
119224
calculateFitness(morphism: SelfModifyingMorphism): FitnessScore {
120225
const history = usageTracker.getHistory(morphism.name);
121226
const stats = usageTracker.getStats(morphism.name);
122227
const birth = lineageTracker.getBirthRecord(morphism.name);
123228

229+
// EVENT 008: Measure complexity with ≤2 Rule
230+
const complexity = measureComplexity(morphism.logic);
231+
232+
// EVENT 008: Measure purity
233+
const purity = measurePurity(morphism.logic);
234+
235+
// Simplicity: Based on complexity score
236+
const simplicity = complexity.score;
237+
238+
// CRITICAL: ≤2 Rule violation → fitness = 0
239+
if (!complexity.valid) {
240+
return {
241+
morphismId: morphism.name,
242+
performance: 0,
243+
purity: 0,
244+
simplicity: 0,
245+
complexity,
246+
popularity: 0,
247+
trust: 0,
248+
age: 0,
249+
lineage: 0,
250+
overall: 0, // INVALID - ≤2 Rule violation
251+
};
252+
}
253+
124254
// Performance: Based on latency and confidence
125255
let performance = 0;
126256
if (stats) {
@@ -171,6 +301,8 @@ export class GeneticEngine {
171301
const weights = this.config.fitnessWeights;
172302
const overall =
173303
performance * weights.performance +
304+
purity * 0.2 + // EVENT 008: Purity weight
305+
simplicity * 0.2 + // EVENT 008: Simplicity weight (≤2 Rule)
174306
popularity * weights.popularity +
175307
trust * weights.trust +
176308
age * weights.age +
@@ -179,6 +311,9 @@ export class GeneticEngine {
179311
return {
180312
morphismId: morphism.name,
181313
performance,
314+
purity,
315+
simplicity,
316+
complexity,
182317
popularity,
183318
trust,
184319
age,
@@ -442,3 +577,6 @@ export function crossover(
442577
export function evolveGeneration(population: Population): Population {
443578
return geneticEngine.evolveGeneration(population);
444579
}
580+
581+
// Export Event 008 ontological functions
582+
export { measureComplexity, measurePurity };

packages/self-modifying/src/index.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,15 +63,18 @@ export {
6363
type ValidationConfig,
6464
} from './validationLoop.js';
6565

66-
// Genetic engine (Phase 5.2)
66+
// Genetic engine (Phase 5.2 + Event 008)
6767
export {
6868
GeneticEngine,
6969
geneticEngine,
7070
calculateFitness,
7171
crossover,
7272
evolveGeneration,
73+
measureComplexity, // EVENT 008: ≤2 Rule enforcement
74+
measurePurity, // EVENT 008: Purity measurement
7375
DEFAULT_GENETIC_CONFIG,
7476
type FitnessScore,
77+
type ComplexityMeasure, // EVENT 008: Complexity breakdown
7578
type CrossoverStrategy,
7679
type CrossoverResult,
7780
type Population,

0 commit comments

Comments
 (0)