import sqlite3 import time import logging from backend.services.usb_monitor import get_db_path def _init_memory_table(): try: with sqlite3.connect(get_db_path()) as conn: conn.execute("PRAGMA journal_mode=WAL") conn.execute(""" CREATE TABLE IF NOT EXISTS global_omni_memory ( id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp INTEGER NOT NULL, ecosystem TEXT NOT NULL, model TEXT NOT NULL, task_type TEXT NOT NULL, action_summary TEXT NOT NULL ) """) conn.commit() except Exception as e: logging.error(f"OmniMemory: Failed to init table: {e}") _init_memory_table() class GlobalOmniMemory: @staticmethod def record_action(ecosystem: str, model: str, task_type: str, action_summary: str): """Records a completed action by any key/model into the hive mind.""" try: with sqlite3.connect(get_db_path()) as conn: conn.execute( "INSERT INTO global_omni_memory (timestamp, ecosystem, model, task_type, action_summary) VALUES (?, ?, ?, ?, ?)", (int(time.time()), ecosystem, model, task_type, action_summary) ) conn.commit() logging.info(f"OmniMemory: Recorded {ecosystem} ({model}) action for {task_type}") except Exception as e: logging.error(f"OmniMemory: Failed to record action: {e}") @staticmethod def get_global_context_stream(limit: int = 5) -> str: """Retrieves the recent hive-mind events to inject into prompts.""" try: with sqlite3.connect(get_db_path()) as conn: conn.row_factory = sqlite3.Row rows = conn.execute( "SELECT * FROM global_omni_memory ORDER BY timestamp DESC LIMIT ?", (limit,) ).fetchall() if not rows: return "" context_lines = ["[RECENT OMNI-MEMORY EVENTS - HIVE MIND SYNC]"] for r in reversed(rows): # chronological order context_lines.append(f"- [{r['ecosystem']} Key | Model: {r['model']}] executed {r['task_type']} task: {r['action_summary']}") return "\n".join(context_lines) + "\n\n" except Exception as e: logging.error(f"OmniMemory: Failed to get context stream: {e}") return ""