Spaces:
Sleeping

File size: 10,004 Bytes
358492d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f7b159
 
 
 
 
358492d
 
 
 
 
 
 
 
 
9f7b159
 
 
 
 
358492d
 
 
 
 
 
9f7b159
 
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
import os
import time
import threading
import logging
import asyncio

logger = logging.getLogger(__name__)

class CodebaseWatcher:
    """Monitors the codebase files for changes and automatically rebuilds dependency graphs.
    
    Uses incremental AST updates for sub-second sync and broadcasts notifications via WebSockets.
    """
    
    def __init__(self, debounce_sec: float = 2.0, poll_interval_sec: float = 1.0):
        self.debounce_sec = debounce_sec
        self.poll_interval_sec = poll_interval_sec
        self.scopes = {
            "studiq": "/Users/baljotchohan/Projects/StudIQ/studiq",
            "root": "/Users/baljotchohan/Projects/StudIQ"
        }
        self.last_mtime = {}
        self.change_detected = {}
        self.last_change_time = {}
        self.running = False
        self.thread = None
        self.active_builds = set()
        self.build_lock = threading.Lock()
        self.file_mtimes = {}
        self.modified_files_queue = {}

    def start(self):
        if self.running:
            return
        self.running = True
        
        # Initialize state and run startup sync checks
        for scope, path in self.scopes.items():
            self.file_mtimes[scope] = {}
            self.change_detected[scope] = False
            self.last_change_time[scope] = 0
            self.modified_files_queue[scope] = set()
            
            # Populate initial file times
            self._scan_and_populate_mtimes(scope, path)
            current_mtime = max(self.file_mtimes[scope].values()) if self.file_mtimes[scope] else 0.0
            self.last_mtime[scope] = current_mtime
            
            # Rebuild on startup if codebase is newer than graph.json
            graph_json = os.path.join(path, "graphify-out", "graph.json")
            changed_files_on_startup = []
            needs_full_rebuild = False
            
            if os.path.exists(graph_json):
                try:
                    graph_mtime = os.path.getmtime(graph_json)
                    for file_path, mtime in self.file_mtimes[scope].items():
                        if mtime > graph_mtime + 2.0:
                            changed_files_on_startup.append(file_path)
                except Exception:
                    needs_full_rebuild = True
            else:
                needs_full_rebuild = True
                
            if needs_full_rebuild or len(changed_files_on_startup) > 20:
                logger.info(f"[Code Watcher] Codebase changes require full rebuild on startup for scope '{scope}'...")
                self._trigger_rebuild(scope, [], is_startup=True)
            elif changed_files_on_startup:
                logger.info(f"[Code Watcher] Codebase changes detected on startup for scope '{scope}' on {len(changed_files_on_startup)} files. Triggering fast incremental sync...")
                self._trigger_rebuild(scope, changed_files_on_startup, is_startup=False)

        self.thread = threading.Thread(target=self._watch_loop, daemon=True)
        self.thread.start()
        logger.info("[Code Watcher] Background directory monitor initialized.")

    def stop(self):
        self.running = False
        if self.thread:
            self.thread.join(timeout=2.0)
            logger.info("[Code Watcher] Background directory monitor stopped.")

    def _scan_and_populate_mtimes(self, scope: str, dir_path: str):
        """Scans the directory and populates the initial modification times for all code files."""
        for root, dirs, files in os.walk(dir_path):
            dirs[:] = [d for d in dirs if d not in [
                "venv", "graphify_venv", ".git", "__pycache__", "graphify-out", "scratch", ".gemini", "node_modules"
            ]]
            for file in files:
                if file.endswith((".py", ".js", ".html", ".css", ".json")):
                    if "graphify-out" in root:
                        continue
                    file_path = os.path.join(root, file)
                    try:
                        self.file_mtimes[scope][file_path] = os.path.getmtime(file_path)
                    except Exception:
                        pass

    def _watch_loop(self):
        while self.running:
            time.sleep(self.poll_interval_sec)
            now = time.time()
            
            for scope, path in self.scopes.items():
                try:
                    # Scan directory for changed files
                    changed_files = []
                    stored_mtimes = self.file_mtimes.get(scope, {})
                    
                    for root, dirs, files in os.walk(path):
                        dirs[:] = [d for d in dirs if d not in [
                            "venv", "graphify_venv", ".git", "__pycache__", "graphify-out", "scratch", ".gemini", "node_modules"
                        ]]
                        for file in files:
                            if file.endswith((".py", ".js", ".html", ".css", ".json")):
                                if "graphify-out" in root:
                                    continue
                                file_path = os.path.join(root, file)
                                try:
                                    mtime = os.path.getmtime(file_path)
                                    prev_mtime = stored_mtimes.get(file_path)
                                    
                                    # Update state and flag modification
                                    if prev_mtime is not None and mtime > prev_mtime:
                                        changed_files.append(file_path)
                                    stored_mtimes[file_path] = mtime
                                except Exception:
                                    pass
                    
                    if changed_files:
                        logger.info(f"[Code Watcher] {len(changed_files)} file change(s) detected in scope '{scope}': {changed_files}")
                        self.change_detected[scope] = True
                        self.last_change_time[scope] = now
                        self.modified_files_queue[scope].update(changed_files)
                except Exception as e:
                    logger.error(f"[Code Watcher] Error in watch loop for scope '{scope}': {e}")
                    continue
                
                # Trigger build once files have settled
                if self.change_detected[scope] and (now - self.last_change_time[scope] >= self.debounce_sec):
                    self.change_detected[scope] = False
                    modified_list = list(self.modified_files_queue[scope])
                    self.modified_files_queue[scope].clear()
                    
                    logger.info(f"[Code Watcher] Debounce window elapsed for scope '{scope}'. Triggering incremental rebuild for: {modified_list}")
                    self._trigger_rebuild(scope, modified_list, is_startup=False)

    def _trigger_rebuild(self, scope: str, modified_files: list[str], is_startup: bool = False):
        with self.build_lock:
            if scope in self.active_builds:
                logger.info(f"[Code Watcher] Rebuild already in progress for scope '{scope}'. Queuing files.")
                # Put them back in queue
                self.modified_files_queue[scope].update(modified_files)
                return
            self.active_builds.add(scope)
            
        loop = asyncio.new_event_loop()
        threading.Thread(target=self._run_async_task, args=(loop, scope, modified_files, is_startup), daemon=True).start()

    def _run_async_task(self, loop, scope, modified_files, is_startup):
        try:
            asyncio.set_event_loop(loop)
            loop.run_until_complete(self._execute_update(scope, modified_files, is_startup))
            loop.close()
        except Exception as e:
            logger.error(f"[Code Watcher] Error running graphify update for scope '{scope}': {e}")
        finally:
            with self.build_lock:
                self.active_builds.discard(scope)
            logger.info(f"[Code Watcher] Background rebuild finished for scope '{scope}'.")

    async def _execute_update(self, scope: str, modified_files: list[str], is_startup: bool):
        if is_startup or not modified_files:
            # Startup fallback: Run slow full rebuild to ensure consistency
            logger.info(f"[Code Watcher] Running full sync rebuild on startup for scope '{scope}'...")
            try:
                from app.api.v1.admin import rebuild_code_graph_task
                await rebuild_code_graph_task(scope)
            except ImportError:
                logger.debug(f"[Code Watcher] rebuild_code_graph_task not available for scope '{scope}'.")
        else:
            # Standard dev flow: Run fast incremental update
            from app.services.incremental_updater import update_codebase_graph_incrementally
            logger.info(f"[Code Watcher] Running fast incremental update for scope '{scope}'...")
            success = update_codebase_graph_incrementally(scope, modified_files)
            if success:
                logger.info(f"[Code Watcher] Fast incremental update succeeded for scope '{scope}'")
            else:
                logger.warning("[Code Watcher] Incremental update failed. Falling back to full rebuild.")
                try:
                    from app.api.v1.admin import rebuild_code_graph_task
                    await rebuild_code_graph_task(scope)
                except ImportError:
                    logger.debug(f"[Code Watcher] rebuild_code_graph_task not available for scope '{scope}'.")

        # Broadcast update to active browser WebSocket clients
        try:
            from app.api.v1.admin import code_graph_manager
            logger.info(f"[Code Watcher] Broadcasting 'graph_updated' event for scope '{scope}'")
            await code_graph_manager.broadcast({"event": "graph_updated", "scope": scope})
        except Exception:
            pass