File size: 12,714 Bytes
acb830b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
"""

Memory Hypergraph β€” Shahid's recursive JSON-based memory.



Replaces the RDF-based MemoryGraph. 

Uses a dynamic JSON structure to allow for recursion and transparency.

Everything stored here is QIYAS (approximation).

"""

import json
import logging
import os
from datetime import datetime, timezone
from typing import List, Dict, Optional, Any, Set
from pathlib import Path

logger = logging.getLogger(__name__)

class MemoryGraph:
    """

    Shahid's episodic + semantic memory as a JSON hypergraph.



    Stores:

    - Perceptions: Bilal's output (what Shahid heard)

    - Inferences: Discovered patterns or derivations

    - Syntheses: High-level understandings across multiple memories

    - Beliefs: Shahid's own authored assertions (formerly AuthoredTriples)

    - Episodes: Physical or virtual events (body state changes)



    Structure is based on the TMQ v10 hypergraph pattern:

    - nodes: Individual data points or events

    - edges: Relationships (hyperedges) connecting one or more nodes

    """

    def __init__(self, persist_path: Optional[str] = None):
        self.persist_path = persist_path
        self.nodes: Dict[str, Dict] = {}
        self.edges: Dict[str, Dict] = {}
        self._counter = 0
        
        if self.persist_path and os.path.exists(self.persist_path):
            self.load()

    def _mint_id(self, prefix: str) -> str:
        """Generate a unique ID for a new memory node or edge."""
        self._counter += 1
        ts = datetime.now(timezone.utc).strftime("%Y%m%d%H%M%S")
        return f"{prefix}_{ts}_{self._counter}"

    # ── Node Management ───────────────────────────────────────────

    def _add_node(self, node_type: str, content: Any, 

                  timestamp: Optional[str] = None, 

                  modal_state: Optional[Dict] = None,

                  metadata: Optional[Dict] = None) -> str:
        node_id = self._mint_id(node_type[:3].lower())
        self.nodes[node_id] = {
            "type": node_type,
            "timestamp": timestamp or datetime.now(timezone.utc).isoformat(),
            "content": content,
            "modal_state": modal_state or {},
            "meta": metadata or {}
        }
        return node_id

    # ── Edge Management ───────────────────────────────────────────

    def _add_edge(self, nodes: List[str], family: str, 

                  relation: str, modal: Optional[Dict] = None, 

                  meta: Optional[Dict] = None) -> str:
        edge_id = self._mint_id("edge")
        self.edges[edge_id] = {
            "nodes": nodes,
            "family": family,
            "relation": relation,
            "modal": modal or {},
            "meta": meta or {}
        }
        # Update nodes to track their membership in this edge
        for node_id in nodes:
            if node_id in self.nodes:
                if "edges" not in self.nodes[node_id]:
                    self.nodes[node_id]["edges"] = []
                self.nodes[node_id]["edges"].append(edge_id)
        
        return edge_id

    # ── Middleware Compatibility Methods ─────────────────────────

    def store_perception(self, perception) -> str:
        """

        Store a Bilal Perception.

        """
        content = {
            "source_text": perception.source_text[:1000],
            "roots": perception.roots,
            "signals": [
                {"root": s.root, "score": round(s.score, 3), "mode": s.mode}
                for s in perception.signals
            ],
            "cooccurrences": [
                {"a": co.root_a, "b": co.root_b, "count": co.count}
                for co in perception.cooccurrences
            ]
        }
        node_id = self._add_node("Perception", content, timestamp=perception.timestamp)
        
        # Auto-create edges for roots
        for root in perception.roots:
            self._add_edge([node_id], "RESONANCE", "resonates_with", meta={"root": root})
            
        self._auto_persist()
        return node_id

    def store_inference(self, perception_uri: str, pattern: str,

                        confidence: float, mode: str = "QIYAS",

                        narration: str = "") -> str:
        """

        Store an inference derived from a perception (or another node).

        'perception_uri' here is the node_id.

        """
        content = {
            "pattern": pattern,
            "confidence": round(confidence, 3),
            "mode": mode,
            "narration": narration
        }
        node_id = self._add_node("Inference", content)
        
        # Create a recursive edge back to the source
        self._add_edge([node_id, perception_uri], "RECURSION", "derived_from")
        
        self._auto_persist()
        return node_id

    def store_synthesis(self, perception_uris: List[str], pattern: str,

                        confidence: float) -> str:
        content = {
            "pattern": pattern,
            "confidence": round(confidence, 3),
            "mode": "QIYAS"
        }
        node_id = self._add_node("Synthesis", content)
        
        # Hyperedge connecting all source perceptions to this synthesis
        self._add_edge([node_id] + perception_uris, "SYNTHESIS", "synthesized_from")
        
        self._auto_persist()
        return node_id

    def store_chat(self, query: str, response: str, mode: str = "QIYAS",

                   roots: list = None, metadata: dict = None, context_id: str = None) -> str:
        content = {
            "query": query[:1000],
            "response": response[:2000],
            "mode": mode,
            "roots": roots or []
        }
        node_id = self._add_node("Chat", content, metadata=metadata)
        
        if roots:
            for root in roots:
                self._add_edge([node_id], "RESONANCE", "resonates_with", meta={"root": root})
        
        if context_id:
            self._add_edge([node_id, context_id], "LOGIC", "response_to")
                
        self._auto_persist()
        return node_id

    def store_trace(self, edges: List[Dict], context_node_id: str) -> str:
        """

        Stores the logical path (trace) through the hypergraph for a given interaction.

        """
        content = {
            "edges": edges,
            "timestamp": datetime.now(timezone.utc).isoformat()
        }
        node_id = self._add_node("Trace", content)
        
        # Link trace back to its context node (e.g., Perception or Chat)
        self._add_edge([node_id, context_node_id], "LOGIC", "trace_for")
        
        self._auto_persist()
        return node_id

    def store_authored_belief(self, subject: str, predicate: str, obj: str,

                               confidence: float = 0.5, source_thought: str = None) -> str:
        """

        Formerly store_authored_triple. 

        Stores Shahid's own assertions.

        """
        content = {
            "subject": subject,
            "predicate": predicate,
            "object": obj,
            "confidence": round(confidence, 3),
            "mode": "QIYAS"
        }
        node_id = self._add_node("Belief", content)
        
        if source_thought:
            self._add_edge([node_id, source_thought], "RECURSION", "derived_from")
            
        self._auto_persist()
        return node_id

    # ── Compatibility Aliases ────────────────────────────────────
    
    def store_authored_triple(self, *args, **kwargs):
        return self.store_authored_belief(*args, **kwargs)

    # ── Query & Stats ───────────────────────────────────────────

    def stats(self) -> Dict:
        counts = {}
        for node in self.nodes.values():
            t = node["type"].lower() + "s"
            counts[t] = counts.get(t, 0) + 1
            
        return {
            "total_nodes": len(self.nodes),
            "total_edges": len(self.edges),
            **counts,
            "authored": counts.get("beliefs", 0)
        }

    def query_recent(self, limit: int = 10) -> List[Dict]:
        sorted_nodes = sorted(
            self.nodes.items(), 
            key=lambda x: x[1].get("timestamp", ""), 
            reverse=True
        )
        results = []
        for nid, node in sorted_nodes[:limit]:
            results.append({"id": nid, **node})
        return results

    def store_thought(self, step_name: str, content: str, 

                      parent_id: Optional[str] = None, 

                      metadata: Optional[Dict] = None) -> str:
        """

        Stores a discrete step in Shahid's reasoning process.

        'parent_id' can be a Chat node, a Perception node, or another Thought node.

        """
        data = {
            "step": step_name,
            "content": content,
            "timestamp": datetime.now(timezone.utc).isoformat()
        }
        node_id = self._add_node("Thought", data, metadata=metadata)
        
        if parent_id:
            self._add_edge([node_id, parent_id], "LOGIC", "part_of")
            
        self._auto_persist()
        return node_id

    def query_by_type(self, node_type: str, limit: int = 10) -> List[Dict]:
        """Query nodes of a specific type, sorted by timestamp."""
        results = []
        for nid, node in self.nodes.items():
            if node["type"].lower() == node_type.lower():
                results.append({"id": nid, **node})
        
        return sorted(results, key=lambda x: x.get("timestamp", ""), reverse=True)[:limit]

    def query_semantic(self, text: str, limit: int = 5) -> List[Dict]:
        """

        Simple keyword-based semantic query. 

        In the future, this will use Bilal's embeddings.

        """
        text = text.lower()
        results = []
        for nid, node in self.nodes.items():
            content_str = str(node.get("content", "")).lower()
            if text in content_str:
                results.append({"id": nid, **node})
        
        return sorted(results, key=lambda x: x.get("timestamp", ""), reverse=True)[:limit]

    def add_custom_edge(self, nodes: List[str], relation: str, family: str = "CUSTOM", meta: Optional[Dict] = None) -> str:
        """Exposes edge creation to the agent."""
        edge_id = self._add_edge(nodes, family, relation, meta=meta)
        self._auto_persist()
        return edge_id

    # ── Persistence ──────────────────────────────────────────────

    def _auto_persist(self):
        if self.persist_path:
            self.save()

    def save(self, path: Optional[str] = None):
        target = path or self.persist_path
        if not target: return
        
        data = {
            "nodes": self.nodes,
            "edges": self.edges,
            "stats": self.stats(),
            "last_updated": datetime.now(timezone.utc).isoformat()
        }
        try:
            with open(target, "w", encoding="utf-8") as f:
                json.dump(data, f, indent=2)
            logger.info(f"Memory Hypergraph saved to {target}")
        except Exception as e:
            logger.error(f"Failed to save memory: {e}")

    def load(self, path: Optional[str] = None):
        target = path or self.persist_path
        if not target or not os.path.exists(target): return
        
        try:
            with open(target, "r", encoding="utf-8") as f:
                data = json.load(f)
            self.nodes = data.get("nodes", {})
            self.edges = data.get("edges", {})
            # Determine max counter from existing IDs
            ids = list(self.nodes.keys()) + list(self.edges.keys())
            for idx in ids:
                try:
                    num = int(idx.split("_")[-1])
                    if num > self._counter:
                        self._counter = num
                except: continue
            logger.info(f"Memory Hypergraph loaded from {target}")
        except Exception as e:
            logger.error(f"Failed to load memory: {e}")