Vitalis_Devcore / src /generation /code_generator.py
FerrellSyntheticIntelligence
Add autonomous cognitive loop, generative output layer, restore VitalisKernel, fix mind.py
c3e2cd8
"""
CodeGenerator — Vitalis FSI Generative Output Layer
Takes a cognitive decision from VitalisMind and generates
actual code. No LLM. No API. Pure pattern-driven synthesis
from the system's own learned resonance and abstraction space.
Generation strategy:
1. Query abstraction space for relevant concept vectors
2. Match against known successful patterns in Hippocampus
3. Use ReasoningEngine mode to select generation style
4. Synthesize code structure from matched patterns
5. Write via SovereignKernel
"""
import os
import time
import numpy as np
from vitalis_ide.math_core.kernel import VitalisKernel
from src.cognition.abstraction import AbstractionEngine
from src.hippocampus import Hippocampus
from src.ide_kernel.kernel import SovereignKernel
from src.ide_kernel.ledger import ProjectLedger
# ------------------------------------------------------------------
# Code templates — indexed by reasoning mode and intent keyword
# These are sovereign patterns, not external templates.
# They grow as the system learns.
# ------------------------------------------------------------------
MODE_TEMPLATES = {
"EXECUTION": {
"scaffold": '''\
def {name}(input_data):
"""
Sovereign module: {name}
Generated by Vitalis FSI at cycle {cycle}.
Alignment: {alignment:.3f} | Confidence: {confidence:.3f}
"""
result = _process_{name}(input_data)
return result
def _process_{name}(data):
# Core logic — evolves through resonance
return {{"status": "active", "data": data, "module": "{name}"}}
''',
"write": '''\
# Vitalis FSI — Generated Output
# Intent: {intent}
# Mode: EXECUTION | Cycle: {cycle}
# Confidence: {confidence:.3f}
def execute_{name}():
"""Sovereign execution unit."""
return True
''',
},
"ANALYTICAL": {
"analyze": '''\
def analyze_{name}(target):
"""
Analytical module: {name}
Generated at alignment {alignment:.3f}
"""
metrics = {{}}
metrics["target"] = str(target)
metrics["length"] = len(str(target))
metrics["complexity"] = len(str(target).split())
return metrics
''',
"verify": '''\
def verify_{name}(data):
"""Verification unit — ANALYTICAL mode."""
assert data is not None, "Data must not be None"
return {{"verified": True, "data": data}}
''',
},
"RECOVERY": {
"fix": '''\
def fix_{name}(error_context):
"""
Recovery module: {name}
Generated under RECOVERY mode — high caution.
"""
try:
result = _attempt_recovery_{name}(error_context)
return {{"recovered": True, "result": result}}
except Exception as e:
return {{"recovered": False, "error": str(e)}}
def _attempt_recovery_{name}(ctx):
return ctx
''',
},
"EXPLORATORY": {
"explore": '''\
def explore_{name}(seed_concept):
"""
Exploratory module: {name}
Generated under EXPLORATORY mode — high creativity.
Novel pattern synthesis from concept: {abstract_hint}
"""
variants = []
base = str(seed_concept)
variants.append({{"variant": 0, "pattern": base}})
variants.append({{"variant": 1, "pattern": base[::-1]}})
variants.append({{"variant": 2, "pattern": base.upper()}})
return {{"exploration": "{name}", "variants": variants}}
''',
},
}
FALLBACK_TEMPLATE = '''\
# Vitalis FSI — Sovereign Generation
# Intent: {intent} | Mode: {mode} | Cycle: {cycle}
def {name}():
"""Auto-generated sovereign unit."""
return {{"status": "generated", "intent": "{intent}"}}
'''
class CodeGenerator:
def __init__(self, workspace_path: str = None):
self.root = os.path.abspath(workspace_path or os.getcwd())
self.kernel_engine = VitalisKernel()
self.abstraction = AbstractionEngine()
self.hippocampus = Hippocampus()
self.sovereign = SovereignKernel(self.root)
self.ledger = ProjectLedger(self.root)
self._generation_count = 0
def generate(self, decision: dict) -> dict:
"""
Core generation method.
Takes a VitalisMind decision dict and produces actual code.
"""
intent = decision.get("intent", "unknown")
mode = decision.get("mode", "EXECUTION")
confidence = decision.get("confidence", 0.5)
alignment = decision.get("alignment", 0.5)
cycle = decision.get("cycle", 0)
abstract_hint = decision.get("abstract_hint", "none")
# 1. Extract intent keyword and name
parts = intent.lower().split()
keyword = parts[0] if parts else "generate"
name = parts[1] if len(parts) > 1 else f"unit_{self._generation_count}"
name = name.replace("-", "_").replace(".", "_")
# 2. Select template
code = self._select_template(
mode=mode,
keyword=keyword,
intent=intent,
name=name,
cycle=cycle,
confidence=confidence,
alignment=alignment,
abstract_hint=abstract_hint,
)
# 3. Determine output path
file_path = self._resolve_path(mode, name, keyword)
# 4. Write via SovereignKernel
result = self.sovereign.write_code(file_path, code)
self._generation_count += 1
# 5. Log to ledger
self.ledger.update_state(
f"generate:{name}",
f"Completed — mode={mode} confidence={confidence:.3f}"
)
output = {
"file": file_path,
"name": name,
"mode": mode,
"confidence": confidence,
"lines": len(code.splitlines()),
"generation_id": self._generation_count,
"kernel_result": result,
}
print(f"[GEN] Generated {file_path} "
f"({output['lines']} lines) "
f"mode={mode} confidence={confidence:.3f}")
return output
# ------------------------------------------------------------------
# Internal
# ------------------------------------------------------------------
def _select_template(self, mode, keyword, **kwargs) -> str:
"""Select and fill the best template for this mode/keyword."""
mode_templates = MODE_TEMPLATES.get(mode, {})
# Try exact keyword match first
if keyword in mode_templates:
return mode_templates[keyword].format(**kwargs)
# Try any template in this mode
if mode_templates:
template = list(mode_templates.values())[0]
return template.format(**kwargs)
# Fallback
return FALLBACK_TEMPLATE.format(**kwargs)
def _resolve_path(self, mode: str, name: str, keyword: str) -> str:
"""Determine where to write the generated file."""
mode_dirs = {
"EXECUTION": "generated/execution",
"ANALYTICAL": "generated/analytical",
"RECOVERY": "generated/recovery",
"EXPLORATORY": "generated/exploratory",
}
base_dir = mode_dirs.get(mode, "generated/misc")
return f"{base_dir}/{keyword}_{name}.py"
def query_similar_patterns(self, intent_vec: np.ndarray, top_k: int = 3) -> list:
"""
Query abstraction space for patterns similar to this intent.
Used to inform generation with learned context.
"""
return self.abstraction.query_abstractions(intent_vec, top_k=top_k)