File size: 8,832 Bytes
a1365f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import asyncio
import hashlib
import os
import time
from datetime import datetime
from typing import Dict, Any

from src.cognition.curriculum import CurriculumManager, CurriculumTask
from src.memory.ledger import QuantumResistantLedger
from src.engine.validator import ArtifactValidator
from src.cognition._constants import logger
from src.core.lfm_controller import LFMController


class QuadruflowOrchestrator:
    """The Neurosynthetic Quadruflow Engine implementing four discrete cognitive flows."""

    def __init__(self, random_seed: int | None = None):
        logger.info("Initializing Quadruflow Engine Core...")
        self.curriculum = CurriculumManager(random_seed=random_seed)
        self.ledger = QuantumResistantLedger()
        self.validator = ArtifactValidator()

        candidates = [
            os.path.expanduser("~/.vitalis/models/Llama-3.2-3B-Instruct-Q4_K_M.gguf"),
            os.path.expanduser("~/.vitalis/models/LFM2.5-1.2B-Instruct-Q4_K_M.gguf"),
            "Llama-3.2-3B-Instruct-Q4_K_M.gguf",
            "LFM2.5-1.2B-Instruct-Q4_K_M.gguf",
        ]
        model_path = ""
        for c in candidates:
            if os.path.exists(c):
                model_path = c
                break
        if not model_path:
            model_path = candidates[0]
        logger.info("Wiring LFMController -> %s", model_path)
        self.controller = LFMController(
            model_path=model_path,
            n_ctx=8192,
            n_threads=6,
            n_gpu_layers=-1,
        )

        if not self.ledger.verify_integrity():
            raise SecurityError("Critical Error: Cryptographic ledger validation failed during boot sequence.")
        logger.info("[Evaluation Ready] Core engine verified and integrated with evaluation hooks.")

    def _normalize_val_report(self, v_out) -> dict:
        if isinstance(v_out, dict):
            return v_out
        if isinstance(v_out, tuple) and len(v_out) == 2:
            valid, reason = v_out
            valid = bool(valid)
            return {
                "valid": valid,
                "errors": [] if valid else [str(reason)],
                "score_components": {
                    "schema": 1.0 if valid else 0.0,
                    "semantics": 1.0 if valid else 0.0,
                    "length": 1.0,
                },
            }
        return {
            "valid": getattr(v_out, "valid", False),
            "errors": getattr(v_out, "errors", []),
            "score_components": getattr(v_out, "score_components", {"schema": 0.0, "semantics": 0.0, "length": 0.0}),
        }

    def flow1_ingest(self, state: dict) -> dict:
        if "task_id" not in state or "prompt" not in state:
            raise ValueError("Schema validation failed: missing task_id or prompt")
        return {
            "task_id": str(state["task_id"]),
            "prompt": str(state["prompt"]),
            "expected_type": state.get("expected_type", "code"),
            "provenance": "vitalis_devcore_ingest",
        }

    def flow2_simulate(self, state: dict, seed: int) -> dict:
        formatted_prompt = f"<|im_start|>user\n{state['prompt']}<|im_end|>\n<|im_start|>assistant\n"
        text = self.controller.execute_raw(formatted_prompt, max_tokens=256, temperature=0.0)
        return {"text": text, "task_id": state["task_id"]}

    def flow3_debug(self, candidate: dict, errors: list) -> tuple[dict, dict]:
        repair_prompt = (
            f"Fix the following errors in your previous output:\n"
            f"Errors: {', '.join(errors)}\n"
            f"Previous Output:\n{candidate['text']}"
        )
        return (
            {"task_id": candidate["task_id"], "prompt": repair_prompt},
            {"repair_prompt": repair_prompt, "previous_errors": errors},
        )

    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:
        det_hash = hashlib.sha256(candidate["text"].encode("utf-8")).hexdigest()
        return {
            "artifact_id": f"art_{candidate['task_id']}_{int(time.time())}",
            "task_id": candidate["task_id"],
            "result": {"output": candidate["text"]},
            "validator": {
                "valid": val_report.get("valid", False),
                "errors": val_report.get("errors", []),
                "score_components": val_report.get("score_components", {"schema": 0.0, "semantics": 0.0, "length": 0.0}),
            },
            "attestation": {
                "hash": det_hash,
                "signature": "<placeholder>",
                "timestamp": datetime.utcnow().isoformat() + "Z",
                "attested": attested,
            },
            "meta": {
                "retries": retries,
                "runtime_ms": int(runtime_ms),
                "rejection_reason": rejection_reason,
            },
        }

    def run_cognitive_cycle(self, task: CurriculumTask, seed: int) -> dict:
        start_time = time.time()
        initial_state = {
            "task_id": task.task_id,
            "prompt": getattr(task, "prompt", f"Complete task {task.task_id}"),
            "expected_type": task.expected_type,
        }
        state = self.flow1_ingest(initial_state)
        retries = 0
        rejection_reason = None
        candidate = {"text": "", "task_id": task.task_id}
        corrections = None
        val_report: dict = {
            "valid": False,
            "errors": [],
            "score_components": {"schema": 0.0, "semantics": 0.0, "length": 0.0},
        }

        while retries <= 2:
            candidate = self.flow2_simulate(state, seed)
            v_out = self.validator.validate(candidate["text"])
            val_report = self._normalize_val_report(v_out)
            if val_report.get("valid"):
                break
            retries += 1
            if retries <= 2:
                state, corrections = self.flow3_debug(candidate, val_report.get("errors", []))
            else:
                rejection_reason = "Max retries exceeded without valid artifact"

        runtime_ms = (time.time() - start_time) * 1000
        attested = val_report.get("valid", False) and (rejection_reason is None)
        artifact = self.flow4_attest(candidate, corrections, val_report, min(retries, 2), runtime_ms, attested, rejection_reason)

        sc = val_report.get("score_components", {"schema": 0.0, "semantics": 0.0, "length": 0.0})
        risk = (
            0.5 * (1.0 - sc.get("schema", 0.0))
            + 0.3 * (1.0 - sc.get("semantics", 0.0))
            + 0.2 * (min(retries, 2) / 2.0)
        )

        metrics_payload = (
            f"status={'SUCCESS' if attested else 'REJECTED'}"
            f"|risk={round(risk, 4)}"
            f"|duration={int(runtime_ms)}"
            f"|attested={str(attested).lower()}"
            f"|rejection_reason={rejection_reason}"
        )
        block = self.ledger.append_record(task_id=task.task_id, outcome_metrics=metrics_payload)
        artifact["attestation"]["signature"] = getattr(block, "signature", "<placeholder>")
        self.curriculum.record_result(success=attested, risk_encountered=risk)
        return artifact

    async def execute_closed_loop_cycle(self) -> Dict[str, Any]:
        task: CurriculumTask = self.curriculum.generate_next_task()
        logger.info("Executing Task Channel: %s [Tier %d]", task.task_id, task.tier)
        loop = asyncio.get_running_loop()
        try:
            artifact = await loop.run_in_executor(None, lambda: self.run_cognitive_cycle(task, 42))
            success = artifact["attestation"]["attested"]
            sig = artifact["attestation"]["signature"]
            block_idx = artifact.get("ledger_block_index", 1)
        except Exception as err:
            logger.error("Execution exception encountered on %s: %s", task.task_id, str(err))
            block = self.ledger.append_record(
                task_id=task.task_id,
                outcome_metrics="status=CRASHED|risk=1.0|duration=0|attested=false|rejection_reason=catastrophic_failure",
            )
            success = False
            sig = getattr(block, "signature", "<placeholder>")
            block_idx = getattr(block, "index", 1)

        return {
            "task_id": task.task_id,
            "success": success,
            "ledger_block_index": block_idx,
            "ledger_signature": sig,
            "curriculum_state": self.curriculum.export_state(),
        }

    def verify_system_health(self) -> bool:
        return self.ledger.verify_integrity()

    def shutdown(self) -> None:
        self.controller.shutdown()


class SecurityError(Exception):
    """Raised when cryptographic data structures show validation failures."""