Coverage for /Users/les/Projects/crackerjack/crackerjack/mcp/tools/workflow_executor.py: 0%

175 statements  

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

1import asyncio 

2import time 

3import typing as t 

4import uuid 

5 

6from crackerjack.mcp.context import get_context 

7 

8from .progress_tools import _update_progress 

9 

10 

11async def execute_crackerjack_workflow( 

12 args: str, kwargs: dict[str, t.Any] 

13) -> dict[str, t.Any]: 

14 job_id = str(uuid.uuid4())[:8] 

15 

16 try: 

17 return await _execute_crackerjack_sync(job_id, args, kwargs, get_context()) 

18 except Exception as e: 

19 import traceback 

20 

21 error_details = traceback.format_exc() 

22 return { 

23 "job_id": job_id, 

24 "status": "failed", 

25 "error": f"Execution failed: {e}", 

26 "traceback": error_details, 

27 "timestamp": time.time(), 

28 } 

29 

30 

31async def _execute_crackerjack_sync( 

32 job_id: str, 

33 args: str, 

34 kwargs: dict[str, t.Any], 

35 context: t.Any, 

36) -> dict[str, t.Any]: 

37 setup_result = await _initialize_execution(job_id, args, kwargs, context) 

38 if setup_result.get("status") == "failed": 

39 return setup_result 

40 

41 orchestrator_result = await _setup_orchestrator( 

42 job_id, args, kwargs, setup_result["working_dir"], context 

43 ) 

44 if orchestrator_result.get("status") == "failed": 

45 return orchestrator_result 

46 

47 orchestrator = orchestrator_result["orchestrator"] 

48 

49 return await _run_workflow_iterations(job_id, orchestrator, kwargs, context) 

50 

51 

52async def _initialize_execution( 

53 job_id: str, 

54 args: str, 

55 kwargs: dict[str, t.Any], 

56 context: t.Any, 

57) -> dict[str, t.Any]: 

58 _update_progress( 

59 job_id, 

60 { 

61 "type": "initialization", 

62 "status": "starting", 

63 "message": "Initializing crackerjack execution...", 

64 }, 

65 context, 

66 ) 

67 

68 working_dir = kwargs.get("working_directory", ".") 

69 from pathlib import Path 

70 

71 working_path = Path(working_dir) 

72 if not working_path.exists(): 

73 return { 

74 "status": "failed", 

75 "error": f"Working directory does not exist: {working_dir}", 

76 "job_id": job_id, 

77 } 

78 

79 _update_progress( 

80 job_id, 

81 { 

82 "type": "initialization", 

83 "status": "ready", 

84 "working_directory": str(working_path.absolute()), 

85 }, 

86 context, 

87 ) 

88 

89 return { 

90 "status": "initialized", 

91 "working_dir": working_path.absolute(), 

92 "job_id": job_id, 

93 } 

94 

95 

96async def _setup_orchestrator( 

97 job_id: str, 

98 args: str, 

99 kwargs: dict[str, t.Any], 

100 working_dir: t.Any, 

101 context: t.Any, 

102) -> dict[str, t.Any]: 

103 _update_progress( 

104 job_id, 

105 { 

106 "type": "setup", 

107 "status": "creating_orchestrator", 

108 "message": "Setting up workflow orchestrator...", 

109 }, 

110 context, 

111 ) 

112 

113 use_advanced = kwargs.get("advanced_orchestration", False) 

114 

115 try: 

116 if use_advanced: 

117 orchestrator = await _create_advanced_orchestrator( 

118 working_dir, kwargs, context 

119 ) 

120 else: 

121 orchestrator = _create_standard_orchestrator(working_dir, kwargs) 

122 

123 return { 

124 "status": "ready", 

125 "orchestrator": orchestrator, 

126 "job_id": job_id, 

127 } 

128 

129 except Exception as e: 

130 return { 

131 "status": "failed", 

132 "error": f"Failed to create orchestrator: {e}", 

133 "job_id": job_id, 

134 } 

135 

136 

137async def _create_advanced_orchestrator( 

138 working_dir: t.Any, kwargs: dict[str, t.Any], context: t.Any 

139) -> t.Any: 

140 from pathlib import Path 

141 

142 from crackerjack.core.async_workflow_orchestrator import AsyncWorkflowOrchestrator 

143 from crackerjack.core.enhanced_container import EnhancedContainer 

144 

145 container = EnhancedContainer() 

146 

147 await _register_core_services(container, Path(working_dir)) 

148 

149 orchestrator = AsyncWorkflowOrchestrator( 

150 pkg_path=Path(working_dir), 

151 ) 

152 

153 return orchestrator 

154 

155 

156def _create_standard_orchestrator( 

157 working_dir: t.Any, kwargs: dict[str, t.Any] 

158) -> t.Any: 

159 from pathlib import Path 

160 

161 from crackerjack.core.workflow_orchestrator import WorkflowOrchestrator 

162 

163 return WorkflowOrchestrator(pkg_path=Path(working_dir)) 

164 

165 

166async def _register_core_services(container: t.Any, working_dir: t.Any) -> None: 

167 from rich.console import Console 

168 

169 from crackerjack.core.enhanced_container import ServiceLifetime 

170 from crackerjack.managers.hook_manager import AsyncHookManager 

171 from crackerjack.managers.publish_manager import PublishManager 

172 from crackerjack.managers.test_manager import TestManager 

173 from crackerjack.models.protocols import ( 

174 HookManagerProtocol, 

175 PublishManagerProtocol, 

176 TestManagerProtocol, 

177 ) 

178 from crackerjack.services.enhanced_filesystem import EnhancedFileSystemService 

179 

180 console = Console() 

181 

182 container.register_service( 

183 HookManagerProtocol, 

184 AsyncHookManager(console, working_dir), 

185 ServiceLifetime.SINGLETON, 

186 ) 

187 

188 container.register_service( 

189 TestManagerProtocol, 

190 TestManager(console, working_dir), 

191 ServiceLifetime.SINGLETON, 

192 ) 

193 

194 container.register_service( 

195 PublishManagerProtocol, 

196 PublishManager(console, working_dir), 

197 ServiceLifetime.SINGLETON, 

198 ) 

199 

200 container.register_service( 

201 EnhancedFileSystemService, 

202 EnhancedFileSystemService(), 

203 ServiceLifetime.SINGLETON, 

204 ) 

205 

206 

207async def _run_workflow_iterations( 

208 job_id: str, 

209 orchestrator: t.Any, 

210 kwargs: dict[str, t.Any], 

211 context: t.Any, 

212) -> dict[str, t.Any]: 

213 options = _create_workflow_options(kwargs) 

214 max_iterations = kwargs.get("max_iterations", 10) 

215 

216 for iteration in range(max_iterations): 

217 _update_progress( 

218 job_id, 

219 { 

220 "type": "iteration", 

221 "iteration": iteration + 1, 

222 "max_iterations": max_iterations, 

223 "status": "running", 

224 }, 

225 context, 

226 ) 

227 

228 try: 

229 success = await _execute_single_iteration( 

230 job_id, orchestrator, options, iteration, context 

231 ) 

232 

233 if success: 

234 coverage_result = None 

235 if kwargs.get("boost_coverage", False): 

236 coverage_result = await _attempt_coverage_improvement( 

237 job_id, orchestrator, context 

238 ) 

239 return _create_success_result( 

240 job_id, iteration + 1, context, coverage_result 

241 ) 

242 

243 if iteration < max_iterations - 1: 

244 await _handle_iteration_retry(job_id, iteration, context) 

245 

246 except Exception as e: 

247 return await _handle_iteration_error(job_id, iteration, e, context) 

248 

249 return _create_failure_result(job_id, max_iterations, context) 

250 

251 

252def _create_workflow_options(kwargs: dict[str, t.Any]) -> t.Any: 

253 from types import SimpleNamespace 

254 

255 options = SimpleNamespace() 

256 

257 options.commit = kwargs.get("commit", False) 

258 options.interactive = kwargs.get("interactive", False) 

259 options.no_config_updates = kwargs.get("no_config_updates", False) 

260 options.verbose = kwargs.get("verbose", True) 

261 options.clean = kwargs.get("clean", False) 

262 options.test = kwargs.get("test_mode", True) 

263 options.benchmark = kwargs.get("benchmark", False) 

264 options.skip_hooks = kwargs.get("skip_hooks", False) 

265 options.ai_agent = kwargs.get("ai_agent", True) 

266 options.async_mode = kwargs.get("async_mode", True) 

267 

268 options.test_workers = kwargs.get("test_workers", 0) 

269 options.test_timeout = kwargs.get("test_timeout", 0) 

270 

271 options.publish = kwargs.get("publish") 

272 options.bump = kwargs.get("bump") 

273 options.all = kwargs.get("all") 

274 options.create_pr = kwargs.get("create_pr", False) 

275 options.no_git_tags = kwargs.get("no_git_tags", False) 

276 options.skip_version_check = kwargs.get("skip_version_check", False) 

277 options.cleanup_pypi = kwargs.get("cleanup_pypi", False) 

278 options.keep_releases = kwargs.get("keep_releases", 10) 

279 

280 options.start_mcp_server = kwargs.get("start_mcp_server", False) 

281 

282 options.update_precommit = kwargs.get("update_precommit", False) 

283 options.experimental_hooks = kwargs.get("experimental_hooks", False) 

284 options.enable_pyrefly = kwargs.get("enable_pyrefly", False) 

285 options.enable_ty = kwargs.get("enable_ty", False) 

286 

287 options.cleanup = kwargs.get("cleanup") 

288 

289 options.coverage = kwargs.get("coverage", False) 

290 options.track_progress = kwargs.get("track_progress", False) 

291 

292 options.fast = kwargs.get("fast", False) 

293 options.comp = kwargs.get("comp", False) 

294 

295 return options 

296 

297 

298async def _execute_single_iteration( 

299 job_id: str, 

300 orchestrator: t.Any, 

301 options: t.Any, 

302 iteration: int, 

303 context: t.Any, 

304) -> bool: 

305 try: 

306 if hasattr(orchestrator, "run_complete_workflow_async"): 

307 result = orchestrator.run_complete_workflow_async(options) 

308 if result is None: 

309 raise ValueError( 

310 "Method run_complete_workflow_async returned None instead of awaitable" 

311 ) 

312 return await result 

313 elif hasattr(orchestrator, "run_complete_workflow"): 

314 result = orchestrator.run_complete_workflow(options) 

315 if result is None: 

316 raise ValueError( 

317 "Method run_complete_workflow returned None instead of awaitable" 

318 ) 

319 return await result 

320 elif hasattr(orchestrator, "execute_workflow"): 

321 result = orchestrator.execute_workflow(options) 

322 if result is None: 

323 raise ValueError( 

324 "Method execute_workflow returned None instead of awaitable" 

325 ) 

326 return await result 

327 elif hasattr(orchestrator, "run"): 

328 return orchestrator.run(options) 

329 else: 

330 raise ValueError( 

331 f"Orchestrator {type(orchestrator)} has no recognized workflow execution method" 

332 ) 

333 except Exception as e: 

334 raise RuntimeError( 

335 f"Error in _execute_single_iteration (iteration {iteration}): {e}" 

336 ) from e 

337 

338 

339def _create_success_result( 

340 job_id: str, 

341 iterations: int, 

342 context: t.Any, 

343 coverage_result: dict[str, t.Any] | None = None, 

344) -> dict[str, t.Any]: 

345 result = { 

346 "job_id": job_id, 

347 "status": "completed", 

348 "iterations": iterations, 

349 "result": "All quality checks passed successfully", 

350 "timestamp": time.time(), 

351 "success": True, 

352 } 

353 

354 if coverage_result: 

355 result["coverage_improvement"] = coverage_result 

356 

357 return result 

358 

359 

360async def _handle_iteration_retry(job_id: str, iteration: int, context: t.Any) -> None: 

361 _update_progress( 

362 job_id, 

363 { 

364 "type": "iteration", 

365 "iteration": iteration + 1, 

366 "status": "retrying", 

367 "message": f"Issues found in iteration {iteration + 1}, retrying...", 

368 }, 

369 context, 

370 ) 

371 

372 await asyncio.sleep(1) 

373 

374 

375async def _handle_iteration_error( 

376 job_id: str, iteration: int, error: Exception, context: t.Any 

377) -> dict[str, t.Any]: 

378 _update_progress( 

379 job_id, 

380 { 

381 "type": "error", 

382 "iteration": iteration + 1, 

383 "error": str(error), 

384 "status": "failed", 

385 }, 

386 context, 

387 ) 

388 

389 return { 

390 "job_id": job_id, 

391 "status": "failed", 

392 "error": f"Iteration {iteration + 1} failed: {error}", 

393 "timestamp": time.time(), 

394 "success": False, 

395 } 

396 

397 

398async def _attempt_coverage_improvement( 

399 job_id: str, orchestrator: t.Any, context: t.Any 

400) -> dict[str, t.Any]: 

401 try: 

402 _update_progress( 

403 job_id, 

404 { 

405 "type": "coverage_improvement", 

406 "status": "starting", 

407 "message": "Analyzing coverage for improvement opportunities...", 

408 }, 

409 context, 

410 ) 

411 

412 project_path = getattr(orchestrator, "pkg_path", None) 

413 if not project_path: 

414 return {"status": "skipped", "reason": "No project path available"} 

415 

416 from crackerjack.orchestration.coverage_improvement import ( 

417 create_coverage_improvement_orchestrator, 

418 ) 

419 

420 coverage_orchestrator = await create_coverage_improvement_orchestrator( 

421 project_path, 

422 console=getattr(orchestrator, "console", None), 

423 ) 

424 

425 should_improve = await coverage_orchestrator.should_improve_coverage() 

426 if not should_improve: 

427 _update_progress( 

428 job_id, 

429 { 

430 "type": "coverage_improvement", 

431 "status": "skipped", 

432 "message": "Coverage improvement not needed (already at 100 %)", 

433 }, 

434 context, 

435 ) 

436 return {"status": "skipped", "reason": "Coverage at 100 %"} 

437 

438 from crackerjack.agents.base import AgentContext 

439 

440 agent_context = AgentContext(project_path=project_path, console=None) 

441 

442 _update_progress( 

443 job_id, 

444 { 

445 "type": "coverage_improvement", 

446 "status": "executing", 

447 "message": "Generating tests to improve coverage...", 

448 }, 

449 context, 

450 ) 

451 

452 improvement_result = await coverage_orchestrator.execute_coverage_improvement( 

453 agent_context 

454 ) 

455 

456 if improvement_result["status"] == "completed": 

457 _update_progress( 

458 job_id, 

459 { 

460 "type": "coverage_improvement", 

461 "status": "completed", 

462 "message": f"Coverage improvement: {len(improvement_result.get('fixes_applied', []))} tests created", 

463 "fixes_applied": improvement_result.get("fixes_applied", []), 

464 "files_modified": improvement_result.get("files_modified", []), 

465 }, 

466 context, 

467 ) 

468 else: 

469 _update_progress( 

470 job_id, 

471 { 

472 "type": "coverage_improvement", 

473 "status": "completed_with_issues", 

474 "message": f"Coverage improvement attempted: {improvement_result.get('status', 'unknown')}", 

475 }, 

476 context, 

477 ) 

478 

479 return improvement_result 

480 

481 except Exception as e: 

482 _update_progress( 

483 job_id, 

484 { 

485 "type": "coverage_improvement", 

486 "status": "failed", 

487 "error": str(e), 

488 "message": f"Coverage improvement failed: {e}", 

489 }, 

490 context, 

491 ) 

492 

493 return { 

494 "status": "failed", 

495 "error": str(e), 

496 "fixes_applied": [], 

497 "files_modified": [], 

498 } 

499 

500 

501def _create_failure_result( 

502 job_id: str, max_iterations: int, context: t.Any 

503) -> dict[str, t.Any]: 

504 return { 

505 "job_id": job_id, 

506 "status": "failed", 

507 "error": f"Maximum iterations ({max_iterations}) reached without success", 

508 "timestamp": time.time(), 

509 "success": False, 

510 }