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

602 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2026-04-02 13:03 -0500

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 os 

11import re 

12import shutil 

13import signal 

14import subprocess 

15import tempfile 

16import threading 

17import time 

18from datetime import datetime 

19from pathlib import Path 

20from typing import TYPE_CHECKING, Any 

21 

22from little_loops.issue_parser import IssueInfo 

23from little_loops.logger import Logger, format_duration 

24from little_loops.parallel.git_lock import GitLock 

25from little_loops.parallel.merge_coordinator import MergeCoordinator 

26from little_loops.parallel.overlap_detector import OverlapDetector 

27from little_loops.parallel.priority_queue import IssuePriorityQueue 

28from little_loops.parallel.types import ( 

29 OrchestratorState, 

30 ParallelConfig, 

31 PendingWorktreeInfo, 

32 WorkerResult, 

33) 

34from little_loops.parallel.worker_pool import WorkerPool 

35from little_loops.session_log import append_session_log_entry 

36 

37if TYPE_CHECKING: 

38 from little_loops.config import BRConfig 

39 

40 

41class ParallelOrchestrator: 

42 """Main controller for parallel issue processing. 

43 

44 Coordinates: 

45 - Issue scanning and prioritization 

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

47 - Merge coordination 

48 - State persistence for resume capability 

49 - Graceful shutdown on signals 

50 

51 Example: 

52 >>> from little_loops.config import BRConfig 

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

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

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

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

57 >>> exit_code = orchestrator.run() 

58 """ 

59 

60 def __init__( 

61 self, 

62 parallel_config: ParallelConfig, 

63 br_config: BRConfig, 

64 repo_path: Path | None = None, 

65 verbose: bool = True, 

66 wave_label: str | None = None, 

67 ) -> None: 

68 """Initialize the orchestrator. 

69 

70 Args: 

71 parallel_config: Parallel processing configuration 

72 br_config: Project configuration 

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

74 verbose: Whether to output progress messages 

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

76 """ 

77 self.parallel_config = parallel_config 

78 self.br_config = br_config 

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

80 self.logger = Logger(verbose=verbose) 

81 self.wave_label = wave_label 

82 self._execution_duration: float = 0.0 

83 

84 # Create shared git lock for serializing main repo operations 

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

86 self._git_lock = GitLock(self.logger) 

87 

88 # Initialize components with shared git lock 

89 self.queue = IssuePriorityQueue() 

90 self.worker_pool = WorkerPool( 

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

92 ) 

93 self.merge_coordinator = MergeCoordinator( 

94 parallel_config, self.logger, self.repo_path, self._git_lock 

95 ) 

96 

97 # State management 

98 self.state = OrchestratorState() 

99 self._state_lock = threading.Lock() 

100 self._shutdown_requested = False 

101 self._original_sigint: Any = None 

102 self._original_sigterm: Any = None 

103 

104 # Track issue info for lifecycle completion after merge 

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

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

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

108 # Track PR-ready branches when use_feature_branches=True (ENH-665) 

109 self._pr_ready_branches: dict[str, str] = {} # issue_id -> branch_name 

110 

111 # Overlap detection (ENH-143) 

112 self.overlap_detector: OverlapDetector | None = ( 

113 OverlapDetector(config=br_config.dependency_mapping) 

114 if parallel_config.overlap_detection 

115 else None 

116 ) 

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

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

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

120 self._last_status_time: float = 0.0 

121 self._last_status_line: str = "" 

122 # Track last state save time to throttle disk writes (ENH-485) 

123 self._last_save_time: float = 0.0 

124 

125 @property 

126 def execution_duration(self) -> float: 

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

128 return self._execution_duration 

129 

130 def run(self) -> int: 

131 """Run the parallel issue processor. 

132 

133 Returns: 

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

135 """ 

136 try: 

137 self._setup_signal_handlers() 

138 self._ensure_gitignore_entries() 

139 

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

141 if not self.parallel_config.clean_start: 

142 pending_worktrees = self._check_pending_worktrees() 

143 

144 # Handle pending worktrees based on flags 

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

146 if pending_with_work: 

147 if self.parallel_config.merge_pending: 

148 self._merge_pending_worktrees(pending_worktrees) 

149 elif not self.parallel_config.ignore_pending: 

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

151 self.logger.info( 

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

153 ) 

154 

155 self._cleanup_orphaned_worktrees() 

156 self._load_state() 

157 

158 if self.parallel_config.dry_run: 

159 return self._dry_run() 

160 

161 return self._execute() 

162 

163 except KeyboardInterrupt: 

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

165 return 1 

166 except Exception as e: 

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

168 return 1 

169 finally: 

170 self._cleanup() 

171 self._restore_signal_handlers() 

172 

173 def _setup_signal_handlers(self) -> None: 

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

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

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

177 

178 def _restore_signal_handlers(self) -> None: 

179 """Restore original signal handlers.""" 

180 if self._original_sigint is not None: 

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

182 if self._original_sigterm is not None: 

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

184 

185 def _ensure_gitignore_entries(self) -> None: 

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

187 

188 Adds entries for: 

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

190 - .worktrees/ (git worktree directory) 

191 

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

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

194 """ 

195 gitignore_path = self.repo_path / ".gitignore" 

196 required_entries = [ 

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

198 ".worktrees/", 

199 ] 

200 

201 existing_content = "" 

202 if gitignore_path.exists(): 

203 existing_content = gitignore_path.read_text() 

204 

205 # Check which entries are missing 

206 missing_entries = [] 

207 for entry in required_entries: 

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

209 if entry not in existing_content: 

210 missing_entries.append(entry) 

211 

212 if not missing_entries: 

213 return 

214 

215 # Append missing entries 

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

217 for entry in missing_entries: 

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

219 

220 # Ensure file ends with newline before adding 

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

222 addition = "\n" + addition 

223 

224 gitignore_path.write_text(existing_content + addition) 

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

226 

227 def _cleanup_orphaned_worktrees(self) -> None: 

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

229 

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

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

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

233 """ 

234 worktree_base = self.repo_path / self.parallel_config.worktree_base 

235 if not worktree_base.exists(): 

236 return 

237 

238 # Get list of worktree directories, skipping those owned by live processes (BUG-579) 

239 orphaned = [] 

240 for item in worktree_base.iterdir(): 

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

242 # Check for a .ll-session-<pid> marker left by an active orchestrator 

243 owned_by_live = False 

244 for marker in item.glob(".ll-session-*"): 

245 try: 

246 pid = int(marker.name.split("-")[-1]) 

247 os.kill(pid, 0) # Signal 0: check if process exists 

248 owned_by_live = True 

249 break 

250 except (ProcessLookupError, ValueError): 

251 pass 

252 except PermissionError: 

253 owned_by_live = True # Process exists, no permission to signal 

254 break 

255 if owned_by_live: 

256 self.logger.info(f"Skipping {item.name}: owned by running process") 

257 continue 

258 orphaned.append(item) 

259 

260 if not orphaned: 

261 return 

262 

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

264 

265 for worktree_path in orphaned: 

266 try: 

267 # Try git worktree remove first 

268 self._git_lock.run( 

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

270 cwd=self.repo_path, 

271 timeout=30, 

272 ) 

273 

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

275 if worktree_path.exists(): 

276 shutil.rmtree(worktree_path, ignore_errors=True) 

277 

278 # Try to delete the associated branch using the actual branch name 

279 branch_result = subprocess.run( 

280 ["git", "rev-parse", "--abbrev-ref", "HEAD"], 

281 cwd=worktree_path, 

282 capture_output=True, 

283 text=True, 

284 ) 

285 branch_name = ( 

286 branch_result.stdout.strip() if branch_result.returncode == 0 else None 

287 ) 

288 if branch_name and branch_name.startswith("parallel/"): 

289 self._git_lock.run( 

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

291 cwd=self.repo_path, 

292 timeout=10, 

293 ) 

294 except Exception as e: 

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

296 

297 # Also prune git worktree references 

298 self._git_lock.run( 

299 ["worktree", "prune"], 

300 cwd=self.repo_path, 

301 timeout=30, 

302 ) 

303 

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

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

306 

307 Args: 

308 worktree_path: Path to the worktree directory 

309 

310 Returns: 

311 PendingWorktreeInfo if inspection succeeded, None if failed 

312 """ 

313 try: 

314 # Read actual branch name from worktree via rev-parse 

315 branch_result = subprocess.run( 

316 ["git", "rev-parse", "--abbrev-ref", "HEAD"], 

317 cwd=worktree_path, 

318 capture_output=True, 

319 text=True, 

320 ) 

321 if branch_result.returncode == 0: 

322 branch_name = branch_result.stdout.strip() 

323 else: 

324 # Fall back to string derivation if rev-parse fails 

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

326 

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

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

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

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

331 

332 # Check commits ahead of main 

333 result = self._git_lock.run( 

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

335 cwd=self.repo_path, 

336 timeout=10, 

337 ) 

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

339 

340 # Check for uncommitted changes in worktree 

341 result = self._git_lock.run( 

342 ["status", "--porcelain"], 

343 cwd=worktree_path, 

344 timeout=10, 

345 ) 

346 changed_files = [] 

347 has_uncommitted = False 

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

349 has_uncommitted = True 

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

351 

352 return PendingWorktreeInfo( 

353 worktree_path=worktree_path, 

354 branch_name=branch_name, 

355 issue_id=issue_id, 

356 commits_ahead=commits_ahead, 

357 has_uncommitted_changes=has_uncommitted, 

358 changed_files=changed_files, 

359 ) 

360 except Exception as e: 

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

362 return None 

363 

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

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

366 

367 Returns: 

368 List of pending worktree information 

369 """ 

370 worktree_base = self.repo_path / self.parallel_config.worktree_base 

371 if not worktree_base.exists(): 

372 return [] 

373 

374 # Find all worker directories 

375 worktrees = [ 

376 item 

377 for item in worktree_base.iterdir() 

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

379 ] 

380 

381 if not worktrees: 

382 return [] 

383 

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

385 

386 # Inspect each worktree 

387 pending_info: list[PendingWorktreeInfo] = [] 

388 for worktree_path in worktrees: 

389 info = self._inspect_worktree(worktree_path) 

390 if info: 

391 pending_info.append(info) 

392 

393 # Report findings 

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

395 if with_work: 

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

397 for info in with_work: 

398 status_parts = [] 

399 if info.commits_ahead > 0: 

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

401 if info.has_uncommitted_changes: 

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

403 status = ", ".join(status_parts) 

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

405 

406 self.logger.info("") 

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

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

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

410 self.logger.info( 

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

412 ) 

413 elif pending_info: 

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

415 

416 return pending_info 

417 

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

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

420 

421 Args: 

422 pending: List of pending worktree information 

423 """ 

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

425 if not with_work: 

426 return 

427 

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

429 

430 for info in with_work: 

431 try: 

432 # If there are uncommitted changes, commit them first 

433 if info.has_uncommitted_changes: 

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

435 self._git_lock.run( 

436 ["add", "-A"], 

437 cwd=info.worktree_path, 

438 timeout=30, 

439 ) 

440 self._git_lock.run( 

441 [ 

442 "commit", 

443 "-m", 

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

445 ], 

446 cwd=info.worktree_path, 

447 timeout=30, 

448 ) 

449 

450 # Attempt merge 

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

452 result = self._git_lock.run( 

453 [ 

454 "merge", 

455 "--no-ff", 

456 info.branch_name, 

457 "-m", 

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

459 ], 

460 cwd=self.repo_path, 

461 timeout=60, 

462 ) 

463 

464 if result.returncode == 0: 

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

466 # Clean up the worktree after successful merge 

467 self._git_lock.run( 

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

469 cwd=self.repo_path, 

470 timeout=30, 

471 ) 

472 self._git_lock.run( 

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

474 cwd=self.repo_path, 

475 timeout=10, 

476 ) 

477 else: 

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

479 # Abort the merge if it failed 

480 self._git_lock.run( 

481 ["merge", "--abort"], 

482 cwd=self.repo_path, 

483 timeout=10, 

484 ) 

485 

486 except Exception as e: 

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

488 

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

490 """Handle shutdown signals gracefully.""" 

491 self._shutdown_requested = True 

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

493 self.worker_pool.set_shutdown_requested(True) 

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

495 

496 def _load_state(self) -> None: 

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

498 if self.parallel_config.clean_start: 

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

500 return 

501 state_file = self.repo_path / self.parallel_config.state_file 

502 if not state_file.exists(): 

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

504 return 

505 

506 try: 

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

508 self.state = OrchestratorState.from_dict(data) 

509 

510 # Restore queue state 

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

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

513 

514 self.logger.info( 

515 f"Resumed from previous state: " 

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

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

518 ) 

519 except Exception as e: 

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

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

522 

523 def _save_state(self, force: bool = False) -> None: 

524 """Save current state to file using an atomic write. 

525 

526 Writes are throttled to at most once every 5 seconds to reduce filesystem I/O 

527 during high-frequency loop ticks (e.g., merge-waiting phase). Pass force=True 

528 to bypass the throttle, e.g., on shutdown. 

529 """ 

530 now = time.time() 

531 if not force and now - self._last_save_time < 5.0: 

532 return 

533 self._last_save_time = now 

534 with self._state_lock: 

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

536 self.state.completed_issues = self.queue.completed_ids 

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

538 self.state.in_progress_issues = self.queue.in_progress_ids 

539 

540 state_file = self.repo_path / self.parallel_config.state_file 

541 data = json.dumps(self.state.to_dict(), indent=2) 

542 tmp_fd, tmp_path = tempfile.mkstemp(dir=state_file.parent, suffix=".tmp") 

543 try: 

544 with os.fdopen(tmp_fd, "w") as f: 

545 f.write(data) 

546 os.replace(tmp_path, state_file) 

547 except Exception: 

548 os.unlink(tmp_path) 

549 raise 

550 

551 def _cleanup_state(self) -> None: 

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

553 state_file = self.repo_path / self.parallel_config.state_file 

554 if state_file.exists(): 

555 state_file.unlink() 

556 

557 def _dry_run(self) -> int: 

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

559 

560 Returns: 

561 Exit code (always 0 for dry run) 

562 """ 

563 issues = self._scan_issues() 

564 

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

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

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

568 self.logger.info("") 

569 

570 if not issues: 

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

572 return 0 

573 

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

575 self.logger.info("") 

576 

577 # Group by priority 

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

579 for issue in issues: 

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

581 

582 for priority in IssuePriorityQueue.DEFAULT_PRIORITIES: 

583 if priority not in by_priority: 

584 continue 

585 

586 priority_issues = by_priority[priority] 

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

588 for issue in priority_issues: 

589 mode = ( 

590 "sequential" 

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

592 else "parallel" 

593 ) 

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

595 

596 self.logger.info("") 

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

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

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

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

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

602 

603 return 0 

604 

605 def _maybe_report_status(self) -> None: 

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

607 

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

609 Suppresses duplicate lines when nothing has changed. 

610 """ 

611 now = time.time() 

612 # Report every 5 seconds 

613 if now - self._last_status_time < 5.0: 

614 return 

615 

616 self._last_status_time = now 

617 

618 # Build status line 

619 parts = [] 

620 

621 # Add wave label if present 

622 if self.wave_label: 

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

624 

625 # Get queue counts 

626 in_progress = len(self.queue.in_progress_ids) 

627 completed = self.queue.completed_count 

628 failed = self.queue.failed_count 

629 pending_merge = self.merge_coordinator.pending_count 

630 

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

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

633 if failed > 0: 

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

635 if pending_merge > 0: 

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

637 

638 # Build status line 

639 status = " | ".join(parts) 

640 

641 # Get active worker stages 

642 active_stages = self.worker_pool.get_active_stages() 

643 

644 # Add worker details if any are active 

645 if active_stages: 

646 # Group by stage 

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

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

649 stage_name = worker_stage.value.title() 

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

651 

652 stage_parts = [] 

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

654 if stage_name in by_stage: 

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

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

657 

658 if stage_parts: 

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

660 

661 # Skip if nothing changed since last report 

662 if status == self._last_status_line: 

663 return 

664 self._last_status_line = status 

665 

666 # Log with gray color to distinguish from normal logs 

667 if self.logger.use_color: 

668 color = self.logger.GRAY 

669 ts = self.logger._timestamp() 

670 print(f"{color}[{ts}]{self.logger.RESET} {status}", flush=True) 

671 else: 

672 self.logger.info(status) 

673 

674 def _execute(self) -> int: 

675 """Execute parallel issue processing. 

676 

677 Returns: 

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

679 """ 

680 start_time = time.time() 

681 

682 # Scan and queue issues 

683 issues = self._scan_issues() 

684 if not issues: 

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

686 return 0 

687 

688 # Store issue info for lifecycle completion after merge 

689 for issue in issues: 

690 self._issue_info_by_id[issue.issue_id] = issue 

691 

692 added = self.queue.add_many(issues) 

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

694 

695 # Start components 

696 self.worker_pool.start() 

697 self.merge_coordinator.start() 

698 

699 # Process issues 

700 issues_processed = 0 

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

702 

703 while not self._shutdown_requested: 

704 # Check if done 

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

706 # Wait for pending merges 

707 if self.merge_coordinator.pending_count == 0: 

708 break 

709 

710 # Check max issues limit 

711 if issues_processed >= max_issues: 

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

713 break 

714 

715 # Get next issue if workers available 

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

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

718 if queued: 

719 issue = queued.issue_info 

720 

721 # P0 sequential processing 

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

723 self._process_sequential(issue) 

724 else: 

725 self._process_parallel(issue) 

726 

727 issues_processed += 1 

728 

729 # Save state periodically 

730 self._save_state() 

731 

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

733 self._maybe_report_status() 

734 

735 # Small sleep to prevent busy loop 

736 time.sleep(0.1) 

737 

738 # Wait for completion 

739 self._wait_for_completion() 

740 

741 # Report results 

742 self._report_results(start_time) 

743 

744 # Cleanup state on success 

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

746 self._cleanup_state() 

747 

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

749 

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

751 """Scan for issues matching criteria. 

752 

753 Returns: 

754 List of issues sorted by priority 

755 """ 

756 # Combine skip_ids from state and config 

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

758 if self.parallel_config.skip_ids: 

759 skip_ids |= self.parallel_config.skip_ids 

760 

761 issues = IssuePriorityQueue.scan_issues( 

762 self.br_config, 

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

764 skip_ids=skip_ids, 

765 only_ids=self.parallel_config.only_ids, 

766 type_prefixes=self.parallel_config.type_prefixes, 

767 ) 

768 

769 # Apply max issues limit 

770 if self.parallel_config.max_issues > 0: 

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

772 

773 return issues 

774 

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

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

777 

778 Args: 

779 issue: Issue to process 

780 """ 

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

782 

783 # Wait for any parallel work to finish 

784 while self.worker_pool.active_count > 0: 

785 time.sleep(0.5) 

786 

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

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

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

790 future = self.worker_pool.submit(issue) 

791 

792 # Wait for completion 

793 try: 

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

795 if result.success: 

796 # Merge immediately for P0 

797 self._merge_sequential(result) 

798 except Exception as e: 

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

800 self.queue.mark_failed(issue.issue_id) 

801 

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

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

804 

805 Args: 

806 issue: Issue to process 

807 """ 

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

809 if self.overlap_detector: 

810 overlap = self.overlap_detector.check_overlap(issue) 

811 if overlap: 

812 if self.parallel_config.serialize_overlapping: 

813 self.logger.warning( 

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

815 ) 

816 # Track for re-check when active issues complete 

817 self._deferred_issues.append(issue) 

818 return 

819 else: 

820 self.logger.warning( 

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

822 ) 

823 

824 # Register as active before dispatch 

825 self.overlap_detector.register_issue(issue) 

826 

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

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

829 

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

831 """Callback when a worker completes. 

832 

833 Args: 

834 result: Result from the worker 

835 """ 

836 # Unregister from overlap tracking (ENH-143) 

837 if self.overlap_detector: 

838 self.overlap_detector.unregister_issue(result.issue_id) 

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

840 self._requeue_deferred_issues() 

841 

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

843 if result.interrupted: 

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

845 self._interrupted_issues.append(result.issue_id) 

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

847 return 

848 

849 # Handle issue closure (no merge needed) 

850 if result.should_close: 

851 # Lazy import to avoid circular dependency 

852 from little_loops.issue_lifecycle import close_issue 

853 

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

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

856 if info: 

857 if close_issue( 

858 info, 

859 self.br_config, 

860 self.logger, 

861 result.close_reason, 

862 result.close_status, 

863 ): 

864 self.queue.mark_completed(result.issue_id) 

865 else: 

866 self.queue.mark_failed(result.issue_id) 

867 else: 

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

869 self.queue.mark_failed(result.issue_id) 

870 elif result.success: 

871 self.logger.success( 

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

873 ) 

874 if result.was_corrected: 

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

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

877 for correction in result.corrections: 

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

879 if result.corrections: 

880 with self._state_lock: 

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

882 if self.parallel_config.use_feature_branches: 

883 # Feature branch mode: skip auto-merge, branch stays alive for a PR (ENH-665) 

884 self.logger.info(f"{result.issue_id}: feature branch ready — {result.branch_name}") 

885 self.queue.mark_completed(result.issue_id) 

886 self._complete_issue_lifecycle_if_needed(result.issue_id) 

887 with self._state_lock: 

888 self._pr_ready_branches[result.issue_id] = result.branch_name 

889 else: 

890 self.merge_coordinator.queue_merge(result) 

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

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

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

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

895 self.merge_coordinator.wait_for_completion(timeout=120) 

896 else: 

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

898 self.queue.mark_failed(result.issue_id) 

899 

900 # Update timing 

901 with self._state_lock: 

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

903 "total": result.duration, 

904 } 

905 

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

907 # Delay briefly so status reporter can show completion 

908 self.worker_pool.remove_worker_stage(result.issue_id) 

909 

910 def _requeue_deferred_issues(self) -> None: 

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

912 if not self._deferred_issues: 

913 return 

914 

915 # Check each deferred issue for remaining overlaps 

916 still_deferred = [] 

917 for issue in self._deferred_issues: 

918 if self.overlap_detector: 

919 overlap = self.overlap_detector.check_overlap(issue) 

920 if overlap: 

921 # Still has overlaps, keep deferred 

922 still_deferred.append(issue) 

923 else: 

924 # No more overlaps, add back to queue 

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

926 self.queue.add(issue) 

927 

928 self._deferred_issues = still_deferred 

929 

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

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

932 

933 Args: 

934 result: Result to merge 

935 """ 

936 # Handle closure for sequential issues 

937 if result.should_close: 

938 # Lazy import to avoid circular dependency 

939 from little_loops.issue_lifecycle import close_issue 

940 

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

942 if info and close_issue( 

943 info, 

944 self.br_config, 

945 self.logger, 

946 result.close_reason, 

947 result.close_status, 

948 ): 

949 self.queue.mark_completed(result.issue_id) 

950 else: 

951 self.queue.mark_failed(result.issue_id) 

952 return 

953 

954 self.merge_coordinator.queue_merge(result) 

955 # Wait for this specific merge 

956 self.merge_coordinator.wait_for_completion(timeout=60) 

957 

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

959 self.queue.mark_completed(result.issue_id) 

960 self._complete_issue_lifecycle_if_needed(result.issue_id) 

961 else: 

962 self.queue.mark_failed(result.issue_id) 

963 

964 def _wait_for_completion(self) -> None: 

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

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

967 

968 # Calculate timeout 

969 if self.parallel_config.orchestrator_timeout > 0: 

970 timeout = self.parallel_config.orchestrator_timeout 

971 else: 

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

973 

974 start = time.time() 

975 while self.worker_pool.active_count > 0: 

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

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

978 self.worker_pool.terminate_all_processes() 

979 break 

980 time.sleep(1.0) 

981 

982 # Wait for merges 

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

984 self.merge_coordinator.wait_for_completion(timeout=120) 

985 

986 # Update queue with merge results and complete lifecycle 

987 for issue_id in self.merge_coordinator.merged_ids: 

988 self.queue.mark_completed(issue_id) 

989 self._complete_issue_lifecycle_if_needed(issue_id) 

990 

991 for issue_id in self.merge_coordinator.failed_merges: 

992 self.queue.mark_failed(issue_id) 

993 

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

995 """Report processing results. 

996 

997 Args: 

998 start_time: When processing started 

999 """ 

1000 total_time = time.time() - start_time 

1001 self._execution_duration = total_time 

1002 

1003 self.logger.info("") 

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

1005 if self.wave_label: 

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

1007 else: 

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

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

1010 self.logger.info("") 

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

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

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

1014 if self._interrupted_issues: 

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

1016 

1017 with self._state_lock: 

1018 timing_snapshot = dict(self.state.timing) 

1019 corrections_snapshot = dict(self.state.corrections) 

1020 

1021 if self.queue.completed_count > 0: 

1022 total_issue_time = sum(t.get("total", 0) for t in timing_snapshot.values()) 

1023 if total_issue_time > 0: 

1024 speedup = total_issue_time / total_time 

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

1026 

1027 if self.queue.failed_ids: 

1028 self.logger.info("") 

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

1030 for issue_id in self.queue.failed_ids: 

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

1032 

1033 # Report interrupted issues separately (ENH-036) 

1034 if self._interrupted_issues: 

1035 self.logger.info("") 

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

1037 for issue_id in self._interrupted_issues: 

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

1039 

1040 # Report PR-ready branches when use_feature_branches=True (ENH-665) 

1041 if self._pr_ready_branches: 

1042 self.logger.info("") 

1043 self.logger.info(f"PR-ready: {len(self._pr_ready_branches)} branch(es)") 

1044 for issue_id, branch in self._pr_ready_branches.items(): 

1045 self.logger.info(f" - {issue_id}: {branch}") 

1046 

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

1048 if corrections_snapshot: 

1049 total_corrected = len(corrections_snapshot) 

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

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

1052 self.logger.info("") 

1053 self.logger.info( 

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

1055 ) 

1056 

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

1058 from collections import Counter, defaultdict 

1059 

1060 all_corrections: list[str] = [] 

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

1062 for corrections in corrections_snapshot.values(): 

1063 all_corrections.extend(corrections) 

1064 for correction in corrections: 

1065 # Extract category from [category] prefix if present 

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

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

1068 by_category[category] += 1 

1069 else: 

1070 by_category["uncategorized"] += 1 

1071 

1072 # Log corrections by type/category 

1073 if by_category: 

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

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

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

1077 

1078 # Log most common individual corrections 

1079 if all_corrections: 

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

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

1082 for correction, count in common: 

1083 # Truncate long correction descriptions 

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

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

1086 

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

1088 stash_warnings = self.merge_coordinator.stash_pop_failures 

1089 if stash_warnings: 

1090 self.logger.info("") 

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

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

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

1094 self.logger.warning("") 

1095 self.logger.warning( 

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

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

1098 ) 

1099 

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

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

1102 

1103 Args: 

1104 issue_id: ID of the issue to complete 

1105 

1106 Returns: 

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

1108 """ 

1109 info = self._issue_info_by_id.get(issue_id) 

1110 if not info: 

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

1112 return False 

1113 

1114 original_path = info.path 

1115 completed_dir = self.br_config.get_completed_dir() 

1116 completed_path = completed_dir / original_path.name 

1117 

1118 # Check if already moved to completed 

1119 if completed_path.exists(): 

1120 return True 

1121 

1122 # Check if still in original location 

1123 if not original_path.exists(): 

1124 return True 

1125 

1126 # Issue file still in original location - complete lifecycle 

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

1128 

1129 try: 

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

1131 

1132 # Read original content 

1133 content = original_path.read_text() 

1134 

1135 # Add resolution section if not already present 

1136 if "## Resolution" not in content: 

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

1138 resolution = f""" 

1139 

1140--- 

1141 

1142## Resolution 

1143 

1144- **Action**: {action} 

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

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

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

1148 

1149### Changes Made 

1150- See git history for implementation details 

1151 

1152### Verification Results 

1153- Work verification passed before merge 

1154 

1155### Commits 

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

1157""" 

1158 content += resolution 

1159 

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

1161 result = self._git_lock.run( 

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

1163 cwd=self.repo_path, 

1164 ) 

1165 

1166 if result.returncode != 0: 

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

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

1169 # Write content to destination (may overwrite existing) 

1170 completed_path.write_text(content) 

1171 # Remove source if it still exists 

1172 original_path.unlink(missing_ok=True) 

1173 else: 

1174 # git mv succeeded, write updated content 

1175 completed_path.write_text(content) 

1176 append_session_log_entry(completed_path, "ll-parallel") 

1177 

1178 # Stage and commit 

1179 self._git_lock.run( 

1180 ["add", "-A"], 

1181 cwd=self.repo_path, 

1182 ) 

1183 

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

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

1186 

1187Parallel merge fallback - issue file moved to completed. 

1188 

1189Issue: {issue_id} 

1190Type: {info.issue_type} 

1191Title: {info.title} 

1192""" 

1193 commit_result = self._git_lock.run( 

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

1195 cwd=self.repo_path, 

1196 ) 

1197 

1198 if commit_result.returncode != 0: 

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

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

1201 else: 

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

1203 if commit_hash_match: 

1204 self.logger.success( 

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

1206 ) 

1207 else: 

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

1209 

1210 return True 

1211 

1212 except Exception as e: 

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

1214 return False 

1215 

1216 def _cleanup(self) -> None: 

1217 """Clean up resources.""" 

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

1219 

1220 # Save final state (force=True bypasses throttle to ensure shutdown state is persisted) 

1221 self._save_state(force=True) 

1222 

1223 # Shutdown components 

1224 self.worker_pool.shutdown(wait=True) 

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

1226 

1227 # Clean up worktrees if not interrupted 

1228 if not self._shutdown_requested: 

1229 self.worker_pool.cleanup_all_worktrees()