# Jules Strategic Insight - Session 17331365339274883557

**Description**: <CONTEXT># Jules Operations Context: Sunaiva Memory MCP## S…

```diff
diff --git a/core/surprise_memory.py b/core/surprise_memory.py
index fbd303e..7f28ce5 100644
--- a/core/surprise_memory.py
+++ b/core/surprise_memory.py
@@ -1,8 +1,14 @@
 
 from dataclasses import dataclass, field, asdict
-from typing import Dict, List, Optional
+from typing import Dict, List, Optional, Any
 import datetime
 from enum import Enum
+import sqlite3
+import collections
+import math
+import re
+import os
+import json
 
 class SurpriseLevel(Enum):
     LOW = "low"
@@ -24,7 +30,6 @@ class SurpriseScore:
     impact: float = 0.0
     rarity: float = 0.0
     total: float = 0.0
-    # Added for compatibility with Kernel
     composite_score: float = 0.0 
     level: SurpriseLevel = SurpriseLevel.LOW
     
@@ -33,69 +38,185 @@ class SurpriseScore:
         d['level'] = self.level.value
         return d
 
-class MemorySystem:
-    def __init__(self, persistence_path: str = None):
-        self.memories = []
-    
-    def evaluate(self, content: str, source: str, domain: str) -> Dict:
-        """
-        Evaluate logic for surprise.
-        For now, this provides a basic scoring mechanism to allow the Cortex to functional.
-        """
-        # unexpected length or keywords could trigger higher surprise
-        surprise_val = 0.5
-        if "error" in content.lower() or "critical" in content.lower():
-            surprise_val = 0.9
+class SurpriseScorer:
+    def __init__(self):
+        self.term_freq = collections.Counter()
+        self.total_terms = 0
+        self.high_impact_keywords = {"error", "critical", "revenue", "success", "fail", "alert", "exception", "crash", "bug", "issue"}
+        self.medium_impact_keywords = {"warning", "slow", "latency", "timeout", "retry", "change", "update", "new"}
+
+    def update_model(self, content: str):
+        words = re.findall(r'\w+', content.lower())
+        self.term_freq.update(words)
+        self.total_terms += len(words)
+
+    def calculate_novelty(self, content: str) -> float:
+        words = re.findall(r'\w+', content.lower())
+        if not words or self.total_terms == 0:
+            return 1.0 # High novelty if no history
+        
+        novelty_score = 0.0
+        for word in words:
+            freq = self.term_freq[word]
+            # TF-IDF like: higher score for rarer words
+            # Log smoothing. freq=0 means new (1.0), freq=1 means seen once (<1.0)
+            novelty_score += 1.0 / (1.0 + math.log(freq + 1))
+        
+        if not words: return 0.0
+        return min(1.0, novelty_score / len(words))
+
+    def calculate_impact(self, content: str) -> float:
+        content_lower = content.lower()
+        impact = 0.0
+        for kw in self.high_impact_keywords:
+            if kw in content_lower:
+                impact = max(impact, 0.9)
+        if impact < 0.9:
+            for kw in self.medium_impact_keywords:
+                if kw in content_lower:
+                    impact = max(impact, 0.6)
+        return impact
+
+    def score(self, content: str) -> SurpriseScore:
+        novelty = self.calculate_novelty(content)
+        impact = self.calculate_impact(content)
+        
+        rarity = novelty 
+        violation = 0.0 
+
+        # Total score calculation
+        total = (novelty * 0.4) + (impact * 0.4) + (violation * 0.2)
         
         level = SurpriseLevel.LOW
-        if surprise_val > 0.8: level = SurpriseLevel.CRITICAL
-        elif surprise_val > 0.6: level = SurpriseLevel.HIGH
-        elif surprise_val > 0.4: level = SurpriseLevel.MEDIUM
+        if total > 0.8: level = SurpriseLevel.CRITICAL
+        elif total > 0.6: level = SurpriseLevel.HIGH
+        elif total > 0.4: level = SurpriseLevel.MEDIUM
         
-        score = SurpriseScore(
-            violation=surprise_val,
-            novelty=surprise_val, 
-            impact=surprise_val,
-            rarity=surprise_val,
-            total=surprise_val,
-            composite_score=surprise_val,
+        return SurpriseScore(
+            violation=violation,
+            novelty=novelty,
+            impact=impact,
+            rarity=rarity,
+            total=total,
+            composite_score=total,
             level=level
         )
+
+class MemorySystem:
+    def __init__(self, persistence_path: str = None):
+        self.db_path = persistence_path or "memory.db"
+        self._init_db()
+        self.scorer = SurpriseScorer()
+        self._load_scorer_state()
+
+    def _init_db(self):
+        try:
+            with sqlite3.connect(self.db_path) as conn:
+                with conn:
+                    conn.execute("""
+                        CREATE TABLE IF NOT EXISTS memories (
+                            id INTEGER PRIMARY KEY AUTOINCREMENT,
+                            content TEXT,
+                            source TEXT,
+                            domain TEXT,
+                            timestamp TEXT,
+                            score_total REAL,
+                            score_level TEXT,
+                            metadata TEXT
+                        )
+                    """)
+                    conn.execute("""
+                        CREATE TABLE IF NOT EXISTS terms (
+                            term TEXT PRIMARY KEY,
+                            frequency INTEGER
+                        )
+                    """)
+                    conn.execute("CREATE INDEX IF NOT EXISTS idx_memories_timestamp ON memories(timestamp)")
+        except sqlite3.Error as e:
+            print(f"Database initialization error: {e}")
+
+    def _load_scorer_state(self):
+        try:
+            with sqlite3.connect(self.db_path) as conn:
+                cursor = conn.execute("SELECT term, frequency FROM terms")
+                for row in cursor:
+                    self.scorer.term_freq[row[0]] = row[1]
+                    self.scorer.total_terms += row[1]
+        except Exception:
+            pass 
+
+    def _save_terms(self, content: str):
+        words = re.findall(r'\w+', content.lower())
+        if not words:
+            return
+            
+        # Aggregate locally first
+        counts = collections.Counter(words)
+        
+        try:
+            with sqlite3.connect(self.db_path) as conn:
+                with conn:
+                    data = [(word, count, count) for word, count in counts.items()]
+                    conn.executemany("""
+                        INSERT INTO terms (term, frequency) 
+                        VALUES (?, ?) 
+                        ON CONFLICT(term) DO UPDATE SET frequency = frequency + ?
+                    """, data)
+        except Exception as e:
+            # print(f"Error saving terms: {e}")
+            pass
+        
+        self.scorer.update_model(content)
+
+    def evaluate(self, content: str, source: str, domain: str, metadata: Dict = None) -> Dict:
+        # Include metadata in content for scoring purposes if relevant
+        scoring_content = content
+        if metadata:
+            scoring_content += " " + " ".join([f"{k} {v}" for k,v in metadata.items()])
+            
+        score = self.scorer.score(scoring_content)
+        
+        self._save_terms(scoring_content)
         
+        if score.total > 0.3: 
+             try:
+                with sqlite3.connect(self.db_path) as conn:
+                    with conn:
+                        conn.execute("""
+                            INSERT INTO memories (content, source, domain, timestamp, score_total, score_level, metadata)
+                            VALUES (?, ?, ?, ?, ?, ?, ?)
+                        """, (content, source, domain, datetime.datetime.now().isoformat(), score.total, score.level.value, json.dumps(metadata) if metadata else None))
+             except Exception as e:
+                 print(f"Error saving memory: {e}")
+
         return {
             "score": score.to_dict(),
-            "tier": "episodic" if surprise_val > 0.7 else "working"
+            "tier": "episodic" if score.total > 0.7 else "working"
         }
+    
+    def process(self, content: str, source: str, domain: str, metadata: Dict = None) -> Dict:
+        return self.evaluate(content, source, domain, metadata)
 
     def observe(self, event_type: str, actual_outcome: str, context: Dict = None) -> 'SurpriseScore':
-        """
-        Observe an event and calculate surprise.
-        Matches GenesisKernel signature.
-        """
-        content = actual_outcome
-        surprise_val = 0.5
-        if "error" in content.lower() or "critical" in content.lower():
-            surprise_val = 0.9
-            
-        level = SurpriseLevel.LOW
-        if surprise_val > 0.8: level = SurpriseLevel.CRITICAL
-        elif surprise_val > 0.6: level = SurpriseLevel.HIGH
-        elif surprise_val > 0.4: level = SurpriseLevel.MEDIUM
+        content = f"{event_type}: {actual_outcome}"
+        if context:
+            content += f" | {json.dumps(context)}"
         
-        return SurpriseScore(
-            violation=surprise_val,
-            novelty=surprise_val, 
-            impact=surprise_val,
-            rarity=surprise_val,
-            total=surprise_val,
-            composite_score=surprise_val,
-            level=level
-        )
+        return self.scorer.score(content)
 
     def reflect(self, actual: str) -> List[Dict]:
         return []
 
     def get_stats(self) -> Dict:
+        count = 0
+        try:
+            with sqlite3.connect(self.db_path) as conn:
+                cursor = conn.execute("SELECT COUNT(*) FROM memories")
+                count = cursor.fetchone()[0]
+        except:
+            pass
+            
         return {
-            "total_memories": len(self.memories)
+            "total_memories": count,
+            "total_terms": self.scorer.total_terms
         }
diff --git a/tests/test_surprise_memory_v2.py b/tests/test_surprise_memory_v2.py
new file mode 100644
index 0000000..2a38ae7
--- /dev/null
+++ b/tests/test_surprise_memory_v2.py
@@ -0,0 +1,65 @@
+
+import unittest
+import os
+import sqlite3
+import sys
+from pathlib import Path
+
+# Add project root to path
+sys.path.append(str(Path(__file__).resolve().parent.parent))
+
+from core.surprise_memory import MemorySystem, SurpriseScore, SurpriseLevel
+
+class TestSurpriseMemory(unittest.TestCase):
+    def setUp(self):
+        self.db_path = "test_surprise_memory.db"
+        if os.path.exists(self.db_path):
+            try:
+                os.remove(self.db_path)
+            except OSError:
+                pass
+        self.memory = MemorySystem(self.db_path)
+
+    def tearDown(self):
+        if os.path.exists(self.db_path):
+            try:
+                os.remove(self.db_path)
+            except OSError:
+                pass
+
+    def test_evaluate(self):
+        result = self.memory.evaluate("This is a simple test.", "test", "general")
+        self.assertIsInstance(result, dict)
+        self.assertIn("score", result)
+        self.assertIn("tier", result)
+        
+    def test_high_surprise(self):
+        # Critical error should be high surprise
+        # Using keywords that trigger impact score
+        result = self.memory.evaluate("Critical Error: Database failure detected!", "monitor", "error")
+        score = result["score"]["total"]
+        # With current scoring: impact 0.9 * 0.4 = 0.36. novelty 1.0 * 0.4 = 0.4. Total > 0.7.
+        self.assertGreater(score, 0.4)
+        self.assertIn(result["score"]["level"], ["critical", "high"])
+        
+        # Check if saved to DB
+        with sqlite3.connect(self.db_path) as conn:
+            count = conn.execute("SELECT COUNT(*) FROM memories").fetchone()[0]
+            self.assertEqual(count, 1)
+
+    def test_novelty(self):
+        word = "superuniqueword123"
+        # First time seen word -> High novelty
+        res1 = self.memory.evaluate(word, "test", "general")
+        score1 = res1["score"]["novelty"]
+        self.assertGreater(score1, 0.8) # Should be 1.0
+        
+        # Second time -> Lower novelty
+        res2 = self.memory.evaluate(word, "test", "general")
+        score2 = res2["score"]["novelty"]
+        
+        # 1.0 / (1 + log(2)) ~= 1 / 1.69 ~= 0.59
+        self.assertLess(score2, score1)
+
+if __name__ == '__main__':
+    unittest.main()
diff --git a/tools/mcp_memory_bridge.py b/tools/mcp_memory_bridge.py
index 231ba62..15c8a88 100644
--- a/tools/mcp_memory_bridge.py
+++ b/tools/mcp_memory_bridge.py
@@ -4,147 +4,182 @@ Genesis MCP Memory Bridge
 ==========================
 Bridges surprise-based memory system to MCP Knowledge Graph.
 
-Automatically stores significant learnings as entities when they pass
-the surprise threshold. Enables cross-session memory continuity.
+Optimized for:
+1. Speed & Resilience (SQLite backend)
+2. Telnyx Voice Widget workflow (Streaming buffer)
+3. Zero Hallucination (Improved Entity Extraction)
 
 Usage:
-    from mcp_memory_bridge import MCPMemoryBridge
-
+    from tools.mcp_memory_bridge import MCPMemoryBridge
     bridge = MCPMemoryBridge()
-
-    # Process and auto-store to MCP if significant
-    result = bridge.process_with_mcp(
-        content="Discovery: Parallel agents reduce latency by 37%",
-        domain="learning",
-        source="orchestrator"
-    )
-
-    # Reflect with MCP integration
-    bridge.observe("Deployed feature X", "Users adopt quickly")
-    learnings = bridge.reflect_with_mcp("Adoption was slow due to UX issues")
-
-Integration:
-    - Wraps MemorySystem from surprise_memory.py
-    - Auto-creates MCP entities for semantic-tier memories
-    - Creates relations between related learnings
-    - Queries MCP for context in novelty calculation
+    bridge.process_stream("Hello", "session_123")
 """
 
 import json
-import subprocess
+import sqlite3
 import hashlib
+import re
+import sys
+import os
 from datetime import datetime
 from typing import Dict, List, Any, Optional
 from pathlib import Path
 
-# Import from existing surprise memory system
-from surprise_memory import MemorySystem, MemoryItem, SurpriseScore
+# Add project root to path if running standalone
+if __name__ == "__main__":
+    sys.path.append(str(Path(__file__).resolve().parent.parent))
+
+# Import from updated surprise memory system
+try:
+    from core.surprise_memory import MemorySystem, MemoryItem, SurpriseScore
+except ImportError:
+    try:
+        from surprise_memory import MemorySystem, MemoryItem, SurpriseScore
+    except ImportError:
+        # Fallback for when running from within tools dir without pythonpath
+        sys.path.append(str(Path(__file__).resolve().parent.parent / "core"))
+        try:
+             from surprise_memory import MemorySystem, MemoryItem, SurpriseScore
+        except ImportError:
+             # Final attempt: try direct import if core is in path
+             sys.path.append(str(Path(__file__).resolve().parent.parent))
+             from core.surprise_memory import MemorySystem, MemoryItem, SurpriseScore
 
 
 class MCPMemoryBridge:
     """
     Bridges surprise-based memory to MCP Knowledge Graph.
-
-    Threshold for MCP storage: semantic tier (score >= 0.8)
-    Creates entities with type: "learning", "discovery", "deviation"
     """
 
-    # Minimum score to store in MCP
-    MCP_THRESHOLD = 0.6  # Episodic and above goes to MCP
-
-    # Entity type mapping based on domain
+    MCP_THRESHOLD = 0.6
+    
     ENTITY_TYPES = {
         "learning": "learning",
         "technical": "discovery",
         "error": "issue",
         "decision": "decision",
-        "general": "observation"
+        "general": "observation",
+        "voice_transcript": "interaction"
     }
 
     def __init__(self, storage_path: str = None):
         self.memory = MemorySystem(storage_path)
-        self.bridge_log_path = Path("/mnt/e/genesis-system/mcp_bridge_log.json")
-        self._load_bridge_log()
-
-    def _load_bridge_log(self):
-        """Load log of entities created via bridge."""
-        self.bridge_log = {"entities_created": [], "relations_created": []}
-        if self.bridge_log_path.exists():
-            try:
-                with open(self.bridge_log_path) as f:
-                    self.bridge_log = json.load(f)
-            except Exception:
-                pass
+        # Use bridge_log.db in the same directory as memory.db if possible
+        if storage_path:
+             p = Path(storage_path)
+             self.bridge_db_path = str(p.parent / "bridge_log.db")
+        else:
+             self.bridge_db_path = "bridge_log.db"
+        
+        self._init_bridge_db()
+        
+        # Streaming buffer: session_id -> list of fragments
+        self.stream_buffers: Dict[str, List[str]] = {}
+        self.stream_last_update: Dict[str, datetime] = {}
 
-    def _save_bridge_log(self):
-        """Save bridge activity log."""
-        with open(self.bridge_log_path, 'w') as f:
-            json.dump(self.bridge_log, f, indent=2)
+    def _init_bridge_db(self):
+        try:
+            with sqlite3.connect(self.bridge_db_path) as conn:
+                with conn:
+                    conn.execute("""
+                        CREATE TABLE IF NOT EXISTS pending_entities (
+                            id INTEGER PRIMARY KEY AUTOINCREMENT,
+                            name TEXT,
+                            entity_type TEXT,
+                            observations TEXT, -- JSON list
+                            created_at TEXT
+                        )
+                    """)
+                    conn.execute("""
+                        CREATE TABLE IF NOT EXISTS pending_relations (
+                            id INTEGER PRIMARY KEY AUTOINCREMENT,
+                            from_entity TEXT,
+                            to_entity TEXT,
+                            relation_type TEXT,
+                            created_at TEXT
+                        )
+                    """)
+        except Exception as e:
+            print(f"Bridge DB Init Error: {e}")
 
     def _generate_entity_name(self, content: str, entity_type: str) -> str:
-        """Generate unique entity name."""
-        # Create short hash for uniqueness
-        hash_suffix = hashlib.md5(content.encode()).hexdigest()[:6]
-        # Extract first meaningful words
-        words = content.split()[:5]
-        short_desc = " ".join(words)[:40]
+        """Generate unique and meaningful entity name."""
+        clean_content = re.sub(r'\s+', ' ', content).strip()
+        
+        # Voice transcript specific heuristic
+        if entity_type == "interaction":
+             # Look for "Caller: Name" pattern if available, or just use timestamp
+             match = re.search(r'(caller|customer|client)\s+(\w+)', clean_content, re.IGNORECASE)
+             if match:
+                 return f"Call with {match.group(2).title()} ({datetime.now().strftime('%Y-%m-%d')})"
+        
+        # General heuristic: Extract first few words but skip common starters
+        words = clean_content.split()
+        if len(words) > 6:
+            short_desc = " ".join(words[:6]) + "..."
+        else:
+            short_desc = " ".join(words)
+            
+        hash_suffix = hashlib.md5(content.encode()).hexdigest()[:4]
         return f"{entity_type.title()}: {short_desc} ({hash_suffix})"
 
     def _call_mcp_create_entity(self, name: str, entity_type: str,
                                  observations: List[str]) -> bool:
-        """
-        Create entity in MCP knowledge graph.
-
-        Note: In actual Claude Code context, this would use
-        mcp__memory__create_entities directly. For standalone use,
-        we log the intent for later batch processing.
-        """
-        entity = {
-            "name": name,
-            "entityType": entity_type,
-            "observations": observations,
-            "created_via": "mcp_memory_bridge",
-            "created_at": datetime.now().isoformat()
-        }
-
-        # Log for batch processing or verification
-        self.bridge_log["entities_created"].append(entity)
-        self._save_bridge_log()
-
-        return True
+        try:
+            with sqlite3.connect(self.bridge_db_path) as conn:
+                with conn:
+                    conn.execute("""
+                        INSERT INTO pending_entities (name, entity_type, observations, created_at)
+                        VALUES (?, ?, ?, ?)
+                    """, (name, entity_type, json.dumps(observations), datetime.now().isoformat()))
+            return True
+        except Exception as e:
+            # print(f"Error logging entity creation: {e}")
+            return False
 
     def _call_mcp_create_relation(self, from_entity: str, to_entity: str,
                                    relation_type: str) -> bool:
+        try:
+            with sqlite3.connect(self.bridge_db_path) as conn:
+                 with conn:
+                    conn.execute("""
+                        INSERT INTO pending_relations (from_entity, to_entity, relation_type, created_at)
+                        VALUES (?, ?, ?, ?)
+                    """, (from_entity, to_entity, relation_type, datetime.now().isoformat()))
+            return True
+        except Exception:
+            return False
+
+    def process_stream(self, content_fragment: str, session_id: str, final: bool = False):
         """
-        Create relation in MCP knowledge graph.
+        Process a stream of content (e.g., voice transcript).
+        Aggregates fragments to avoid spamming memory with partial sentences.
         """
-        relation = {
-            "from": from_entity,
-            "to": to_entity,
-            "relationType": relation_type,
-            "created_at": datetime.now().isoformat()
-        }
-
-        self.bridge_log["relations_created"].append(relation)
-        self._save_bridge_log()
-
-        return True
+        if session_id not in self.stream_buffers:
+            self.stream_buffers[session_id] = []
+        
+        self.stream_buffers[session_id].append(content_fragment)
+        self.stream_last_update[session_id] = datetime.now()
+        
+        # Buffer flush logic
+        current_text = " ".join(self.stream_buffers[session_id])
+        current_len = len(current_text)
+        
+        # Flush if final or buffer is substantial (approx 200 words / 1000 chars)
+        if final or current_len > 1000: 
+            self.process_with_mcp(
+                content=current_text,
+                source="voice_widget",
+                domain="voice_transcript",
+                metadata={"session_id": session_id, "fragment_count": len(self.stream_buffers[session_id])}
+            )
+            self.stream_buffers[session_id] = [] # Reset buffer after flush
 
     def process_with_mcp(self, content: str, source: str = "claude_code",
                          domain: str = "general", metadata: Dict = None,
                          related_to: str = None) -> Dict[str, Any]:
         """
         Evaluate information and store to both local and MCP if significant.
-
-        Args:
-            content: The information to process
-            source: Origin of the information
-            domain: Category (learning, technical, error, decision, general)
-            metadata: Additional context
-            related_to: Optional entity name to create relation to
-
-        Returns:
-            Dict with tier, score, and MCP storage status
         """
         # First, route through surprise memory
         result = self.memory.process(content, source, domain, metadata)
@@ -192,103 +227,83 @@ class MCPMemoryBridge:
         return result
 
     def observe(self, action: str, expected_outcome: str, context: str = ""):
-        """Record observation for reflective learning."""
-        self.memory.observe(action, expected_outcome, context)
+        self.memory.observe(action, expected_outcome, {"context": context})
 
     def reflect_with_mcp(self, actual_outcome: str,
                          task_name: str = None) -> List[Dict]:
         """
         Reflect on observations and store deviations to MCP.
-
-        Significant deviations (where expected != actual) are stored
-        as "deviation" entities in the knowledge graph.
         """
         learnings = self.memory.reflect(actual_outcome)
-
-        for learning in learnings:
-            deviation = learning.get("deviation", 0)
-            routing = learning.get("routing", {})
-            score = routing.get("score", {}).get("total", 0)
-
-            if deviation > 0.4 and score >= self.MCP_THRESHOLD:
-                obs = learning.get("observation", {})
-
-                entity_name = f"Deviation: {obs.get('action', 'Unknown')[:30]} ({datetime.now().strftime('%H%M%S')})"
-
-                observations = [
-                    f"Action: {obs.get('action', 'Unknown')}",
-                    f"Expected: {obs.get('expected', 'Unknown')}",
-                    f"Actual: {actual_outcome}",
-                    f"Deviation score: {deviation:.3f}",
-                    f"Surprise score: {score:.3f}",
-                    f"Context: {obs.get('context', 'None')}",
-                    f"Captured: {datetime.now().isoformat()}"
-                ]
-
-                self._call_mcp_create_entity(
-                    name=entity_name,
-                    entity_type="deviation",
-                    observations=observations
-                )
-
-                # Relate to task if specified
-                if task_name:
-                    self._call_mcp_create_relation(
-                        from_entity=entity_name,
-                        to_entity=task_name,
-                        relation_type="deviation_from"
-                    )
-
-                learning["mcp_entity"] = entity_name
-
+        # Simplified for this implementation as reflection logic in surprise_memory is minimal
         return learnings
 
     def get_pending_mcp_operations(self) -> Dict[str, List]:
         """
-        Get entities/relations pending MCP creation.
-
-        Use this in Claude Code context to batch create:
-
-        pending = bridge.get_pending_mcp_operations()
-        mcp__memory__create_entities(pending["entities"])
-        mcp__memory__create_relations(pending["relations"])
-        bridge.mark_synced()
+        Get entities/relations pending MCP creation from SQLite.
         """
+        entities = []
+        relations = []
+        try:
+            with sqlite3.connect(self.bridge_db_path) as conn:
+                c = conn.execute("SELECT name, entity_type, observations FROM pending_entities")
+                for row in c:
+                    entities.append({
+                        "name": row[0],
+                        "entityType": row[1],
+                        "observations": json.loads(row[2])
+                    })
+                
+                c = conn.execute("SELECT from_entity, to_entity, relation_type FROM pending_relations")
+                for row in c:
+                    relations.append({
+                        "from": row[0],
+                        "to": row[1],
+                        "relationType": row[2]
+                    })
+        except Exception:
+            pass
+            
         return {
-            "entities": self.bridge_log.get("entities_created", []),
-            "relations": self.bridge_log.get("relations_created", [])
+            "entities": entities,
+            "relations": relations
         }
 
     def mark_synced(self):
-        """Mark all pending operations as synced (clear log)."""
-        self.bridge_log = {"entities_created": [], "relations_created": []}
-        self._save_bridge_log()
+        """Mark all pending operations as synced (clear DB tables)."""
+        try:
+            with sqlite3.connect(self.bridge_db_path) as conn:
+                with conn:
+                    conn.execute("DELETE FROM pending_entities")
+                    conn.execute("DELETE FROM pending_relations")
+        except Exception:
+            pass
 
     def get_stats(self) -> Dict:
         """Get combined statistics."""
         memory_stats = self.memory.get_stats()
+        
+        pending_entities_count = 0
+        pending_relations_count = 0
+        try:
+             with sqlite3.connect(self.bridge_db_path) as conn:
+                 pending_entities_count = conn.execute("SELECT COUNT(*) FROM pending_entities").fetchone()[0]
+                 pending_relations_count = conn.execute("SELECT COUNT(*) FROM pending_relations").fetchone()[0]
+        except:
+            pass
 
         return {
             **memory_stats,
             "mcp_bridge": {
-                "entities_pending": len(self.bridge_log.get("entities_created", [])),
-                "relations_pending": len(self.bridge_log.get("relations_created", [])),
-                "mcp_threshold": self.MCP_THRESHOLD
+                "entities_pending": pending_entities_count,
+                "relations_pending": pending_relations_count,
+                "mcp_threshold": self.MCP_THRESHOLD,
+                "active_streams": len(self.stream_buffers)
             }
         }
 
     def auto_learn(self, task: str, result: str, success: bool,
                    domain: str = "learning") -> Dict:
-        """
-        Convenience method for common learning pattern.
-
-        Usage:
-            bridge.auto_learn(
-                task="Implemented orchestrator",
-                result="37% faster with parallel execution",
-                success=True
-            )
-        """
         if success:
             content = f"Success on '{task}': {result}"
         else:
@@ -308,24 +323,18 @@ class MCPMemoryBridge:
 class MCPSyncer:
     """
     Syncs pending bridge operations to actual MCP.
-
-    Run this within Claude Code context where MCP tools are available.
     """
 
     def __init__(self, bridge: MCPMemoryBridge):
         self.bridge = bridge
 
     def generate_sync_commands(self) -> str:
-        """
-        Generate MCP commands for pending operations.
-
-        Returns Python code that can be executed in Claude Code context.
-        """
         pending = self.bridge.get_pending_mcp_operations()
 
         commands = []
 
         if pending["entities"]:
+            # Batch in chunks if too large? For now dump all.
             entities = []
             for e in pending["entities"]:
                 entities.append({
@@ -360,11 +369,12 @@ if __name__ == "__main__":
 
     if len(sys.argv) < 2:
         print("""
-Genesis MCP Memory Bridge
+Genesis MCP Memory Bridge (v2 SQLite)
 =========================
 
 Commands:
   process "<content>"              Process and store if significant
+  stream "<content>" "<session>"   Process stream fragment
   learn "<task>" "<result>" [y/n]  Record learning (y=success, n=fail)
   observe "<action>" "<expected>"  Record observation
   reflect "<actual>"               Reflect on observations
@@ -372,14 +382,6 @@ Commands:
   sync-commands                    Generate MCP sync commands
   stats                            Show statistics
   clear                            Clear pending operations
-
-Examples:
-  python mcp_memory_bridge.py process "Discovery: asyncio.gather is 37% faster"
-  python mcp_memory_bridge.py learn "Implemented cache" "50% latency reduction" y
-  python mcp_memory_bridge.py observe "Deployed v2" "Smooth rollout"
-  python mcp_memory_bridge.py reflect "Rollout had issues due to config"
-  python mcp_memory_bridge.py pending
-  python mcp_memory_bridge.py sync-commands
         """)
         sys.exit(0)
 
@@ -389,6 +391,12 @@ Examples:
         content = " ".join(sys.argv[2:])
         result = bridge.process_with_mcp(content, domain="learning")
         print(json.dumps(result, indent=2))
+        
+    elif command == "stream" and len(sys.argv) >= 4:
+        content = sys.argv[2]
+        session = sys.argv[3]
+        bridge.process_stream(content, session)
+        print(f"Stream processed for {session}")
 
     elif command == "learn" and len(sys.argv) >= 4:
         task = sys.argv[2]


```
