Coverage for little_loops / parallel / orchestrator.py: 81%

541 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2026-03-04 01:17 -0600

1"""Main orchestrator for parallel issue processing. 

2 

3Coordinates the priority queue, worker pool, and merge coordinator to process 

4multiple issues concurrently. 

5""" 

6 

7from __future__ import annotations 

8 

9import json 

10import re 

11import shutil 

12import signal 

13import time 

14from datetime import datetime 

15from pathlib import Path 

16from typing import TYPE_CHECKING, Any 

17 

18from little_loops.issue_parser import IssueInfo 

19from little_loops.logger import Logger, format_duration 

20from little_loops.parallel.git_lock import GitLock 

21from little_loops.parallel.merge_coordinator import MergeCoordinator 

22from little_loops.parallel.overlap_detector import OverlapDetector 

23from little_loops.parallel.priority_queue import IssuePriorityQueue 

24from little_loops.parallel.types import ( 

25 OrchestratorState, 

26 ParallelConfig, 

27 PendingWorktreeInfo, 

28 WorkerResult, 

29) 

30from little_loops.parallel.worker_pool import WorkerPool 

31 

32if TYPE_CHECKING: 

33 from little_loops.config import BRConfig 

34 

35 

36class ParallelOrchestrator: 

37 """Main controller for parallel issue processing. 

38 

39 Coordinates: 

40 - Issue scanning and prioritization 

41 - Worker dispatch (P0 sequential, P1-P5 parallel) 

42 - Merge coordination 

43 - State persistence for resume capability 

44 - Graceful shutdown on signals 

45 

46 Example: 

47 >>> from little_loops.config import BRConfig 

48 >>> from little_loops.parallel import ParallelConfig, ParallelOrchestrator 

49 >>> br_config = BRConfig(Path.cwd()) 

50 >>> parallel_config = ParallelConfig(max_workers=2) 

51 >>> orchestrator = ParallelOrchestrator(parallel_config, br_config) 

52 >>> exit_code = orchestrator.run() 

53 """ 

54 

55 def __init__( 

56 self, 

57 parallel_config: ParallelConfig, 

58 br_config: BRConfig, 

59 repo_path: Path | None = None, 

60 verbose: bool = True, 

61 wave_label: str | None = None, 

62 ) -> None: 

63 """Initialize the orchestrator. 

64 

65 Args: 

66 parallel_config: Parallel processing configuration 

67 br_config: Project configuration 

68 repo_path: Path to the git repository (default: current directory) 

69 verbose: Whether to output progress messages 

70 wave_label: Optional label for wave-based execution (e.g., "Wave 1") 

71 """ 

72 self.parallel_config = parallel_config 

73 self.br_config = br_config 

74 self.repo_path = repo_path or Path.cwd() 

75 self.logger = Logger(verbose=verbose) 

76 self.wave_label = wave_label 

77 self._execution_duration: float = 0.0 

78 

79 # Create shared git lock for serializing main repo operations 

80 # This prevents index.lock race conditions between workers and merge coordinator 

81 self._git_lock = GitLock(self.logger) 

82 

83 # Initialize components with shared git lock 

84 self.queue = IssuePriorityQueue() 

85 self.worker_pool = WorkerPool( 

86 parallel_config, br_config, self.logger, self.repo_path, self._git_lock 

87 ) 

88 self.merge_coordinator = MergeCoordinator( 

89 parallel_config, self.logger, self.repo_path, self._git_lock 

90 ) 

91 

92 # State management 

93 self.state = OrchestratorState() 

94 self._shutdown_requested = False 

95 self._original_sigint: Any = None 

96 self._original_sigterm: Any = None 

97 

98 # Track issue info for lifecycle completion after merge 

99 self._issue_info_by_id: dict[str, IssueInfo] = {} 

100 # Track interrupted issues separately from failures (ENH-036) 

101 self._interrupted_issues: list[str] = [] 

102 

103 # Overlap detection (ENH-143) 

104 self.overlap_detector: OverlapDetector | None = ( 

105 OverlapDetector(config=br_config.dependency_mapping) 

106 if parallel_config.overlap_detection 

107 else None 

108 ) 

109 # Track deferred issues for re-check after active issues complete 

110 self._deferred_issues: list[IssueInfo] = [] 

111 # Track last status report time for progress visibility (ENH-262) 

112 self._last_status_time: float = 0.0 

113 self._last_status_line: str = "" 

114 

115 @property 

116 def execution_duration(self) -> float: 

117 """Return the total execution duration in seconds.""" 

118 return self._execution_duration 

119 

120 def run(self) -> int: 

121 """Run the parallel issue processor. 

122 

123 Returns: 

124 Exit code (0 = success, 1 = failure) 

125 """ 

126 try: 

127 self._setup_signal_handlers() 

128 self._ensure_gitignore_entries() 

129 

130 # Check for pending work from previous runs (unless clean start) 

131 if not self.parallel_config.clean_start: 

132 pending_worktrees = self._check_pending_worktrees() 

133 

134 # Handle pending worktrees based on flags 

135 pending_with_work = [p for p in pending_worktrees if p.has_pending_work] 

136 if pending_with_work: 

137 if self.parallel_config.merge_pending: 

138 self._merge_pending_worktrees(pending_worktrees) 

139 elif not self.parallel_config.ignore_pending: 

140 # Default behavior: just report (cleanup happens below) 

141 self.logger.info( 

142 "Continuing with cleanup (use --merge-pending to merge)..." 

143 ) 

144 

145 self._cleanup_orphaned_worktrees() 

146 self._load_state() 

147 

148 if self.parallel_config.dry_run: 

149 return self._dry_run() 

150 

151 return self._execute() 

152 

153 except KeyboardInterrupt: 

154 self.logger.warning("Interrupted by user") 

155 return 1 

156 except Exception as e: 

157 self.logger.error(f"Fatal error: {e}") 

158 return 1 

159 finally: 

160 self._cleanup() 

161 self._restore_signal_handlers() 

162 

163 def _setup_signal_handlers(self) -> None: 

164 """Setup signal handlers for graceful shutdown.""" 

165 self._original_sigint = signal.signal(signal.SIGINT, self._signal_handler) 

166 self._original_sigterm = signal.signal(signal.SIGTERM, self._signal_handler) 

167 

168 def _restore_signal_handlers(self) -> None: 

169 """Restore original signal handlers.""" 

170 if self._original_sigint is not None: 

171 signal.signal(signal.SIGINT, self._original_sigint) 

172 if self._original_sigterm is not None: 

173 signal.signal(signal.SIGTERM, self._original_sigterm) 

174 

175 def _ensure_gitignore_entries(self) -> None: 

176 """Ensure .gitignore has entries for parallel processing artifacts. 

177 

178 Adds entries for: 

179 - .parallel-manage-state.json (state file) 

180 - .worktrees/ (git worktree directory) 

181 

182 This prevents these files from being tracked by git, which would cause 

183 conflicts during merge operations (state file is continuously updated). 

184 """ 

185 gitignore_path = self.repo_path / ".gitignore" 

186 required_entries = [ 

187 ".parallel-manage-state.json", 

188 ".worktrees/", 

189 ] 

190 

191 existing_content = "" 

192 if gitignore_path.exists(): 

193 existing_content = gitignore_path.read_text() 

194 

195 # Check which entries are missing 

196 missing_entries = [] 

197 for entry in required_entries: 

198 # Check for exact match or pattern that would cover it 

199 if entry not in existing_content: 

200 missing_entries.append(entry) 

201 

202 if not missing_entries: 

203 return 

204 

205 # Append missing entries 

206 addition = "\n# ll-parallel artifacts\n" 

207 for entry in missing_entries: 

208 addition += f"{entry}\n" 

209 

210 # Ensure file ends with newline before adding 

211 if existing_content and not existing_content.endswith("\n"): 

212 addition = "\n" + addition 

213 

214 gitignore_path.write_text(existing_content + addition) 

215 self.logger.info(f"Added {len(missing_entries)} entries to .gitignore") 

216 

217 def _cleanup_orphaned_worktrees(self) -> None: 

218 """Clean up worktrees from previous interrupted runs. 

219 

220 Scans the worktree base directory and removes any worktrees that are 

221 not from the current session. This handles cases where a previous run 

222 was interrupted (Ctrl+C) and worktrees were not cleaned up. 

223 """ 

224 worktree_base = self.repo_path / self.parallel_config.worktree_base 

225 if not worktree_base.exists(): 

226 return 

227 

228 # Get list of worktree directories 

229 orphaned = [] 

230 for item in worktree_base.iterdir(): 

231 if item.is_dir() and item.name.startswith("worker-"): 

232 orphaned.append(item) 

233 

234 if not orphaned: 

235 return 

236 

237 self.logger.info(f"Cleaning up {len(orphaned)} orphaned worktree(s) from previous run") 

238 

239 for worktree_path in orphaned: 

240 try: 

241 # Try git worktree remove first 

242 self._git_lock.run( 

243 ["worktree", "remove", "--force", str(worktree_path)], 

244 cwd=self.repo_path, 

245 timeout=30, 

246 ) 

247 

248 # If git worktree remove failed, force delete the directory 

249 if worktree_path.exists(): 

250 shutil.rmtree(worktree_path, ignore_errors=True) 

251 

252 # Try to delete the associated branch 

253 # Branch name format: parallel/<issue-id>-<timestamp> 

254 branch_name = worktree_path.name.replace("worker-", "parallel/") 

255 self._git_lock.run( 

256 ["branch", "-D", branch_name], 

257 cwd=self.repo_path, 

258 timeout=10, 

259 ) 

260 except Exception as e: 

261 self.logger.warning(f"Failed to clean up {worktree_path.name}: {e}") 

262 

263 # Also prune git worktree references 

264 self._git_lock.run( 

265 ["worktree", "prune"], 

266 cwd=self.repo_path, 

267 timeout=30, 

268 ) 

269 

270 def _inspect_worktree(self, worktree_path: Path) -> PendingWorktreeInfo | None: 

271 """Inspect a worktree to determine its status. 

272 

273 Args: 

274 worktree_path: Path to the worktree directory 

275 

276 Returns: 

277 PendingWorktreeInfo if inspection succeeded, None if failed 

278 """ 

279 try: 

280 # Extract branch name from worktree path 

281 # worker-bug-045-20260117-143022 -> parallel/bug-045-20260117-143022 

282 branch_name = worktree_path.name.replace("worker-", "parallel/") 

283 

284 # Extract issue ID (e.g., bug-045 -> BUG-045) 

285 # Pattern: worker-<issue-id>-<timestamp> 

286 match = re.match(r"worker-([a-z]+-\d+)-\d{8}-\d{6}", worktree_path.name) 

287 issue_id = match.group(1).upper() if match else worktree_path.name 

288 

289 # Check commits ahead of main 

290 result = self._git_lock.run( 

291 ["rev-list", "--count", f"{self.parallel_config.base_branch}..{branch_name}"], 

292 cwd=self.repo_path, 

293 timeout=10, 

294 ) 

295 commits_ahead = int(result.stdout.strip()) if result.returncode == 0 else 0 

296 

297 # Check for uncommitted changes in worktree 

298 result = self._git_lock.run( 

299 ["status", "--porcelain"], 

300 cwd=worktree_path, 

301 timeout=10, 

302 ) 

303 changed_files = [] 

304 has_uncommitted = False 

305 if result.returncode == 0 and result.stdout.strip(): 

306 has_uncommitted = True 

307 changed_files = [line[3:] for line in result.stdout.strip().split("\n") if line] 

308 

309 return PendingWorktreeInfo( 

310 worktree_path=worktree_path, 

311 branch_name=branch_name, 

312 issue_id=issue_id, 

313 commits_ahead=commits_ahead, 

314 has_uncommitted_changes=has_uncommitted, 

315 changed_files=changed_files, 

316 ) 

317 except Exception as e: 

318 self.logger.warning(f"Failed to inspect worktree {worktree_path.name}: {e}") 

319 return None 

320 

321 def _check_pending_worktrees(self) -> list[PendingWorktreeInfo]: 

322 """Check for pending worktrees from previous runs and report status. 

323 

324 Returns: 

325 List of pending worktree information 

326 """ 

327 worktree_base = self.repo_path / self.parallel_config.worktree_base 

328 if not worktree_base.exists(): 

329 return [] 

330 

331 # Find all worker directories 

332 worktrees = [ 

333 item 

334 for item in worktree_base.iterdir() 

335 if item.is_dir() and item.name.startswith("worker-") 

336 ] 

337 

338 if not worktrees: 

339 return [] 

340 

341 self.logger.info("Checking for pending work from previous runs...") 

342 

343 # Inspect each worktree 

344 pending_info: list[PendingWorktreeInfo] = [] 

345 for worktree_path in worktrees: 

346 info = self._inspect_worktree(worktree_path) 

347 if info: 

348 pending_info.append(info) 

349 

350 # Report findings 

351 with_work = [p for p in pending_info if p.has_pending_work] 

352 if with_work: 

353 self.logger.warning(f"Found {len(with_work)} worktree(s) with pending work:") 

354 for info in with_work: 

355 status_parts = [] 

356 if info.commits_ahead > 0: 

357 status_parts.append(f"{info.commits_ahead} commit(s) ahead of main") 

358 if info.has_uncommitted_changes: 

359 status_parts.append(f"{len(info.changed_files)} uncommitted file(s)") 

360 status = ", ".join(status_parts) 

361 self.logger.warning(f" - {info.worktree_path.name}: {info.issue_id} ({status})") 

362 

363 self.logger.info("") 

364 self.logger.info("Options:") 

365 self.logger.info(" --merge-pending Attempt to merge pending work before continuing") 

366 self.logger.info(" --clean-start Remove all worktrees and start fresh") 

367 self.logger.info( 

368 " --ignore-pending Continue without action (worktrees will be cleaned up)" 

369 ) 

370 elif pending_info: 

371 self.logger.info(f"Found {len(pending_info)} orphaned worktree(s) with no pending work") 

372 

373 return pending_info 

374 

375 def _merge_pending_worktrees(self, pending: list[PendingWorktreeInfo]) -> None: 

376 """Attempt to merge pending worktrees from previous runs. 

377 

378 Args: 

379 pending: List of pending worktree information 

380 """ 

381 with_work = [p for p in pending if p.has_pending_work] 

382 if not with_work: 

383 return 

384 

385 self.logger.info(f"Attempting to merge {len(with_work)} pending worktree(s)...") 

386 

387 for info in with_work: 

388 try: 

389 # If there are uncommitted changes, commit them first 

390 if info.has_uncommitted_changes: 

391 self.logger.info(f" Committing uncommitted changes in {info.issue_id}...") 

392 self._git_lock.run( 

393 ["add", "-A"], 

394 cwd=info.worktree_path, 

395 timeout=30, 

396 ) 

397 self._git_lock.run( 

398 [ 

399 "commit", 

400 "-m", 

401 f"WIP: Auto-commit from interrupted session for {info.issue_id}", 

402 ], 

403 cwd=info.worktree_path, 

404 timeout=30, 

405 ) 

406 

407 # Attempt merge 

408 self.logger.info(f" Merging {info.issue_id} ({info.branch_name})...") 

409 result = self._git_lock.run( 

410 [ 

411 "merge", 

412 "--no-ff", 

413 info.branch_name, 

414 "-m", 

415 f"Merge pending work for {info.issue_id}", 

416 ], 

417 cwd=self.repo_path, 

418 timeout=60, 

419 ) 

420 

421 if result.returncode == 0: 

422 self.logger.success(f" Successfully merged {info.issue_id}") 

423 # Clean up the worktree after successful merge 

424 self._git_lock.run( 

425 ["worktree", "remove", "--force", str(info.worktree_path)], 

426 cwd=self.repo_path, 

427 timeout=30, 

428 ) 

429 self._git_lock.run( 

430 ["branch", "-D", info.branch_name], 

431 cwd=self.repo_path, 

432 timeout=10, 

433 ) 

434 else: 

435 self.logger.warning(f" Failed to merge {info.issue_id}: {result.stderr}") 

436 # Abort the merge if it failed 

437 self._git_lock.run( 

438 ["merge", "--abort"], 

439 cwd=self.repo_path, 

440 timeout=10, 

441 ) 

442 

443 except Exception as e: 

444 self.logger.warning(f" Error merging {info.issue_id}: {e}") 

445 

446 def _signal_handler(self, signum: int, frame: object) -> None: 

447 """Handle shutdown signals gracefully.""" 

448 self._shutdown_requested = True 

449 # Propagate to worker pool for interrupted worker detection (ENH-036) 

450 self.worker_pool.set_shutdown_requested(True) 

451 self.logger.warning(f"Received signal {signum}, shutting down gracefully...") 

452 

453 def _load_state(self) -> None: 

454 """Load state from file for resume capability.""" 

455 state_file = self.repo_path / self.parallel_config.state_file 

456 if not state_file.exists(): 

457 self.state.started_at = datetime.now().isoformat() 

458 return 

459 

460 try: 

461 data = json.loads(state_file.read_text()) 

462 self.state = OrchestratorState.from_dict(data) 

463 

464 # Restore queue state 

465 self.queue.load_completed(self.state.completed_issues) 

466 self.queue.load_failed(self.state.failed_issues.keys()) 

467 

468 self.logger.info( 

469 f"Resumed from previous state: " 

470 f"{len(self.state.completed_issues)} completed, " 

471 f"{len(self.state.failed_issues)} failed" 

472 ) 

473 except Exception as e: 

474 self.logger.warning(f"Could not load state: {e}") 

475 self.state.started_at = datetime.now().isoformat() 

476 

477 def _save_state(self) -> None: 

478 """Save current state to file.""" 

479 self.state.last_checkpoint = datetime.now().isoformat() 

480 self.state.completed_issues = self.queue.completed_ids 

481 self.state.failed_issues = dict.fromkeys(self.queue.failed_ids, "Failed") 

482 self.state.in_progress_issues = self.queue.in_progress_ids 

483 

484 state_file = self.repo_path / self.parallel_config.state_file 

485 state_file.write_text(json.dumps(self.state.to_dict(), indent=2)) 

486 

487 def _cleanup_state(self) -> None: 

488 """Remove state file on successful completion.""" 

489 state_file = self.repo_path / self.parallel_config.state_file 

490 if state_file.exists(): 

491 state_file.unlink() 

492 

493 def _dry_run(self) -> int: 

494 """Preview what would be processed without executing. 

495 

496 Returns: 

497 Exit code (always 0 for dry run) 

498 """ 

499 issues = self._scan_issues() 

500 

501 self.logger.info("=" * 60) 

502 self.logger.info("DRY RUN - No changes will be made") 

503 self.logger.info("=" * 60) 

504 self.logger.info("") 

505 

506 if not issues: 

507 self.logger.info("No issues found matching criteria") 

508 return 0 

509 

510 self.logger.info(f"Found {len(issues)} issues to process:") 

511 self.logger.info("") 

512 

513 # Group by priority 

514 by_priority: dict[str, list[IssueInfo]] = {} 

515 for issue in issues: 

516 by_priority.setdefault(issue.priority, []).append(issue) 

517 

518 for priority in IssuePriorityQueue.DEFAULT_PRIORITIES: 

519 if priority not in by_priority: 

520 continue 

521 

522 priority_issues = by_priority[priority] 

523 self.logger.info(f" {priority} ({len(priority_issues)} issues):") 

524 for issue in priority_issues: 

525 mode = ( 

526 "sequential" 

527 if priority == "P0" and self.parallel_config.p0_sequential 

528 else "parallel" 

529 ) 

530 self.logger.info(f" - {issue.issue_id}: {issue.title} [{mode}]") 

531 

532 self.logger.info("") 

533 self.logger.info("Configuration:") 

534 self.logger.info(f" Workers: {self.parallel_config.max_workers}") 

535 self.logger.info(f" P0 Sequential: {self.parallel_config.p0_sequential}") 

536 self.logger.info(f" Max Issues: {self.parallel_config.max_issues or 'unlimited'}") 

537 self.logger.info(f" Command Prefix: {self.parallel_config.command_prefix}") 

538 

539 return 0 

540 

541 def _maybe_report_status(self) -> None: 

542 """Report status if enough time has elapsed since last report. 

543 

544 Reports every 5 seconds during active processing for progress visibility (ENH-262). 

545 Suppresses duplicate lines when nothing has changed. 

546 """ 

547 now = time.time() 

548 # Report every 5 seconds 

549 if now - self._last_status_time < 5.0: 

550 return 

551 

552 self._last_status_time = now 

553 

554 # Build status line 

555 parts = [] 

556 

557 # Add wave label if present 

558 if self.wave_label: 

559 parts.append(f"{self.wave_label}") 

560 

561 # Get queue counts 

562 in_progress = len(self.queue.in_progress_ids) 

563 completed = self.queue.completed_count 

564 failed = self.queue.failed_count 

565 pending_merge = self.merge_coordinator.pending_count 

566 

567 parts.append(f"Active: {in_progress}") 

568 parts.append(f"Done: {completed}") 

569 if failed > 0: 

570 parts.append(f"Failed: {failed}") 

571 if pending_merge > 0: 

572 parts.append(f"Merging: {pending_merge}") 

573 

574 # Build status line 

575 status = " | ".join(parts) 

576 

577 # Get active worker stages 

578 active_stages = self.worker_pool.get_active_stages() 

579 

580 # Add worker details if any are active 

581 if active_stages: 

582 # Group by stage 

583 by_stage: dict[str, list[str]] = {} 

584 for issue_id, worker_stage in active_stages.items(): 

585 stage_name = worker_stage.value.title() 

586 by_stage.setdefault(stage_name, []).append(issue_id) 

587 

588 stage_parts = [] 

589 for stage_name in ["Validating", "Implementing", "Verifying", "Merging"]: 

590 if stage_name in by_stage: 

591 issue_ids = ", ".join(by_stage[stage_name]) 

592 stage_parts.append(f"{stage_name}: [{issue_ids}]") 

593 

594 if stage_parts: 

595 status += " | " + " | ".join(stage_parts) 

596 

597 # Skip if nothing changed since last report 

598 if status == self._last_status_line: 

599 return 

600 self._last_status_line = status 

601 

602 # Log with gray color to distinguish from normal logs 

603 if self.logger.use_color: 

604 color = self.logger.GRAY 

605 ts = self.logger._timestamp() 

606 print(f"{color}[{ts}]{self.logger.RESET} {status}") 

607 else: 

608 self.logger.info(status) 

609 

610 def _execute(self) -> int: 

611 """Execute parallel issue processing. 

612 

613 Returns: 

614 Exit code (0 = success, 1 = failure) 

615 """ 

616 start_time = time.time() 

617 

618 # Scan and queue issues 

619 issues = self._scan_issues() 

620 if not issues: 

621 self.logger.info("No issues to process") 

622 return 0 

623 

624 # Store issue info for lifecycle completion after merge 

625 for issue in issues: 

626 self._issue_info_by_id[issue.issue_id] = issue 

627 

628 added = self.queue.add_many(issues) 

629 self.logger.info(f"Queued {added} issues for processing") 

630 

631 # Start components 

632 self.worker_pool.start() 

633 self.merge_coordinator.start() 

634 

635 # Process issues 

636 issues_processed = 0 

637 max_issues = self.parallel_config.max_issues or float("inf") 

638 

639 while not self._shutdown_requested: 

640 # Check if done 

641 if self.queue.empty() and self.worker_pool.active_count == 0: 

642 # Wait for pending merges 

643 if self.merge_coordinator.pending_count == 0: 

644 break 

645 

646 # Check max issues limit 

647 if issues_processed >= max_issues: 

648 self.logger.info(f"Reached max issues limit ({max_issues})") 

649 break 

650 

651 # Get next issue if workers available 

652 if self.worker_pool.active_count < self.parallel_config.max_workers: 

653 queued = self.queue.get(block=False) 

654 if queued: 

655 issue = queued.issue_info 

656 

657 # P0 sequential processing 

658 if issue.priority == "P0" and self.parallel_config.p0_sequential: 

659 self._process_sequential(issue) 

660 else: 

661 self._process_parallel(issue) 

662 

663 issues_processed += 1 

664 

665 # Save state periodically 

666 self._save_state() 

667 

668 # Report status periodically for progress visibility (ENH-262) 

669 self._maybe_report_status() 

670 

671 # Small sleep to prevent busy loop 

672 time.sleep(0.1) 

673 

674 # Wait for completion 

675 self._wait_for_completion() 

676 

677 # Report results 

678 self._report_results(start_time) 

679 

680 # Cleanup state on success 

681 if not self._shutdown_requested and self.queue.failed_count == 0: 

682 self._cleanup_state() 

683 

684 return 0 if self.queue.failed_count == 0 else 1 

685 

686 def _scan_issues(self) -> list[IssueInfo]: 

687 """Scan for issues matching criteria. 

688 

689 Returns: 

690 List of issues sorted by priority 

691 """ 

692 # Combine skip_ids from state and config 

693 skip_ids = set(self.state.completed_issues) | set(self.state.failed_issues.keys()) 

694 if self.parallel_config.skip_ids: 

695 skip_ids |= self.parallel_config.skip_ids 

696 

697 issues = IssuePriorityQueue.scan_issues( 

698 self.br_config, 

699 priority_filter=list(self.parallel_config.priority_filter), 

700 skip_ids=skip_ids, 

701 only_ids=self.parallel_config.only_ids, 

702 type_prefixes=self.parallel_config.type_prefixes, 

703 ) 

704 

705 # Apply max issues limit 

706 if self.parallel_config.max_issues > 0: 

707 issues = issues[: self.parallel_config.max_issues] 

708 

709 return issues 

710 

711 def _process_sequential(self, issue: IssueInfo) -> None: 

712 """Process an issue sequentially (blocking). 

713 

714 Args: 

715 issue: Issue to process 

716 """ 

717 self.logger.info(f"Processing {issue.issue_id} sequentially (P0)") 

718 

719 # Wait for any parallel work to finish 

720 while self.worker_pool.active_count > 0: 

721 time.sleep(0.5) 

722 

723 # Process in main repo (no worktree isolation needed) 

724 # Note: No callback here - _merge_sequential handles the result explicitly 

725 # to avoid double-processing (callback would also queue merge/close) 

726 future = self.worker_pool.submit(issue) 

727 

728 # Wait for completion 

729 try: 

730 result = future.result(timeout=self.parallel_config.timeout_per_issue) 

731 if result.success: 

732 # Merge immediately for P0 

733 self._merge_sequential(result) 

734 except Exception as e: 

735 self.logger.error(f"Sequential processing failed: {e}") 

736 self.queue.mark_failed(issue.issue_id) 

737 

738 def _process_parallel(self, issue: IssueInfo) -> None: 

739 """Process an issue in parallel (non-blocking). 

740 

741 Args: 

742 issue: Issue to process 

743 """ 

744 # Check for overlaps if enabled (ENH-143) 

745 if self.overlap_detector: 

746 overlap = self.overlap_detector.check_overlap(issue) 

747 if overlap: 

748 if self.parallel_config.serialize_overlapping: 

749 self.logger.warning( 

750 f"Deferring {issue.issue_id} - overlaps with {overlap.overlapping_issues}" 

751 ) 

752 # Track for re-check when active issues complete 

753 self._deferred_issues.append(issue) 

754 return 

755 else: 

756 self.logger.warning( 

757 f"Warning: {issue.issue_id} may conflict with {overlap.overlapping_issues}" 

758 ) 

759 

760 # Register as active before dispatch 

761 self.overlap_detector.register_issue(issue) 

762 

763 self.logger.info(f"Dispatching {issue.issue_id} to worker pool") 

764 self.worker_pool.submit(issue, self._on_worker_complete) 

765 

766 def _on_worker_complete(self, result: WorkerResult) -> None: 

767 """Callback when a worker completes. 

768 

769 Args: 

770 result: Result from the worker 

771 """ 

772 # Unregister from overlap tracking (ENH-143) 

773 if self.overlap_detector: 

774 self.overlap_detector.unregister_issue(result.issue_id) 

775 # Re-queue deferred issues that were waiting on this one 

776 self._requeue_deferred_issues() 

777 

778 # Handle interrupted workers (not counted as failed) - ENH-036 

779 if result.interrupted: 

780 self.logger.info(f"{result.issue_id} was interrupted during shutdown (can retry)") 

781 self._interrupted_issues.append(result.issue_id) 

782 # Don't mark as failed - they can be retried on next run 

783 return 

784 

785 # Handle issue closure (no merge needed) 

786 if result.should_close: 

787 # Lazy import to avoid circular dependency 

788 from little_loops.issue_lifecycle import close_issue 

789 

790 self.logger.info(f"{result.issue_id} should be closed: {result.close_status}") 

791 info = self._issue_info_by_id.get(result.issue_id) 

792 if info: 

793 if close_issue( 

794 info, 

795 self.br_config, 

796 self.logger, 

797 result.close_reason, 

798 result.close_status, 

799 ): 

800 self.queue.mark_completed(result.issue_id) 

801 else: 

802 self.queue.mark_failed(result.issue_id) 

803 else: 

804 self.logger.warning(f"No issue info found for {result.issue_id}") 

805 self.queue.mark_failed(result.issue_id) 

806 elif result.success: 

807 self.logger.success( 

808 f"{result.issue_id} completed in {format_duration(result.duration)}" 

809 ) 

810 if result.was_corrected: 

811 self.logger.info(f"{result.issue_id} was auto-corrected during validation") 

812 # Log and store corrections for pattern analysis (ENH-010) 

813 for correction in result.corrections: 

814 self.logger.info(f" Correction: {correction}") 

815 if result.corrections: 

816 self.state.corrections[result.issue_id] = result.corrections 

817 self.merge_coordinator.queue_merge(result) 

818 # Wait for merge to complete before returning from callback. 

819 # This prevents dispatch of next worker while merge is in progress, 

820 # avoiding race conditions between worktree creation and merge ops. 

821 # (BUG-140: Race condition between worktree creation and merge) 

822 self.merge_coordinator.wait_for_completion(timeout=120) 

823 else: 

824 self.logger.error(f"{result.issue_id} failed: {result.error}") 

825 self.queue.mark_failed(result.issue_id) 

826 

827 # Update timing 

828 self.state.timing[result.issue_id] = { 

829 "total": result.duration, 

830 } 

831 

832 # Clean up stage tracking after callback completes (ENH-262) 

833 # Delay briefly so status reporter can show completion 

834 self.worker_pool.remove_worker_stage(result.issue_id) 

835 

836 def _requeue_deferred_issues(self) -> None: 

837 """Re-queue deferred issues that no longer have overlaps (ENH-143).""" 

838 if not self._deferred_issues: 

839 return 

840 

841 # Check each deferred issue for remaining overlaps 

842 still_deferred = [] 

843 for issue in self._deferred_issues: 

844 if self.overlap_detector: 

845 overlap = self.overlap_detector.check_overlap(issue) 

846 if overlap: 

847 # Still has overlaps, keep deferred 

848 still_deferred.append(issue) 

849 else: 

850 # No more overlaps, add back to queue 

851 self.logger.info(f"Re-queuing {issue.issue_id} - no longer overlapping") 

852 self.queue.add(issue) 

853 

854 self._deferred_issues = still_deferred 

855 

856 def _merge_sequential(self, result: WorkerResult) -> None: 

857 """Merge a sequential (P0) result immediately. 

858 

859 Args: 

860 result: Result to merge 

861 """ 

862 # Handle closure for sequential issues 

863 if result.should_close: 

864 # Lazy import to avoid circular dependency 

865 from little_loops.issue_lifecycle import close_issue 

866 

867 info = self._issue_info_by_id.get(result.issue_id) 

868 if info and close_issue( 

869 info, 

870 self.br_config, 

871 self.logger, 

872 result.close_reason, 

873 result.close_status, 

874 ): 

875 self.queue.mark_completed(result.issue_id) 

876 else: 

877 self.queue.mark_failed(result.issue_id) 

878 return 

879 

880 self.merge_coordinator.queue_merge(result) 

881 # Wait for this specific merge 

882 self.merge_coordinator.wait_for_completion(timeout=60) 

883 

884 if result.issue_id in self.merge_coordinator.merged_ids: 

885 self.queue.mark_completed(result.issue_id) 

886 self._complete_issue_lifecycle_if_needed(result.issue_id) 

887 else: 

888 self.queue.mark_failed(result.issue_id) 

889 

890 def _wait_for_completion(self) -> None: 

891 """Wait for all workers and merges to complete.""" 

892 self.logger.info("Waiting for workers to complete...") 

893 

894 # Calculate timeout 

895 if self.parallel_config.orchestrator_timeout > 0: 

896 timeout = self.parallel_config.orchestrator_timeout 

897 else: 

898 timeout = self.parallel_config.timeout_per_issue * self.parallel_config.max_workers 

899 

900 start = time.time() 

901 while self.worker_pool.active_count > 0: 

902 if time.time() - start > timeout: 

903 self.logger.warning(f"Timeout waiting for workers after {timeout}s") 

904 self.worker_pool.terminate_all_processes() 

905 break 

906 time.sleep(1.0) 

907 

908 # Wait for merges 

909 self.logger.info("Waiting for pending merges...") 

910 self.merge_coordinator.wait_for_completion(timeout=120) 

911 

912 # Update queue with merge results and complete lifecycle 

913 for issue_id in self.merge_coordinator.merged_ids: 

914 self.queue.mark_completed(issue_id) 

915 self._complete_issue_lifecycle_if_needed(issue_id) 

916 

917 for issue_id in self.merge_coordinator.failed_merges: 

918 self.queue.mark_failed(issue_id) 

919 

920 def _report_results(self, start_time: float) -> None: 

921 """Report processing results. 

922 

923 Args: 

924 start_time: When processing started 

925 """ 

926 total_time = time.time() - start_time 

927 self._execution_duration = total_time 

928 

929 self.logger.info("") 

930 self.logger.info("=" * 60) 

931 if self.wave_label: 

932 self.logger.info(f"{self.wave_label.upper()} PROCESSING COMPLETE") 

933 else: 

934 self.logger.info("PARALLEL ISSUE PROCESSING COMPLETE") 

935 self.logger.info("=" * 60) 

936 self.logger.info("") 

937 self.logger.timing(f"Total time: {format_duration(total_time)}") 

938 self.logger.info(f"Completed: {self.queue.completed_count}") 

939 self.logger.info(f"Failed: {self.queue.failed_count}") 

940 if self._interrupted_issues: 

941 self.logger.info(f"Interrupted: {len(self._interrupted_issues)}") 

942 

943 if self.queue.completed_count > 0: 

944 total_issue_time = sum(t.get("total", 0) for t in self.state.timing.values()) 

945 if total_issue_time > 0: 

946 speedup = total_issue_time / total_time 

947 self.logger.info(f"Estimated speedup: {speedup:.2f}x") 

948 

949 if self.queue.failed_ids: 

950 self.logger.info("") 

951 self.logger.warning("Failed issues:") 

952 for issue_id in self.queue.failed_ids: 

953 self.logger.warning(f" - {issue_id}") 

954 

955 # Report interrupted issues separately (ENH-036) 

956 if self._interrupted_issues: 

957 self.logger.info("") 

958 self.logger.info(f"Interrupted: {len(self._interrupted_issues)} (can retry)") 

959 for issue_id in self._interrupted_issues: 

960 self.logger.info(f" - {issue_id}") 

961 

962 # Report correction statistics for quality tracking (ENH-010) 

963 if self.state.corrections: 

964 total_corrected = len(self.state.corrections) 

965 total_issues = self.queue.completed_count + self.queue.failed_count 

966 correction_rate = (total_corrected / total_issues * 100) if total_issues > 0 else 0 

967 self.logger.info("") 

968 self.logger.info( 

969 f"Auto-corrections: {total_corrected}/{total_issues} ({correction_rate:.1f}%)" 

970 ) 

971 

972 # Group corrections by category (ENH-010 fourth fix) 

973 from collections import Counter, defaultdict 

974 

975 all_corrections: list[str] = [] 

976 by_category: dict[str, int] = defaultdict(int) 

977 for corrections in self.state.corrections.values(): 

978 all_corrections.extend(corrections) 

979 for correction in corrections: 

980 # Extract category from [category] prefix if present 

981 if correction.startswith("[") and "]" in correction: 

982 category = correction[1 : correction.index("]")] 

983 by_category[category] += 1 

984 else: 

985 by_category["uncategorized"] += 1 

986 

987 # Log corrections by type/category 

988 if by_category: 

989 self.logger.info("Corrections by type:") 

990 for category, count in sorted(by_category.items(), key=lambda x: -x[1]): 

991 self.logger.info(f" - {category}: {count}") 

992 

993 # Log most common individual corrections 

994 if all_corrections: 

995 common = Counter(all_corrections).most_common(3) 

996 self.logger.info("Most common corrections:") 

997 for correction, count in common: 

998 # Truncate long correction descriptions 

999 display = correction[:60] + "..." if len(correction) > 60 else correction 

1000 self.logger.info(f" - {display}: {count}") 

1001 

1002 # Report stash pop warnings (local changes need manual recovery) 

1003 stash_warnings = self.merge_coordinator.stash_pop_failures 

1004 if stash_warnings: 

1005 self.logger.info("") 

1006 self.logger.warning("Stash recovery warnings (local changes need manual restoration):") 

1007 for issue_id, message in stash_warnings.items(): 

1008 self.logger.warning(f" - {issue_id}: {message}") 

1009 self.logger.warning("") 

1010 self.logger.warning( 

1011 "To recover: Run 'git stash list' to find your changes, " 

1012 "then 'git stash pop' or 'git stash apply stash@{N}'" 

1013 ) 

1014 

1015 def _complete_issue_lifecycle_if_needed(self, issue_id: str) -> bool: 

1016 """Complete issue lifecycle if the issue file wasn't moved during merge. 

1017 

1018 Args: 

1019 issue_id: ID of the issue to complete 

1020 

1021 Returns: 

1022 True if lifecycle was completed (or already complete), False on error 

1023 """ 

1024 info = self._issue_info_by_id.get(issue_id) 

1025 if not info: 

1026 self.logger.warning(f"No issue info found for {issue_id}") 

1027 return False 

1028 

1029 original_path = info.path 

1030 completed_dir = self.br_config.get_completed_dir() 

1031 completed_path = completed_dir / original_path.name 

1032 

1033 # Check if already moved to completed 

1034 if completed_path.exists(): 

1035 return True 

1036 

1037 # Check if still in original location 

1038 if not original_path.exists(): 

1039 return True 

1040 

1041 # Issue file still in original location - complete lifecycle 

1042 self.logger.info(f"Completing lifecycle for {issue_id} (merged but file not moved)") 

1043 

1044 try: 

1045 completed_dir.mkdir(parents=True, exist_ok=True) 

1046 

1047 # Read original content 

1048 content = original_path.read_text() 

1049 

1050 # Add resolution section if not already present 

1051 if "## Resolution" not in content: 

1052 action = self.br_config.get_category_action(info.issue_type) 

1053 resolution = f""" 

1054 

1055--- 

1056 

1057## Resolution 

1058 

1059- **Action**: {action} 

1060- **Completed**: {datetime.now().strftime("%Y-%m-%d")} 

1061- **Status**: Completed (parallel merge fallback) 

1062- **Implementation**: Merged from parallel worker branch 

1063 

1064### Changes Made 

1065- See git history for implementation details 

1066 

1067### Verification Results 

1068- Work verification passed before merge 

1069 

1070### Commits 

1071- See `git log --oneline` for merge commit details 

1072""" 

1073 content += resolution 

1074 

1075 # Use git mv if possible (before writing content to avoid "destination exists") 

1076 result = self._git_lock.run( 

1077 ["mv", str(original_path), str(completed_path)], 

1078 cwd=self.repo_path, 

1079 ) 

1080 

1081 if result.returncode != 0: 

1082 # git mv failed (destination may exist or other error) 

1083 self.logger.warning(f"git mv failed for {issue_id}: {result.stderr}") 

1084 # Write content to destination (may overwrite existing) 

1085 completed_path.write_text(content) 

1086 # Remove source if it still exists 

1087 original_path.unlink(missing_ok=True) 

1088 else: 

1089 # git mv succeeded, write updated content 

1090 completed_path.write_text(content) 

1091 

1092 # Stage and commit 

1093 self._git_lock.run( 

1094 ["add", "-A"], 

1095 cwd=self.repo_path, 

1096 ) 

1097 

1098 action = self.br_config.get_category_action(info.issue_type) 

1099 commit_msg = f"""{action}({info.issue_type}): complete {issue_id} lifecycle 

1100 

1101Parallel merge fallback - issue file moved to completed. 

1102 

1103Issue: {issue_id} 

1104Type: {info.issue_type} 

1105Title: {info.title} 

1106""" 

1107 commit_result = self._git_lock.run( 

1108 ["commit", "-m", commit_msg], 

1109 cwd=self.repo_path, 

1110 ) 

1111 

1112 if commit_result.returncode != 0: 

1113 if "nothing to commit" not in commit_result.stdout.lower(): 

1114 self.logger.warning(f"git commit failed: {commit_result.stderr}") 

1115 else: 

1116 commit_hash_match = re.search(r"\[[\w-]+\s+([a-f0-9]+)\]", commit_result.stdout) 

1117 if commit_hash_match: 

1118 self.logger.success( 

1119 f"Completed lifecycle for {issue_id}: {commit_hash_match.group(1)}" 

1120 ) 

1121 else: 

1122 self.logger.success(f"Completed lifecycle for {issue_id}") 

1123 

1124 return True 

1125 

1126 except Exception as e: 

1127 self.logger.error(f"Failed to complete lifecycle for {issue_id}: {e}") 

1128 return False 

1129 

1130 def _cleanup(self) -> None: 

1131 """Clean up resources.""" 

1132 self.logger.info("Cleaning up...") 

1133 

1134 # Save final state 

1135 self._save_state() 

1136 

1137 # Shutdown components 

1138 self.worker_pool.shutdown(wait=True) 

1139 self.merge_coordinator.shutdown(wait=True, timeout=30) 

1140 

1141 # Clean up worktrees if not interrupted 

1142 if not self._shutdown_requested: 

1143 self.worker_pool.cleanup_all_worktrees()