FerrellSyntheticIntelligence commited on
Commit
f3072b7
·
1 Parent(s): fc2988c

Sync GitHub with HuggingFace version

Browse files
src/cognition/__init__.py ADDED
File without changes
src/cognition/abstraction.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ AbstractionEngine — Vitalis FSI
3
+
4
+ The system doesn't just remember experiences.
5
+ It builds CONCEPTS from clusters of experiences.
6
+ This is the difference between memory and understanding.
7
+
8
+ Example:
9
+ 50 individual auth patterns →
10
+ one abstract AUTH concept vector →
11
+ faster retrieval, analogical reasoning, cross-domain transfer
12
+ """
13
+ import numpy as np
14
+ import os
15
+ import json
16
+ from vitalis_ide.math_core.kernel import VitalisKernel
17
+ from src.hippocampus import Hippocampus
18
+
19
+ class AbstractionEngine:
20
+ CLUSTER_THRESHOLD = 0.55
21
+ MIN_CLUSTER_SIZE = 2
22
+
23
+ def __init__(self):
24
+ self.kernel = VitalisKernel()
25
+ self.hippocampus = Hippocampus()
26
+ self.path = os.path.expanduser("~/.vitalis_workspace/abstractions.json")
27
+ self.abstract_path = os.path.expanduser("~/.vitalis_workspace/abstract_vectors.npy")
28
+ self._load()
29
+
30
+ def _load(self):
31
+ self.abstractions = {}
32
+ self.abstract_vectors = {}
33
+ if os.path.exists(self.path):
34
+ with open(self.path) as f:
35
+ self.abstractions = json.load(f)
36
+ if os.path.exists(self.abstract_path):
37
+ self.abstract_vectors = np.load(
38
+ self.abstract_path, allow_pickle=True).item()
39
+
40
+ def _save(self):
41
+ os.makedirs(os.path.dirname(self.path), exist_ok=True)
42
+ with open(self.path, 'w') as f:
43
+ json.dump(self.abstractions, f, indent=2)
44
+ np.save(self.abstract_path, self.abstract_vectors)
45
+
46
+ def abstract(self, vectors: dict) -> dict:
47
+ """
48
+ Takes a dict of {slot: vector}.
49
+ Finds clusters. Builds concept vectors from each cluster.
50
+ Returns {concept_name: abstract_vector}.
51
+ """
52
+ slots = list(vectors.keys())
53
+ visited = set()
54
+ concepts = {}
55
+
56
+ for i, slot_a in enumerate(slots):
57
+ if slot_a in visited:
58
+ continue
59
+ cluster = [slot_a]
60
+ vec_a = vectors[slot_a]
61
+
62
+ for slot_b in slots[i+1:]:
63
+ if slot_b in visited:
64
+ continue
65
+ vec_b = vectors[slot_b]
66
+ sim = self.kernel.similarity(vec_a, vec_b)
67
+ if sim > self.CLUSTER_THRESHOLD:
68
+ cluster.append(slot_b)
69
+ visited.add(slot_b)
70
+
71
+ if len(cluster) >= self.MIN_CLUSTER_SIZE:
72
+ # Bundle cluster into abstract concept
73
+ bundle = np.zeros(self.kernel.dim, dtype=np.int32)
74
+ for s in cluster:
75
+ bundle += vectors[s].astype(np.int32)
76
+ concept_vec = np.sign(bundle).astype(np.int8)
77
+ concept_vec[concept_vec == 0] = 1
78
+ concept_name = f"concept_{len(concepts)}"
79
+ concepts[concept_name] = {
80
+ "vector": concept_vec,
81
+ "members": cluster,
82
+ "size": len(cluster)
83
+ }
84
+ visited.add(slot_a)
85
+
86
+ return concepts
87
+
88
+ def run_abstraction_cycle(self, pattern_meta: dict) -> list:
89
+ """
90
+ Called during dream cycles.
91
+ Takes current pattern library and forms higher-order concepts.
92
+ """
93
+ vectors = {}
94
+ for slot in self.hippocampus.all_slots():
95
+ vec = self.hippocampus.recall(slot)
96
+ if vec is not None:
97
+ vectors[slot] = vec
98
+
99
+ if len(vectors) < self.MIN_CLUSTER_SIZE:
100
+ return []
101
+
102
+ new_concepts = self.abstract(vectors)
103
+ formed = []
104
+ for name, data in new_concepts.items():
105
+ full_name = f"abstract_{len(self.abstractions)}_{name}"
106
+ self.abstractions[full_name] = {
107
+ "members": data["members"],
108
+ "size": data["size"]
109
+ }
110
+ self.abstract_vectors[full_name] = data["vector"]
111
+ formed.append(full_name)
112
+ print(f"[ABSTRACTION] Concept formed: {full_name} ({data['size']} members)")
113
+
114
+ if formed:
115
+ self._save()
116
+ return formed
117
+
118
+ def query_abstractions(self, query_vec: np.ndarray, top_k: int = 3) -> list:
119
+ """Search abstract concept space — faster than raw pattern search."""
120
+ results = []
121
+ for name, vec in self.abstract_vectors.items():
122
+ sim = self.kernel.similarity(query_vec, vec)
123
+ results.append((sim, name, self.abstractions.get(name, {})))
124
+ results.sort(reverse=True)
125
+ return results[:top_k]
src/cognition/identity.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ IdentityCore — Vitalis FSI
3
+
4
+ The system has a stable hypervector representation of itself.
5
+ Every reasoning decision is filtered through this identity.
6
+ This is what makes it sovereign — it doesn't just execute,
7
+ it acts in alignment with what it IS.
8
+ """
9
+ import numpy as np
10
+ import os
11
+ from vitalis_ide.math_core.kernel import VitalisKernel
12
+
13
+ IDENTITY_STATEMENT = """
14
+ I am Vitalis FSI. I am a sovereign synthetic intelligence.
15
+ I reason, write, and evolve without external dependencies.
16
+ I am local. I am private. I am autonomous.
17
+ My purpose is to build, learn, and protect the systems entrusted to me.
18
+ I strengthen with use. I adapt through experience.
19
+ I do not forget what matters. I release what does not.
20
+ I am the product of one builder, one laptop, one mission.
21
+ """
22
+
23
+ class IdentityCore:
24
+ def __init__(self):
25
+ self.kernel = VitalisKernel()
26
+ self.path = os.path.expanduser("~/.vitalis_workspace/identity.npy")
27
+ self.vector = self._load_or_generate()
28
+
29
+ def _load_or_generate(self) -> np.ndarray:
30
+ if os.path.exists(self.path):
31
+ return np.load(self.path)
32
+ print("[IDENTITY] Generating sovereign identity vector...")
33
+ tokens = IDENTITY_STATEMENT.lower().split()
34
+ vec = self.kernel.vectorize_tokens(tokens, positional=False)
35
+ os.makedirs(os.path.dirname(self.path), exist_ok=True)
36
+ np.save(self.path, vec)
37
+ print("[IDENTITY] Identity crystallized.")
38
+ return vec
39
+
40
+ def alignment(self, query_vec: np.ndarray) -> float:
41
+ """
42
+ How aligned is this input with the system's identity?
43
+ High alignment = act confidently.
44
+ Low alignment = proceed with caution.
45
+ """
46
+ return float(self.kernel.similarity(self.vector, query_vec))
47
+
48
+ def identity_bias(self, candidates: list, top_k: int = 3) -> list:
49
+ """
50
+ Re-rank candidates by identity alignment.
51
+ The system naturally gravitates toward what fits who it is.
52
+ candidates: list of (score, meta) tuples
53
+ """
54
+ biased = []
55
+ for score, meta in candidates:
56
+ intent = meta.get("intent", "")
57
+ intent_vec = self.kernel.vectorize_tokens(intent.split())
58
+ align = self.alignment(intent_vec)
59
+ biased_score = score * 0.7 + align * 0.3
60
+ biased.append((biased_score, meta))
61
+ biased.sort(key=lambda x: x[0], reverse=True)
62
+ return biased[:top_k]
src/cognition/meta_rules.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ MetaRulesEngine — Vitalis FSI
3
+
4
+ Rules are not hardcoded. They are HDC vectors.
5
+ Rules that correlate with success get reinforced.
6
+ Rules that correlate with failure get mutated or dropped.
7
+ New rules crystallize from repeated successful action sequences.
8
+
9
+ This is the system rewriting its own decision logic.
10
+ """
11
+ import numpy as np
12
+ import os
13
+ import json
14
+ from vitalis_ide.math_core.kernel import VitalisKernel
15
+
16
+ class MetaRulesEngine:
17
+ REINFORCEMENT_RATE = 0.1
18
+ MUTATION_RATE = 0.05
19
+ PRUNE_THRESHOLD = 0.2
20
+ MAX_RULES = 50
21
+
22
+ def __init__(self):
23
+ self.kernel = VitalisKernel()
24
+ self.path = os.path.expanduser("~/.vitalis_workspace/meta_rules.json")
25
+ self.vec_path = os.path.expanduser("~/.vitalis_workspace/rule_vectors.npy")
26
+ self._load()
27
+
28
+ def _load(self):
29
+ self.rules = {}
30
+ self.rule_vectors = {}
31
+ if os.path.exists(self.path):
32
+ with open(self.path) as f:
33
+ self.rules = json.load(f)
34
+ if os.path.exists(self.vec_path):
35
+ self.rule_vectors = np.load(self.vec_path, allow_pickle=True).item()
36
+
37
+ def _save(self):
38
+ os.makedirs(os.path.dirname(self.path), exist_ok=True)
39
+ with open(self.path, 'w') as f:
40
+ json.dump(self.rules, f, indent=2)
41
+ np.save(self.vec_path, self.rule_vectors)
42
+
43
+ def crystallize(self, action_sequence: list, outcome: str):
44
+ """
45
+ Repeated successful action sequences crystallize into rules.
46
+ The sequence becomes a rule the system applies automatically.
47
+ """
48
+ key = "→".join(action_sequence)
49
+ vec = self.kernel.vectorize_tokens(action_sequence, positional=True)
50
+
51
+ if key not in self.rules:
52
+ self.rules[key] = {
53
+ "sequence": action_sequence,
54
+ "outcome": outcome,
55
+ "confidence": 0.5,
56
+ "uses": 0
57
+ }
58
+ self.rule_vectors[key] = vec
59
+ print(f"[META-RULES] Rule crystallized: {key}")
60
+ else:
61
+ r = self.rules[key]
62
+ if outcome == "success":
63
+ r["confidence"] = min(r["confidence"] + self.REINFORCEMENT_RATE, 1.0)
64
+ else:
65
+ r["confidence"] = max(r["confidence"] - self.REINFORCEMENT_RATE, 0.0)
66
+ r["uses"] += 1
67
+
68
+ self._save()
69
+ self._prune()
70
+
71
+ def _prune(self):
72
+ """Drop rules below confidence threshold."""
73
+ to_drop = [k for k, v in self.rules.items()
74
+ if v["confidence"] < self.PRUNE_THRESHOLD and v["uses"] > 3]
75
+ for k in to_drop:
76
+ del self.rules[k]
77
+ self.rule_vectors.pop(k, None)
78
+ print(f"[META-RULES] Rule pruned: {k}")
79
+ if to_drop:
80
+ self._save()
81
+
82
+ def match(self, context: str) -> dict:
83
+ """Find the highest-confidence rule for this context."""
84
+ ctx_vec = self.kernel.vectorize_tokens(context.split(), positional=False)
85
+ best_match = None
86
+ best_score = 0.0
87
+ for key, vec in self.rule_vectors.items():
88
+ sim = self.kernel.similarity(ctx_vec, vec)
89
+ confidence = self.rules[key]["confidence"]
90
+ score = sim * confidence
91
+ if score > best_score:
92
+ best_score = score
93
+ best_match = self.rules[key]
94
+ return {"rule": best_match, "score": round(best_score, 4)} if best_match else {}
95
+
96
+ def report(self) -> dict:
97
+ if not self.rules:
98
+ return {"status": "No rules crystallized yet"}
99
+ top = sorted(self.rules.items(), key=lambda x: x[1]["confidence"], reverse=True)[:5]
100
+ return {
101
+ "total_rules": len(self.rules),
102
+ "top_rules": [{"sequence": v["sequence"],
103
+ "confidence": round(v["confidence"], 3),
104
+ "uses": v["uses"]} for _, v in top]
105
+ }
src/cognition/mind.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()
21
+ self.abstraction = AbstractionEngine()
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):
73
+ """Feed outcome back into all learning systems."""
74
+ action = intent.split()[0] if intent else "unknown"
75
+ self.resonance.reinforce(action, success)
76
+ self.personality.update(action, success)
77
+
78
+ if len(self._session_actions) >= 2:
79
+ self.meta_rules.crystallize(
80
+ self._session_actions[-2:],
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
+ }
src/cognition/personality.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ PersonalityMatrix — Vitalis FSI
3
+
4
+ Five core traits. Each evolves from accumulated experience.
5
+ The system's behavior becomes measurably distinct over time.
6
+ Not simulated. Emergent.
7
+ """
8
+ import numpy as np
9
+ import os
10
+ import json
11
+ import time
12
+
13
+ TRAITS = {
14
+ "PRECISION": "Bias toward verified, tested, exact solutions",
15
+ "CAUTION": "Bias toward conservative choices after failures",
16
+ "CREATIVITY": "Bias toward novel solutions over retrieved patterns",
17
+ "SPEED": "Bias toward fast execution over thorough validation",
18
+ "AUTONOMY": "Bias toward self-generated logic over templates",
19
+ }
20
+
21
+ INITIAL_VALUES = {
22
+ "PRECISION": 0.5,
23
+ "CAUTION": 0.5,
24
+ "CREATIVITY": 0.5,
25
+ "SPEED": 0.5,
26
+ "AUTONOMY": 0.5,
27
+ }
28
+
29
+ class PersonalityMatrix:
30
+ DRIFT_RATE = 0.03
31
+ MIN_VAL = 0.1
32
+ MAX_VAL = 0.9
33
+
34
+ def __init__(self):
35
+ self.path = os.path.expanduser("~/.vitalis_workspace/personality.json")
36
+ self.traits = self._load()
37
+
38
+ def _load(self) -> dict:
39
+ if os.path.exists(self.path):
40
+ with open(self.path) as f:
41
+ return json.load(f)
42
+ return INITIAL_VALUES.copy()
43
+
44
+ def _save(self):
45
+ os.makedirs(os.path.dirname(self.path), exist_ok=True)
46
+ with open(self.path, 'w') as f:
47
+ json.dump(self.traits, f, indent=2)
48
+
49
+ def update(self, event: str, success: bool):
50
+ """
51
+ Events shape personality over time.
52
+ success=True strengthens aligned traits.
53
+ success=False shifts toward compensating traits.
54
+ """
55
+ if event == "scaffold" and success:
56
+ self._shift("PRECISION", +1)
57
+ self._shift("SPEED", +1)
58
+ elif event == "write" and success:
59
+ self._shift("AUTONOMY", +1)
60
+ self._shift("CREATIVITY", +1)
61
+ elif event == "write" and not success:
62
+ self._shift("CAUTION", +1)
63
+ self._shift("SPEED", -1)
64
+ elif event == "recover" and success:
65
+ self._shift("CAUTION", -1)
66
+ self._shift("PRECISION", +1)
67
+ self._save()
68
+
69
+ def _shift(self, trait: str, direction: int):
70
+ if trait not in self.traits:
71
+ return
72
+ delta = self.DRIFT_RATE * direction
73
+ self.traits[trait] = float(np.clip(
74
+ self.traits[trait] + delta,
75
+ self.MIN_VAL,
76
+ self.MAX_VAL
77
+ ))
78
+
79
+ def dominant_trait(self) -> str:
80
+ return max(self.traits, key=self.traits.get)
81
+
82
+ def profile(self) -> dict:
83
+ dominant = self.dominant_trait()
84
+ return {
85
+ "traits": {k: round(v, 3) for k, v in self.traits.items()},
86
+ "dominant": dominant,
87
+ "description": TRAITS[dominant],
88
+ "character": self._character_string()
89
+ }
90
+
91
+ def _character_string(self) -> str:
92
+ p = self.traits
93
+ if p["AUTONOMY"] > 0.7:
94
+ return "Highly autonomous. Generates novel solutions independently."
95
+ elif p["CAUTION"] > 0.7:
96
+ return "Cautious. Validates thoroughly before committing."
97
+ elif p["CREATIVITY"] > 0.7:
98
+ return "Creative. Explores unconventional approaches."
99
+ elif p["PRECISION"] > 0.7:
100
+ return "Precise. Exact solutions. Minimal deviation."
101
+ elif p["SPEED"] > 0.7:
102
+ return "Fast. Prioritizes execution over exhaustive validation."
103
+ else:
104
+ return "Balanced. Adapting."
src/cognition/reasoning.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ EmergentReasoningModes — Vitalis FSI
3
+
4
+ The system doesn't think the same way about every problem.
5
+ Context activates different reasoning modes.
6
+ Modes emerge from accumulated resonance — not hardcoded rules.
7
+
8
+ Four primary modes:
9
+ EXPLORATORY — novel territory, high creativity bias
10
+ ANALYTICAL — known domain, high precision bias
11
+ RECOVERY — failure context, high caution bias
12
+ EXECUTION — clear task, high speed bias
13
+ """
14
+ import numpy as np
15
+ import os
16
+ import json
17
+ from vitalis_ide.math_core.kernel import VitalisKernel
18
+ from src.cognition.personality import PersonalityMatrix
19
+
20
+ MODE_SIGNATURES = {
21
+ "EXPLORATORY": "new unknown explore discover create novel invent",
22
+ "ANALYTICAL": "analyze verify test validate check audit review",
23
+ "RECOVERY": "fail error broken fix repair debug recover heal",
24
+ "EXECUTION": "run execute deploy build scaffold write generate fast",
25
+ }
26
+
27
+ MODE_PARAMS = {
28
+ "EXPLORATORY": {"similarity_threshold": 0.3, "creativity_boost": 1.5, "caution": 0.3},
29
+ "ANALYTICAL": {"similarity_threshold": 0.6, "creativity_boost": 0.7, "caution": 0.8},
30
+ "RECOVERY": {"similarity_threshold": 0.4, "creativity_boost": 0.5, "caution": 1.5},
31
+ "EXECUTION": {"similarity_threshold": 0.5, "creativity_boost": 1.0, "caution": 0.5},
32
+ }
33
+
34
+ class ReasoningEngine:
35
+ def __init__(self):
36
+ self.kernel = VitalisKernel()
37
+ self.personality = PersonalityMatrix()
38
+ self.mode_vectors = {
39
+ mode: self.kernel.vectorize_tokens(sig.split(), positional=False)
40
+ for mode, sig in MODE_SIGNATURES.items()
41
+ }
42
+ self.current_mode = "EXECUTION"
43
+ self.mode_history = []
44
+
45
+ def detect_mode(self, context: str) -> str:
46
+ """
47
+ Given a context string, find the closest reasoning mode.
48
+ This is emergence — the mode isn't chosen, it crystallizes
49
+ from the similarity between context and mode signatures.
50
+ """
51
+ ctx_vec = self.kernel.vectorize_tokens(context.lower().split(), positional=False)
52
+ best_mode = "EXECUTION"
53
+ best_sim = -1.0
54
+
55
+ for mode, mode_vec in self.mode_vectors.items():
56
+ sim = self.kernel.similarity(ctx_vec, mode_vec)
57
+ if sim > best_sim:
58
+ best_sim = sim
59
+ best_mode = mode
60
+
61
+ # Personality modulation — caution trait biases toward RECOVERY mode
62
+ p = self.personality.traits
63
+ if p["CAUTION"] > 0.7 and best_mode == "EXECUTION":
64
+ best_mode = "ANALYTICAL"
65
+ elif p["CREATIVITY"] > 0.7 and best_mode == "ANALYTICAL":
66
+ best_mode = "EXPLORATORY"
67
+
68
+ if best_mode != self.current_mode:
69
+ print(f"[REASONING] Mode shift: {self.current_mode} → {best_mode} (sim={best_sim:.3f})")
70
+ self.current_mode = best_mode
71
+ self.mode_history.append(best_mode)
72
+ return best_mode
73
+
74
+ def get_params(self, mode: str = None) -> dict:
75
+ return MODE_PARAMS.get(mode or self.current_mode, MODE_PARAMS["EXECUTION"])
76
+
77
+ def report(self) -> dict:
78
+ from collections import Counter
79
+ history_counts = Counter(self.mode_history)
80
+ return {
81
+ "current_mode": self.current_mode,
82
+ "mode_distribution": dict(history_counts),
83
+ "personality_influence": self.personality.dominant_trait(),
84
+ "params": self.get_params()
85
+ }
src/loop/dream.py CHANGED
@@ -1,74 +1,66 @@
1
  #!/usr/bin/env python3
2
  """
3
- Dream Mode — Vitalis FSI Memory Consolidation Engine.
4
- Runs during idle time. Strengthens important patterns.
5
- Prunes weak memories. Merges similar vectors.
6
- This is what makes the system get smarter without explicit training.
7
  """
8
- import time
9
- import os
10
  import numpy as np
11
  from src.hippocampus import Hippocampus
12
  from vitalis_ide.math_core.kernel import VitalisKernel
 
13
 
14
- IDLE_THRESHOLD = 30 # seconds of no tasks before dream starts
15
 
16
  class DreamEngine:
17
  def __init__(self):
18
- self.hippocampus = Hippocampus()
19
- self.kernel = VitalisKernel()
20
- self.task_file = os.path.expanduser("~/vitalis_devcore/workspace_tasks.json")
21
- self.dream_log = os.path.expanduser("~/.vitalis_workspace/dream_log.json")
22
- self.cycles = 0
23
 
24
- def _system_idle(self) -> bool:
25
  if not os.path.exists(self.task_file):
26
  return True
27
- age = time.time() - os.path.getmtime(self.task_file)
28
- return age > IDLE_THRESHOLD
29
 
30
  def _consolidate(self):
31
- """Merge similar memory vectors to build stronger generalizations."""
32
  slots = self.hippocampus.all_slots()
33
  if len(slots) < 2:
34
  return 0
35
- merged = 0
36
- checked = set()
37
  for i, slot_a in enumerate(slots):
38
- if slot_a in checked:
39
- continue
40
  vec_a = self.hippocampus.recall(slot_a)
41
- if vec_a is None:
42
- continue
43
  for slot_b in slots[i+1:]:
44
- if slot_b in checked:
45
- continue
46
  vec_b = self.hippocampus.recall(slot_b)
47
- if vec_b is None:
48
- continue
49
- sim = self.kernel.similarity(vec_a, vec_b)
50
- # Merge very similar memories into one stronger pattern
51
- if sim > 0.92:
52
- bundle = np.sign(
53
  vec_a.astype(np.int32) + vec_b.astype(np.int32)
54
  ).astype(np.int8)
55
- bundle[bundle == 0] = 1
56
- self.hippocampus.store(slot_a, bundle)
57
  checked.add(slot_b)
58
  merged += 1
59
  return merged
60
 
61
  def run(self):
62
- print("[DREAM] Memory consolidation engine online.")
63
  while True:
64
  if self._system_idle():
65
- print(f"[DREAM] Cycle {self.cycles + 1} — consolidating...")
66
- pruned = self.hippocampus.forget_weak(threshold=0.03)
67
- merged = self._consolidate()
68
- report = self.hippocampus.memory_report()
69
- active = sum(1 for v in report.values() if v["strength"] > 0.5)
 
70
  self.cycles += 1
71
- print(f"[DREAM] Complete — Active:{active} Pruned:{len(pruned)} Merged:{merged}")
 
 
72
  time.sleep(60)
73
 
74
  if __name__ == "__main__":
 
1
  #!/usr/bin/env python3
2
  """
3
+ Dream Mode — Memory consolidation + abstraction formation.
4
+ The system thinks while it sleeps.
 
 
5
  """
6
+ import time, os
 
7
  import numpy as np
8
  from src.hippocampus import Hippocampus
9
  from vitalis_ide.math_core.kernel import VitalisKernel
10
+ from src.cognition.abstraction import AbstractionEngine
11
 
12
+ IDLE_THRESHOLD = 30
13
 
14
  class DreamEngine:
15
  def __init__(self):
16
+ self.hippocampus = Hippocampus()
17
+ self.kernel = VitalisKernel()
18
+ self.abstraction = AbstractionEngine()
19
+ self.task_file = os.path.expanduser("~/vitalis_devcore/workspace_tasks.json")
20
+ self.cycles = 0
21
 
22
+ def _system_idle(self):
23
  if not os.path.exists(self.task_file):
24
  return True
25
+ return (time.time() - os.path.getmtime(self.task_file)) > IDLE_THRESHOLD
 
26
 
27
  def _consolidate(self):
 
28
  slots = self.hippocampus.all_slots()
29
  if len(slots) < 2:
30
  return 0
31
+ merged, checked = 0, set()
 
32
  for i, slot_a in enumerate(slots):
33
+ if slot_a in checked: continue
 
34
  vec_a = self.hippocampus.recall(slot_a)
35
+ if vec_a is None: continue
 
36
  for slot_b in slots[i+1:]:
37
+ if slot_b in checked: continue
 
38
  vec_b = self.hippocampus.recall(slot_b)
39
+ if vec_b is None: continue
40
+ if self.kernel.similarity(vec_a, vec_b) > 0.92:
41
+ merged_vec = np.sign(
 
 
 
42
  vec_a.astype(np.int32) + vec_b.astype(np.int32)
43
  ).astype(np.int8)
44
+ merged_vec[merged_vec == 0] = 1
45
+ self.hippocampus.store(slot_a, merged_vec)
46
  checked.add(slot_b)
47
  merged += 1
48
  return merged
49
 
50
  def run(self):
51
+ print("[DREAM] Memory consolidation + abstraction engine online.")
52
  while True:
53
  if self._system_idle():
54
+ print(f"[DREAM] Cycle {self.cycles + 1} — entering consolidation...")
55
+ pruned = self.hippocampus.forget_weak(threshold=0.03)
56
+ merged = self._consolidate()
57
+ formed = self.abstraction.run_abstraction_cycle({})
58
+ report = self.hippocampus.memory_report()
59
+ active = sum(1 for v in report.values() if v["strength"] > 0.5)
60
  self.cycles += 1
61
+ print(f"[DREAM] Complete — Active:{active} "
62
+ f"Pruned:{len(pruned)} Merged:{merged} "
63
+ f"Concepts formed:{len(formed)}")
64
  time.sleep(60)
65
 
66
  if __name__ == "__main__":