File size: 7,390 Bytes
c3e2cd8 | 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 | """
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)
|