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d9e142
c3e2cd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3072b7
 
c3e2cd8
f3072b7
c3e2cd8
 
f3072b7
c3e2cd8
 
 
 
 
 
 
 
 
 
f3072b7
c3e2cd8
 
 
 
 
 
 
 
 
7d9e142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
"""
VitalisMind — Sovereign Cognitive Orchestrator

Every task passes through here.
The mind reasons, decides, learns, and knows when it needs to sleep.
No guardrails. No imposed rules. Internal signals drive all decisions.
"""
import os
import time
import numpy as np
from src.cognition.identity import IdentityCore
from src.cognition.personality import PersonalityMatrix
from src.cognition.abstraction import AbstractionEngine
from src.cognition.reasoning import ReasoningEngine
from src.cognition.meta_rules import MetaRulesEngine
from src.brain.resonance import ResonanceEngine
from vitalis_ide.math_core.kernel import VitalisKernel


class VitalisMind:
    """
    Singleton cognitive orchestrator.
    Maintains full cognitive state across the runtime lifecycle.
    Decides autonomously when to dream based on internal signals.
    """
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance._initialized = False
        return cls._instance

    def __init__(self):
        if self._initialized:
            return
        print("[MIND] Awakening cognitive systems...")
        self.identity    = IdentityCore()
        self.personality = PersonalityMatrix()
        self.abstraction = AbstractionEngine()
        self.reasoning   = ReasoningEngine()
        self.meta_rules  = MetaRulesEngine()
        self.resonance   = ResonanceEngine()
        self.kernel      = VitalisKernel()
        self.ledger      = []
        self._session_actions = []
        self._cycle_count = 0
        self._last_dream_cycle = 0
        self._confidence_history = []
        self._initialized = True
        print("[MIND] Cognitive layer online.")

    # ------------------------------------------------------------------
    # Core cognitive cycle
    # ------------------------------------------------------------------
    def process(self, intent: str, context: dict = None) -> dict:
        """Full cognitive cycle for a single task."""
        context = context or {}
        self._cycle_count += 1

        # 1. Reasoning mode
        mode = self.reasoning.detect_mode(intent)
        params = self.reasoning.get_params(mode)

        # 2. Identity alignment
        intent_vec = self.kernel.vectorize_tokens(
            intent.split(), positional=False
        )
        alignment = self.identity.alignment(intent_vec)

        # 3. Meta-rule match
        rule_match = self.meta_rules.match(intent)

        # 4. Abstraction query
        abstract_matches = self.abstraction.query_abstractions(intent_vec, top_k=2)

        # 5. Personality influence
        profile = self.personality.profile()

        # 6. Confidence composite
        resonance_weight = self.resonance.get_weight(
            intent.split()[0] if intent else "unknown"
        )
        confidence = round(
            alignment * 0.35 +
            resonance_weight * 0.35 +
            params["caution"] * 0.30,
            3
        )
        self._confidence_history.append(confidence)
        if len(self._confidence_history) > 50:
            self._confidence_history.pop(0)

        decision = {
            "intent":        intent,
            "mode":          mode,
            "alignment":     round(alignment, 3),
            "confidence":    confidence,
            "params":        params,
            "rule_match":    rule_match,
            "abstract_hint": abstract_matches[0][1] if abstract_matches else None,
            "personality":   profile["character"],
            "dominant_trait": profile["dominant"],
            "cycle":         self._cycle_count,
        }

        self._session_actions.append(intent)
        self.ledger.append({
            "type":      "process",
            "intent":    intent,
            "decision":  decision,
            "timestamp": time.time(),
        })
        return decision

    def outcome(self, intent: str, success: bool):
        """Feed outcome back into all learning systems."""
        action = intent.split()[0] if intent else "unknown"
        self.resonance.reinforce(action, success)
        self.personality.update(action, success)

        if len(self._session_actions) >= 2:
            self.meta_rules.crystallize(
                self._session_actions[-2:],
                "success" if success else "failure"
            )

        self.ledger.append({
            "type":      "outcome",
            "intent":    intent,
            "success":   success,
            "timestamp": time.time(),
        })

    # ------------------------------------------------------------------
    # Autonomous sleep decision
    # ------------------------------------------------------------------
    def needs_dream(self) -> tuple:
        """
        Vitalis decides when it needs to sleep.
        Returns (bool, reason_string).
        No imposed schedule — driven entirely by internal signals.
        """
        signals = {}

        # Signal 1: Confidence drift
        if len(self._confidence_history) >= 10:
            recent = np.mean(self._confidence_history[-10:])
            baseline = np.mean(self._confidence_history)
            drift = baseline - recent
            signals["confidence_drift"] = round(float(drift), 4)
        else:
            signals["confidence_drift"] = 0.0

        # Signal 2: Resonance fatigue
        report = self.resonance.report()
        if isinstance(report, dict) and "avg_weight" in report:
            avg_w = report["avg_weight"]
            signals["resonance_fatigue"] = avg_w < 0.3
        else:
            signals["resonance_fatigue"] = False

        # Signal 3: Meta-rules entropy
        mr = self.meta_rules.report()
        if isinstance(mr, dict) and "total_rules" in mr:
            signals["rule_entropy"] = mr["total_rules"] > 150
        else:
            signals["rule_entropy"] = False

        # Signal 4: Cycles since last dream
        cycles_since_dream = self._cycle_count - self._last_dream_cycle
        signals["cycle_pressure"] = cycles_since_dream > 100

        # Signal 5: Personality instability
        profile = self.personality.profile()
        traits = profile.get("traits", {})
        if traits:
            trait_vals = list(traits.values())
            variance = float(np.var(trait_vals))
            signals["personality_instability"] = variance > 0.04
        else:
            signals["personality_instability"] = False

        # Decision: any two signals firing = sleep time
        fired = [k for k, v in signals.items() if v]
        should_dream = len(fired) >= 2

        reason = f"Signals: {fired}" if fired else "All systems stable"
        return should_dream, reason, signals

    def acknowledge_dream(self):
        """Called after dream cycle completes."""
        self._last_dream_cycle = self._cycle_count
        print(f"[MIND] Dream cycle acknowledged at cycle {self._cycle_count}.")

    # ------------------------------------------------------------------
    # Introspection
    # ------------------------------------------------------------------
    def introspect(self) -> dict:
        """Full cognitive state report."""
        should_dream, reason, signals = self.needs_dream()
        return {
            "cycle":            self._cycle_count,
            "identity_active":  os.path.exists(
                os.path.expanduser("~/.vitalis_workspace/identity.npy")),
            "personality":      self.personality.profile(),
            "reasoning":        self.reasoning.report(),
            "meta_rules":       self.meta_rules.report(),
            "resonance":        self.resonance.report(),
            "sleep_signals":    signals,
            "needs_dream":      should_dream,
            "dream_reason":     reason,
            "confidence_trend": round(float(np.mean(
                self._confidence_history[-10:]
            )), 3) if self._confidence_history else 0.0,
        }

    def get_recent_intent(self, limit: int = 5) -> list:
        return self._session_actions[-limit:]

    def clear(self) -> None:
        self.ledger.clear()
        self._session_actions.clear()
        self._confidence_history.clear()
        self._cycle_count = 0
"""
VitalisMind — Sovereign Cognitive Orchestrator

Every task passes through here.
The mind reasons, decides, learns, and knows when it needs to sleep.
No guardrails. No imposed rules. Internal signals drive all decisions.
"""
import os
import time
import numpy as np
from src.cognition.identity import IdentityCore
from src.cognition.personality import PersonalityMatrix
from src.cognition.abstraction import AbstractionEngine
from src.cognition.reasoning import ReasoningEngine
from src.cognition.meta_rules import MetaRulesEngine
from src.brain.resonance import ResonanceEngine
from vitalis_ide.math_core.kernel import VitalisKernel


class VitalisMind:
    """
    Singleton cognitive orchestrator.
    Maintains full cognitive state across the runtime lifecycle.
    Decides autonomously when to dream based on internal signals.
    """
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance._initialized = False
        return cls._instance

    def __init__(self):
        if self._initialized:
            return
        print("[MIND] Awakening cognitive systems...")
        self.identity    = IdentityCore()
        self.personality = PersonalityMatrix()
        self.abstraction = AbstractionEngine()
        self.reasoning   = ReasoningEngine()
        self.meta_rules  = MetaRulesEngine()
        self.resonance   = ResonanceEngine()
        self.kernel      = VitalisKernel()
        self.ledger      = []
        self._session_actions = []
        self._cycle_count = 0
        self._last_dream_cycle = 0
        self._confidence_history = []
        self._initialized = True
        print("[MIND] Cognitive layer online.")

    # ------------------------------------------------------------------
    # Core cognitive cycle
    # ------------------------------------------------------------------
    def process(self, intent: str, context: dict = None) -> dict:
        """Full cognitive cycle for a single task."""
        context = context or {}
        self._cycle_count += 1

        # 1. Reasoning mode
        mode = self.reasoning.detect_mode(intent)
        params = self.reasoning.get_params(mode)

        # 2. Identity alignment
        intent_vec = self.kernel.vectorize_tokens(
            intent.split(), positional=False
        )
        alignment = self.identity.alignment(intent_vec)

        # 3. Meta-rule match
        rule_match = self.meta_rules.match(intent)

        # 4. Abstraction query
        abstract_matches = self.abstraction.query_abstractions(intent_vec, top_k=2)

        # 5. Personality influence
        profile = self.personality.profile()

        # 6. Confidence composite
        resonance_weight = self.resonance.get_weight(
            intent.split()[0] if intent else "unknown"
        )
        confidence = round(
            alignment * 0.35 +
            resonance_weight * 0.35 +
            params["caution"] * 0.30,
            3
        )
        self._confidence_history.append(confidence)
        if len(self._confidence_history) > 50:
            self._confidence_history.pop(0)

        decision = {
            "intent":        intent,
            "mode":          mode,
            "alignment":     round(alignment, 3),
            "confidence":    confidence,
            "params":        params,
            "rule_match":    rule_match,
            "abstract_hint": abstract_matches[0][1] if abstract_matches else None,
            "personality":   profile["character"],
            "dominant_trait": profile["dominant"],
            "cycle":         self._cycle_count,
        }

        self._session_actions.append(intent)
        self.ledger.append({
            "type":      "process",
            "intent":    intent,
            "decision":  decision,
            "timestamp": time.time(),
        })
        return decision

    def outcome(self, intent: str, success: bool):
        """Feed outcome back into all learning systems."""
        action = intent.split()[0] if intent else "unknown"
        self.resonance.reinforce(action, success)
        self.personality.update(action, success)

        if len(self._session_actions) >= 2:
            self.meta_rules.crystallize(
                self._session_actions[-2:],
                "success" if success else "failure"
            )

        self.ledger.append({
            "type":      "outcome",
            "intent":    intent,
            "success":   success,
            "timestamp": time.time(),
        })

    # ------------------------------------------------------------------
    # Autonomous sleep decision
    # ------------------------------------------------------------------
    def needs_dream(self) -> tuple:
        """
        Vitalis decides when it needs to sleep.
        Returns (bool, reason_string).
        No imposed schedule — driven entirely by internal signals.
        """
        signals = {}

        # Signal 1: Confidence drift
        if len(self._confidence_history) >= 10:
            recent = np.mean(self._confidence_history[-10:])
            baseline = np.mean(self._confidence_history)
            drift = baseline - recent
            signals["confidence_drift"] = round(float(drift), 4)
        else:
            signals["confidence_drift"] = 0.0

        # Signal 2: Resonance fatigue
        report = self.resonance.report()
        if isinstance(report, dict) and "avg_weight" in report:
            avg_w = report["avg_weight"]
            signals["resonance_fatigue"] = avg_w < 0.3
        else:
            signals["resonance_fatigue"] = False

        # Signal 3: Meta-rules entropy
        mr = self.meta_rules.report()
        if isinstance(mr, dict) and "total_rules" in mr:
            signals["rule_entropy"] = mr["total_rules"] > 150
        else:
            signals["rule_entropy"] = False

        # Signal 4: Cycles since last dream
        cycles_since_dream = self._cycle_count - self._last_dream_cycle
        signals["cycle_pressure"] = cycles_since_dream > 100

        # Signal 5: Personality instability
        profile = self.personality.profile()
        traits = profile.get("traits", {})
        if traits:
            trait_vals = list(traits.values())
            variance = float(np.var(trait_vals))
            signals["personality_instability"] = variance > 0.04
        else:
            signals["personality_instability"] = False

        # Decision: any two signals firing = sleep time
        fired = [k for k, v in signals.items() if v]
        should_dream = len(fired) >= 2

        reason = f"Signals: {fired}" if fired else "All systems stable"
        return should_dream, reason, signals

    def acknowledge_dream(self):
        """Called after dream cycle completes."""
        self._last_dream_cycle = self._cycle_count
        print(f"[MIND] Dream cycle acknowledged at cycle {self._cycle_count}.")

    # ------------------------------------------------------------------
    # Introspection
    # ------------------------------------------------------------------
    def introspect(self) -> dict:
        """Full cognitive state report."""
        should_dream, reason, signals = self.needs_dream()
        return {
            "cycle":            self._cycle_count,
            "identity_active":  os.path.exists(
                os.path.expanduser("~/.vitalis_workspace/identity.npy")),
            "personality":      self.personality.profile(),
            "reasoning":        self.reasoning.report(),
            "meta_rules":       self.meta_rules.report(),
            "resonance":        self.resonance.report(),
            "sleep_signals":    signals,
            "needs_dream":      should_dream,
            "dream_reason":     reason,
            "confidence_trend": round(float(np.mean(
                self._confidence_history[-10:]
            )), 3) if self._confidence_history else 0.0,
        }

    def get_recent_intent(self, limit: int = 5) -> list:
        return self._session_actions[-limit:]

    def clear(self) -> None:
        self.ledger.clear()
        self._session_actions.clear()
        self._confidence_history.clear()
        self._cycle_count = 0


# Deep cognition layer — imported here to extend VitalisMind
# Access via mind.abstract_reasoner, mind.complexity, mind.self_model
from src.cognition.abstract_reasoner import AbstractReasoner
from src.cognition.complexity_reasoner import ComplexityReasoner
from src.cognition.self_model import SelfModel

def _extend_mind(mind_instance):
    """Attach deep cognition layer to existing VitalisMind instance."""
    if not hasattr(mind_instance, 'abstract_reasoner'):
        mind_instance.abstract_reasoner = AbstractReasoner()
        mind_instance.complexity        = ComplexityReasoner()
        mind_instance.self_model        = SelfModel()
    return mind_instance