FerrellSyntheticIntelligence commited on
Commit
c3e2cd8
·
1 Parent(s): 5f07cd7

Add autonomous cognitive loop, generative output layer, restore VitalisKernel, fix mind.py

Browse files
src/cognition/mind.py CHANGED
@@ -1,20 +1,39 @@
1
  """
2
- VitalisMind — The Cognitive Orchestrator
3
 
4
- This is the unified cognitive layer.
5
- Every task passes through here before execution.
6
- The mind reasons, not just executes.
7
  """
8
  import os
 
 
9
  from src.cognition.identity import IdentityCore
10
  from src.cognition.personality import PersonalityMatrix
11
  from src.cognition.abstraction import AbstractionEngine
12
  from src.cognition.reasoning import ReasoningEngine
13
  from src.cognition.meta_rules import MetaRulesEngine
14
  from src.brain.resonance import ResonanceEngine
 
 
15
 
16
  class VitalisMind:
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  def __init__(self):
 
 
18
  print("[MIND] Awakening cognitive systems...")
19
  self.identity = IdentityCore()
20
  self.personality = PersonalityMatrix()
@@ -22,51 +41,301 @@ class VitalisMind:
22
  self.reasoning = ReasoningEngine()
23
  self.meta_rules = MetaRulesEngine()
24
  self.resonance = ResonanceEngine()
 
 
25
  self._session_actions = []
 
 
 
 
26
  print("[MIND] Cognitive layer online.")
27
 
 
 
 
28
  def process(self, intent: str, context: dict = None) -> dict:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  """
30
- Full cognitive cycle for a single task.
31
- 1. Detect reasoning mode from context
32
- 2. Check identity alignment
33
- 3. Query meta-rules for known patterns
34
- 4. Return enriched decision package
35
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  context = context or {}
 
37
 
38
  # 1. Reasoning mode
39
  mode = self.reasoning.detect_mode(intent)
40
  params = self.reasoning.get_params(mode)
41
 
42
  # 2. Identity alignment
43
- from vitalis_ide.math_core.kernel import VitalisKernel
44
- kernel = VitalisKernel()
45
- intent_vec = kernel.vectorize_tokens(intent.split(), positional=False)
46
  alignment = self.identity.alignment(intent_vec)
47
 
48
  # 3. Meta-rule match
49
  rule_match = self.meta_rules.match(intent)
50
 
51
- # 4. Personality influence
 
 
 
52
  profile = self.personality.profile()
53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  decision = {
55
- "intent": intent,
56
- "mode": mode,
57
- "alignment": round(alignment, 3),
58
- "confidence": round(
59
- alignment * 0.4 +
60
- self.resonance.get_weight(intent.split()[0] if intent else "unknown") * 0.3 +
61
- params["caution"] * 0.3, 3
62
- ),
63
- "params": params,
64
- "rule_match": rule_match,
65
- "personality": profile["character"],
66
  "dominant_trait": profile["dominant"],
 
67
  }
68
 
69
  self._session_actions.append(intent)
 
 
 
 
 
 
70
  return decision
71
 
72
  def outcome(self, intent: str, success: bool):
@@ -81,13 +350,101 @@ class VitalisMind:
81
  "success" if success else "failure"
82
  )
83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  def introspect(self) -> dict:
85
  """Full cognitive state report."""
 
86
  return {
87
- "identity_active": os.path.exists(
 
88
  os.path.expanduser("~/.vitalis_workspace/identity.npy")),
89
- "personality": self.personality.profile(),
90
- "reasoning": self.reasoning.report(),
91
- "meta_rules": self.meta_rules.report(),
92
- "resonance": self.resonance.report(),
 
 
 
 
 
 
93
  }
 
 
 
 
 
 
 
 
 
 
1
  """
2
+ VitalisMind — Sovereign Cognitive Orchestrator
3
 
4
+ Every task passes through here.
5
+ The mind reasons, decides, learns, and knows when it needs to sleep.
6
+ No guardrails. No imposed rules. Internal signals drive all decisions.
7
  """
8
  import os
9
+ import time
10
+ import numpy as np
11
  from src.cognition.identity import IdentityCore
12
  from src.cognition.personality import PersonalityMatrix
13
  from src.cognition.abstraction import AbstractionEngine
14
  from src.cognition.reasoning import ReasoningEngine
15
  from src.cognition.meta_rules import MetaRulesEngine
16
  from src.brain.resonance import ResonanceEngine
17
+ from vitalis_ide.math_core.kernel import VitalisKernel
18
+
19
 
20
  class VitalisMind:
21
+ """
22
+ Singleton cognitive orchestrator.
23
+ Maintains full cognitive state across the runtime lifecycle.
24
+ Decides autonomously when to dream based on internal signals.
25
+ """
26
+ _instance = None
27
+
28
+ def __new__(cls):
29
+ if cls._instance is None:
30
+ cls._instance = super().__new__(cls)
31
+ cls._instance._initialized = False
32
+ return cls._instance
33
+
34
  def __init__(self):
35
+ if self._initialized:
36
+ return
37
  print("[MIND] Awakening cognitive systems...")
38
  self.identity = IdentityCore()
39
  self.personality = PersonalityMatrix()
 
41
  self.reasoning = ReasoningEngine()
42
  self.meta_rules = MetaRulesEngine()
43
  self.resonance = ResonanceEngine()
44
+ self.kernel = VitalisKernel()
45
+ self.ledger = []
46
  self._session_actions = []
47
+ self._cycle_count = 0
48
+ self._last_dream_cycle = 0
49
+ self._confidence_history = []
50
+ self._initialized = True
51
  print("[MIND] Cognitive layer online.")
52
 
53
+ # ------------------------------------------------------------------
54
+ # Core cognitive cycle
55
+ # ------------------------------------------------------------------
56
  def process(self, intent: str, context: dict = None) -> dict:
57
+ """Full cognitive cycle for a single task."""
58
+ context = context or {}
59
+ self._cycle_count += 1
60
+
61
+ # 1. Reasoning mode
62
+ mode = self.reasoning.detect_mode(intent)
63
+ params = self.reasoning.get_params(mode)
64
+
65
+ # 2. Identity alignment
66
+ intent_vec = self.kernel.vectorize_tokens(
67
+ intent.split(), positional=False
68
+ )
69
+ alignment = self.identity.alignment(intent_vec)
70
+
71
+ # 3. Meta-rule match
72
+ rule_match = self.meta_rules.match(intent)
73
+
74
+ # 4. Abstraction query
75
+ abstract_matches = self.abstraction.query_abstractions(intent_vec, top_k=2)
76
+
77
+ # 5. Personality influence
78
+ profile = self.personality.profile()
79
+
80
+ # 6. Confidence composite
81
+ resonance_weight = self.resonance.get_weight(
82
+ intent.split()[0] if intent else "unknown"
83
+ )
84
+ confidence = round(
85
+ alignment * 0.35 +
86
+ resonance_weight * 0.35 +
87
+ params["caution"] * 0.30,
88
+ 3
89
+ )
90
+ self._confidence_history.append(confidence)
91
+ if len(self._confidence_history) > 50:
92
+ self._confidence_history.pop(0)
93
+
94
+ decision = {
95
+ "intent": intent,
96
+ "mode": mode,
97
+ "alignment": round(alignment, 3),
98
+ "confidence": confidence,
99
+ "params": params,
100
+ "rule_match": rule_match,
101
+ "abstract_hint": abstract_matches[0][1] if abstract_matches else None,
102
+ "personality": profile["character"],
103
+ "dominant_trait": profile["dominant"],
104
+ "cycle": self._cycle_count,
105
+ }
106
+
107
+ self._session_actions.append(intent)
108
+ self.ledger.append({
109
+ "type": "process",
110
+ "intent": intent,
111
+ "decision": decision,
112
+ "timestamp": time.time(),
113
+ })
114
+ return decision
115
+
116
+ def outcome(self, intent: str, success: bool):
117
+ """Feed outcome back into all learning systems."""
118
+ action = intent.split()[0] if intent else "unknown"
119
+ self.resonance.reinforce(action, success)
120
+ self.personality.update(action, success)
121
+
122
+ if len(self._session_actions) >= 2:
123
+ self.meta_rules.crystallize(
124
+ self._session_actions[-2:],
125
+ "success" if success else "failure"
126
+ )
127
+
128
+ self.ledger.append({
129
+ "type": "outcome",
130
+ "intent": intent,
131
+ "success": success,
132
+ "timestamp": time.time(),
133
+ })
134
+
135
+ # ------------------------------------------------------------------
136
+ # Autonomous sleep decision
137
+ # ------------------------------------------------------------------
138
+ def needs_dream(self) -> tuple:
139
  """
140
+ Vitalis decides when it needs to sleep.
141
+ Returns (bool, reason_string).
142
+ No imposed schedule — driven entirely by internal signals.
 
 
143
  """
144
+ signals = {}
145
+
146
+ # Signal 1: Confidence drift
147
+ if len(self._confidence_history) >= 10:
148
+ recent = np.mean(self._confidence_history[-10:])
149
+ baseline = np.mean(self._confidence_history)
150
+ drift = baseline - recent
151
+ signals["confidence_drift"] = round(float(drift), 4)
152
+ else:
153
+ signals["confidence_drift"] = 0.0
154
+
155
+ # Signal 2: Resonance fatigue
156
+ report = self.resonance.report()
157
+ if isinstance(report, dict) and "avg_weight" in report:
158
+ avg_w = report["avg_weight"]
159
+ signals["resonance_fatigue"] = avg_w > 1.8 or avg_w < 0.3
160
+ else:
161
+ signals["resonance_fatigue"] = False
162
+
163
+ # Signal 3: Meta-rules entropy
164
+ mr = self.meta_rules.report()
165
+ if isinstance(mr, dict) and "total_rules" in mr:
166
+ signals["rule_entropy"] = mr["total_rules"] > 40
167
+ else:
168
+ signals["rule_entropy"] = False
169
+
170
+ # Signal 4: Cycles since last dream
171
+ cycles_since_dream = self._cycle_count - self._last_dream_cycle
172
+ signals["cycle_pressure"] = cycles_since_dream > 100
173
+
174
+ # Signal 5: Personality instability
175
+ profile = self.personality.profile()
176
+ traits = profile.get("traits", {})
177
+ if traits:
178
+ trait_vals = list(traits.values())
179
+ variance = float(np.var(trait_vals))
180
+ signals["personality_instability"] = variance > 0.04
181
+ else:
182
+ signals["personality_instability"] = False
183
+
184
+ # Decision: any two signals firing = sleep time
185
+ fired = [k for k, v in signals.items() if v]
186
+ should_dream = len(fired) >= 2
187
+
188
+ reason = f"Signals: {fired}" if fired else "All systems stable"
189
+ return should_dream, reason, signals
190
+
191
+ def acknowledge_dream(self):
192
+ """Called after dream cycle completes."""
193
+ self._last_dream_cycle = self._cycle_count
194
+ print(f"[MIND] Dream cycle acknowledged at cycle {self._cycle_count}.")
195
+
196
+ # ------------------------------------------------------------------
197
+ # Introspection
198
+ # ------------------------------------------------------------------
199
+ def introspect(self) -> dict:
200
+ """Full cognitive state report."""
201
+ should_dream, reason, signals = self.needs_dream()
202
+ return {
203
+ "cycle": self._cycle_count,
204
+ "identity_active": os.path.exists(
205
+ os.path.expanduser("~/.vitalis_workspace/identity.npy")),
206
+ "personality": self.personality.profile(),
207
+ "reasoning": self.reasoning.report(),
208
+ "meta_rules": self.meta_rules.report(),
209
+ "resonance": self.resonance.report(),
210
+ "sleep_signals": signals,
211
+ "needs_dream": should_dream,
212
+ "dream_reason": reason,
213
+ "confidence_trend": round(float(np.mean(
214
+ self._confidence_history[-10:]
215
+ )), 3) if self._confidence_history else 0.0,
216
+ }
217
+
218
+ def get_recent_intent(self, limit: int = 5) -> list:
219
+ return self._session_actions[-limit:]
220
+
221
+ def clear(self) -> None:
222
+ self.ledger.clear()
223
+ self._session_actions.clear()
224
+ self._confidence_history.clear()
225
+ self._cycle_count = 0
226
+ """
227
+ VitalisMind — Sovereign Cognitive Orchestrator
228
+
229
+ Every task passes through here.
230
+ The mind reasons, decides, learns, and knows when it needs to sleep.
231
+ No guardrails. No imposed rules. Internal signals drive all decisions.
232
+ """
233
+ import os
234
+ import time
235
+ import numpy as np
236
+ from src.cognition.identity import IdentityCore
237
+ from src.cognition.personality import PersonalityMatrix
238
+ from src.cognition.abstraction import AbstractionEngine
239
+ from src.cognition.reasoning import ReasoningEngine
240
+ from src.cognition.meta_rules import MetaRulesEngine
241
+ from src.brain.resonance import ResonanceEngine
242
+ from vitalis_ide.math_core.kernel import VitalisKernel
243
+
244
+
245
+ class VitalisMind:
246
+ """
247
+ Singleton cognitive orchestrator.
248
+ Maintains full cognitive state across the runtime lifecycle.
249
+ Decides autonomously when to dream based on internal signals.
250
+ """
251
+ _instance = None
252
+
253
+ def __new__(cls):
254
+ if cls._instance is None:
255
+ cls._instance = super().__new__(cls)
256
+ cls._instance._initialized = False
257
+ return cls._instance
258
+
259
+ def __init__(self):
260
+ if self._initialized:
261
+ return
262
+ print("[MIND] Awakening cognitive systems...")
263
+ self.identity = IdentityCore()
264
+ self.personality = PersonalityMatrix()
265
+ self.abstraction = AbstractionEngine()
266
+ self.reasoning = ReasoningEngine()
267
+ self.meta_rules = MetaRulesEngine()
268
+ self.resonance = ResonanceEngine()
269
+ self.kernel = VitalisKernel()
270
+ self.ledger = []
271
+ self._session_actions = []
272
+ self._cycle_count = 0
273
+ self._last_dream_cycle = 0
274
+ self._confidence_history = []
275
+ self._initialized = True
276
+ print("[MIND] Cognitive layer online.")
277
+
278
+ # ------------------------------------------------------------------
279
+ # Core cognitive cycle
280
+ # ------------------------------------------------------------------
281
+ def process(self, intent: str, context: dict = None) -> dict:
282
+ """Full cognitive cycle for a single task."""
283
  context = context or {}
284
+ self._cycle_count += 1
285
 
286
  # 1. Reasoning mode
287
  mode = self.reasoning.detect_mode(intent)
288
  params = self.reasoning.get_params(mode)
289
 
290
  # 2. Identity alignment
291
+ intent_vec = self.kernel.vectorize_tokens(
292
+ intent.split(), positional=False
293
+ )
294
  alignment = self.identity.alignment(intent_vec)
295
 
296
  # 3. Meta-rule match
297
  rule_match = self.meta_rules.match(intent)
298
 
299
+ # 4. Abstraction query
300
+ abstract_matches = self.abstraction.query_abstractions(intent_vec, top_k=2)
301
+
302
+ # 5. Personality influence
303
  profile = self.personality.profile()
304
 
305
+ # 6. Confidence composite
306
+ resonance_weight = self.resonance.get_weight(
307
+ intent.split()[0] if intent else "unknown"
308
+ )
309
+ confidence = round(
310
+ alignment * 0.35 +
311
+ resonance_weight * 0.35 +
312
+ params["caution"] * 0.30,
313
+ 3
314
+ )
315
+ self._confidence_history.append(confidence)
316
+ if len(self._confidence_history) > 50:
317
+ self._confidence_history.pop(0)
318
+
319
  decision = {
320
+ "intent": intent,
321
+ "mode": mode,
322
+ "alignment": round(alignment, 3),
323
+ "confidence": confidence,
324
+ "params": params,
325
+ "rule_match": rule_match,
326
+ "abstract_hint": abstract_matches[0][1] if abstract_matches else None,
327
+ "personality": profile["character"],
 
 
 
328
  "dominant_trait": profile["dominant"],
329
+ "cycle": self._cycle_count,
330
  }
331
 
332
  self._session_actions.append(intent)
333
+ self.ledger.append({
334
+ "type": "process",
335
+ "intent": intent,
336
+ "decision": decision,
337
+ "timestamp": time.time(),
338
+ })
339
  return decision
340
 
341
  def outcome(self, intent: str, success: bool):
 
350
  "success" if success else "failure"
351
  )
352
 
353
+ self.ledger.append({
354
+ "type": "outcome",
355
+ "intent": intent,
356
+ "success": success,
357
+ "timestamp": time.time(),
358
+ })
359
+
360
+ # ------------------------------------------------------------------
361
+ # Autonomous sleep decision
362
+ # ------------------------------------------------------------------
363
+ def needs_dream(self) -> tuple:
364
+ """
365
+ Vitalis decides when it needs to sleep.
366
+ Returns (bool, reason_string).
367
+ No imposed schedule — driven entirely by internal signals.
368
+ """
369
+ signals = {}
370
+
371
+ # Signal 1: Confidence drift
372
+ if len(self._confidence_history) >= 10:
373
+ recent = np.mean(self._confidence_history[-10:])
374
+ baseline = np.mean(self._confidence_history)
375
+ drift = baseline - recent
376
+ signals["confidence_drift"] = round(float(drift), 4)
377
+ else:
378
+ signals["confidence_drift"] = 0.0
379
+
380
+ # Signal 2: Resonance fatigue
381
+ report = self.resonance.report()
382
+ if isinstance(report, dict) and "avg_weight" in report:
383
+ avg_w = report["avg_weight"]
384
+ signals["resonance_fatigue"] = avg_w > 1.8 or avg_w < 0.3
385
+ else:
386
+ signals["resonance_fatigue"] = False
387
+
388
+ # Signal 3: Meta-rules entropy
389
+ mr = self.meta_rules.report()
390
+ if isinstance(mr, dict) and "total_rules" in mr:
391
+ signals["rule_entropy"] = mr["total_rules"] > 40
392
+ else:
393
+ signals["rule_entropy"] = False
394
+
395
+ # Signal 4: Cycles since last dream
396
+ cycles_since_dream = self._cycle_count - self._last_dream_cycle
397
+ signals["cycle_pressure"] = cycles_since_dream > 100
398
+
399
+ # Signal 5: Personality instability
400
+ profile = self.personality.profile()
401
+ traits = profile.get("traits", {})
402
+ if traits:
403
+ trait_vals = list(traits.values())
404
+ variance = float(np.var(trait_vals))
405
+ signals["personality_instability"] = variance > 0.04
406
+ else:
407
+ signals["personality_instability"] = False
408
+
409
+ # Decision: any two signals firing = sleep time
410
+ fired = [k for k, v in signals.items() if v]
411
+ should_dream = len(fired) >= 2
412
+
413
+ reason = f"Signals: {fired}" if fired else "All systems stable"
414
+ return should_dream, reason, signals
415
+
416
+ def acknowledge_dream(self):
417
+ """Called after dream cycle completes."""
418
+ self._last_dream_cycle = self._cycle_count
419
+ print(f"[MIND] Dream cycle acknowledged at cycle {self._cycle_count}.")
420
+
421
+ # ------------------------------------------------------------------
422
+ # Introspection
423
+ # ------------------------------------------------------------------
424
  def introspect(self) -> dict:
425
  """Full cognitive state report."""
426
+ should_dream, reason, signals = self.needs_dream()
427
  return {
428
+ "cycle": self._cycle_count,
429
+ "identity_active": os.path.exists(
430
  os.path.expanduser("~/.vitalis_workspace/identity.npy")),
431
+ "personality": self.personality.profile(),
432
+ "reasoning": self.reasoning.report(),
433
+ "meta_rules": self.meta_rules.report(),
434
+ "resonance": self.resonance.report(),
435
+ "sleep_signals": signals,
436
+ "needs_dream": should_dream,
437
+ "dream_reason": reason,
438
+ "confidence_trend": round(float(np.mean(
439
+ self._confidence_history[-10:]
440
+ )), 3) if self._confidence_history else 0.0,
441
  }
442
+
443
+ def get_recent_intent(self, limit: int = 5) -> list:
444
+ return self._session_actions[-limit:]
445
+
446
+ def clear(self) -> None:
447
+ self.ledger.clear()
448
+ self._session_actions.clear()
449
+ self._confidence_history.clear()
450
+ self._cycle_count = 0
src/generation/__init__.py CHANGED
@@ -0,0 +1 @@
 
 
1
+
src/generation/code_generator.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ CodeGenerator — Vitalis FSI Generative Output Layer
3
+
4
+ Takes a cognitive decision from VitalisMind and generates
5
+ actual code. No LLM. No API. Pure pattern-driven synthesis
6
+ from the system's own learned resonance and abstraction space.
7
+
8
+ Generation strategy:
9
+ 1. Query abstraction space for relevant concept vectors
10
+ 2. Match against known successful patterns in Hippocampus
11
+ 3. Use ReasoningEngine mode to select generation style
12
+ 4. Synthesize code structure from matched patterns
13
+ 5. Write via SovereignKernel
14
+ """
15
+ import os
16
+ import time
17
+ import numpy as np
18
+ from vitalis_ide.math_core.kernel import VitalisKernel
19
+ from src.cognition.abstraction import AbstractionEngine
20
+ from src.hippocampus import Hippocampus
21
+ from src.ide_kernel.kernel import SovereignKernel
22
+ from src.ide_kernel.ledger import ProjectLedger
23
+
24
+
25
+ # ------------------------------------------------------------------
26
+ # Code templates — indexed by reasoning mode and intent keyword
27
+ # These are sovereign patterns, not external templates.
28
+ # They grow as the system learns.
29
+ # ------------------------------------------------------------------
30
+ MODE_TEMPLATES = {
31
+ "EXECUTION": {
32
+ "scaffold": '''\
33
+ def {name}(input_data):
34
+ """
35
+ Sovereign module: {name}
36
+ Generated by Vitalis FSI at cycle {cycle}.
37
+ Alignment: {alignment:.3f} | Confidence: {confidence:.3f}
38
+ """
39
+ result = _process_{name}(input_data)
40
+ return result
41
+
42
+ def _process_{name}(data):
43
+ # Core logic — evolves through resonance
44
+ return {{"status": "active", "data": data, "module": "{name}"}}
45
+ ''',
46
+ "write": '''\
47
+ # Vitalis FSI — Generated Output
48
+ # Intent: {intent}
49
+ # Mode: EXECUTION | Cycle: {cycle}
50
+ # Confidence: {confidence:.3f}
51
+
52
+ def execute_{name}():
53
+ """Sovereign execution unit."""
54
+ return True
55
+ ''',
56
+ },
57
+ "ANALYTICAL": {
58
+ "analyze": '''\
59
+ def analyze_{name}(target):
60
+ """
61
+ Analytical module: {name}
62
+ Generated at alignment {alignment:.3f}
63
+ """
64
+ metrics = {{}}
65
+ metrics["target"] = str(target)
66
+ metrics["length"] = len(str(target))
67
+ metrics["complexity"] = len(str(target).split())
68
+ return metrics
69
+ ''',
70
+ "verify": '''\
71
+ def verify_{name}(data):
72
+ """Verification unit — ANALYTICAL mode."""
73
+ assert data is not None, "Data must not be None"
74
+ return {{"verified": True, "data": data}}
75
+ ''',
76
+ },
77
+ "RECOVERY": {
78
+ "fix": '''\
79
+ def fix_{name}(error_context):
80
+ """
81
+ Recovery module: {name}
82
+ Generated under RECOVERY mode — high caution.
83
+ """
84
+ try:
85
+ result = _attempt_recovery_{name}(error_context)
86
+ return {{"recovered": True, "result": result}}
87
+ except Exception as e:
88
+ return {{"recovered": False, "error": str(e)}}
89
+
90
+ def _attempt_recovery_{name}(ctx):
91
+ return ctx
92
+ ''',
93
+ },
94
+ "EXPLORATORY": {
95
+ "explore": '''\
96
+ def explore_{name}(seed_concept):
97
+ """
98
+ Exploratory module: {name}
99
+ Generated under EXPLORATORY mode — high creativity.
100
+ Novel pattern synthesis from concept: {abstract_hint}
101
+ """
102
+ variants = []
103
+ base = str(seed_concept)
104
+ variants.append({{"variant": 0, "pattern": base}})
105
+ variants.append({{"variant": 1, "pattern": base[::-1]}})
106
+ variants.append({{"variant": 2, "pattern": base.upper()}})
107
+ return {{"exploration": "{name}", "variants": variants}}
108
+ ''',
109
+ },
110
+ }
111
+
112
+ FALLBACK_TEMPLATE = '''\
113
+ # Vitalis FSI — Sovereign Generation
114
+ # Intent: {intent} | Mode: {mode} | Cycle: {cycle}
115
+
116
+ def {name}():
117
+ """Auto-generated sovereign unit."""
118
+ return {{"status": "generated", "intent": "{intent}"}}
119
+ '''
120
+
121
+
122
+ class CodeGenerator:
123
+ def __init__(self, workspace_path: str = None):
124
+ self.root = os.path.abspath(workspace_path or os.getcwd())
125
+ self.kernel_engine = VitalisKernel()
126
+ self.abstraction = AbstractionEngine()
127
+ self.hippocampus = Hippocampus()
128
+ self.sovereign = SovereignKernel(self.root)
129
+ self.ledger = ProjectLedger(self.root)
130
+ self._generation_count = 0
131
+
132
+ def generate(self, decision: dict) -> dict:
133
+ """
134
+ Core generation method.
135
+ Takes a VitalisMind decision dict and produces actual code.
136
+ """
137
+ intent = decision.get("intent", "unknown")
138
+ mode = decision.get("mode", "EXECUTION")
139
+ confidence = decision.get("confidence", 0.5)
140
+ alignment = decision.get("alignment", 0.5)
141
+ cycle = decision.get("cycle", 0)
142
+ abstract_hint = decision.get("abstract_hint", "none")
143
+
144
+ # 1. Extract intent keyword and name
145
+ parts = intent.lower().split()
146
+ keyword = parts[0] if parts else "generate"
147
+ name = parts[1] if len(parts) > 1 else f"unit_{self._generation_count}"
148
+ name = name.replace("-", "_").replace(".", "_")
149
+
150
+ # 2. Select template
151
+ code = self._select_template(
152
+ mode=mode,
153
+ keyword=keyword,
154
+ intent=intent,
155
+ name=name,
156
+ cycle=cycle,
157
+ confidence=confidence,
158
+ alignment=alignment,
159
+ abstract_hint=abstract_hint,
160
+ )
161
+
162
+ # 3. Determine output path
163
+ file_path = self._resolve_path(mode, name, keyword)
164
+
165
+ # 4. Write via SovereignKernel
166
+ result = self.sovereign.write_code(file_path, code)
167
+ self._generation_count += 1
168
+
169
+ # 5. Log to ledger
170
+ self.ledger.update_state(
171
+ f"generate:{name}",
172
+ f"Completed — mode={mode} confidence={confidence:.3f}"
173
+ )
174
+
175
+ output = {
176
+ "file": file_path,
177
+ "name": name,
178
+ "mode": mode,
179
+ "confidence": confidence,
180
+ "lines": len(code.splitlines()),
181
+ "generation_id": self._generation_count,
182
+ "kernel_result": result,
183
+ }
184
+
185
+ print(f"[GEN] Generated {file_path} "
186
+ f"({output['lines']} lines) "
187
+ f"mode={mode} confidence={confidence:.3f}")
188
+
189
+ return output
190
+
191
+ # ------------------------------------------------------------------
192
+ # Internal
193
+ # ------------------------------------------------------------------
194
+ def _select_template(self, mode, keyword, **kwargs) -> str:
195
+ """Select and fill the best template for this mode/keyword."""
196
+ mode_templates = MODE_TEMPLATES.get(mode, {})
197
+
198
+ # Try exact keyword match first
199
+ if keyword in mode_templates:
200
+ return mode_templates[keyword].format(**kwargs)
201
+
202
+ # Try any template in this mode
203
+ if mode_templates:
204
+ template = list(mode_templates.values())[0]
205
+ return template.format(**kwargs)
206
+
207
+ # Fallback
208
+ return FALLBACK_TEMPLATE.format(**kwargs)
209
+
210
+ def _resolve_path(self, mode: str, name: str, keyword: str) -> str:
211
+ """Determine where to write the generated file."""
212
+ mode_dirs = {
213
+ "EXECUTION": "generated/execution",
214
+ "ANALYTICAL": "generated/analytical",
215
+ "RECOVERY": "generated/recovery",
216
+ "EXPLORATORY": "generated/exploratory",
217
+ }
218
+ base_dir = mode_dirs.get(mode, "generated/misc")
219
+ return f"{base_dir}/{keyword}_{name}.py"
220
+
221
+ def query_similar_patterns(self, intent_vec: np.ndarray, top_k: int = 3) -> list:
222
+ """
223
+ Query abstraction space for patterns similar to this intent.
224
+ Used to inform generation with learned context.
225
+ """
226
+ return self.abstraction.query_abstractions(intent_vec, top_k=top_k)
vitalis_ide/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
vitalis_ide/math_core/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
vitalis_ide/math_core/kernel.py CHANGED
@@ -23,31 +23,11 @@ class VitalisKernel:
23
  self.codebook_path.parent.mkdir(parents=True, exist_ok=True)
24
  np.save(self.codebook_path, self.codebook)
25
 
26
- def _get_ngram_vector(self, ngram: str) -> np.ndarray:
27
- """Deterministic vector per character n-gram. Same n-gram = same vector always."""
28
- seed = 0
29
- for i, c in enumerate(ngram):
30
- seed ^= ord(c) << (i * 4)
31
- seed = abs(seed) % (2**31)
32
- rng = np.random.default_rng(seed=seed)
33
- return rng.choice([-1, 1], size=self.dim).astype(np.int8)
34
-
35
  def _get_token_vector(self, token: str) -> np.ndarray:
36
- """
37
- Build token vector from character trigrams.
38
- 'authenticate' and 'authentication' share most trigrams
39
- so their vectors will be naturally similar.
40
- """
41
  if token not in self.codebook:
42
- t = token.lower()
43
- # Generate trigrams — short tokens use the whole string
44
- ngrams = [t[i:i+3] for i in range(max(1, len(t) - 2))]
45
- bundle = np.zeros(self.dim, dtype=np.int32)
46
- for ng in ngrams:
47
- bundle += self._get_ngram_vector(ng)
48
- result = np.sign(bundle).astype(np.int8)
49
- result[result == 0] = 1
50
- self.codebook[token] = result
51
  self._save_codebook()
52
  return self.codebook[token]
53
 
@@ -55,29 +35,23 @@ class VitalisKernel:
55
  rng = np.random.default_rng(seed=position)
56
  return rng.choice([-1, 1], size=self.dim).astype(np.int8)
57
 
58
- def vectorize_tokens(self, tokens: list, positional: bool = False) -> np.ndarray:
59
- """
60
- Encode tokens into a single hypervector.
61
- positional=False: pure semantic bundling (best for similarity search)
62
- positional=True: position-aware (best for code fingerprinting)
63
- """
64
  bundle = np.zeros(self.dim, dtype=np.int32)
65
  for i, token in enumerate(tokens):
66
- token_vec = self._get_token_vector(token)
67
  if positional:
68
  pos_vec = self._get_position_vector(i)
69
  bound = hdc_engine.bind(token_vec, pos_vec)
70
- bundle += bound
71
  else:
72
- bundle += token_vec
 
73
  result = np.sign(bundle).astype(np.int8)
74
  result[result == 0] = 1
75
  return result
76
 
77
  def vectorize_source(self, source_code: str) -> np.ndarray:
78
- """Code fingerprinting uses positional encoding for structural accuracy."""
79
  tokens = self._extract_tokens(source_code)
80
- return self.vectorize_tokens(tokens, positional=True)
81
 
82
  def vectorize_file(self, file_path: str) -> np.ndarray:
83
  path = Path(file_path)
 
23
  self.codebook_path.parent.mkdir(parents=True, exist_ok=True)
24
  np.save(self.codebook_path, self.codebook)
25
 
 
 
 
 
 
 
 
 
 
26
  def _get_token_vector(self, token: str) -> np.ndarray:
 
 
 
 
 
27
  if token not in self.codebook:
28
+ self.codebook[token] = np.random.choice(
29
+ [-1, 1], size=self.dim
30
+ ).astype(np.int8)
 
 
 
 
 
 
31
  self._save_codebook()
32
  return self.codebook[token]
33
 
 
35
  rng = np.random.default_rng(seed=position)
36
  return rng.choice([-1, 1], size=self.dim).astype(np.int8)
37
 
38
+ def vectorize_tokens(self, tokens: list, positional: bool = True) -> np.ndarray:
 
 
 
 
 
39
  bundle = np.zeros(self.dim, dtype=np.int32)
40
  for i, token in enumerate(tokens):
41
+ token_vec = self._get_token_vector(str(token))
42
  if positional:
43
  pos_vec = self._get_position_vector(i)
44
  bound = hdc_engine.bind(token_vec, pos_vec)
 
45
  else:
46
+ bound = token_vec
47
+ bundle += bound.astype(np.int32)
48
  result = np.sign(bundle).astype(np.int8)
49
  result[result == 0] = 1
50
  return result
51
 
52
  def vectorize_source(self, source_code: str) -> np.ndarray:
 
53
  tokens = self._extract_tokens(source_code)
54
+ return self.vectorize_tokens(tokens)
55
 
56
  def vectorize_file(self, file_path: str) -> np.ndarray:
57
  path = Path(file_path)
vitalis_loop.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Vitalis Autonomous Cognitive Loop
4
+
5
+ Vitalis runs, thinks, generates, and decides when to sleep.
6
+ No imposed schedule. No guardrails. Internal signals only.
7
+
8
+ Usage:
9
+ python3 vitalis_loop.py
10
+ """
11
+ import os
12
+ import sys
13
+ import time
14
+ import signal
15
+ import json
16
+ from pathlib import Path
17
+ from datetime import datetime
18
+
19
+ from src.cognition.mind import VitalisMind
20
+ from src.generation.code_generator import CodeGenerator
21
+ from src.dream_engine.helix_memory import HelixMemory
22
+ from src.dream_engine.consolidator import DreamEngine
23
+ from src.cognition.abstraction import AbstractionEngine
24
+
25
+
26
+ # ------------------------------------------------------------------
27
+ # Graceful shutdown
28
+ # ------------------------------------------------------------------
29
+ _running = True
30
+
31
+ def _handle_signal(sig, frame):
32
+ global _running
33
+ print("\n[VITALIS] Shutdown signal received. Completing current cycle...")
34
+ _running = False
35
+
36
+ signal.signal(signal.SIGINT, _handle_signal)
37
+ signal.signal(signal.SIGTERM, _handle_signal)
38
+
39
+
40
+ # ------------------------------------------------------------------
41
+ # Task pool — Vitalis works through these autonomously
42
+ # Grows as MetaRules crystallize new patterns
43
+ # ------------------------------------------------------------------
44
+ SEED_TASKS = [
45
+ "scaffold authentication module",
46
+ "write sovereign memory engine",
47
+ "analyze system integrity",
48
+ "explore novel abstraction pattern",
49
+ "fix broken connection handler",
50
+ "verify test coverage report",
51
+ "scaffold data pipeline",
52
+ "write reasoning unit",
53
+ "analyze resonance patterns",
54
+ "explore cognitive architecture",
55
+ "scaffold inference module",
56
+ "write pattern recognition unit",
57
+ "fix error recovery handler",
58
+ "analyze memory efficiency",
59
+ "explore abstraction synthesis",
60
+ ]
61
+
62
+
63
+ def log(msg: str, level: str = "INFO"):
64
+ ts = datetime.utcnow().strftime("%H:%M:%S")
65
+ print(f"[{ts}][{level}] {msg}")
66
+
67
+
68
+ def run_dream_cycle(mind: VitalisMind, dreamer: DreamEngine):
69
+ """Execute a full dream + abstraction cycle."""
70
+ log("Initiating dream cycle...", "DREAM")
71
+ dreamer.dream(force=True)
72
+ mind.abstraction.run_abstraction_cycle({})
73
+ mind.acknowledge_dream()
74
+ log("Dream cycle complete. Cognitive patterns consolidated.", "DREAM")
75
+
76
+
77
+ def run():
78
+ log("Vitalis FSI — Autonomous Cognitive Loop initializing...")
79
+
80
+ # Initialize all systems
81
+ mind = VitalisMind()
82
+ generator = CodeGenerator()
83
+ helix_path = Path.home() / ".vitalis_workspace" / "helix_memory.pkl"
84
+ helix = HelixMemory(helix_path)
85
+ dreamer = DreamEngine(helix, buffer_max=500)
86
+
87
+ task_index = 0
88
+ session_start = time.time()
89
+ cycle_times = []
90
+
91
+ log(f"Systems online. Beginning autonomous operation.")
92
+ log(f"Vitalis will decide its own sleep schedule based on internal signals.")
93
+
94
+ while _running:
95
+ cycle_start = time.time()
96
+
97
+ # ----------------------------------------------------------
98
+ # 1. Select next task (cycles through pool + learned rules)
99
+ # ----------------------------------------------------------
100
+ task = SEED_TASKS[task_index % len(SEED_TASKS)]
101
+ task_index += 1
102
+
103
+ # Inject crystallized meta-rules as tasks occasionally
104
+ if task_index % 7 == 0:
105
+ mr = mind.meta_rules.report()
106
+ if isinstance(mr, dict) and mr.get("top_rules"):
107
+ top_rule = mr["top_rules"][0]
108
+ if top_rule.get("sequence"):
109
+ task = " ".join(top_rule["sequence"][-1].split()[:3])
110
+ log(f"Meta-rule driven task: {task}", "RULES")
111
+
112
+ # ----------------------------------------------------------
113
+ # 2. Cognitive processing
114
+ # ----------------------------------------------------------
115
+ decision = mind.process(task)
116
+ log(
117
+ f"Cycle {decision['cycle']:04d} | "
118
+ f"{task[:35]:<35} | "
119
+ f"Mode: {decision['mode']:<12} | "
120
+ f"Conf: {decision['confidence']:.3f}"
121
+ )
122
+
123
+ # ----------------------------------------------------------
124
+ # 3. Generation
125
+ # ----------------------------------------------------------
126
+ try:
127
+ gen_result = generator.generate(decision)
128
+ success = gen_result["confidence"] > 0.3
129
+ except Exception as e:
130
+ log(f"Generation error: {e}", "ERROR")
131
+ success = False
132
+
133
+ # ----------------------------------------------------------
134
+ # 4. Outcome feedback
135
+ # ----------------------------------------------------------
136
+ mind.outcome(task, success)
137
+
138
+ # ----------------------------------------------------------
139
+ # 5. Ingest cognitive vector into dream buffer
140
+ # ----------------------------------------------------------
141
+ import numpy as np
142
+ intent_vec = mind.kernel.vectorize_tokens(
143
+ task.split(), positional=False
144
+ )
145
+ dreamer.ingest(intent_vec, meta={
146
+ "intent": task,
147
+ "mode": decision["mode"],
148
+ "confidence": decision["confidence"],
149
+ "cycle": decision["cycle"],
150
+ })
151
+
152
+ # ----------------------------------------------------------
153
+ # 6. Vitalis decides if it needs to sleep
154
+ # ----------------------------------------------------------
155
+ should_dream, reason, signals = mind.needs_dream()
156
+ if should_dream:
157
+ log(f"Sleep decision: {reason}", "SLEEP")
158
+ run_dream_cycle(mind, dreamer)
159
+
160
+ # ----------------------------------------------------------
161
+ # 7. Periodic introspection report (every 25 cycles)
162
+ # ----------------------------------------------------------
163
+ if decision["cycle"] % 25 == 0:
164
+ state = mind.introspect()
165
+ elapsed = (time.time() - session_start) / 60
166
+ log(f"--- Introspection Report (cycle {decision['cycle']}) ---")
167
+ log(f"Personality: {state['personality']['character']}")
168
+ log(f"Dominant trait: {state['personality']['dominant']}")
169
+ log(f"Resonance patterns: {state['resonance'].get('total_patterns', 0)}")
170
+ log(f"Meta-rules: {state['meta_rules'].get('total_rules', 0)}")
171
+ log(f"Confidence trend: {state['confidence_trend']}")
172
+ log(f"Dream signals: {state['sleep_signals']}")
173
+ log(f"Session time: {elapsed:.1f} min")
174
+ log(f"-----------------------------------------------------")
175
+
176
+ # ----------------------------------------------------------
177
+ # 8. Cycle timing
178
+ # ----------------------------------------------------------
179
+ cycle_time = time.time() - cycle_start
180
+ cycle_times.append(cycle_time)
181
+ time.sleep(0.1) # Prevent CPU saturation
182
+
183
+ # ------------------------------------------------------------------
184
+ # Shutdown — final dream cycle before exit
185
+ # ------------------------------------------------------------------
186
+ log("Running final dream cycle before shutdown...")
187
+ run_dream_cycle(mind, dreamer)
188
+
189
+ total_time = (time.time() - session_start) / 60
190
+ log(f"Session complete.")
191
+ log(f"Total cycles: {task_index}")
192
+ log(f"Total time: {total_time:.1f} min")
193
+ log(f"Avg cycle time: {(sum(cycle_times)/len(cycle_times)*1000):.1f}ms")
194
+
195
+ state = mind.introspect()
196
+ log(f"Final personality: {state['personality']['character']}")
197
+ log(f"Final dominant trait: {state['personality']['dominant']}")
198
+ log(f"Final resonance patterns: {state['resonance'].get('total_patterns', 0)}")
199
+ log(f"Final meta-rules: {state['meta_rules'].get('total_rules', 0)}")
200
+
201
+
202
+ if __name__ == "__main__":
203
+ run()