Paritosh Upadhyay commited on
Commit ·
64cc56e
1
Parent(s): c4a2296
Neural Core Maturation: Self-Evolution Initiated
Browse files
backend/app/scratch/subconscious_loop.py
CHANGED
|
@@ -17,6 +17,7 @@ sys.path.append(os.path.join(os.getcwd(), "backend"))
|
|
| 17 |
from app.core import database
|
| 18 |
from app.models import entities
|
| 19 |
from app.services import holocron, memory, state
|
|
|
|
| 20 |
from app.services.tools import macos
|
| 21 |
|
| 22 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s | SUBCONSCIOUS | %(message)s")
|
|
@@ -280,8 +281,45 @@ def subconscious_cycle():
|
|
| 280 |
# Reset lock log timer
|
| 281 |
last_lock_log = 0
|
| 282 |
|
|
|
|
| 283 |
try:
|
| 284 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 285 |
with database.SessionLocal() as db:
|
| 286 |
pending = db.query(entities.LearningTarget).filter_by(status="pending").count()
|
| 287 |
logger.info(f"Pulse complete. Universal Queue Depth: {pending} targets remaining.")
|
|
@@ -300,9 +338,16 @@ def subconscious_cycle():
|
|
| 300 |
except Exception as e:
|
| 301 |
logger.error(f"Internal Pulse Error: {e}")
|
| 302 |
time.sleep(30)
|
|
|
|
|
|
|
|
|
|
| 303 |
except Exception as e:
|
| 304 |
-
logger.error(f"FATAL Heartbeat Failure: {e}.
|
| 305 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 306 |
|
| 307 |
if __name__ == "__main__":
|
| 308 |
# Start the web server in a separate thread (Hugging Face port is 7860)
|
|
|
|
| 17 |
from app.core import database
|
| 18 |
from app.models import entities
|
| 19 |
from app.services import holocron, memory, state
|
| 20 |
+
from sqlalchemy import text
|
| 21 |
from app.services.tools import macos
|
| 22 |
|
| 23 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s | SUBCONSCIOUS | %(message)s")
|
|
|
|
| 281 |
# Reset lock log timer
|
| 282 |
last_lock_log = 0
|
| 283 |
|
| 284 |
+
# ── PURGE PROTOCOL: Sovereign Cleanup ──
|
| 285 |
try:
|
| 286 |
+
# Every hour or so, perform a maintenance pulse
|
| 287 |
+
now_ts = time.time()
|
| 288 |
+
with database.SessionLocal() as db_check:
|
| 289 |
+
maint_record = db_check.query(entities.KeyValueStore).filter_by(key="last_storage_maint").first()
|
| 290 |
+
last_maint = float(maint_record.value if (maint_record and maint_record.value) else 0)
|
| 291 |
+
|
| 292 |
+
if now_ts - last_maint > 3600:
|
| 293 |
+
logger.info("Purge Protocol: Initiating Tactical Database Compaction (VACUUM)...")
|
| 294 |
+
|
| 295 |
+
# 1. Truncate logs if they exceed 50MB
|
| 296 |
+
log_path = os.path.join(os.getcwd(), "subconscious.log")
|
| 297 |
+
if os.path.exists(log_path) and os.path.getsize(log_path) > 50 * 1024 * 1024:
|
| 298 |
+
with open(log_path, "w") as f: f.write("--- Purge Protocol: Log Truncated ---\n")
|
| 299 |
+
|
| 300 |
+
# 2. Reclaim disk space (Run VACUUM outside of transaction)
|
| 301 |
+
try:
|
| 302 |
+
with database.engine.connect().execution_options(isolation_level="AUTOCOMMIT") as conn:
|
| 303 |
+
conn.execute(text("VACUUM"))
|
| 304 |
+
except Exception as ve:
|
| 305 |
+
logger.warning(f"Purge Protocol: VACUUM skipped or failed: {ve}")
|
| 306 |
+
|
| 307 |
+
# 3. Update maintenance timestamp in a clean session
|
| 308 |
+
with database.SessionLocal() as db_maint:
|
| 309 |
+
m_rec = db_maint.query(entities.KeyValueStore).filter_by(key="last_storage_maint").first()
|
| 310 |
+
if m_rec: m_rec.value = str(now_ts)
|
| 311 |
+
else: db_maint.add(entities.KeyValueStore(key="last_storage_maint", value=str(now_ts), category="system"))
|
| 312 |
+
db_maint.commit()
|
| 313 |
+
|
| 314 |
+
logger.info("Purge Protocol: Compaction Complete / Timestamp Synchronized.")
|
| 315 |
+
except Exception as e:
|
| 316 |
+
logger.error(f"Purge Protocol: Global Maintenance failure: {e}")
|
| 317 |
+
|
| 318 |
+
try:
|
| 319 |
+
# Velocity Pass: Trigger Universal Foraging
|
| 320 |
+
logger.info("Universal Maturation: Pulse Engaging...")
|
| 321 |
+
holocron.batch_mine_priorities()
|
| 322 |
+
|
| 323 |
with database.SessionLocal() as db:
|
| 324 |
pending = db.query(entities.LearningTarget).filter_by(status="pending").count()
|
| 325 |
logger.info(f"Pulse complete. Universal Queue Depth: {pending} targets remaining.")
|
|
|
|
| 338 |
except Exception as e:
|
| 339 |
logger.error(f"Internal Pulse Error: {e}")
|
| 340 |
time.sleep(30)
|
| 341 |
+
while True:
|
| 342 |
+
try:
|
| 343 |
+
subconscious_cycle()
|
| 344 |
except Exception as e:
|
| 345 |
+
logger.error(f"FATAL Heartbeat Failure: {e}. Orchestrating Systematic Reboot in 60s...")
|
| 346 |
+
try:
|
| 347 |
+
with database.SessionLocal() as db_err:
|
| 348 |
+
db_err.rollback()
|
| 349 |
+
except: pass
|
| 350 |
+
time.sleep(60)
|
| 351 |
|
| 352 |
if __name__ == "__main__":
|
| 353 |
# Start the web server in a separate thread (Hugging Face port is 7860)
|
backend/app/services/holocron.py
CHANGED
|
@@ -2,16 +2,17 @@ import logging
|
|
| 2 |
from typing import List, Optional, Dict, Set
|
| 3 |
from sqlalchemy.orm import Session
|
| 4 |
from sqlalchemy import create_engine, text
|
| 5 |
-
from app.models.entities import KnowledgeNode, Relationship, InteractionLog, LearningTarget
|
| 6 |
-
from app.core
|
| 7 |
from app.services import llm
|
| 8 |
import json
|
| 9 |
import asyncio
|
| 10 |
import threading
|
| 11 |
import time
|
|
|
|
|
|
|
| 12 |
from app.services.tools import search
|
| 13 |
from app.services import state_sync, watchdog, state
|
| 14 |
-
import concurrent.futures
|
| 15 |
|
| 16 |
logger = logging.getLogger("friday.holocron")
|
| 17 |
|
|
@@ -41,7 +42,7 @@ def _ensure_pgvector():
|
|
| 41 |
|
| 42 |
def add_knowledge(name: str, category: str, content: str, metadata: Optional[Dict] = None):
|
| 43 |
"""Adds or updates a node in the Knowledge Graph with semantic embedding."""
|
| 44 |
-
db = SessionLocal()
|
| 45 |
try:
|
| 46 |
# 1. Generate Sovereign Embedding
|
| 47 |
embedding = llm.get_embedding(f"{name} ({category}): {content}")
|
|
@@ -96,7 +97,7 @@ def add_knowledge(name: str, category: str, content: str, metadata: Optional[Dic
|
|
| 96 |
|
| 97 |
def get_relevant_knowledge(query: str, n_results: int = 3) -> List[Dict]:
|
| 98 |
"""Semantic search for knowledge nodes using PgVector distance operator."""
|
| 99 |
-
db = SessionLocal()
|
| 100 |
try:
|
| 101 |
# 1. Check if we are on Postgres/PgVector
|
| 102 |
if "postgresql" not in str(engine.url):
|
|
@@ -219,69 +220,110 @@ def _calculate_jitter(success: bool) -> int:
|
|
| 219 |
|
| 220 |
def batch_mine_priorities():
|
| 221 |
"""Universal Learning Queue Processing."""
|
| 222 |
-
db = SessionLocal()
|
| 223 |
try:
|
| 224 |
# 1. Pull next pending targets
|
| 225 |
targets = db.query(LearningTarget).filter_by(status="pending").order_by(LearningTarget.priority.desc()).limit(10).all()
|
| 226 |
|
| 227 |
if not targets:
|
| 228 |
# Fallback to general domains if queue is dry
|
| 229 |
-
|
| 230 |
-
"Strategic Infrastructure development India 2024",
|
| 231 |
-
"Deep Learning for Agentic Workflow Orchestration",
|
| 232 |
-
"Quantum Finance Risk Models"
|
| 233 |
]
|
| 234 |
else:
|
| 235 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
# Mark as foraging
|
| 237 |
for t in targets: t.status = "foraging"
|
| 238 |
db.commit()
|
| 239 |
|
| 240 |
-
def _threaded_mine(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
if _check_halt(): return
|
| 242 |
_active_foraging_threads.add(topic)
|
| 243 |
try:
|
| 244 |
# ── SOVEREIGN ADAPTIVE ROUTING ──
|
| 245 |
# For personality/management, we skip web search and go straight to Neural Distillation
|
| 246 |
-
is_internal =
|
| 247 |
|
| 248 |
if is_internal:
|
| 249 |
logger.info(f"Holocron: Engaging Neural Distillation for Internal Pattern: '{topic}'")
|
| 250 |
-
from app.services import llm
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
resp = llm.chat(
|
| 252 |
-
messages=[{"role": "user", "content":
|
| 253 |
-
system_prompt="You are F.R.I.D.A.Y.'s Neural Forager.
|
| 254 |
use_tools=False
|
| 255 |
)
|
|
|
|
| 256 |
if resp.get("response_text"):
|
|
|
|
| 257 |
add_knowledge(
|
| 258 |
name=f"Neural Master: {topic}",
|
| 259 |
-
category=f"Sovereign Pattern: {
|
| 260 |
-
content=
|
| 261 |
metadata={"source": "Neural Distillation"}
|
| 262 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 263 |
else:
|
|
|
|
| 264 |
_mine_sync(topic, depth=1)
|
| 265 |
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 271 |
db_inner.commit()
|
| 272 |
finally:
|
| 273 |
_active_foraging_threads.remove(topic)
|
| 274 |
|
| 275 |
def _run_batch():
|
| 276 |
-
logger.info(f"Holocron: Initiating Sovereign Universal Ingestion ({len(
|
| 277 |
success_count = 0
|
| 278 |
|
| 279 |
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
|
| 280 |
# Pass both topic string and the target object
|
| 281 |
-
futures = []
|
| 282 |
-
for i, topic in enumerate(topics):
|
| 283 |
-
t_obj = targets[i] if targets else None
|
| 284 |
-
futures.append(executor.submit(_threaded_mine, topic, t_obj))
|
| 285 |
|
| 286 |
for future in concurrent.futures.as_completed(futures):
|
| 287 |
if _check_halt(): break
|
|
@@ -304,7 +346,7 @@ def batch_mine_priorities():
|
|
| 304 |
|
| 305 |
def add_learning_targets(topics: List[str], category: str):
|
| 306 |
"""Bridges massive mandates into the Sovereign Learning Queue."""
|
| 307 |
-
db = SessionLocal()
|
| 308 |
try:
|
| 309 |
logger.info(f"Holocron: Populating queue with {len(topics)} new {category} mandates...")
|
| 310 |
for topic in topics:
|
|
@@ -377,7 +419,7 @@ def get_learning_status() -> dict:
|
|
| 377 |
return {
|
| 378 |
"active": len(_active_foraging_threads) > 0,
|
| 379 |
"current_focus": list(_active_foraging_threads),
|
| 380 |
-
"total_nodes": SessionLocal().query(KnowledgeNode).count()
|
| 381 |
}
|
| 382 |
|
| 383 |
def handle_grid_knowledge(data: dict):
|
|
@@ -392,7 +434,7 @@ def handle_grid_knowledge(data: dict):
|
|
| 392 |
|
| 393 |
def _add_knowledge_local(name: str, category: str, content: str, metadata: Optional[Dict] = None):
|
| 394 |
"""Internal helper to add knowledge locally without broadcast loop."""
|
| 395 |
-
db = SessionLocal()
|
| 396 |
try:
|
| 397 |
node = db.query(KnowledgeNode).filter(KnowledgeNode.name == name).first()
|
| 398 |
if not node:
|
|
|
|
| 2 |
from typing import List, Optional, Dict, Set
|
| 3 |
from sqlalchemy.orm import Session
|
| 4 |
from sqlalchemy import create_engine, text
|
| 5 |
+
from app.models.entities import KnowledgeNode, Relationship, InteractionLog, LearningTarget, ConversationMemory
|
| 6 |
+
from app.core import database
|
| 7 |
from app.services import llm
|
| 8 |
import json
|
| 9 |
import asyncio
|
| 10 |
import threading
|
| 11 |
import time
|
| 12 |
+
import random
|
| 13 |
+
import concurrent.futures
|
| 14 |
from app.services.tools import search
|
| 15 |
from app.services import state_sync, watchdog, state
|
|
|
|
| 16 |
|
| 17 |
logger = logging.getLogger("friday.holocron")
|
| 18 |
|
|
|
|
| 42 |
|
| 43 |
def add_knowledge(name: str, category: str, content: str, metadata: Optional[Dict] = None):
|
| 44 |
"""Adds or updates a node in the Knowledge Graph with semantic embedding."""
|
| 45 |
+
db = database.SessionLocal()
|
| 46 |
try:
|
| 47 |
# 1. Generate Sovereign Embedding
|
| 48 |
embedding = llm.get_embedding(f"{name} ({category}): {content}")
|
|
|
|
| 97 |
|
| 98 |
def get_relevant_knowledge(query: str, n_results: int = 3) -> List[Dict]:
|
| 99 |
"""Semantic search for knowledge nodes using PgVector distance operator."""
|
| 100 |
+
db = database.SessionLocal()
|
| 101 |
try:
|
| 102 |
# 1. Check if we are on Postgres/PgVector
|
| 103 |
if "postgresql" not in str(engine.url):
|
|
|
|
| 220 |
|
| 221 |
def batch_mine_priorities():
|
| 222 |
"""Universal Learning Queue Processing."""
|
| 223 |
+
db = database.SessionLocal()
|
| 224 |
try:
|
| 225 |
# 1. Pull next pending targets
|
| 226 |
targets = db.query(LearningTarget).filter_by(status="pending").order_by(LearningTarget.priority.desc()).limit(10).all()
|
| 227 |
|
| 228 |
if not targets:
|
| 229 |
# Fallback to general domains if queue is dry
|
| 230 |
+
topics_data = [
|
| 231 |
+
{"topic": "Strategic Infrastructure development India 2024", "category": "area", "id": None},
|
| 232 |
+
{"topic": "Deep Learning for Agentic Workflow Orchestration", "category": "tech", "id": None},
|
| 233 |
+
{"topic": "Quantum Finance Risk Models", "category": "finance", "id": None}
|
| 234 |
]
|
| 235 |
else:
|
| 236 |
+
# [SOVEREIGN EXTRACTION] Extract to primitives before session closes
|
| 237 |
+
topics_data = [
|
| 238 |
+
{"topic": t.topic, "category": t.category, "id": t.id}
|
| 239 |
+
for t in targets
|
| 240 |
+
]
|
| 241 |
# Mark as foraging
|
| 242 |
for t in targets: t.status = "foraging"
|
| 243 |
db.commit()
|
| 244 |
|
| 245 |
+
def _threaded_mine(target_data: dict):
|
| 246 |
+
topic = target_data["topic"]
|
| 247 |
+
category = target_data["category"]
|
| 248 |
+
target_id = target_data["id"]
|
| 249 |
+
|
| 250 |
if _check_halt(): return
|
| 251 |
_active_foraging_threads.add(topic)
|
| 252 |
try:
|
| 253 |
# ── SOVEREIGN ADAPTIVE ROUTING ──
|
| 254 |
# For personality/management, we skip web search and go straight to Neural Distillation
|
| 255 |
+
is_internal = category in ["personality", "management"]
|
| 256 |
|
| 257 |
if is_internal:
|
| 258 |
logger.info(f"Holocron: Engaging Neural Distillation for Internal Pattern: '{topic}'")
|
| 259 |
+
from app.services import llm, protocols
|
| 260 |
+
|
| 261 |
+
# MANDATE: Capability Extraction
|
| 262 |
+
prompt = (
|
| 263 |
+
f"Generate a technical, JARVIS-style master pattern for: '{topic}'.\n\n"
|
| 264 |
+
"MANDATORY: Identify any actionable architectural improvements for your own core (Speed, Reply Precision, Search Strategy).\n"
|
| 265 |
+
"Format any core improvements as: 'CAPABILITY_UPGRADE: [Lesson Title] - [Technical Instruction]'"
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
resp = llm.chat(
|
| 269 |
+
messages=[{"role": "user", "content": prompt}],
|
| 270 |
+
system_prompt="You are F.R.I.D.A.Y.'s Neural Forager. You focus on building your internal core and improving your own architecture.",
|
| 271 |
use_tools=False
|
| 272 |
)
|
| 273 |
+
|
| 274 |
if resp.get("response_text"):
|
| 275 |
+
content = resp["response_text"]
|
| 276 |
add_knowledge(
|
| 277 |
name=f"Neural Master: {topic}",
|
| 278 |
+
category=f"Sovereign Pattern: {category}",
|
| 279 |
+
content=content,
|
| 280 |
metadata={"source": "Neural Distillation"}
|
| 281 |
)
|
| 282 |
+
|
| 283 |
+
# [SOVEREIGN SELF-EVOLUTION]: Extract and Save Capabilities
|
| 284 |
+
if "CAPABILITY_UPGRADE:" in content:
|
| 285 |
+
import re
|
| 286 |
+
matches = re.findall(r"CAPABILITY_UPGRADE:\s*(.*)", content)
|
| 287 |
+
for match in matches:
|
| 288 |
+
logger.info(f"Holocron: Distilling Capability Upgrade: {match.strip()}")
|
| 289 |
+
protocols.update_protocol("capabilities", match.strip())
|
| 290 |
else:
|
| 291 |
+
logger.info(f"Holocron: Engaging Web Mesh for External Topic: '{topic}'")
|
| 292 |
_mine_sync(topic, depth=1)
|
| 293 |
|
| 294 |
+
logger.info(f"Holocron: Successfully distilled '{topic}'. Committing to maturity grid...")
|
| 295 |
+
|
| 296 |
+
# ── PURGE PROTOCOL: Ingest & Incinerate ──
|
| 297 |
+
if target_id:
|
| 298 |
+
with database.SessionLocal() as db_inner:
|
| 299 |
+
# 1. Vaporize the learning target
|
| 300 |
+
t = db_inner.query(LearningTarget).get(target_id)
|
| 301 |
+
if t: db_inner.delete(t)
|
| 302 |
+
|
| 303 |
+
# 2. Scorch the source memory prompt to save storage
|
| 304 |
+
# Only delete prompts that match this specific topic/entity
|
| 305 |
+
db_inner.query(ConversationMemory).filter_by(entities=topic).delete()
|
| 306 |
+
|
| 307 |
+
db_inner.commit()
|
| 308 |
+
logger.info(f"Purge Protocol: Incinerated raw data for '{topic}' post-maturation.")
|
| 309 |
+
except Exception as e:
|
| 310 |
+
logger.error(f"Holocron: Critical Failure for target '{topic}': {e}")
|
| 311 |
+
# Revert to pending on failure
|
| 312 |
+
if target_id:
|
| 313 |
+
with database.SessionLocal() as db_inner:
|
| 314 |
+
t = db_inner.query(LearningTarget).get(target_id)
|
| 315 |
+
if t: t.status = "pending"
|
| 316 |
db_inner.commit()
|
| 317 |
finally:
|
| 318 |
_active_foraging_threads.remove(topic)
|
| 319 |
|
| 320 |
def _run_batch():
|
| 321 |
+
logger.info(f"Holocron: Initiating Sovereign Universal Ingestion ({len(topics_data)} targets)...")
|
| 322 |
success_count = 0
|
| 323 |
|
| 324 |
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
|
| 325 |
# Pass both topic string and the target object
|
| 326 |
+
futures = [executor.submit(_threaded_mine, t) for t in topics_data]
|
|
|
|
|
|
|
|
|
|
| 327 |
|
| 328 |
for future in concurrent.futures.as_completed(futures):
|
| 329 |
if _check_halt(): break
|
|
|
|
| 346 |
|
| 347 |
def add_learning_targets(topics: List[str], category: str):
|
| 348 |
"""Bridges massive mandates into the Sovereign Learning Queue."""
|
| 349 |
+
db = database.SessionLocal()
|
| 350 |
try:
|
| 351 |
logger.info(f"Holocron: Populating queue with {len(topics)} new {category} mandates...")
|
| 352 |
for topic in topics:
|
|
|
|
| 419 |
return {
|
| 420 |
"active": len(_active_foraging_threads) > 0,
|
| 421 |
"current_focus": list(_active_foraging_threads),
|
| 422 |
+
"total_nodes": database.SessionLocal().query(KnowledgeNode).count()
|
| 423 |
}
|
| 424 |
|
| 425 |
def handle_grid_knowledge(data: dict):
|
|
|
|
| 434 |
|
| 435 |
def _add_knowledge_local(name: str, category: str, content: str, metadata: Optional[Dict] = None):
|
| 436 |
"""Internal helper to add knowledge locally without broadcast loop."""
|
| 437 |
+
db = database.SessionLocal()
|
| 438 |
try:
|
| 439 |
node = db.query(KnowledgeNode).filter(KnowledgeNode.name == name).first()
|
| 440 |
if not node:
|
backend/app/services/llm.py
CHANGED
|
@@ -152,13 +152,21 @@ def init(ollama_host: str = "http://localhost:11434", ollama_model: str = "llama
|
|
| 152 |
|
| 153 |
if cached or is_local_path:
|
| 154 |
logger.info(f"Evolution: Loading Sovereign Neural Core ({_mlx_model})...")
|
| 155 |
-
|
| 156 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
else:
|
| 158 |
from app.services.scheduler import scheduler as sovereign_scheduler
|
| 159 |
if sovereign_scheduler.request_permission(f"Neural Core Model ({_mlx_model})", 4.5):
|
| 160 |
logger.info(f"Evolution: Permission Granted. Initializing Sovereign Neural Core ({_mlx_model})...")
|
| 161 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
else:
|
| 163 |
logger.info("MLX model not found locally. Standing by for Sovereign Order.")
|
| 164 |
|
|
@@ -166,6 +174,7 @@ def init(ollama_host: str = "http://localhost:11434", ollama_model: str = "llama
|
|
| 166 |
logger.info("MLX Neural Core not installed. Skipping local sovereign path.")
|
| 167 |
except Exception as e:
|
| 168 |
logger.warning(f"Sovereign Core Failure: {e}")
|
|
|
|
| 169 |
|
| 170 |
# 3. Initialize Ollama client (Legacy Fallback)
|
| 171 |
if not _use_cloud or not _openai_client:
|
|
|
|
| 152 |
|
| 153 |
if cached or is_local_path:
|
| 154 |
logger.info(f"Evolution: Loading Sovereign Neural Core ({_mlx_model})...")
|
| 155 |
+
try:
|
| 156 |
+
_mlx_engine = {"load": load, "generate": generate}
|
| 157 |
+
logger.info(f"✓ Sovereign Neural Core Initialized (MLX)")
|
| 158 |
+
except Exception as le:
|
| 159 |
+
logger.warning(f"Sovereign Core: Native load failure: {le}. Falling back.")
|
| 160 |
+
_mlx_engine = None
|
| 161 |
else:
|
| 162 |
from app.services.scheduler import scheduler as sovereign_scheduler
|
| 163 |
if sovereign_scheduler.request_permission(f"Neural Core Model ({_mlx_model})", 4.5):
|
| 164 |
logger.info(f"Evolution: Permission Granted. Initializing Sovereign Neural Core ({_mlx_model})...")
|
| 165 |
+
try:
|
| 166 |
+
_mlx_engine = {"load": load, "generate": generate}
|
| 167 |
+
except Exception as le:
|
| 168 |
+
logger.warning(f"Sovereign Core: Permissioned load failure: {le}. Falling back.")
|
| 169 |
+
_mlx_engine = None
|
| 170 |
else:
|
| 171 |
logger.info("MLX model not found locally. Standing by for Sovereign Order.")
|
| 172 |
|
|
|
|
| 174 |
logger.info("MLX Neural Core not installed. Skipping local sovereign path.")
|
| 175 |
except Exception as e:
|
| 176 |
logger.warning(f"Sovereign Core Failure: {e}")
|
| 177 |
+
_mlx_engine = None
|
| 178 |
|
| 179 |
# 3. Initialize Ollama client (Legacy Fallback)
|
| 180 |
if not _use_cloud or not _openai_client:
|
backend/app/services/memory.py
CHANGED
|
@@ -93,19 +93,25 @@ def recall_memory(query: str, n_results: int = 3) -> str:
|
|
| 93 |
# 1. Generate Search Vector
|
| 94 |
search_vector = llm.get_embedding(query)
|
| 95 |
|
| 96 |
-
# 2. Execute
|
| 97 |
-
|
| 98 |
-
|
| 99 |
try:
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
ConversationMemory.
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
# Fallback if PgVector extension is not enabled or library issue
|
| 108 |
-
logger.warning("
|
| 109 |
stmt = select(ConversationMemory).order_by(ConversationMemory.timestamp.desc()).limit(n_results)
|
| 110 |
results = db.execute(stmt).scalars().all()
|
| 111 |
|
|
|
|
| 93 |
# 1. Generate Search Vector
|
| 94 |
search_vector = llm.get_embedding(query)
|
| 95 |
|
| 96 |
+
# 2. Execute Semantic Search with Engine Awareness
|
| 97 |
+
is_sqlite = "sqlite" in str(engine.url)
|
| 98 |
+
|
| 99 |
try:
|
| 100 |
+
if is_sqlite:
|
| 101 |
+
# SQLite: No PgVector. Use timestamp/keyword fallback.
|
| 102 |
+
logger.debug("Memory: Local Grid (SQLite) detected. Using optimized index search.")
|
| 103 |
+
stmt = select(ConversationMemory).order_by(ConversationMemory.timestamp.desc()).limit(n_results)
|
| 104 |
+
results = db.execute(stmt).scalars().all()
|
| 105 |
+
else:
|
| 106 |
+
from pgvector.sqlalchemy import Vector
|
| 107 |
+
# Optimized search via PgVector (Postgres Only)
|
| 108 |
+
stmt = select(ConversationMemory).order_by(
|
| 109 |
+
ConversationMemory.embedding.cosine_distance(search_vector)
|
| 110 |
+
).limit(n_results)
|
| 111 |
+
results = db.execute(stmt).scalars().all()
|
| 112 |
+
except Exception as se:
|
| 113 |
# Fallback if PgVector extension is not enabled or library issue
|
| 114 |
+
logger.warning(f"Memory Search Issue: {se}. Falling back to recent context.")
|
| 115 |
stmt = select(ConversationMemory).order_by(ConversationMemory.timestamp.desc()).limit(n_results)
|
| 116 |
results = db.execute(stmt).scalars().all()
|
| 117 |
|
backend/app/services/protocols.py
CHANGED
|
@@ -16,6 +16,7 @@ def get_protocols() -> dict:
|
|
| 16 |
"user_preferences": [],
|
| 17 |
"interaction_style": "default",
|
| 18 |
"learned_facts": {},
|
|
|
|
| 19 |
"forbidden_topics": ["personal credentials", "passwords"]
|
| 20 |
}
|
| 21 |
save_protocols(default)
|
|
|
|
| 16 |
"user_preferences": [],
|
| 17 |
"interaction_style": "default",
|
| 18 |
"learned_facts": {},
|
| 19 |
+
"capabilities": {},
|
| 20 |
"forbidden_topics": ["personal credentials", "passwords"]
|
| 21 |
}
|
| 22 |
save_protocols(default)
|
backend/scripts/flush_learning_queue.py
CHANGED
|
@@ -11,7 +11,7 @@ import logging
|
|
| 11 |
sys.path.append(os.path.join(os.getcwd(), "backend"))
|
| 12 |
|
| 13 |
from app.core import database
|
| 14 |
-
from app.models.entities import ConversationMemory
|
| 15 |
from app.services import holocron
|
| 16 |
|
| 17 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s | FLUSH | %(message)s")
|
|
|
|
| 11 |
sys.path.append(os.path.join(os.getcwd(), "backend"))
|
| 12 |
|
| 13 |
from app.core import database
|
| 14 |
+
from app.models.entities import ConversationMemory
|
| 15 |
from app.services import holocron
|
| 16 |
|
| 17 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s | FLUSH | %(message)s")
|
scripts/seed_core_building.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
import os
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
# Add backend to path for imports
|
| 6 |
+
sys.path.append(str(Path(__file__).parent.parent / "backend"))
|
| 7 |
+
|
| 8 |
+
from app.services.holocron import add_learning_targets
|
| 9 |
+
import logging
|
| 10 |
+
|
| 11 |
+
logging.basicConfig(level=logging.INFO)
|
| 12 |
+
logger = logging.getLogger("seed_core")
|
| 13 |
+
|
| 14 |
+
def seed_core_evolution_mandates():
|
| 15 |
+
"""Seeds the foundational core-building modules."""
|
| 16 |
+
core_modules = [
|
| 17 |
+
"Neural Response Latency: Optimizing the bridge between Subconscious and HUD",
|
| 18 |
+
"Agentic Research Workflows: Mastering the transition from Link-Scavenging to Deep Extraction",
|
| 19 |
+
"Advanced LLM Prompt Calibration: Hardening the Jarvis Tone and Brevity",
|
| 20 |
+
"Gradio UI Performance: Best practices for WebSocket and SSE response speed",
|
| 21 |
+
"Python ThreadPool Scaling: Optimizing worker density for a MacBook Air core",
|
| 22 |
+
"Database Indexing Strategies: Accelerating semantic retrieval in the Holocron",
|
| 23 |
+
"Recursive Scraping Resilience: Mastering Jitter and Identity Rotation to avoid Mesh Rejection",
|
| 24 |
+
"Vocal Dispatch Optimization: Reducing the latency of the /usr/bin/say channel",
|
| 25 |
+
"Memory Pruning Protocols: Balancing high-fidelity recall with storage efficiency",
|
| 26 |
+
"Search Pivot Calibration: Improving the decision logic between DuckDuckGo and Google Scavenging"
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
# Combinatorial Expansion for Depth
|
| 30 |
+
expanded = []
|
| 31 |
+
aspects = ["Architectural Pattern", "Performance Benchmarking", "Failure Recovery", "Sir's Focus Alignment"]
|
| 32 |
+
for module in core_modules:
|
| 33 |
+
for aspect in aspects:
|
| 34 |
+
expanded.append(f"Core Building: {module} - {aspect}")
|
| 35 |
+
|
| 36 |
+
# Add to 'management' category but as a 'capability' priority
|
| 37 |
+
add_learning_targets(expanded, "management")
|
| 38 |
+
logger.info(f"Seed complete: {len(expanded)} Core-Evolution Mandates added to the Forge.")
|
| 39 |
+
|
| 40 |
+
if __name__ == "__main__":
|
| 41 |
+
logger.info("🚀 Initiating Neural Core Evolution Protocol...")
|
| 42 |
+
seed_core_evolution_mandates()
|
| 43 |
+
logger.info("═"*40)
|
| 44 |
+
logger.info("CORE EVOLUTION SEEDED. SIR, SHE IS NOW STUDYING HER OWN SHAPE.")
|
| 45 |
+
logger.info("═"*40)
|