Coverage for little_loops / parallel / worker_pool.py: 86%

417 statements  

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

1"""Worker pool for parallel issue processing with git worktree isolation. 

2 

3Each worker operates in an isolated git worktree, allowing concurrent issue 

4processing without file conflicts. 

5""" 

6 

7from __future__ import annotations 

8 

9import json 

10import os 

11import re 

12import shutil 

13import subprocess 

14import sys 

15import threading 

16import time 

17from collections.abc import Callable 

18from concurrent.futures import Future, ThreadPoolExecutor 

19from datetime import datetime 

20from pathlib import Path 

21from typing import TYPE_CHECKING, Any, cast 

22 

23from little_loops.output_parsing import parse_ready_issue_output 

24from little_loops.parallel.git_lock import GitLock 

25from little_loops.parallel.types import ParallelConfig, WorkerResult, WorkerStage 

26from little_loops.subprocess_utils import ( 

27 detect_context_handoff, 

28 read_continuation_prompt, 

29) 

30from little_loops.subprocess_utils import ( 

31 run_claude_command as _run_claude_base, 

32) 

33from little_loops.work_verification import EXCLUDED_DIRECTORIES, verify_work_was_done 

34 

35if TYPE_CHECKING: 

36 from little_loops.config import BRConfig 

37 from little_loops.issue_parser import IssueInfo 

38 from little_loops.logger import Logger 

39 

40 

41class WorkerPool: 

42 """Thread pool for processing issues in isolated git worktrees. 

43 

44 Each worker: 

45 1. Creates a dedicated git worktree and branch 

46 2. Runs issue validation and implementation via Claude CLI 

47 3. Commits changes locally 

48 4. Returns results for merge coordination 

49 

50 Example: 

51 >>> pool = WorkerPool(parallel_config, br_config, logger) 

52 >>> pool.start() 

53 >>> future = pool.submit(issue_info) 

54 >>> result = future.result() # WorkerResult 

55 >>> pool.shutdown() 

56 """ 

57 

58 def __init__( 

59 self, 

60 parallel_config: ParallelConfig, 

61 br_config: BRConfig, 

62 logger: Logger, 

63 repo_path: Path | None = None, 

64 git_lock: GitLock | None = None, 

65 ) -> None: 

66 """Initialize the worker pool. 

67 

68 Args: 

69 parallel_config: Parallel processing configuration 

70 br_config: Project configuration (for category actions) 

71 logger: Logger for worker output 

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

73 git_lock: Shared lock for git operations (created if not provided) 

74 """ 

75 self.parallel_config = parallel_config 

76 self.br_config = br_config 

77 self.logger = logger 

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

79 self._git_lock = git_lock or GitLock(logger) 

80 self._executor: ThreadPoolExecutor | None = None 

81 self._active_workers: dict[str, Future[WorkerResult]] = {} 

82 # Track active subprocesses for forceful termination on shutdown 

83 self._active_processes: dict[str, subprocess.Popen[str]] = {} 

84 # Track active worktree paths to prevent cleanup while in use (BUG-142) 

85 self._active_worktrees: set[Path] = set() 

86 self._process_lock = threading.Lock() 

87 # Track callbacks currently executing 

88 self._pending_callbacks: set[str] = set() 

89 self._callback_lock = threading.Lock() 

90 # Shutdown tracking for interrupted worker detection (ENH-036) 

91 self._shutdown_requested = False 

92 self._terminated_during_shutdown: set[str] = set() 

93 # Track worker processing stages for progress visibility (ENH-262) 

94 self._worker_stages: dict[str, WorkerStage] = {} 

95 

96 def start(self) -> None: 

97 """Start the worker pool.""" 

98 if self._executor is not None: 

99 return 

100 

101 # Ensure worktree base directory exists 

102 worktree_base = self.repo_path / self.parallel_config.worktree_base 

103 worktree_base.mkdir(parents=True, exist_ok=True) 

104 

105 self._executor = ThreadPoolExecutor( 

106 max_workers=self.parallel_config.max_workers, 

107 thread_name_prefix="issue-worker", 

108 ) 

109 self.logger.info(f"Worker pool started with {self.parallel_config.max_workers} workers") 

110 

111 def shutdown(self, wait: bool = True) -> None: 

112 """Shutdown the worker pool. 

113 

114 Args: 

115 wait: Whether to wait for pending tasks to complete 

116 """ 

117 if self._executor is None: 

118 return 

119 

120 self.logger.info("Shutting down worker pool...") 

121 

122 # First, terminate all active subprocesses to unblock worker threads 

123 if not wait: 

124 self.terminate_all_processes() 

125 

126 self._executor.shutdown(wait=wait) 

127 self._executor = None 

128 

129 def set_shutdown_requested(self, value: bool = True) -> None: 

130 """Set the shutdown flag. 

131 

132 Called by orchestrator during shutdown to enable tracking of 

133 workers that are terminated due to shutdown vs. actual failures. 

134 """ 

135 self._shutdown_requested = value 

136 

137 def terminate_all_processes(self) -> None: 

138 """Forcefully terminate all active subprocesses. 

139 

140 Called when we need to abort workers immediately, 

141 such as on timeout or shutdown. 

142 """ 

143 with self._process_lock: 

144 for issue_id, process in list(self._active_processes.items()): 

145 if process.poll() is None: # Still running 

146 self.logger.warning( 

147 f"Terminating subprocess for {issue_id} (PID {process.pid})" 

148 ) 

149 # Track issues terminated during shutdown for interrupted detection (ENH-036) 

150 if self._shutdown_requested: 

151 self._terminated_during_shutdown.add(issue_id) 

152 try: 

153 # Send SIGTERM first for graceful termination 

154 process.terminate() 

155 try: 

156 process.wait(timeout=5) 

157 except subprocess.TimeoutExpired: 

158 # Force kill if SIGTERM didn't work 

159 self.logger.warning(f"Force killing {issue_id} (PID {process.pid})") 

160 process.kill() 

161 process.wait(timeout=2) 

162 except Exception as e: 

163 self.logger.error(f"Failed to terminate {issue_id}: {e}") 

164 self._active_processes.clear() 

165 

166 def submit( 

167 self, 

168 issue: IssueInfo, 

169 on_complete: Callable[[WorkerResult], None] | None = None, 

170 ) -> Future[WorkerResult]: 

171 """Submit an issue for processing. 

172 

173 Args: 

174 issue: Issue to process 

175 on_complete: Optional callback when processing completes 

176 

177 Returns: 

178 Future that will contain the WorkerResult 

179 """ 

180 if self._executor is None: 

181 raise RuntimeError("Worker pool not started") 

182 

183 future = self._executor.submit(self._process_issue, issue) 

184 self._active_workers[issue.issue_id] = future 

185 

186 if on_complete: 

187 future.add_done_callback( 

188 lambda f: self._handle_completion(f, on_complete, issue.issue_id) 

189 ) 

190 

191 return future 

192 

193 def _handle_completion( 

194 self, 

195 future: Future[WorkerResult], 

196 callback: Callable[[WorkerResult], None], 

197 issue_id: str, 

198 ) -> None: 

199 """Handle worker completion and invoke callback.""" 

200 with self._callback_lock: 

201 self._pending_callbacks.add(issue_id) 

202 try: 

203 try: 

204 result = future.result() 

205 except Exception as e: 

206 self.logger.error(f"Worker future failed for {issue_id}: {e}") 

207 result = WorkerResult( 

208 issue_id=issue_id, 

209 success=False, 

210 branch_name="", 

211 worktree_path=Path(), 

212 error=f"Worker future failed: {e}", 

213 ) 

214 # Set final stage based on result (ENH-262) 

215 if result.success: 

216 self.set_worker_stage(issue_id, WorkerStage.COMPLETED) 

217 elif result.interrupted: 

218 self.set_worker_stage(issue_id, WorkerStage.INTERRUPTED) 

219 else: 

220 self.set_worker_stage(issue_id, WorkerStage.FAILED) 

221 try: 

222 callback(result) 

223 except Exception as e: 

224 self.logger.error(f"Worker completion callback failed for {issue_id}: {e}") 

225 finally: 

226 with self._callback_lock: 

227 self._pending_callbacks.discard(issue_id) 

228 

229 def _process_issue(self, issue: IssueInfo) -> WorkerResult: 

230 """Process a single issue in an isolated worktree. 

231 

232 Args: 

233 issue: Issue to process 

234 

235 Returns: 

236 WorkerResult with processing outcome 

237 """ 

238 start_time = time.time() 

239 timestamp = datetime.now().strftime("%Y%m%d-%H%M%S") 

240 branch_name = f"parallel/{issue.issue_id.lower()}-{timestamp}" 

241 worktree_path = ( 

242 self.repo_path 

243 / self.parallel_config.worktree_base 

244 / f"worker-{issue.issue_id.lower()}-{timestamp}" 

245 ) 

246 

247 # Set initial stage for progress tracking (ENH-262) 

248 self.set_worker_stage(issue.issue_id, WorkerStage.SETUP) 

249 

250 # Capture baseline of main repo status before worker starts 

251 # Used to detect files incorrectly written to main repo 

252 baseline_status = self._get_main_repo_baseline() 

253 

254 try: 

255 # Step 1: Create worktree with new branch 

256 self._setup_worktree(worktree_path, branch_name) 

257 

258 # Register worktree as active to prevent cleanup while in use (BUG-142) 

259 with self._process_lock: 

260 self._active_worktrees.add(worktree_path) 

261 

262 # Update stage for progress tracking (ENH-262) 

263 self.set_worker_stage(issue.issue_id, WorkerStage.VALIDATING) 

264 

265 # Step 2: Run ready-issue validation 

266 ready_cmd = self.parallel_config.get_ready_command(issue.issue_id) 

267 ready_result = self._run_claude_command( 

268 ready_cmd, 

269 worktree_path, 

270 issue_id=issue.issue_id, 

271 ) 

272 

273 # Check if worker was terminated during shutdown (ENH-036) 

274 if issue.issue_id in self._terminated_during_shutdown: 

275 self.set_worker_stage(issue.issue_id, WorkerStage.INTERRUPTED) 

276 return WorkerResult( 

277 issue_id=issue.issue_id, 

278 success=False, 

279 interrupted=True, 

280 branch_name=branch_name, 

281 worktree_path=worktree_path, 

282 duration=time.time() - start_time, 

283 error="Interrupted during shutdown", 

284 stdout=ready_result.stdout, 

285 stderr=ready_result.stderr, 

286 ) 

287 

288 if ready_result.returncode != 0: 

289 return WorkerResult( 

290 issue_id=issue.issue_id, 

291 success=False, 

292 branch_name=branch_name, 

293 worktree_path=worktree_path, 

294 duration=time.time() - start_time, 

295 error=f"ready-issue failed: {ready_result.stderr}", 

296 stdout=ready_result.stdout, 

297 stderr=ready_result.stderr, 

298 ) 

299 

300 # Step 3: Parse ready-issue output and check verdict 

301 ready_parsed = parse_ready_issue_output(ready_result.stdout) 

302 

303 # Handle CLOSE verdict - issue should not be implemented 

304 if ready_parsed.get("should_close"): 

305 return WorkerResult( 

306 issue_id=issue.issue_id, 

307 success=True, # Closure is a valid outcome 

308 branch_name=branch_name, 

309 worktree_path=worktree_path, 

310 duration=time.time() - start_time, 

311 should_close=True, 

312 close_reason=ready_parsed.get("close_reason"), 

313 close_status=ready_parsed.get("close_status"), 

314 stdout=ready_result.stdout, 

315 stderr=ready_result.stderr, 

316 ) 

317 

318 # Handle NOT_READY verdict 

319 if not ready_parsed["is_ready"]: 

320 concerns = ready_parsed.get("concerns", []) 

321 if concerns: 

322 concern_msg = "; ".join(concerns) 

323 elif ready_parsed["verdict"] == "UNKNOWN": 

324 # For UNKNOWN verdicts, show a snippet of output for debugging 

325 raw_out = (ready_result.stdout or "")[:200].strip() 

326 concern_msg = ( 

327 f"Could not parse verdict. Output: {raw_out}..." 

328 if raw_out 

329 else "No output from ready-issue" 

330 ) 

331 else: 

332 concern_msg = "Issue not ready" 

333 return WorkerResult( 

334 issue_id=issue.issue_id, 

335 success=False, 

336 branch_name=branch_name, 

337 worktree_path=worktree_path, 

338 duration=time.time() - start_time, 

339 error=f"ready-issue verdict: {ready_parsed['verdict']} - {concern_msg}", 

340 stdout=ready_result.stdout, 

341 stderr=ready_result.stderr, 

342 ) 

343 

344 # Track if issue was corrected (corrections stay in worktree) 

345 was_corrected = ready_parsed.get("was_corrected", False) 

346 corrections = ready_parsed.get("corrections", []) 

347 

348 # Update stage for progress tracking (ENH-262) 

349 self.set_worker_stage(issue.issue_id, WorkerStage.IMPLEMENTING) 

350 

351 # Step 4: Get action from BRConfig 

352 action = self.br_config.get_category_action(issue.issue_type) 

353 

354 # Step 5: Run manage-issue implementation (with continuation support) 

355 manage_cmd = self.parallel_config.get_manage_command( 

356 issue.issue_type, action, issue.issue_id 

357 ) 

358 manage_result = self._run_with_continuation( 

359 manage_cmd, 

360 worktree_path, 

361 issue_id=issue.issue_id, 

362 ) 

363 

364 # Update stage for progress tracking (ENH-262) 

365 self.set_worker_stage(issue.issue_id, WorkerStage.VERIFYING) 

366 

367 # Check if worker was terminated during shutdown (ENH-036) 

368 if issue.issue_id in self._terminated_during_shutdown: 

369 self.set_worker_stage(issue.issue_id, WorkerStage.INTERRUPTED) 

370 return WorkerResult( 

371 issue_id=issue.issue_id, 

372 success=False, 

373 interrupted=True, 

374 branch_name=branch_name, 

375 worktree_path=worktree_path, 

376 duration=time.time() - start_time, 

377 error="Interrupted during shutdown", 

378 stdout=manage_result.stdout, 

379 stderr=manage_result.stderr, 

380 ) 

381 

382 # Step 6: Get list of changed files 

383 changed_files = self._get_changed_files(worktree_path) 

384 

385 # Step 7: Verify actual work was done 

386 # Pass full filename for better doc-only keyword matching 

387 issue_filename = issue.path.stem if issue.path else "" 

388 work_verified, verification_error = self._verify_work_was_done( 

389 changed_files, issue.issue_id, issue_filename 

390 ) 

391 

392 # Step 8: Detect files leaked to main repo instead of worktree 

393 leaked_files = self._detect_main_repo_leaks(issue.issue_id, baseline_status) 

394 if leaked_files: 

395 self.logger.warning( 

396 f"{issue.issue_id} leaked {len(leaked_files)} file(s) to main repo: " 

397 f"{leaked_files}" 

398 ) 

399 # Clean up leaked files to prevent stash conflicts during merge. 

400 # The actual work is preserved in the worktree branch. 

401 self._cleanup_leaked_files(leaked_files) 

402 

403 if manage_result.returncode != 0: 

404 return WorkerResult( 

405 issue_id=issue.issue_id, 

406 success=False, 

407 branch_name=branch_name, 

408 worktree_path=worktree_path, 

409 changed_files=changed_files, 

410 leaked_files=leaked_files, 

411 duration=time.time() - start_time, 

412 error=f"manage-issue failed: {manage_result.stderr}", 

413 stdout=manage_result.stdout, 

414 stderr=manage_result.stderr, 

415 ) 

416 

417 if not work_verified: 

418 return WorkerResult( 

419 issue_id=issue.issue_id, 

420 success=False, 

421 branch_name=branch_name, 

422 worktree_path=worktree_path, 

423 changed_files=changed_files, 

424 leaked_files=leaked_files, 

425 duration=time.time() - start_time, 

426 error=verification_error, 

427 stdout=manage_result.stdout, 

428 stderr=manage_result.stderr, 

429 ) 

430 

431 # Step 9: Update branch base before merge (BUG-180) 

432 # Fetch origin/main and rebase to ensure branch is based on latest main 

433 base_updated, base_error = self._update_branch_base(worktree_path, issue.issue_id) 

434 

435 # Update stage for progress tracking (ENH-262) 

436 self.set_worker_stage(issue.issue_id, WorkerStage.MERGING) 

437 

438 if not base_updated: 

439 return WorkerResult( 

440 issue_id=issue.issue_id, 

441 success=False, 

442 branch_name=branch_name, 

443 worktree_path=worktree_path, 

444 changed_files=changed_files, 

445 leaked_files=leaked_files, 

446 duration=time.time() - start_time, 

447 error=base_error, 

448 stdout=manage_result.stdout, 

449 stderr=manage_result.stderr, 

450 ) 

451 

452 return WorkerResult( 

453 issue_id=issue.issue_id, 

454 success=True, 

455 branch_name=branch_name, 

456 worktree_path=worktree_path, 

457 changed_files=changed_files, 

458 leaked_files=leaked_files, 

459 duration=time.time() - start_time, 

460 error=None, 

461 stdout=manage_result.stdout, 

462 stderr=manage_result.stderr, 

463 was_corrected=was_corrected, 

464 corrections=corrections, 

465 ) 

466 

467 except Exception as e: 

468 return WorkerResult( 

469 issue_id=issue.issue_id, 

470 success=False, 

471 branch_name=branch_name, 

472 worktree_path=worktree_path, 

473 duration=time.time() - start_time, 

474 error=str(e), 

475 ) 

476 finally: 

477 # Unregister worktree as no longer active (BUG-142) 

478 with self._process_lock: 

479 self._active_worktrees.discard(worktree_path) 

480 

481 def _setup_worktree(self, worktree_path: Path, branch_name: str) -> None: 

482 """Create a git worktree with a new branch. 

483 

484 Args: 

485 worktree_path: Path for the new worktree 

486 branch_name: Name of the new branch 

487 """ 

488 # Remove existing worktree if present 

489 if worktree_path.exists(): 

490 self._cleanup_worktree(worktree_path) 

491 

492 # Create new worktree with branch 

493 result = self._git_lock.run( 

494 ["worktree", "add", "-b", branch_name, str(worktree_path)], 

495 cwd=self.repo_path, 

496 timeout=60, 

497 ) 

498 

499 if result.returncode != 0: 

500 raise RuntimeError(f"Failed to create worktree: {result.stderr}") 

501 

502 # Copy git identity from main repo 

503 for config_key in ["user.email", "user.name"]: 

504 value_result = self._git_lock.run( 

505 ["config", config_key], 

506 cwd=self.repo_path, 

507 ) 

508 if value_result.returncode == 0 and value_result.stdout.strip(): 

509 # Worktree config operations don't need the main repo lock 

510 subprocess.run( 

511 ["git", "config", config_key, value_result.stdout.strip()], 

512 cwd=worktree_path, 

513 capture_output=True, 

514 ) 

515 

516 # Copy .claude/ directory to establish project root for Claude Code (BUG-007) 

517 # Claude Code uses .claude/ directory as highest priority for project root detection. 

518 # Without this, Claude may detect the main repo as project root in worktrees, 

519 # causing file writes to leak to the main repository. 

520 claude_dir = self.repo_path / ".claude" 

521 if claude_dir.exists() and claude_dir.is_dir(): 

522 dest_claude_dir = worktree_path / ".claude" 

523 if dest_claude_dir.exists(): 

524 shutil.rmtree(dest_claude_dir) 

525 shutil.copytree(claude_dir, dest_claude_dir) 

526 self.logger.info("Copied .claude/ directory to worktree") 

527 

528 # Copy additional configured files from main repo to worktree 

529 for file_path in self.parallel_config.worktree_copy_files: 

530 if file_path.startswith(".claude/"): 

531 continue # Already copied with full .claude/ directory above 

532 src = self.repo_path / file_path 

533 if src.exists(): 

534 if src.is_dir(): 

535 self.logger.warning( 

536 f"Skipping '{file_path}' in worktree_copy_files: " 

537 "is a directory (use symlinks or copytree for directories)" 

538 ) 

539 continue 

540 dest = worktree_path / file_path 

541 dest.parent.mkdir(parents=True, exist_ok=True) 

542 shutil.copy2(src, dest) 

543 self.logger.info(f"Copied {file_path} to worktree") 

544 else: 

545 self.logger.debug(f"Skipped {file_path} (not found in main repo)") 

546 

547 self.logger.info(f"Created worktree at {worktree_path} on branch {branch_name}") 

548 

549 # Verify model if --show-model flag is set (requires API call) 

550 if self.parallel_config.show_model: 

551 model = self._detect_worktree_model_via_api(worktree_path) 

552 if model: 

553 self.logger.info(f" Using model: {model}") 

554 else: 

555 self.logger.warning(" Could not detect Claude CLI model") 

556 

557 def _detect_worktree_model_via_api(self, worktree_path: Path) -> str | None: 

558 """Detect the model Claude will use by making an API call. 

559 

560 Runs a minimal Claude command with JSON output and parses the modelUsage 

561 field to verify settings.local.json is being respected. 

562 

563 Args: 

564 worktree_path: Path to the worktree to test 

565 

566 Returns: 

567 Model name (e.g., "claude-sonnet-4-20250514") or None if unable to detect 

568 """ 

569 try: 

570 # Set environment to keep Claude in the project working directory (BUG-007) 

571 # This ensures the first Claude CLI invocation in the worktree has the same 

572 # project root behavior as subsequent invocations via run_claude_command() 

573 env = os.environ.copy() 

574 env["CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR"] = "1" 

575 

576 # Use a minimal prompt that requires an API call to get modelUsage 

577 result = subprocess.run( 

578 [ 

579 "claude", 

580 "-p", 

581 "reply with just 'ok'", 

582 "--output-format", 

583 "json", 

584 ], 

585 cwd=worktree_path, 

586 capture_output=True, 

587 text=True, 

588 timeout=30, 

589 env=env, 

590 ) 

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

592 data: dict[str, Any] = json.loads(result.stdout.strip()) 

593 model_usage: dict[str, Any] = data.get("modelUsage", {}) 

594 # Return the first (primary) model from modelUsage 

595 if model_usage: 

596 return cast(str, next(iter(model_usage.keys()))) 

597 except (subprocess.TimeoutExpired, FileNotFoundError, json.JSONDecodeError): 

598 pass 

599 return None 

600 

601 def _cleanup_worktree(self, worktree_path: Path) -> None: 

602 """Remove a git worktree and its associated branch. 

603 

604 Args: 

605 worktree_path: Path to the worktree to remove 

606 """ 

607 if not worktree_path.exists(): 

608 return 

609 

610 # Skip cleanup if worktree is actively in use by a running worker (BUG-142) 

611 with self._process_lock: 

612 if worktree_path in self._active_worktrees: 

613 self.logger.warning( 

614 f"Skipping cleanup of {worktree_path.name}: worktree is in active use" 

615 ) 

616 return 

617 

618 # Get branch name before removing worktree (worktree operation, no lock needed) 

619 branch_result = subprocess.run( 

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

621 cwd=worktree_path, 

622 capture_output=True, 

623 text=True, 

624 ) 

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

626 

627 # Remove worktree (main repo operation) 

628 self._git_lock.run( 

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

630 cwd=self.repo_path, 

631 timeout=30, 

632 ) 

633 

634 # If worktree removal failed, force delete directory 

635 if worktree_path.exists(): 

636 shutil.rmtree(worktree_path, ignore_errors=True) 

637 

638 # Delete the branch if it was a parallel branch (main repo operation) 

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

640 self._git_lock.run( 

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

642 cwd=self.repo_path, 

643 timeout=10, 

644 ) 

645 

646 def _run_claude_command( 

647 self, 

648 command: str, 

649 working_dir: Path, 

650 issue_id: str | None = None, 

651 ) -> subprocess.CompletedProcess[str]: 

652 """Run a Claude CLI command with real-time output streaming. 

653 

654 Args: 

655 command: The command to run (e.g., "/ll:ready-issue BUG-123") 

656 working_dir: Directory to run the command in 

657 issue_id: Optional issue ID for subprocess tracking 

658 

659 Returns: 

660 CompletedProcess with stdout and stderr 

661 """ 

662 stream_output = self.parallel_config.stream_subprocess_output 

663 

664 def stream_callback(line: str, is_stderr: bool) -> None: 

665 if stream_output: 

666 if is_stderr: 

667 print(f" {line}", file=sys.stderr) 

668 else: 

669 self.logger.info(f" {line}") 

670 

671 def on_start(process: subprocess.Popen[str]) -> None: 

672 if issue_id: 

673 with self._process_lock: 

674 self._active_processes[issue_id] = process 

675 

676 def on_end(process: subprocess.Popen[str]) -> None: 

677 if issue_id: 

678 with self._process_lock: 

679 self._active_processes.pop(issue_id, None) 

680 

681 return _run_claude_base( 

682 command=command, 

683 timeout=self.parallel_config.timeout_per_issue, 

684 working_dir=working_dir, 

685 stream_callback=stream_callback if stream_output else None, 

686 on_process_start=on_start if issue_id else None, 

687 on_process_end=on_end if issue_id else None, 

688 idle_timeout=self.parallel_config.idle_timeout_per_issue, 

689 ) 

690 

691 def _run_with_continuation( 

692 self, 

693 command: str, 

694 working_dir: Path, 

695 issue_id: str | None = None, 

696 max_continuations: int = 3, 

697 ) -> subprocess.CompletedProcess[str]: 

698 """Run a Claude command with automatic continuation on context handoff. 

699 

700 If the command signals CONTEXT_HANDOFF, reads the continuation prompt 

701 from the worktree and spawns a fresh Claude session to continue. 

702 

703 Args: 

704 command: The command to run 

705 working_dir: Directory (worktree) to run the command in 

706 issue_id: Optional issue ID for subprocess tracking 

707 max_continuations: Maximum number of continuation attempts 

708 

709 Returns: 

710 Combined CompletedProcess with all session outputs 

711 """ 

712 all_stdout: list[str] = [] 

713 all_stderr: list[str] = [] 

714 current_command = command 

715 continuation_count = 0 

716 result: subprocess.CompletedProcess[str] = subprocess.CompletedProcess( 

717 args=[], returncode=1, stdout="", stderr="" 

718 ) 

719 

720 while continuation_count <= max_continuations: 

721 result = self._run_claude_command( 

722 current_command, 

723 working_dir, 

724 issue_id=issue_id, 

725 ) 

726 

727 all_stdout.append(result.stdout) 

728 all_stderr.append(result.stderr) 

729 

730 # Check for context handoff signal 

731 if detect_context_handoff(result.stdout): 

732 self.logger.info(f"[{issue_id}] Detected CONTEXT_HANDOFF signal") 

733 

734 # Read continuation prompt from worktree 

735 prompt_content = read_continuation_prompt(working_dir) 

736 if not prompt_content: 

737 self.logger.warning( 

738 f"[{issue_id}] Context handoff signaled but no continuation prompt found" 

739 ) 

740 break 

741 

742 if continuation_count >= max_continuations: 

743 self.logger.warning( 

744 f"[{issue_id}] Reached max continuations ({max_continuations}), stopping" 

745 ) 

746 break 

747 

748 continuation_count += 1 

749 self.logger.info( 

750 f"[{issue_id}] Starting continuation session #{continuation_count}" 

751 ) 

752 

753 # Re-invoke the original command with --resume flag so the skill 

754 # lifecycle (including completion/file-move) runs in the new session. 

755 current_command = f"{command} --resume" 

756 continue 

757 

758 # No handoff signal, we're done 

759 break 

760 

761 return subprocess.CompletedProcess( 

762 args=result.args, 

763 returncode=result.returncode, 

764 stdout="\n---CONTINUATION---\n".join(all_stdout), 

765 stderr="\n---CONTINUATION---\n".join(all_stderr), 

766 ) 

767 

768 def _get_changed_files(self, worktree_path: Path) -> list[str]: 

769 """Get list of files changed in the worktree. 

770 

771 Args: 

772 worktree_path: Path to the worktree 

773 

774 Returns: 

775 List of changed file paths relative to repo root 

776 """ 

777 result = subprocess.run( 

778 ["git", "diff", "--name-only", self.parallel_config.base_branch, "HEAD"], 

779 cwd=worktree_path, 

780 capture_output=True, 

781 text=True, 

782 timeout=30, 

783 ) 

784 

785 if result.returncode != 0: 

786 return [] 

787 

788 return [f.strip() for f in result.stdout.strip().split("\n") if f.strip()] 

789 

790 def _update_branch_base(self, worktree_path: Path, issue_id: str) -> tuple[bool, str]: 

791 """Fetch origin/main and rebase worker branch onto it. 

792 

793 This ensures the worker branch is based on the latest main before 

794 merge coordination, preventing conflicts when main advances during 

795 sprint execution (BUG-180). 

796 

797 Args: 

798 worktree_path: Path to the worker's worktree 

799 issue_id: Issue ID for logging 

800 

801 Returns: 

802 Tuple of (success, error_message) 

803 """ 

804 # Fetch latest base branch from origin 

805 base = self.parallel_config.base_branch 

806 fetch_result = subprocess.run( 

807 ["git", "fetch", "origin", base], 

808 cwd=worktree_path, 

809 capture_output=True, 

810 text=True, 

811 timeout=60, 

812 ) 

813 

814 if fetch_result.returncode != 0: 

815 return False, f"Failed to fetch origin/{base}: {fetch_result.stderr}" 

816 

817 # Rebase current branch onto origin base branch 

818 rebase_result = subprocess.run( 

819 ["git", "rebase", f"origin/{base}"], 

820 cwd=worktree_path, 

821 capture_output=True, 

822 text=True, 

823 timeout=120, 

824 ) 

825 

826 if rebase_result.returncode != 0: 

827 # Abort the failed rebase 

828 subprocess.run( 

829 ["git", "rebase", "--abort"], 

830 cwd=worktree_path, 

831 capture_output=True, 

832 timeout=10, 

833 ) 

834 return False, f"Failed to rebase onto origin/{base}: {rebase_result.stderr}" 

835 

836 self.logger.info(f"[{issue_id}] Rebased branch onto origin/{base}") 

837 return True, "" 

838 

839 def _verify_work_was_done( 

840 self, changed_files: list[str], issue_id: str, issue_filename: str = "" 

841 ) -> tuple[bool, str]: 

842 """Verify that actual implementation work was done. 

843 

844 Uses the shared verify_work_was_done() function to check that changed 

845 files include meaningful work, not just issue files or other artifacts. 

846 

847 Args: 

848 changed_files: List of files changed during processing 

849 issue_id: The issue ID being processed (unused, kept for compatibility) 

850 issue_filename: Full issue filename (unused, kept for compatibility) 

851 

852 Returns: 

853 Tuple of (success, error_message) 

854 """ 

855 if not changed_files: 

856 return False, "No files were changed during implementation" 

857 

858 # Check if code changes are required 

859 if not self.parallel_config.require_code_changes: 

860 return True, "" 

861 

862 # Use shared verification function 

863 if verify_work_was_done(self.logger, changed_files): 

864 return True, "" 

865 

866 # Generate descriptive error with actual excluded files 

867 excluded_files = [ 

868 f 

869 for f in changed_files 

870 if f and any(f.startswith(excl) for excl in EXCLUDED_DIRECTORIES) 

871 ] 

872 if excluded_files: 

873 files_preview = ", ".join(excluded_files[:5]) 

874 if len(excluded_files) > 5: 

875 files_preview += f" (+{len(excluded_files) - 5} more)" 

876 return False, f"Only excluded files modified: {files_preview}" 

877 return False, "Only excluded files modified (e.g., .issues/, thoughts/)" 

878 

879 def _has_other_issue_id(self, file_lower: str, current_issue_id_lower: str) -> bool: 

880 """Check if file contains a different issue ID than the current worker's. 

881 

882 This prevents cross-worker contamination where worker A detects worker B's 

883 leaked file. When multiple workers run in parallel, their leaked files may 

884 both appear in the main repo. Each worker should only clean up its own leaks. 

885 

886 Args: 

887 file_lower: Lowercase file path to check 

888 current_issue_id_lower: Lowercase issue ID of the current worker 

889 

890 Returns: 

891 True if the file contains a different issue ID (belongs to another worker), 

892 False if the file contains the current issue ID or no recognizable issue ID 

893 """ 

894 # Pattern matches common issue ID formats: BUG-123, ENH-456, FEAT-789 

895 # Use non-capturing group (?:...) so findall returns full match, not group 

896 matches = re.findall(r"(?:bug|enh|feat)-\d+", file_lower) 

897 

898 if not matches: 

899 # No issue ID found - file doesn't belong to any specific worker 

900 return False 

901 

902 # Check if any of the found issue IDs match the current worker 

903 for match in matches: 

904 if match == current_issue_id_lower: 

905 return False # File belongs to current worker 

906 

907 # File has issue ID(s) but none match current worker - belongs to another worker 

908 return True 

909 

910 def _detect_main_repo_leaks(self, issue_id: str, baseline_status: set[str]) -> list[str]: 

911 """Detect files incorrectly written to main repo instead of worktree. 

912 

913 Claude Code may write files to the main repository instead of the 

914 worktree due to project root detection issues (see GitHub #8771). 

915 This method detects such leaks by comparing main repo status before 

916 and after worker execution. 

917 

918 Args: 

919 issue_id: ID of the issue being processed (for pattern matching) 

920 baseline_status: Set of file paths from git status before worker started 

921 

922 Returns: 

923 List of file paths that were leaked to main repo 

924 """ 

925 # Get current status of main repo 

926 result = self._git_lock.run( 

927 ["status", "--porcelain"], 

928 cwd=self.repo_path, 

929 timeout=30, 

930 ) 

931 

932 if result.returncode != 0: 

933 return [] 

934 

935 current_files: set[str] = set() 

936 for line in result.stdout.strip().split("\n"): 

937 if not line or len(line) < 3: 

938 continue 

939 # Extract file path (after status codes and space) 

940 file_path = line[3:].strip() 

941 # Handle renamed files (old -> new) 

942 if " -> " in file_path: 

943 file_path = file_path.split(" -> ")[-1] 

944 current_files.add(file_path) 

945 

946 # Find new files that appeared during worker execution 

947 new_files = current_files - baseline_status 

948 

949 # Filter to files likely related to this issue 

950 issue_id_lower = issue_id.lower() 

951 leaked_files: list[str] = [] 

952 

953 for file_path in new_files: 

954 # Skip state file (managed by orchestrator) 

955 if file_path.endswith(".parallel-manage-state.json"): 

956 continue 

957 # Skip .gitignore (may be modified by ll-parallel) 

958 if file_path == ".gitignore": 

959 continue 

960 

961 # Check if file is related to this issue 

962 file_lower = file_path.lower() 

963 if issue_id_lower in file_lower: 

964 leaked_files.append(file_path) 

965 # Also catch source files that shouldn't be modified in main 

966 elif file_path.startswith(("backend/", "src/", "lib/", "tests/")): 

967 leaked_files.append(file_path) 

968 # Catch thoughts/plans files 

969 elif file_path.startswith("thoughts/"): 

970 leaked_files.append(file_path) 

971 # Catch issue files in any issue directory variant 

972 # Handles both .issues/ (with dot) and issues/ (without dot) 

973 # Only include files without a different issue ID - files WITH other issue IDs 

974 # belong to other workers running in parallel (cross-worker contamination) 

975 elif file_path.startswith((".issues/", "issues/")): 

976 if not self._has_other_issue_id(file_lower, issue_id_lower): 

977 leaked_files.append(file_path) 

978 

979 return leaked_files 

980 

981 def _cleanup_leaked_files(self, leaked_files: list[str]) -> int: 

982 """Discard leaked files from main repo working directory. 

983 

984 Claude Code sometimes writes files to the main repo instead of the 

985 worktree. These files cause stash conflicts during merge operations. 

986 Since the actual work is preserved in the worktree branch, we can 

987 safely discard these leaked changes from the main repo. 

988 

989 Args: 

990 leaked_files: List of file paths leaked to main repo 

991 

992 Returns: 

993 Number of files successfully cleaned up 

994 """ 

995 if not leaked_files: 

996 return 0 

997 

998 cleaned = 0 

999 

1000 # Get status to determine which files are tracked vs untracked 

1001 status_result = self._git_lock.run( 

1002 ["status", "--porcelain", "--"] + leaked_files, 

1003 cwd=self.repo_path, 

1004 timeout=30, 

1005 ) 

1006 

1007 tracked_files: list[str] = [] 

1008 untracked_files: list[str] = [] 

1009 

1010 for line in status_result.stdout.splitlines(): 

1011 if not line or len(line) < 3: 

1012 continue 

1013 status_code = line[:2] 

1014 file_path = line[3:].split(" -> ")[-1].strip() 

1015 

1016 if status_code.startswith("?"): 

1017 # Untracked file - need to delete 

1018 untracked_files.append(file_path) 

1019 else: 

1020 # Tracked file - can use git checkout to discard 

1021 tracked_files.append(file_path) 

1022 

1023 # Discard changes to tracked files 

1024 if tracked_files: 

1025 checkout_result = self._git_lock.run( 

1026 ["checkout", "--"] + tracked_files, 

1027 cwd=self.repo_path, 

1028 timeout=30, 

1029 ) 

1030 if checkout_result.returncode == 0: 

1031 cleaned += len(tracked_files) 

1032 else: 

1033 self.logger.warning( 

1034 f"Failed to discard tracked leaked files: {checkout_result.stderr}" 

1035 ) 

1036 

1037 # Delete untracked files 

1038 for file_path in untracked_files: 

1039 full_path = self.repo_path / file_path 

1040 try: 

1041 if full_path.exists(): 

1042 full_path.unlink() 

1043 cleaned += 1 

1044 except OSError as e: 

1045 self.logger.warning(f"Failed to delete leaked file {file_path}: {e}") 

1046 

1047 # Fallback: directly delete files not reported by git status 

1048 # This handles gitignored files that git status --porcelain doesn't show 

1049 accounted_files = set(tracked_files + untracked_files) 

1050 for file_path in leaked_files: 

1051 if file_path not in accounted_files: 

1052 full_path = self.repo_path / file_path 

1053 if full_path.exists(): 

1054 try: 

1055 full_path.unlink() 

1056 cleaned += 1 

1057 self.logger.info(f"Deleted gitignored leaked file: {file_path}") 

1058 except OSError as e: 

1059 self.logger.warning( 

1060 f"Failed to delete gitignored leaked file {file_path}: {e}" 

1061 ) 

1062 else: 

1063 self.logger.debug(f"Leaked file not found (may have been moved): {file_path}") 

1064 

1065 if cleaned > 0: 

1066 self.logger.info(f"Cleaned up {cleaned} leaked file(s) from main repo") 

1067 

1068 return cleaned 

1069 

1070 def _get_main_repo_baseline(self) -> set[str]: 

1071 """Get baseline of modified/untracked files in main repo. 

1072 

1073 Returns: 

1074 Set of file paths currently showing in git status 

1075 """ 

1076 result = self._git_lock.run( 

1077 ["status", "--porcelain"], 

1078 cwd=self.repo_path, 

1079 timeout=30, 

1080 ) 

1081 

1082 if result.returncode != 0: 

1083 return set() 

1084 

1085 files: set[str] = set() 

1086 for line in result.stdout.strip().split("\n"): 

1087 if not line or len(line) < 3: 

1088 continue 

1089 file_path = line[3:].strip() 

1090 if " -> " in file_path: 

1091 file_path = file_path.split(" -> ")[-1] 

1092 files.add(file_path) 

1093 

1094 return files 

1095 

1096 @property 

1097 def active_count(self) -> int: 

1098 """Number of currently active workers. 

1099 

1100 Includes both workers with running futures AND workers whose futures 

1101 are done but callbacks haven't completed yet. 

1102 """ 

1103 running_futures = sum(1 for f in self._active_workers.values() if not f.done()) 

1104 with self._callback_lock: 

1105 pending_callback_count = len(self._pending_callbacks) 

1106 return running_futures + pending_callback_count 

1107 

1108 def set_worker_stage(self, issue_id: str, stage: WorkerStage) -> None: 

1109 """Update the stage of a worker. 

1110 

1111 Args: 

1112 issue_id: Issue ID being processed 

1113 stage: New stage value 

1114 """ 

1115 with self._process_lock: 

1116 self._worker_stages[issue_id] = stage 

1117 

1118 def get_worker_stage(self, issue_id: str) -> WorkerStage | None: 

1119 """Get the current stage of a worker. 

1120 

1121 Args: 

1122 issue_id: Issue ID being processed 

1123 

1124 Returns: 

1125 Current stage, or None if issue not being tracked 

1126 """ 

1127 with self._process_lock: 

1128 return self._worker_stages.get(issue_id) 

1129 

1130 def get_active_stages(self) -> dict[str, WorkerStage]: 

1131 """Get all active worker stages. 

1132 

1133 Returns: 

1134 Dictionary mapping issue_id to current stage for active workers 

1135 """ 

1136 with self._process_lock: 

1137 # Only return workers that are actually active 

1138 active_ids = set(self._active_workers.keys()) 

1139 return { 

1140 issue_id: stage 

1141 for issue_id, stage in self._worker_stages.items() 

1142 if issue_id in active_ids 

1143 } 

1144 

1145 def remove_worker_stage(self, issue_id: str) -> None: 

1146 """Remove a worker from stage tracking. 

1147 

1148 Args: 

1149 issue_id: Issue ID to remove 

1150 """ 

1151 with self._process_lock: 

1152 self._worker_stages.pop(issue_id, None) 

1153 

1154 def cleanup_all_worktrees(self) -> None: 

1155 """Clean up all worker worktrees.""" 

1156 worktree_base = self.repo_path / self.parallel_config.worktree_base 

1157 if not worktree_base.exists(): 

1158 return 

1159 

1160 for worktree_dir in worktree_base.iterdir(): 

1161 if worktree_dir.is_dir() and worktree_dir.name.startswith("worker-"): 

1162 self._cleanup_worktree(worktree_dir) 

1163 

1164 self.logger.info("Cleaned up all worker worktrees")