File size: 12,629 Bytes
b8e3e42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
#!/usr/bin/env python3
"""
Stack 2.9 - Context Management Module
Handles project awareness, session memory, and long-term memory integration.
"""

import os
import json
import re
from pathlib import Path
from typing import Any, Dict, List, Optional, Set
from datetime import datetime, timedelta
from dataclasses import dataclass, field
from collections import defaultdict


@dataclass
class ProjectContext:
    """Represents a project's context."""
    name: str
    path: str
    language: Optional[str] = None
    framework: Optional[str] = None
    files: List[str] = field(default_factory=list)
    dirs: List[str] = field(default_factory=list)
    has_git: bool = False
    dependencies: List[str] = field(default_factory=list)
    entry_points: List[str] = field(default_factory=list)
    metadata: Dict[str, Any] = field(default_factory=dict)


@dataclass
class SessionMemory:
    """Represents the current session's memory."""
    messages: List[Dict[str, Any]] = field(default_factory=list)
    tools_used: List[str] = field(default_factory=list)
    files_touched: List[str] = field(default_factory=list)
    commands_run: List[str] = field(default_factory=list)
    created_at: datetime = field(default_factory=datetime.now)
    last_updated: datetime = field(default_factory=datetime.now)
    
    def add_message(self, role: str, content: str, metadata: Optional[Dict] = None):
        """Add a message to session memory."""
        self.messages.append({
            "role": role,
            "content": content,
            "timestamp": datetime.now().isoformat(),
            "metadata": metadata or {}
        })
        self.last_updated = datetime.now()
    
    def add_tool_usage(self, tool_name: str, result: Any):
        """Record tool usage."""
        self.tools_used.append({
            "tool": tool_name,
            "timestamp": datetime.now().isoformat(),
            "success": result.get("success", False) if isinstance(result, dict) else True
        })
        self.last_updated = datetime.now()
    
    def add_file_touched(self, file_path: str, action: str):
        """Record file access."""
        self.files_touched.append({
            "path": file_path,
            "action": action,
            "timestamp": datetime.now().isoformat()
        })
        self.last_updated = datetime.now()
    
    def add_command(self, command: str, result: Optional[Dict] = None):
        """Record command execution."""
        self.commands_run.append({
            "command": command,
            "result": result,
            "timestamp": datetime.now().isoformat()
        })
        self.last_updated = datetime.now()
    
    def get_summary(self) -> Dict[str, Any]:
        """Get session summary."""
        return {
            "messages_count": len(self.messages),
            "tools_used_count": len(self.tools_used),
            "files_touched_count": len(self.files_touched),
            "commands_run_count": len(self.commands_run),
            "duration_minutes": (datetime.now() - self.created_at).total_seconds() / 60,
            "created_at": self.created_at.isoformat(),
            "last_updated": self.last_updated.isoformat()
        }


class ContextManager:
    """Manages context across projects, sessions, and long-term memory."""
    
    def __init__(self, workspace_path: str = "/Users/walidsobhi/.openclaw/workspace"):
        self.workspace = Path(workspace_path)
        self.session = SessionMemory()
        self.projects: Dict[str, ProjectContext] = {}
        self.current_project: Optional[ProjectContext] = None
        self._load_context()
    
    def _load_context(self):
        """Load existing context files."""
        # Load workspace context files
        context_files = {
            "AGENTS.md": "agents",
            "SOUL.md": "soul",
            "TOOLS.md": "tools",
            "USER.md": "user",
            "MEMORY.md": "memory"
        }
        
        self.context = {}
        for filename, key in context_files.items():
            file_path = self.workspace / filename
            if file_path.exists():
                self.context[key] = file_path.read_text(encoding='utf-8')
        
        # Scan for projects
        self._scan_projects()
    
    def _scan_projects(self):
        """Scan workspace for projects."""
        for item in self.workspace.iterdir():
            if item.is_dir() and not item.name.startswith('.'):
                # Check if it's a project
                if (item / "pyproject.toml").exists() or (item / "package.json").exists():
                    self.projects[item.name] = ProjectContext(
                        name=item.name,
                        path=str(item)
                    )
    
    def load_project(self, project_name: str) -> Optional[ProjectContext]:
        """Load a specific project."""
        project_path = self.workspace / project_name
        
        if not project_path.exists():
            return None
        
        # Create project context
        ctx = ProjectContext(
            name=project_name,
            path=str(project_path)
        )
        
        # Detect language/framework
        if (project_path / "pyproject.toml").exists():
            ctx.language = "python"
            try:
                content = (project_path / "pyproject.toml").read_text()
                if "fastapi" in content:
                    ctx.framework = "fastapi"
                elif "django" in content:
                    ctx.framework = "django"
                elif "flask" in content:
                    ctx.framework = "flask"
            except:
                pass
        
        if (project_path / "package.json").exists():
            ctx.language = "javascript"
            try:
                content = json.loads((project_path / "package.json").read_text())
                ctx.dependencies = list(content.get("dependencies", {}).keys())
                if "next" in content.get("dependencies", {}):
                    ctx.framework = "next"
                elif "react" in content.get("dependencies", {}):
                    ctx.framework = "react"
            except:
                pass
        
        # Check for git
        ctx.has_git = (project_path / ".git").exists()
        
        # Scan files
        try:
            for item in project_path.rglob("*"):
                if len(ctx.files) > 100:
                    break
                rel = item.relative_to(project_path)
                if item.is_file():
                    ctx.files.append(str(rel))
                elif item.is_dir() and not item.name.startswith('.'):
                    ctx.dirs.append(str(rel))
        except:
            pass
        
        # Find entry points
        entry_patterns = ["main.py", "app.py", "index.js", "main.js", "server.py"]
        for pattern in entry_patterns:
            for f in ctx.files:
                if f.endswith(pattern):
                    ctx.entry_points.append(f)
        
        self.projects[project_name] = ctx
        self.current_project = ctx
        return ctx
    
    def get_context_summary(self) -> Dict[str, Any]:
        """Get context summary."""
        return {
            "workspace": str(self.workspace),
            "projects": list(self.projects.keys()),
            "current_project": self.current_project.name if self.current_project else None,
            "session": self.session.get_summary(),
            "has_agents": "agents" in self.context,
            "has_soul": "soul" in self.context,
            "has_tools": "tools" in self.context,
            "has_memory": "memory" in self.context
        }
    
    def get_workspace_context(self) -> str:
        """Get formatted workspace context."""
        lines = ["# Workspace Context"]
        lines.append(f"\n## Projects ({len(self.projects)})")
        
        for name, proj in self.projects.items():
            lines.append(f"- **{name}** ({proj.language or 'unknown'})")
            if proj.framework:
                lines.append(f"  - Framework: {proj.framework}")
            lines.append(f"  - Path: {proj.path}")
            if proj.has_git:
                lines.append("  - Git: ✓")
        
        if self.current_project:
            lines.append(f"\n## Current Project: {self.current_project.name}")
            lines.append(f"- Files: {len(self.current_project.files)}")
            lines.append(f"- Dirs: {len(self.current_project.dirs)}")
            if self.current_project.entry_points:
                lines.append(f"- Entry: {self.current_project.entry_points[0]}")
        
        lines.append(f"\n## Session")
        summary = self.session.get_summary()
        lines.append(f"- Messages: {summary['messages_count']}")
        lines.append(f"- Tools used: {summary['tools_used_count']}")
        lines.append(f"- Files touched: {summary['files_touched_count']}")
        
        return "\n".join(lines)
    
    def search_memory(self, query: str, max_results: int = 5) -> List[Dict[str, Any]]:
        """Search long-term memory."""
        results = []
        
        # Search MEMORY.md
        memory_file = self.workspace / "MEMORY.md"
        if memory_file.exists():
            content = memory_file.read_text()
            if query.lower() in content.lower():
                results.append({
                    "file": str(memory_file),
                    "type": "memory",
                    "content": content[:500]
                })
        
        # Search memory folder
        memory_dir = self.workspace / "memory"
        if memory_dir.exists():
            for f in memory_dir.rglob("*.md"):
                try:
                    content = f.read_text()
                    if query.lower() in content.lower():
                        results.append({
                            "file": str(f),
                            "type": "daily",
                            "content": content[:500]
                        })
                except:
                    continue
        
        return results[:max_results]
    
    def save_to_memory(self, key: str, value: str):
        """Save to long-term memory."""
        memory_file = self.workspace / "MEMORY.md"
        
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M")
        entry = f"\n### {key}\n_{timestamp}_\n{value}\n"
        
        with open(memory_file, "a") as f:
            f.write(entry)
    
    def get_recent_context(self, days: int = 7) -> List[Dict[str, Any]]:
        """Get recent context from memory."""
        results = []
        
        memory_dir = self.workspace / "memory"
        if memory_dir.exists():
            # Get files from last N days
            cutoff = datetime.now() - timedelta(days=days)
            
            for f in sorted(memory_dir.glob("*.md"), key=lambda x: x.stat().st_mtime, reverse=True):
                try:
                    mtime = datetime.fromtimestamp(f.stat().st_mtime)
                    if mtime > cutoff:
                        content = f.read_text()
                        results.append({
                            "file": str(f),
                            "date": mtime.isoformat(),
                            "content": content[:1000]
                        })
                except:
                    continue
        
        return results


class ProjectAware:
    """Mixin for project-aware functionality."""
    
    def __init__(self):
        self.context_manager = ContextManager()
    
    def detect_project(self, path: str) -> Optional[str]:
        """Detect project from path."""
        p = Path(path).resolve()
        
        # Walk up to find project root
        while p != p.parent:
            for name in ["pyproject.toml", "package.json", "Cargo.toml", "go.mod"]:
                if (p / name).exists():
                    return p.name
            p = p.parent
        
        return None
    
    def get_project_context(self, project_name: str) -> Optional[ProjectContext]:
        """Get project context."""
        return self.context_manager.load_project(project_name)
    
    def format_context_for_prompt(self) -> str:
        """Format context for LLM prompt."""
        return self.context_manager.get_workspace_context()


def create_context_manager(workspace: Optional[str] = None) -> ContextManager:
    """Factory function to create context manager."""
    return ContextManager(workspace or "/Users/walidsobhi/.openclaw/workspace")


if __name__ == "__main__":
    print("Stack 2.9 Context Module")
    cm = ContextManager()
    print(cm.get_context_summary())