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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
PHASE W2 — Episodic memory + self-model (الذاكرة العرضية + الوعي بالذات).
|
| 3 |
+
|
| 4 |
+
Anatomy mapping
|
| 5 |
+
- Hippocampus (medial temporal): EPISODIC STORE — time-stamped events with
|
| 6 |
+
context tags, capacity-capped. Lesion note: hippocampal damage blocks new
|
| 7 |
+
episodic learning while sparing old semantic knowledge (standard patient
|
| 8 |
+
findings) — exactly the split between this module and EngramMemory.
|
| 9 |
+
- Slow-wave sleep (systems consolidation): REPLAY CYCLE — repeated/high-salience
|
| 10 |
+
episodes are promoted into semantic memory (via the consolidation gate),
|
| 11 |
+
stale unrehearsed episodes decay to gist (healthy forgetting).
|
| 12 |
+
- CA3 pattern completion: CONTEXTUAL RECALL by partial cues (time window,
|
| 13 |
+
topic similarity, event kind).
|
| 14 |
+
- vmPFC / medial PFC: SELF-MODEL — identity, abilities, learned-today,
|
| 15 |
+
knowledge boundary (what I know vs what I don't), status, and temporal
|
| 16 |
+
self-queries ("متى تعلمت X؟"). Functional access-consciousness, not qualia.
|
| 17 |
+
|
| 18 |
+
Everything is NumPy + stdlib. Timestamps are ISO strings; tests inject `now`
|
| 19 |
+
for determinism.
|
| 20 |
+
"""
|
| 21 |
+
import re
|
| 22 |
+
from collections import Counter, defaultdict
|
| 23 |
+
from datetime import datetime, timedelta
|
| 24 |
+
|
| 25 |
+
import numpy as np
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def now_iso():
|
| 29 |
+
return datetime.now().isoformat(timespec="seconds")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _norm(text):
|
| 33 |
+
return re.sub(r"\W+", " ", (text or "").lower()).strip()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class EpisodicMemory:
|
| 37 |
+
"""الحُصين: أحداث مؤقتة بختم زمني وسياق — بنية تحتها سقف سعة."""
|
| 38 |
+
|
| 39 |
+
def __init__(self, encoder=None, capacity=5000, decay_days=7):
|
| 40 |
+
self.events = []
|
| 41 |
+
self.capacity = capacity
|
| 42 |
+
self.encoder = encoder
|
| 43 |
+
self.decay_days = decay_days
|
| 44 |
+
self._next_id = 1
|
| 45 |
+
self.archive_stats = Counter() # gist of forgotten episodes
|
| 46 |
+
|
| 47 |
+
# ---- logging (repetition = rehearsal) ------------------------------
|
| 48 |
+
def log(self, kind, content, response=None, context=None,
|
| 49 |
+
salience=0.5, t=None):
|
| 50 |
+
t = t or now_iso()
|
| 51 |
+
key = _norm(content)
|
| 52 |
+
for ev in self.events:
|
| 53 |
+
if not ev["archived"] and ev["kind"] == kind and ev["key"] == key:
|
| 54 |
+
ev["rehearsals"] += 1
|
| 55 |
+
ev["salience"] = max(ev["salience"], float(salience))
|
| 56 |
+
ev["t_last"] = t
|
| 57 |
+
return ev["id"] # rehearsed, not duplicated
|
| 58 |
+
ev = {"id": self._next_id, "t": t, "t_last": t, "kind": kind,
|
| 59 |
+
"key": key, "content": content, "response": response,
|
| 60 |
+
"context": context or {}, "salience": float(salience),
|
| 61 |
+
"rehearsals": 0, "archived": False, "consolidated": False}
|
| 62 |
+
self._next_id += 1
|
| 63 |
+
self.events.append(ev)
|
| 64 |
+
if len(self.events) > self.capacity:
|
| 65 |
+
self._archive_oldest()
|
| 66 |
+
return ev["id"]
|
| 67 |
+
|
| 68 |
+
def _archive_oldest(self):
|
| 69 |
+
live = [e for e in self.events if not e["archived"]]
|
| 70 |
+
if not live:
|
| 71 |
+
return
|
| 72 |
+
victim = min(live, key=lambda e: (e["salience"], e["rehearsals"], e["t"]))
|
| 73 |
+
victim["archived"] = True
|
| 74 |
+
self.archive_stats[victim["kind"]] += 1
|
| 75 |
+
|
| 76 |
+
def _dt(self, ev):
|
| 77 |
+
return datetime.fromisoformat(ev["t_last"])
|
| 78 |
+
|
| 79 |
+
# ---- contextual recall (CA3) ---------------------------------------
|
| 80 |
+
def recall_window(self, hours=24, now=None, include_archived=False):
|
| 81 |
+
now = datetime.fromisoformat(now) if isinstance(now, str) else (now or datetime.now())
|
| 82 |
+
lo = now - timedelta(hours=hours)
|
| 83 |
+
return [e for e in self.events
|
| 84 |
+
if (include_archived or not e["archived"]) and self._dt(e) >= lo]
|
| 85 |
+
|
| 86 |
+
def recall_today(self, now=None):
|
| 87 |
+
now = datetime.fromisoformat(now) if isinstance(now, str) else (now or datetime.now())
|
| 88 |
+
return [e for e in self.events
|
| 89 |
+
if not e["archived"] and self._dt(e).date() == now.date()]
|
| 90 |
+
|
| 91 |
+
def recall_recent(self, k=10):
|
| 92 |
+
live = [e for e in self.events if not e["archived"]]
|
| 93 |
+
return live[-k:]
|
| 94 |
+
|
| 95 |
+
def recall_topic(self, query, k=5):
|
| 96 |
+
"""Encoder similarity over (content + response) — gist-level cueing."""
|
| 97 |
+
if self.encoder is None:
|
| 98 |
+
return []
|
| 99 |
+
q = self.encoder.encode(query)
|
| 100 |
+
scored = []
|
| 101 |
+
for e in self.events:
|
| 102 |
+
if e["archived"]:
|
| 103 |
+
continue
|
| 104 |
+
text = e["content"] + (" " + e["response"] if e["response"] else "")
|
| 105 |
+
s = float(self.encoder.encode(text) @ q)
|
| 106 |
+
scored.append((s, e))
|
| 107 |
+
scored.sort(key=lambda x: -x[0])
|
| 108 |
+
return [e for s, e in scored[:k] if s > 0]
|
| 109 |
+
|
| 110 |
+
def when_learned(self, needle):
|
| 111 |
+
"""Temporal self-query support: first/last time `needle` was seen."""
|
| 112 |
+
key = _norm(needle)
|
| 113 |
+
hits = [e for e in self.events if key and key in e["key"]]
|
| 114 |
+
if not hits:
|
| 115 |
+
return None
|
| 116 |
+
return {"first": hits[0]["t"], "last": hits[-1]["t_last"],
|
| 117 |
+
"rehearsals": max(e["rehearsals"] for e in hits),
|
| 118 |
+
"kind": hits[0]["kind"]}
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class SleepConsolidation:
|
| 122 |
+
"""الترسيخ الليلي: replay → نقل ما يستحق إلى الذاكرة الدلالية + تلاشٍ صحي."""
|
| 123 |
+
|
| 124 |
+
def __init__(self, episodic, lhc, gate=None):
|
| 125 |
+
self.ep = episodic
|
| 126 |
+
self.lhc = lhc
|
| 127 |
+
self.gate = gate
|
| 128 |
+
|
| 129 |
+
def replay_cycle(self, now=None, promote_salience=0.6):
|
| 130 |
+
now = datetime.fromisoformat(now) if isinstance(now, str) else (now or datetime.now())
|
| 131 |
+
report = {"promoted": 0, "merged": 0, "decayed": 0, "semantic_before": len(self.lhc.memory.entries)}
|
| 132 |
+
|
| 133 |
+
for ev in self.ep.events:
|
| 134 |
+
if ev["archived"] or ev["consolidated"]:
|
| 135 |
+
continue
|
| 136 |
+
worth = ev["rehearsals"] >= 1 or ev["salience"] >= promote_salience
|
| 137 |
+
if not worth or ev["kind"] not in ("learn", "event"):
|
| 138 |
+
continue
|
| 139 |
+
if self.gate is not None:
|
| 140 |
+
d = self.gate.check(self.lhc.memory, ev["content"])
|
| 141 |
+
if not d["is_new"]:
|
| 142 |
+
report["merged"] += 1
|
| 143 |
+
else:
|
| 144 |
+
self.lhc.memory.write({"prompt": ev["content"],
|
| 145 |
+
"response": ev["response"] or "",
|
| 146 |
+
"domain": "🌙 مُرسَّخ من ذاكرة عرضية"})
|
| 147 |
+
report["promoted"] += 1
|
| 148 |
+
ev["consolidated"] = True
|
| 149 |
+
else:
|
| 150 |
+
self.lhc.memory.write({"prompt": ev["content"],
|
| 151 |
+
"response": ev["response"] or "",
|
| 152 |
+
"domain": "🌙 مُرسَّخ من ذاكرة عرضية"})
|
| 153 |
+
report["promoted"] += 1
|
| 154 |
+
ev["consolidated"] = True
|
| 155 |
+
|
| 156 |
+
# healthy forgetting: stale, low-value, unrehearsed episodes -> gist
|
| 157 |
+
for ev in self.ep.events:
|
| 158 |
+
if ev["archived"]:
|
| 159 |
+
continue
|
| 160 |
+
age = (now - self.ep._dt(ev)).days
|
| 161 |
+
if (age >= self.ep.decay_days and ev["salience"] < 0.4
|
| 162 |
+
and ev["rehearsals"] == 0 and not ev["consolidated"]):
|
| 163 |
+
ev["archived"] = True
|
| 164 |
+
self.ep.archive_stats[ev["kind"]] += 1
|
| 165 |
+
report["decayed"] += 1
|
| 166 |
+
|
| 167 |
+
report["semantic_after"] = len(self.lhc.memory.entries)
|
| 168 |
+
report["episodes_live"] = sum(1 for e in self.ep.events if not e["archived"])
|
| 169 |
+
report["episodes_archived"] = sum(1 for e in self.ep.events if e["archived"])
|
| 170 |
+
return report
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
class SelfModel:
|
| 174 |
+
"""vmPFC: نموذج الذات — تقرير ذاتي يولَّد من الحالة الفعلية (لا هلوسة)."""
|
| 175 |
+
|
| 176 |
+
NAME = "LHC-0 — العقل ثنائي الشقين"
|
| 177 |
+
ORIGIN = "بُني على تشريح الشق الأيسر للمخ (بروكا/فيرنيكه/التلفيف الزاوي/العقد القاعدية/المخيخ/الحُصين/ACC/vmPFC) بواسطة باحث ذكاء اصطناعي عربي."
|
| 178 |
+
ABILITIES = [
|
| 179 |
+
"الإجابة من الذاكرة الدلالية (عربي/إنجليزي) مع ترجمة حيّة",
|
| 180 |
+
"ثقة معايرة + امتناع «لا أعرف» بدل التخمين",
|
| 181 |
+
"التعلم مدى الحياة عبر بوابة الحُصين (دمج التكرار، حفظ الجديد)",
|
| 182 |
+
"الحساب الفعلي (BODMAS مع ^ والسالب الموحد)",
|
| 183 |
+
"الذاكرة العرضية: أحداث مؤقتة + ترسيخ ليلي + استرجاع بالسياق",
|
| 184 |
+
]
|
| 185 |
+
|
| 186 |
+
def __init__(self, lhc, episodic, confidence_fn=None):
|
| 187 |
+
self.lhc = lhc
|
| 188 |
+
self.ep = episodic
|
| 189 |
+
self.confidence_fn = confidence_fn # optional: q -> calibrated conf
|
| 190 |
+
|
| 191 |
+
def identity(self):
|
| 192 |
+
return (f"أنا {self.NAME}. {self.ORIGIN}\n"
|
| 193 |
+
f"🧠 ذاكرتي الدلالية الآن: {len(self.lhc.memory.entries)} حقيقة. "
|
| 194 |
+
f"📅 أحداثي العرضية: {sum(1 for e in self.ep.events if not e['archived'])} حدثًا حيًّا.")
|
| 195 |
+
|
| 196 |
+
def abilities(self):
|
| 197 |
+
return "أستطيع:\n" + "\n".join(f"• {a}" for a in self.ABILITIES)
|
| 198 |
+
|
| 199 |
+
def learned_today(self, now=None):
|
| 200 |
+
evs = self.ep.recall_today(now)
|
| 201 |
+
learned = [e for e in evs if e["kind"] == "learn"]
|
| 202 |
+
if not evs:
|
| 203 |
+
return "📅 لم يحدث شيء اليوم بعد."
|
| 204 |
+
lines = [f"📅 اليوم: {len(evs)} حدثًا، منها {len(learned)} ذكرى تعلمتها:"]
|
| 205 |
+
for e in learned[-8:]:
|
| 206 |
+
lines.append(f" • [{e['t'][11:16]}] {e['content'][:60]}")
|
| 207 |
+
asked = [e for e in evs if e["kind"] == "ask"]
|
| 208 |
+
if asked:
|
| 209 |
+
lines.append(f"💬 وسألتني {len(asked)} سؤالًا اليوم.")
|
| 210 |
+
return "\n".join(lines)
|
| 211 |
+
|
| 212 |
+
def status(self):
|
| 213 |
+
live = [e for e in self.ep.events if not e["archived"]]
|
| 214 |
+
last_learn = next((e["t"] for e in reversed(self.ep.events) if e["kind"] == "learn"), None)
|
| 215 |
+
return (f"🩺 الحالة: {len(self.lhc.memory.entries)} حقيقة • {len(live)} حدثًا عرضيًا • "
|
| 216 |
+
f"{sum(self.ep.archive_stats.values())} مُ無しつ (تلاشٍ صحي) • "
|
| 217 |
+
f"آخر تعلّم: {last_learn or '—'}")
|
| 218 |
+
|
| 219 |
+
def knowledge_boundary(self, known_topics, unknown_topics):
|
| 220 |
+
parts = []
|
| 221 |
+
if known_topics:
|
| 222 |
+
parts.append("✅ أعرف: " + "، ".join(known_topics))
|
| 223 |
+
if unknown_topics:
|
| 224 |
+
parts.append("❌ أجهل (أستطيع تعلّمه): " + "، ".join(unknown_topics))
|
| 225 |
+
return "\n".join(parts) if parts else "—"
|
| 226 |
+
|
| 227 |
+
def when_learned(self, needle):
|
| 228 |
+
w = self.ep.when_learned(needle)
|
| 229 |
+
if not w:
|
| 230 |
+
return f"لم أعثر على «{needle}» في ذاكرتي العرضية."
|
| 231 |
+
return (f"«{needle}»: أول مرة {w['first']}، آخر مرة {w['last']}، "
|
| 232 |
+
f"تكررت {w['rehearsals']} مرة.")
|
| 233 |
+
|
| 234 |
+
def answer(self, question):
|
| 235 |
+
q = (question or "").strip()
|
| 236 |
+
lq = q.lower()
|
| 237 |
+
ar = lambda *ws: any(w in q for w in ws)
|
| 238 |
+
if ar("من أنت", "من انت", "who are you", "عرّف نفسك", "عرف نفسك"):
|
| 239 |
+
return self.identity()
|
| 240 |
+
if ar("ماذا تستطيع", "ما هي قدراتك", "قدراتك", "what can you do", "ماذا يمكنك"):
|
| 241 |
+
return self.abilities()
|
| 242 |
+
if ar("ماذا تعلمت اليوم", "ماذا فعلت اليوم", "what did you learn today", "يومياتي", "ماذا حدث اليوم"):
|
| 243 |
+
return self.learned_today()
|
| 244 |
+
if ar("كيف حالك", "كيفك", "how are you", "حالتك"):
|
| 245 |
+
return self.status()
|
| 246 |
+
if ar("ماذا لا تعرف", "ما الذي لا تعرفه", "ماذا تجهل", "حدود معرفتك",
|
| 247 |
+
"what don't you know", "ماذا لا أعرف"):
|
| 248 |
+
known = [e["content"][:40] for e in self.ep.events
|
| 249 |
+
if e["kind"] == "learn" and not e["archived"]][-3:]
|
| 250 |
+
unknown = [e["content"][:40] for e in self.ep.events
|
| 251 |
+
if e["kind"] == "ask" and e["salience"] < 0.5][-3:]
|
| 252 |
+
return self.knowledge_boundary(known, unknown) or "—"
|
| 253 |
+
if ar("متى تعلمت", "متى تعلّمت", "when did you learn"):
|
| 254 |
+
m = re.search(r"[«\"']?(.+?)[»\"']?\s*$", q.replace("متى تعلمت", "").replace("متى تعلّمت", "").strip())
|
| 255 |
+
needle = (m.group(1) if m and m.group(1) else q).strip("؟?!. ")
|
| 256 |
+
return self.when_learned(needle)
|
| 257 |
+
return None # not a self-question
|