File size: 7,945 Bytes
09801ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
ChatGPT-Level Persistent Memory System
======================================

THREE-LAYER MEMORY ARCHITECTURE:
1. USER PROFILE MEMORY (PERSISTENT)
   - Stores user-provided identity and preferences
   - Scoped strictly to user_id
   - Persists across sessions and chats

2. SESSION MEMORY (TEMPORARY)
   - Stores short-term conversational context
   - Cleared when session ends

3. WORKSPACE MEMORY (OPTIONAL)
   - Stores dataset-level context (schemas, defaults)

MEMORY WRITE RULES:
- Write on explicit user input only ("My name is X", "Call me X")
- Mark source as "explicit_user_input"
- Scope to user_id only
- NEVER guess or infer identity

MEMORY READ RULES:
- Always check USER PROFILE MEMORY before answering identity questions
- If exists → answer directly
- If not → ask politely

PRIVACY:
- Memory isolated per authenticated user
- No data sharing across users
- Never expose storage details
"""

import json
from pathlib import Path
from typing import Optional, Dict, Any, Tuple
from datetime import datetime

# Import paths utility
try:
    from utils.paths import get_user_paths
except ImportError:
    def get_user_paths(user_id):
        from pathlib import Path
        base = Path("storage/users") / user_id / "memory"
        base.mkdir(parents=True, exist_ok=True)
        return {"memory": base}


def get_user_context(user_id: str) -> str:
    """
    Get personalized context for user from stored memory.
    Returns formatted context string for LLM prompts.
    """
    if not user_id:
        return ""
    
    try:
        paths = get_user_paths(user_id)
        memory_path = paths["memory"] / "user_context.json"
        
        if not memory_path.exists():
            return ""
        
        with open(memory_path, 'r') as f:
            context = json.load(f)
        
        # Build context string
        parts = []
        
        if context.get("name"):
            parts.append(f"User Name: {context['name']}")
        
        if context.get("company"):
            parts.append(f"Company: {context['company']}")
        
        if context.get("role"):
            parts.append(f"Role: {context['role']}")
        
        if context.get("preferences"):
            parts.append(f"Preferences: {context['preferences']}")
        
        if context.get("last_topics"):
            topics = ", ".join(context['last_topics'][-5:])  # Last 5 topics
            parts.append(f"Recent Topics: {topics}")
        
        return "\n".join(parts) if parts else ""
        
    except Exception as e:
        print(f"Error loading user context: {e}")
        return ""


def get_user_name(user_id: str) -> Optional[str]:
    """
    MEMORY READ: Get user's name from persistent storage.
    
    This is the PRIMARY function for answering "What is my name?" questions.
    Returns None if name is not stored (triggers polite request).
    """
    if not user_id:
        return None
    
    try:
        paths = get_user_paths(user_id)
        memory_path = paths["memory"] / "user_context.json"
        
        if not memory_path.exists():
            return None
        
        with open(memory_path, 'r') as f:
            context = json.load(f)
        
        return context.get("name")
        
    except Exception as e:
        print(f"Error reading user name: {e}")
        return None


def save_user_context(user_id: str, context: Dict[str, Any]) -> bool:
    """
    Save or update user context to persistent storage.
    """
    if not user_id:
        return False
    
    try:
        paths = get_user_paths(user_id)
        memory_path = paths["memory"] / "user_context.json"
        
        # Load existing context if any
        existing = {}
        if memory_path.exists():
            with open(memory_path, 'r') as f:
                existing = json.load(f)
        
        # Merge with new context
        existing.update(context)
        existing["updated_at"] = datetime.now().isoformat()
        
        # Save
        with open(memory_path, 'w') as f:
            json.dump(existing, f, indent=2)
        
        print(f"💾 Saved user context for {user_id}")
        return True
        
    except Exception as e:
        print(f"⚠️ Error saving user context: {e}")
        return False


def process_personal_info(user_id: str, query: str) -> bool:
    """
    Extract and save personal information from user's message.
    Looks for patterns like "My name is X", "I work at Y", etc.
    """
    if not user_id or not query:
        return False
    
    import re
    context_updates = {}
    
    # Extract name - EXPANDED PATTERNS (case-insensitive, auto-capitalize)
    name_patterns = [
        r"(?:my name is|i am|i'm|this is|call me|hey i'm|hi i'm|hello i'm)\s+([a-zA-Z]+(?:\s+[a-zA-Z]+)?)",
        r"^([a-zA-Z]+)\s+here\b",  # "naveen here"
        r"^i'm?\s+([a-zA-Z]+)\b",  # "I'm naveen" at start
        r"^([a-zA-Z]+)$",  # Just a name by itself like "naveen"
    ]
    for pattern in name_patterns:
        match = re.search(pattern, query.strip(), re.IGNORECASE)
        if match:
            # Auto-capitalize the name
            context_updates["name"] = match.group(1).strip().title()
            print(f"💾 Extracted name: {context_updates['name']}")
            break
    
    # Extract company
    company_patterns = [
        r"i work (?:at|for) ([A-Z][A-Za-z\s]+(?:Inc|Corp|Ltd|LLC)?)",
        r"my company is ([A-Z][A-Za-z\s]+)",
        r"(?:at|from) ([A-Z][A-Za-z]+(?:\s+[A-Z][A-Za-z]+)*) company",
    ]
    for pattern in company_patterns:
        match = re.search(pattern, query, re.IGNORECASE)
        if match:
            context_updates["company"] = match.group(1).strip()
            break
    
    # Extract role
    role_patterns = [
        r"i'?m (?:a|an|the) ([A-Za-z\s]+(?:manager|director|ceo|cfo|analyst|engineer|developer))",
        r"my (?:role|job|position) is ([A-Za-z\s]+)",
    ]
    for pattern in role_patterns:
        match = re.search(pattern, query, re.IGNORECASE)
        if match:
            context_updates["role"] = match.group(1).strip()
            break
    
    if context_updates:
        return save_user_context(user_id, context_updates)
    
    return False


def add_conversation_topic(user_id: str, topic: str) -> bool:
    """
    Add a topic to user's recent topics for context.
    """
    if not user_id or not topic:
        return False
    
    try:
        paths = get_user_paths(user_id)
        memory_path = paths["memory"] / "user_context.json"
        
        existing = {}
        if memory_path.exists():
            with open(memory_path, 'r') as f:
                existing = json.load(f)
        
        # Add topic to list (keep last 10)
        topics = existing.get("last_topics", [])
        if topic not in topics:
            topics.append(topic)
            topics = topics[-10:]
        existing["last_topics"] = topics
        existing["updated_at"] = datetime.now().isoformat()
        
        with open(memory_path, 'w') as f:
            json.dump(existing, f, indent=2)
        
        return True
        
    except Exception as e:
        print(f"⚠️ Error adding topic: {e}")
        return False


def get_memory():
    """
    Get global memory instance - returns a simple dict-based memory.
    For more advanced memory, use memory_engine.py
    """
    return {"active": True, "type": "persistent"}


def clear_user_memory(user_id: str) -> bool:
    """
    Clear all stored memory for a user.
    """
    if not user_id:
        return False
    
    try:
        paths = get_user_paths(user_id)
        memory_path = paths["memory"] / "user_context.json"
        
        if memory_path.exists():
            memory_path.unlink()
            print(f"🗑️ Cleared memory for {user_id}")
        
        return True
        
    except Exception as e:
        print(f"⚠️ Error clearing memory: {e}")
        return False