FerrellSyntheticIntelligence commited on
Commit
a1365f7
·
1 Parent(s): d66263c

Fix architecture integration: remove duplicate mind class, add LFM-backed embeddings, wire SovereignLFMBridge with chat/process/generate

Browse files
src/cognition/mind.py CHANGED
@@ -223,231 +223,6 @@ class VitalisMind:
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):
342
- """Feed outcome back into all learning systems."""
343
- action = intent.split()[0] if intent else "unknown"
344
- self.resonance.reinforce(action, success)
345
- self.personality.update(action, success)
346
-
347
- if len(self._session_actions) >= 2:
348
- self.meta_rules.crystallize(
349
- self._session_actions[-2:],
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 < 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"] > 150
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
451
 
452
 
453
  # Deep cognition layer — imported here to extend VitalisMind
 
223
  self._session_actions.clear()
224
  self._confidence_history.clear()
225
  self._cycle_count = 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
226
 
227
 
228
  # Deep cognition layer — imported here to extend VitalisMind
src/core/lfm_controller.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import asyncio
3
+ import logging
4
+ from concurrent.futures import ThreadPoolExecutor
5
+ from llama_cpp import Llama
6
+
7
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - [LFMController] - %(levelname)s - %(message)s')
8
+ logger = logging.getLogger("LFMController")
9
+
10
+ class LFMController:
11
+ def __init__(self, model_path: str = "", n_ctx: int = 4096, n_threads: int = 6, n_gpu_layers: int = -1):
12
+ if not model_path:
13
+ candidates = [
14
+ os.path.expanduser("~/.vitalis/models/Llama-3.2-3B-Instruct-Q4_K_M.gguf"),
15
+ os.path.expanduser("~/.vitalis/models/LFM2.5-1.2B-Instruct-Q4_K_M.gguf"),
16
+ "Llama-3.2-3B-Instruct-Q4_K_M.gguf",
17
+ "LFM2.5-1.2B-Instruct-Q4_K_M.gguf",
18
+ ]
19
+ for c in candidates:
20
+ if os.path.exists(c):
21
+ model_path = c
22
+ break
23
+ if not model_path:
24
+ model_path = candidates[0]
25
+ if not os.path.exists(model_path):
26
+ logger.critical(f"Target model weights missing at path: {model_path}")
27
+ raise FileNotFoundError(f"Model file target missing: {model_path}")
28
+
29
+ logger.info(f"Initializing local model instance from {model_path}...")
30
+ try:
31
+ self.llm = Llama(
32
+ model_path=model_path,
33
+ n_ctx=n_ctx,
34
+ n_threads=n_threads,
35
+ n_gpu_layers=n_gpu_layers,
36
+ verbose=False
37
+ )
38
+ logger.info("Model hardware acceleration context successfully initialized.")
39
+ except Exception as e:
40
+ logger.error(f"Failed to load hardware context for GGUF: {str(e)}")
41
+ raise e
42
+
43
+ self.executor = ThreadPoolExecutor(max_workers=1)
44
+
45
+ def execute_raw(self, prompt: str, max_tokens: int = 1024, temperature: float = 0.2, top_p: float = 0.95) -> str:
46
+ try:
47
+ response = self.llm(
48
+ prompt=prompt,
49
+ max_tokens=max_tokens,
50
+ temperature=temperature,
51
+ top_p=top_p,
52
+ stop=["<|endoftext|>", "###", "Instruction:", "Response:"]
53
+ )
54
+ output_text = response["choices"][0]["text"].strip()
55
+ return output_text
56
+ except Exception as e:
57
+ logger.error(f"Error encountered during raw execution sequence: {str(e)}")
58
+ return f"EXECUTION_ERROR: {str(e)}"
59
+
60
+ async def generate_async(self, prompt: str, max_tokens: int = 1024, temperature: float = 0.2, top_p: float = 0.95) -> str:
61
+ loop = asyncio.get_running_loop()
62
+ try:
63
+ return await loop.run_in_executor(
64
+ self.executor,
65
+ self.execute_raw,
66
+ prompt, max_tokens, temperature, top_p
67
+ )
68
+ except Exception as e:
69
+ logger.error(f"Async worker thread crashed: {str(e)}")
70
+ return f"ASYNC_EXECUTION_ERROR: {str(e)}"
71
+
72
+ def shutdown(self):
73
+ self.executor.shutdown(wait=True)
src/core/sovereign_lfm_bridge.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ import ast
4
+ from src.devcore.quad_flow_engine import NeurosynthticQuadFlowEngine
5
+ from src.core.lfm_controller import LFMController
6
+
7
+ class SovereignLFMBridge:
8
+ def __init__(self, model_path: str = ""):
9
+ if not model_path:
10
+ candidates = [
11
+ os.path.expanduser("~/.vitalis/models/Llama-3.2-3B-Instruct-Q4_K_M.gguf"),
12
+ os.path.expanduser("~/.vitalis/models/LFM2.5-1.2B-Instruct-Q4_K_M.gguf"),
13
+ "Llama-3.2-3B-Instruct-Q4_K_M.gguf",
14
+ "LFM2.5-1.2B-Instruct-Q4_K_M.gguf",
15
+ ]
16
+ for c in candidates:
17
+ if os.path.exists(c):
18
+ model_path = c
19
+ break
20
+ if not model_path:
21
+ model_path = candidates[0]
22
+ self.model = LFMController(model_path=model_path, n_ctx=8192, n_threads=4, n_gpu_layers=-1)
23
+ self.engine = NeurosynthticQuadFlowEngine()
24
+
25
+ def process(self, query: str, mode: str = None) -> str:
26
+ return self.chat(query)
27
+
28
+ def chat(self, user_input: str, max_tokens: int = 2048, temperature: float = 0.7) -> str:
29
+ from src.cognition.mind import VitalisMind, _extend_mind
30
+ mind = _extend_mind(VitalisMind())
31
+ d = mind.process(user_input)
32
+ mode = d["mode"]
33
+ conf = d["confidence"]
34
+ personality = d.get("personality", "Balanced. Adapting.")
35
+ dominant_trait = d.get("dominant_trait", "PRECISION")
36
+
37
+ prompt = (
38
+ f"<|im_start|>system\n"
39
+ f"Identity: Vitalis Cognitive Engine (mode: {mode}, confidence: {conf}).\n"
40
+ f"Personality: {personality}. Dominant trait: {dominant_trait}.\n"
41
+ f"Respond naturally, honestly, and according to your identity alignment.\n"
42
+ f"<|im_end|>\n"
43
+ f"<|im_start|>user\n{user_input}<|im_end|>\n"
44
+ f"<|im_start|>assistant\n"
45
+ )
46
+
47
+ response = self.model.execute_raw(prompt, max_tokens=max_tokens, temperature=temperature)
48
+
49
+ mind.outcome(user_input, True)
50
+
51
+ try:
52
+ vec = mind.kernel.vectorize_tokens(user_input.split(), positional=False)
53
+ self.engine.nexus.wm.push(user_input, vec, conf)
54
+ self.engine.nexus.helix.encode(
55
+ event=user_input,
56
+ meaning=f"chat mode={mode} conf={conf}",
57
+ )
58
+ except Exception:
59
+ pass
60
+
61
+ return response
62
+
63
+ def generate(self, intent: str) -> dict:
64
+ from src.cognition.mind import VitalisMind, _extend_mind
65
+ mind = _extend_mind(VitalisMind())
66
+ d = mind.process(intent)
67
+ mode = d["mode"]
68
+ conf = d["confidence"]
69
+
70
+ response = self.model.llm.create_chat_completion(
71
+ messages=[
72
+ {"role": "system", "content": f"You are a Python code engine in {mode} mode. Output executable Python code only. No explanations. Always end with a print() statement."},
73
+ {"role": "user", "content": f"Write Python code to: {intent}"}
74
+ ],
75
+ max_tokens=512,
76
+ temperature=0.2,
77
+ )
78
+ raw = response["choices"][0]["message"]["content"].strip()
79
+ code = self._extract_code(raw)
80
+ result = self._sandbox(code)
81
+ mind.outcome(intent, result["status"] == "SUCCESS")
82
+
83
+ vec = mind.kernel.vectorize_tokens(intent.split(), positional=False)
84
+ self.engine.nexus.wm.push(intent, vec, conf)
85
+ self.engine.nexus.helix.encode(intent, result["output"] or "fail")
86
+
87
+ return {"intent":intent,"mode":mode,"confidence":conf,
88
+ "code":code,"output":result["output"],"status":result["status"]}
89
+
90
+ def _extract_code(self, raw: str) -> str:
91
+ raw = raw.replace("```python","").replace("```","").strip()
92
+ if not raw: return "print('no output')"
93
+ lines = raw.splitlines()
94
+ clean = []
95
+ for line in lines:
96
+ s = line.strip()
97
+ if s and not s.startswith('#'):
98
+ if (s[0].isupper() and '=' not in s and '(' not in s
99
+ and not any(s.startswith(k) for k in
100
+ ['def ','class ','import ','from ','for ',
101
+ 'if ','while ','try','return','print','True','False'])):
102
+ break
103
+ clean.append(line)
104
+ code = '\n'.join(clean).strip()
105
+ try:
106
+ ast.parse(code)
107
+ except SyntaxError:
108
+ code = "print('syntax error in generated code')"
109
+ if not code: return "print('no output')"
110
+ if "print(" not in code:
111
+ defs = [l for l in code.splitlines() if l.strip().startswith("def ")]
112
+ if defs:
113
+ fname = defs[-1].strip().split("def ")[1].split("(")[0]
114
+ code += f"\nprint({fname}(10))"
115
+ return code
116
+
117
+ def _sandbox(self, code: str) -> dict:
118
+ try:
119
+ r = subprocess.run(["python3","-c",code],
120
+ capture_output=True, text=True, timeout=10)
121
+ if r.returncode == 0:
122
+ return {"status":"SUCCESS","output":r.stdout.strip()}
123
+ return {"status":"FAIL","output":r.stderr.strip()[:200]}
124
+ except subprocess.TimeoutExpired:
125
+ return {"status":"TIMEOUT","output":""}
src/core/transformer_wrapper.py CHANGED
@@ -7,14 +7,24 @@ import numpy as np
7
  import torch
8
 
9
  class SovereignTransformer:
10
- def __init__(self, model_name: str = "facebook/opt-125m"):
11
  self.model_name = model_name
12
  self.dim = 768
 
13
 
14
  def encode(self, text: str):
 
 
 
 
 
 
 
 
15
  seed = sum(ord(c) for c in (text or "")[:80]) % (2**31)
16
  rng = np.random.default_rng(seed)
17
  vec = rng.standard_normal(self.dim).astype(np.float32)
18
  norm = np.linalg.norm(vec)
19
- if norm > 0: vec /= norm
 
20
  return torch.from_numpy(vec)
 
7
  import torch
8
 
9
  class SovereignTransformer:
10
+ def __init__(self, model_name: str = "facebook/opt-125m", controller=None):
11
  self.model_name = model_name
12
  self.dim = 768
13
+ self.controller = controller
14
 
15
  def encode(self, text: str):
16
+ if self.controller is not None:
17
+ try:
18
+ resp = self.controller.llm.create_embedding(input=text)
19
+ emb = resp["data"][0]["embedding"]
20
+ return torch.tensor(emb, dtype=torch.float32)
21
+ except Exception:
22
+ pass
23
+
24
  seed = sum(ord(c) for c in (text or "")[:80]) % (2**31)
25
  rng = np.random.default_rng(seed)
26
  vec = rng.standard_normal(self.dim).astype(np.float32)
27
  norm = np.linalg.norm(vec)
28
+ if norm > 0:
29
+ vec /= norm
30
  return torch.from_numpy(vec)
src/devcore/quad_flow_engine.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from src.devcore.vitalis_cognitive_engine import VitalisCognitiveEngine
3
+ from src.cognition.working_memory import WorkingMemory
4
+ from src.cognition.predictive_engine import PredictiveEngine
5
+ from src.dream_engine.synthetic_helix import SyntheticHelixMemory
6
+ from vitalis_ide.math_core.kernel import VitalisKernel
7
+
8
+ log = logging.getLogger('QuadFlow')
9
+
10
+
11
+ class NexusHead:
12
+ def __init__(self):
13
+ self.kernel = VitalisKernel()
14
+ self.wm = WorkingMemory()
15
+ self.predictor = PredictiveEngine()
16
+ self.helix = SyntheticHelixMemory()
17
+
18
+ def pre(self, intent, mind_state):
19
+ resonance_w = {
20
+ k: v for k, v in
21
+ mind_state.get('resonance', {}).get('strongest', [])
22
+ }
23
+ prediction = self.predictor.predict_next(
24
+ intent,
25
+ mind_state.get('meta_rules', {}),
26
+ resonance_w,
27
+ )
28
+ if prediction.get('predicted_next'):
29
+ self.predictor.anticipate(prediction, self.wm)
30
+ vec = self.kernel.vectorize_tokens(intent.split(), positional=False)
31
+ self.wm.push(intent, vec, 1.0)
32
+ return {'prediction': prediction, 'wm_context': self.wm.context(3)}
33
+
34
+ def post(self, intent, result, success):
35
+ accuracy = self.predictor.score(intent)
36
+ mode = result.get('mode', 'unknown')
37
+ conf = result.get('confidence', 0.0)
38
+ status = 'success' if success else 'fail'
39
+ meaning = status + ' mode=' + mode + ' conf=' + str(round(conf, 3))
40
+ self.helix.encode(event=intent, meaning=meaning)
41
+ return {'accuracy': accuracy}
42
+
43
+ def report(self):
44
+ return {
45
+ 'working_memory': self.wm.report(),
46
+ 'predictor': self.predictor.report(),
47
+ 'helix': self.helix.report(),
48
+ }
49
+
50
+
51
+ class NeurosynthticQuadFlowEngine(VitalisCognitiveEngine):
52
+ def __init__(self):
53
+ super().__init__()
54
+ self.nexus = NexusHead()
55
+ print('')
56
+ print(' ╔══════════════════════════════════════╗')
57
+ print(' ║ NEUROSYNTHETIC QUAD FLOW ENGINE ║')
58
+ print(' ║ Sensu | Ratio | Cor | Nexus ║')
59
+ print(' ║ WorkingMem + Foresight + Helix ║')
60
+ print(' ╚══════════════════════════════════════╝')
61
+ print('')
62
+
63
+ def think_and_act(self, intent, token, **kwargs):
64
+ if not self.auth.validate_request(token):
65
+ return {'success': False, 'error': 'UNAUTHORIZED'}
66
+ from src.cognition.mind import VitalisMind, _extend_mind
67
+ mind = VitalisMind()
68
+ ms = mind.introspect()
69
+ pre = self.nexus.pre(intent, ms)
70
+ predicted = pre['prediction'].get('predicted_next', '?')
71
+ wm_ctx = pre['wm_context']
72
+ log.info('[NEXUS] Predicted: ' + str(predicted))
73
+ log.info('[NEXUS] WM: ' + str(wm_ctx))
74
+ result = super().think_and_act(intent, token, **kwargs)
75
+ post = self.nexus.post(intent, result, result.get('success', False))
76
+ result['nexus'] = {
77
+ 'predicted_next': predicted,
78
+ 'wm_context': wm_ctx,
79
+ 'prediction_accuracy': post['accuracy'],
80
+ }
81
+ return result
82
+
83
+ def status(self):
84
+ return {
85
+ 'engine': 'NeurosynthticQuadFlowEngine v2.1',
86
+ 'heads': ['Sensu', 'Ratio', 'Cor', 'Nexus'],
87
+ 'nexus': self.nexus.report(),
88
+ }
src/engine/__init__.py ADDED
File without changes
src/engine/quadruflow.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import hashlib
5
+ import os
6
+ import time
7
+ from datetime import datetime
8
+ from typing import Dict, Any
9
+
10
+ from src.cognition.curriculum import CurriculumManager, CurriculumTask
11
+ from src.memory.ledger import QuantumResistantLedger
12
+ from src.engine.validator import ArtifactValidator
13
+ from src.cognition._constants import logger
14
+ from src.core.lfm_controller import LFMController
15
+
16
+
17
+ class QuadruflowOrchestrator:
18
+ """The Neurosynthetic Quadruflow Engine implementing four discrete cognitive flows."""
19
+
20
+ def __init__(self, random_seed: int | None = None):
21
+ logger.info("Initializing Quadruflow Engine Core...")
22
+ self.curriculum = CurriculumManager(random_seed=random_seed)
23
+ self.ledger = QuantumResistantLedger()
24
+ self.validator = ArtifactValidator()
25
+
26
+ candidates = [
27
+ os.path.expanduser("~/.vitalis/models/Llama-3.2-3B-Instruct-Q4_K_M.gguf"),
28
+ os.path.expanduser("~/.vitalis/models/LFM2.5-1.2B-Instruct-Q4_K_M.gguf"),
29
+ "Llama-3.2-3B-Instruct-Q4_K_M.gguf",
30
+ "LFM2.5-1.2B-Instruct-Q4_K_M.gguf",
31
+ ]
32
+ model_path = ""
33
+ for c in candidates:
34
+ if os.path.exists(c):
35
+ model_path = c
36
+ break
37
+ if not model_path:
38
+ model_path = candidates[0]
39
+ logger.info("Wiring LFMController -> %s", model_path)
40
+ self.controller = LFMController(
41
+ model_path=model_path,
42
+ n_ctx=8192,
43
+ n_threads=6,
44
+ n_gpu_layers=-1,
45
+ )
46
+
47
+ if not self.ledger.verify_integrity():
48
+ raise SecurityError("Critical Error: Cryptographic ledger validation failed during boot sequence.")
49
+ logger.info("[Evaluation Ready] Core engine verified and integrated with evaluation hooks.")
50
+
51
+ def _normalize_val_report(self, v_out) -> dict:
52
+ if isinstance(v_out, dict):
53
+ return v_out
54
+ if isinstance(v_out, tuple) and len(v_out) == 2:
55
+ valid, reason = v_out
56
+ valid = bool(valid)
57
+ return {
58
+ "valid": valid,
59
+ "errors": [] if valid else [str(reason)],
60
+ "score_components": {
61
+ "schema": 1.0 if valid else 0.0,
62
+ "semantics": 1.0 if valid else 0.0,
63
+ "length": 1.0,
64
+ },
65
+ }
66
+ return {
67
+ "valid": getattr(v_out, "valid", False),
68
+ "errors": getattr(v_out, "errors", []),
69
+ "score_components": getattr(v_out, "score_components", {"schema": 0.0, "semantics": 0.0, "length": 0.0}),
70
+ }
71
+
72
+ def flow1_ingest(self, state: dict) -> dict:
73
+ if "task_id" not in state or "prompt" not in state:
74
+ raise ValueError("Schema validation failed: missing task_id or prompt")
75
+ return {
76
+ "task_id": str(state["task_id"]),
77
+ "prompt": str(state["prompt"]),
78
+ "expected_type": state.get("expected_type", "code"),
79
+ "provenance": "vitalis_devcore_ingest",
80
+ }
81
+
82
+ def flow2_simulate(self, state: dict, seed: int) -> dict:
83
+ formatted_prompt = f"<|im_start|>user\n{state['prompt']}<|im_end|>\n<|im_start|>assistant\n"
84
+ text = self.controller.execute_raw(formatted_prompt, max_tokens=256, temperature=0.0)
85
+ return {"text": text, "task_id": state["task_id"]}
86
+
87
+ def flow3_debug(self, candidate: dict, errors: list) -> tuple[dict, dict]:
88
+ repair_prompt = (
89
+ f"Fix the following errors in your previous output:\n"
90
+ f"Errors: {', '.join(errors)}\n"
91
+ f"Previous Output:\n{candidate['text']}"
92
+ )
93
+ return (
94
+ {"task_id": candidate["task_id"], "prompt": repair_prompt},
95
+ {"repair_prompt": repair_prompt, "previous_errors": errors},
96
+ )
97
+
98
+ def flow4_attest(self, candidate: dict, corrections: dict | None, val_report: dict, retries: int, runtime_ms: float, attested: bool, rejection_reason: str | None = None) -> dict:
99
+ det_hash = hashlib.sha256(candidate["text"].encode("utf-8")).hexdigest()
100
+ return {
101
+ "artifact_id": f"art_{candidate['task_id']}_{int(time.time())}",
102
+ "task_id": candidate["task_id"],
103
+ "result": {"output": candidate["text"]},
104
+ "validator": {
105
+ "valid": val_report.get("valid", False),
106
+ "errors": val_report.get("errors", []),
107
+ "score_components": val_report.get("score_components", {"schema": 0.0, "semantics": 0.0, "length": 0.0}),
108
+ },
109
+ "attestation": {
110
+ "hash": det_hash,
111
+ "signature": "<placeholder>",
112
+ "timestamp": datetime.utcnow().isoformat() + "Z",
113
+ "attested": attested,
114
+ },
115
+ "meta": {
116
+ "retries": retries,
117
+ "runtime_ms": int(runtime_ms),
118
+ "rejection_reason": rejection_reason,
119
+ },
120
+ }
121
+
122
+ def run_cognitive_cycle(self, task: CurriculumTask, seed: int) -> dict:
123
+ start_time = time.time()
124
+ initial_state = {
125
+ "task_id": task.task_id,
126
+ "prompt": getattr(task, "prompt", f"Complete task {task.task_id}"),
127
+ "expected_type": task.expected_type,
128
+ }
129
+ state = self.flow1_ingest(initial_state)
130
+ retries = 0
131
+ rejection_reason = None
132
+ candidate = {"text": "", "task_id": task.task_id}
133
+ corrections = None
134
+ val_report: dict = {
135
+ "valid": False,
136
+ "errors": [],
137
+ "score_components": {"schema": 0.0, "semantics": 0.0, "length": 0.0},
138
+ }
139
+
140
+ while retries <= 2:
141
+ candidate = self.flow2_simulate(state, seed)
142
+ v_out = self.validator.validate(candidate["text"])
143
+ val_report = self._normalize_val_report(v_out)
144
+ if val_report.get("valid"):
145
+ break
146
+ retries += 1
147
+ if retries <= 2:
148
+ state, corrections = self.flow3_debug(candidate, val_report.get("errors", []))
149
+ else:
150
+ rejection_reason = "Max retries exceeded without valid artifact"
151
+
152
+ runtime_ms = (time.time() - start_time) * 1000
153
+ attested = val_report.get("valid", False) and (rejection_reason is None)
154
+ artifact = self.flow4_attest(candidate, corrections, val_report, min(retries, 2), runtime_ms, attested, rejection_reason)
155
+
156
+ sc = val_report.get("score_components", {"schema": 0.0, "semantics": 0.0, "length": 0.0})
157
+ risk = (
158
+ 0.5 * (1.0 - sc.get("schema", 0.0))
159
+ + 0.3 * (1.0 - sc.get("semantics", 0.0))
160
+ + 0.2 * (min(retries, 2) / 2.0)
161
+ )
162
+
163
+ metrics_payload = (
164
+ f"status={'SUCCESS' if attested else 'REJECTED'}"
165
+ f"|risk={round(risk, 4)}"
166
+ f"|duration={int(runtime_ms)}"
167
+ f"|attested={str(attested).lower()}"
168
+ f"|rejection_reason={rejection_reason}"
169
+ )
170
+ block = self.ledger.append_record(task_id=task.task_id, outcome_metrics=metrics_payload)
171
+ artifact["attestation"]["signature"] = getattr(block, "signature", "<placeholder>")
172
+ self.curriculum.record_result(success=attested, risk_encountered=risk)
173
+ return artifact
174
+
175
+ async def execute_closed_loop_cycle(self) -> Dict[str, Any]:
176
+ task: CurriculumTask = self.curriculum.generate_next_task()
177
+ logger.info("Executing Task Channel: %s [Tier %d]", task.task_id, task.tier)
178
+ loop = asyncio.get_running_loop()
179
+ try:
180
+ artifact = await loop.run_in_executor(None, lambda: self.run_cognitive_cycle(task, 42))
181
+ success = artifact["attestation"]["attested"]
182
+ sig = artifact["attestation"]["signature"]
183
+ block_idx = artifact.get("ledger_block_index", 1)
184
+ except Exception as err:
185
+ logger.error("Execution exception encountered on %s: %s", task.task_id, str(err))
186
+ block = self.ledger.append_record(
187
+ task_id=task.task_id,
188
+ outcome_metrics="status=CRASHED|risk=1.0|duration=0|attested=false|rejection_reason=catastrophic_failure",
189
+ )
190
+ success = False
191
+ sig = getattr(block, "signature", "<placeholder>")
192
+ block_idx = getattr(block, "index", 1)
193
+
194
+ return {
195
+ "task_id": task.task_id,
196
+ "success": success,
197
+ "ledger_block_index": block_idx,
198
+ "ledger_signature": sig,
199
+ "curriculum_state": self.curriculum.export_state(),
200
+ }
201
+
202
+ def verify_system_health(self) -> bool:
203
+ return self.ledger.verify_integrity()
204
+
205
+ def shutdown(self) -> None:
206
+ self.controller.shutdown()
207
+
208
+
209
+ class SecurityError(Exception):
210
+ """Raised when cryptographic data structures show validation failures."""