Coverage for /Users/les/Projects/crackerjack/crackerjack/core/session_coordinator.py: 0%

155 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-09-03 15:39 -0700

1import json 

2import logging 

3import time 

4import typing as t 

5from contextlib import suppress 

6from pathlib import Path 

7 

8from rich.console import Console 

9 

10from crackerjack.models.protocols import OptionsProtocol 

11from crackerjack.models.task import SessionTracker 

12 

13 

14class SessionCoordinator: 

15 def __init__( 

16 self, 

17 console: Console, 

18 pkg_path: Path, 

19 web_job_id: str | None = None, 

20 ) -> None: 

21 self.console = console 

22 self.pkg_path = pkg_path 

23 self.session_tracker: SessionTracker | None = None 

24 self._cleanup_handlers: list[t.Callable[[], None]] = [] 

25 self._thread_pool = None 

26 self._lock_files: set[Path] = set() 

27 

28 import uuid 

29 

30 self.session_id = web_job_id or str(uuid.uuid4()) 

31 self.web_job_id = web_job_id 

32 self.start_time = time.time() 

33 self.tasks: dict[str, t.Any] = {} 

34 self.current_task: str | None = None 

35 self.success: bool = False 

36 

37 self._setup_logging() 

38 

39 if self.web_job_id: 

40 self._setup_websocket_progress_file() 

41 

42 def start_session(self, task_name: str) -> None: 

43 self.current_task = task_name 

44 

45 def end_session(self, success: bool = True) -> None: 

46 self.success = success 

47 self.end_time = time.time() 

48 if success: 

49 self.complete_task("session", "Session completed successfully") 

50 else: 

51 self.fail_task("session", "Session completed with errors") 

52 

53 def initialize_session_tracking(self, options: OptionsProtocol) -> None: 

54 if hasattr(options, "track_progress") and options.track_progress: 

55 import uuid 

56 

57 self.session_tracker = SessionTracker( 

58 console=self.console, 

59 session_id=str(uuid.uuid4()), 

60 start_time=time.time(), 

61 ) 

62 

63 def track_task(self, task_id: str, task_name: str) -> str: 

64 import time 

65 

66 task_obj = type( 

67 "Task", 

68 (), 

69 { 

70 "task_id": task_id, 

71 "description": task_name, 

72 "start_time": time.time(), 

73 "status": "in_progress", 

74 "details": None, 

75 "end_time": None, 

76 "progress": 0, 

77 }, 

78 )() 

79 

80 self.tasks[task_id] = task_obj 

81 

82 if self.session_tracker: 

83 self.session_tracker.start_task(task_id, task_name) 

84 

85 return task_id 

86 

87 def update_task( 

88 self, 

89 task_id: str, 

90 status: str, 

91 details: str | None = None, 

92 progress: int | None = None, 

93 ) -> None: 

94 if task_id in self.tasks: 

95 task = self.tasks[task_id] 

96 task.status = status 

97 if details: 

98 task.details = details 

99 if progress is not None: 

100 task.progress = progress 

101 

102 if status in ("completed", "failed"): 

103 task.end_time = time.time() 

104 

105 def complete_task(self, task_id: str, details: str | None = None) -> None: 

106 if self.session_tracker: 

107 self.session_tracker.complete_task(task_id, details=details) 

108 

109 def fail_task(self, task_id: str, error: str) -> None: 

110 if self.session_tracker: 

111 self.session_tracker.fail_task(task_id, error) 

112 

113 def get_session_summary(self) -> dict[str, int] | None: 

114 if self.session_tracker: 

115 return self.session_tracker.get_summary() 

116 return None 

117 

118 def get_summary(self) -> dict[str, t.Any]: 

119 duration = getattr(self, "end_time", time.time()) - self.start_time 

120 tasks_count = len(self.tasks) 

121 

122 if self.session_tracker: 

123 return self.session_tracker.get_summary() 

124 

125 return { 

126 "session_id": self.session_id, 

127 "duration": duration, 

128 "tasks_count": tasks_count, 

129 "success": self.success, 

130 "tasks": [ 

131 { 

132 "task_id": task.task_id, 

133 "description": task.description, 

134 "status": task.status, 

135 "details": task.details, 

136 "start_time": task.start_time, 

137 "end_time": task.end_time, 

138 "progress": task.progress, 

139 } 

140 for task in self.tasks.values() 

141 ], 

142 } 

143 

144 def finalize_session(self, start_time: float, success: bool) -> None: 

145 total_time = time.time() - start_time 

146 if success: 

147 self.complete_task( 

148 "workflow", 

149 f"Completed successfully in {total_time: .1f}s", 

150 ) 

151 else: 

152 self.complete_task( 

153 "workflow", 

154 f"Completed with issues in {total_time: .1f}s", 

155 ) 

156 

157 def register_cleanup(self, cleanup_handler: t.Callable[[], None]) -> None: 

158 self._cleanup_handlers.append(cleanup_handler) 

159 

160 def track_lock_file(self, lock_file_path: Path) -> None: 

161 self._lock_files.add(lock_file_path) 

162 

163 def cleanup_resources(self) -> None: 

164 for cleanup_handler in self._cleanup_handlers: 

165 with suppress(Exception): 

166 cleanup_handler() 

167 

168 self._cleanup_temporary_files() 

169 

170 def _cleanup_temporary_files(self) -> None: 

171 if not hasattr(self, "_cleanup_config") or self._cleanup_config is None: 

172 self._cleanup_debug_logs() 

173 self._cleanup_coverage_files() 

174 self._cleanup_pycache_directories() 

175 elif self._cleanup_config.auto_cleanup: 

176 self._cleanup_debug_logs(keep_recent=self._cleanup_config.keep_debug_logs) 

177 self._cleanup_coverage_files( 

178 keep_recent=self._cleanup_config.keep_coverage_files, 

179 ) 

180 self._cleanup_pycache_directories() 

181 

182 def set_cleanup_config(self, cleanup_config: t.Any) -> None: 

183 self._cleanup_config = cleanup_config 

184 

185 def _cleanup_debug_logs(self, keep_recent: int = 5) -> None: 

186 with suppress(Exception): 

187 from crackerjack.services.log_manager import get_log_manager 

188 

189 log_manager = get_log_manager() 

190 

191 log_manager.rotate_logs( 

192 log_manager.debug_dir, 

193 "debug-*.log", 

194 max_files=keep_recent, 

195 max_age_days=7, 

196 ) 

197 

198 legacy_pattern = "crackerjack - debug-*.log" 

199 legacy_files = sorted( 

200 self.pkg_path.glob(legacy_pattern), 

201 key=lambda p: p.stat().st_mtime, 

202 ) 

203 

204 for old_file in legacy_files[:-keep_recent]: 

205 with suppress(FileNotFoundError, PermissionError): 

206 old_file.unlink() 

207 

208 def _cleanup_coverage_files(self, keep_recent: int = 10) -> None: 

209 with suppress(Exception): 

210 cache_dir = Path.home() / ".cache" / "crackerjack" / "coverage" 

211 if cache_dir.exists(): 

212 pattern = ".coverage *" 

213 coverage_files = sorted( 

214 cache_dir.glob(pattern), 

215 key=lambda p: p.stat().st_mtime, 

216 ) 

217 

218 for old_file in coverage_files[:-keep_recent]: 

219 with suppress(FileNotFoundError, PermissionError): 

220 old_file.unlink() 

221 

222 pattern = ".coverage.*" 

223 coverage_files = sorted( 

224 self.pkg_path.glob(pattern), 

225 key=lambda p: p.stat().st_mtime, 

226 ) 

227 

228 for old_file in coverage_files: 

229 with suppress(FileNotFoundError, PermissionError): 

230 old_file.unlink() 

231 

232 def _cleanup_pycache_directories(self) -> None: 

233 with suppress(Exception): 

234 import shutil 

235 

236 for pycache_dir in self.pkg_path.rglob("__pycache__"): 

237 if pycache_dir.is_dir(): 

238 with suppress(FileNotFoundError, PermissionError): 

239 shutil.rmtree(pycache_dir) 

240 

241 def _setup_logging(self) -> None: 

242 logger = logging.getLogger("crackerjack") 

243 if not logger.handlers: 

244 handler = logging.StreamHandler() 

245 handler.setLevel(logging.WARNING) 

246 logger.addHandler(handler) 

247 logger.setLevel(logging.WARNING) 

248 

249 def _setup_websocket_progress_file(self) -> None: 

250 import tempfile 

251 

252 self.progress_dir = Path(tempfile.gettempdir()) / "crackerjack - mcp-progress" 

253 self.progress_file = self.progress_dir / f"job -{self.web_job_id}.json" 

254 

255 if self.progress_file.exists(): 

256 self._update_websocket_progress("running", "Crackerjack process started") 

257 

258 def _update_websocket_progress(self, status: str, message: str) -> None: 

259 if not hasattr(self, "progress_file") or not self.progress_file: 

260 return 

261 

262 try: 

263 progress_data = {} 

264 if self.progress_file.exists(): 

265 progress_data = json.loads(self.progress_file.read_text()) 

266 

267 progress_data.update( 

268 { 

269 "status": status, 

270 "message": message, 

271 "updated_at": time.time(), 

272 "current_stage": message, 

273 }, 

274 ) 

275 

276 self.progress_file.write_text(json.dumps(progress_data, indent=2)) 

277 

278 except Exception as e: 

279 self.console.print( 

280 f"[dim yellow]Warning: Could not update progress file: {e}[/ dim yellow]", 

281 ) 

282 

283 def update_stage(self, stage: str, status: str) -> None: 

284 if self.web_job_id: 

285 self._update_websocket_progress(status, f"{stage}: {status}")