Coverage for little_loops / parallel / worker_pool.py: 11%
477 statements
« prev ^ index » next coverage.py v7.12.0, created at 2026-04-02 13:03 -0500
« prev ^ index » next coverage.py v7.12.0, created at 2026-04-02 13:03 -0500
1"""Worker pool for parallel issue processing with git worktree isolation.
3Each worker operates in an isolated git worktree, allowing concurrent issue
4processing without file conflicts.
5"""
7from __future__ import annotations
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
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
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
41class WorkerPool:
42 """Thread pool for processing issues in isolated git worktrees.
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
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 """
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.
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] = {}
96 def start(self) -> None:
97 """Start the worker pool."""
98 if self._executor is not None:
99 return
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)
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")
111 def shutdown(self, wait: bool = True) -> None:
112 """Shutdown the worker pool.
114 Args:
115 wait: Whether to wait for pending tasks to complete
116 """
117 if self._executor is None:
118 return
120 self.logger.info("Shutting down worker pool...")
122 # First, terminate all active subprocesses to unblock worker threads
123 if not wait:
124 self.terminate_all_processes()
126 self._executor.shutdown(wait=wait)
127 self._executor = None
129 def set_shutdown_requested(self, value: bool = True) -> None:
130 """Set the shutdown flag.
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
137 def terminate_all_processes(self) -> None:
138 """Forcefully terminate all active subprocesses.
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()
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.
173 Args:
174 issue: Issue to process
175 on_complete: Optional callback when processing completes
177 Returns:
178 Future that will contain the WorkerResult
179 """
180 if self._executor is None:
181 raise RuntimeError("Worker pool not started")
183 future = self._executor.submit(self._process_issue, issue)
184 with self._process_lock:
185 self._active_workers[issue.issue_id] = future
187 if on_complete:
188 future.add_done_callback(
189 lambda f: self._handle_completion(f, on_complete, issue.issue_id)
190 )
192 return future
194 def _handle_completion(
195 self,
196 future: Future[WorkerResult],
197 callback: Callable[[WorkerResult], None],
198 issue_id: str,
199 ) -> None:
200 """Handle worker completion and invoke callback."""
201 with self._callback_lock:
202 self._pending_callbacks.add(issue_id)
203 try:
204 try:
205 result = future.result()
206 except Exception as e:
207 self.logger.error(f"Worker future failed for {issue_id}: {e}")
208 result = WorkerResult(
209 issue_id=issue_id,
210 success=False,
211 branch_name="",
212 worktree_path=Path(),
213 error=f"Worker future failed: {e}",
214 )
215 # Set final stage based on result (ENH-262)
216 if result.success:
217 self.set_worker_stage(issue_id, WorkerStage.COMPLETED)
218 elif result.interrupted:
219 self.set_worker_stage(issue_id, WorkerStage.INTERRUPTED)
220 else:
221 self.set_worker_stage(issue_id, WorkerStage.FAILED)
222 try:
223 callback(result)
224 except Exception as e:
225 self.logger.error(f"Worker completion callback failed for {issue_id}: {e}")
226 finally:
227 with self._callback_lock:
228 self._pending_callbacks.discard(issue_id)
230 def _process_issue(self, issue: IssueInfo) -> WorkerResult:
231 """Process a single issue in an isolated worktree.
233 Args:
234 issue: Issue to process
236 Returns:
237 WorkerResult with processing outcome
238 """
239 start_time = time.time()
240 timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
241 if self.parallel_config.use_feature_branches:
242 from little_loops.issue_parser import slugify
244 branch_name = f"feature/{issue.issue_id.lower()}-{slugify(issue.title)}"
245 else:
246 branch_name = f"parallel/{issue.issue_id.lower()}-{timestamp}"
247 worktree_path = (
248 self.repo_path
249 / self.parallel_config.worktree_base
250 / f"worker-{issue.issue_id.lower()}-{timestamp}"
251 )
253 # Set initial stage for progress tracking (ENH-262)
254 self.set_worker_stage(issue.issue_id, WorkerStage.SETUP)
256 # Capture baseline of main repo status before worker starts
257 # Used to detect files incorrectly written to main repo
258 baseline_status = self._get_main_repo_baseline()
259 # Capture main HEAD SHA before worker starts to detect committed leaks
260 baseline_head_sha = self._get_main_head_sha()
262 try:
263 # Step 1: Create worktree with new branch
264 self._setup_worktree(worktree_path, branch_name)
266 # Register worktree as active to prevent cleanup while in use (BUG-142)
267 with self._process_lock:
268 self._active_worktrees.add(worktree_path)
270 # Update stage for progress tracking (ENH-262)
271 self.set_worker_stage(issue.issue_id, WorkerStage.VALIDATING)
273 # Step 2: Run ready-issue validation
274 ready_cmd = self.parallel_config.get_ready_command(issue.issue_id)
275 ready_result = self._run_claude_command(
276 ready_cmd,
277 worktree_path,
278 issue_id=issue.issue_id,
279 )
281 # Check if worker was terminated during shutdown (ENH-036)
282 if issue.issue_id in self._terminated_during_shutdown:
283 self.set_worker_stage(issue.issue_id, WorkerStage.INTERRUPTED)
284 return WorkerResult(
285 issue_id=issue.issue_id,
286 success=False,
287 interrupted=True,
288 branch_name=branch_name,
289 worktree_path=worktree_path,
290 duration=time.time() - start_time,
291 error="Interrupted during shutdown",
292 stdout=ready_result.stdout,
293 stderr=ready_result.stderr,
294 )
296 if ready_result.returncode != 0:
297 return WorkerResult(
298 issue_id=issue.issue_id,
299 success=False,
300 branch_name=branch_name,
301 worktree_path=worktree_path,
302 duration=time.time() - start_time,
303 error=f"ready-issue failed: {ready_result.stderr}",
304 stdout=ready_result.stdout,
305 stderr=ready_result.stderr,
306 )
308 # Step 3: Parse ready-issue output and check verdict
309 ready_parsed = parse_ready_issue_output(ready_result.stdout)
311 # Handle CLOSE verdict - issue should not be implemented
312 if ready_parsed.get("should_close"):
313 return WorkerResult(
314 issue_id=issue.issue_id,
315 success=True, # Closure is a valid outcome
316 branch_name=branch_name,
317 worktree_path=worktree_path,
318 duration=time.time() - start_time,
319 should_close=True,
320 close_reason=ready_parsed.get("close_reason"),
321 close_status=ready_parsed.get("close_status"),
322 stdout=ready_result.stdout,
323 stderr=ready_result.stderr,
324 )
326 # Handle BLOCKED verdict - issue has open dependencies
327 if ready_parsed.get("is_blocked"):
328 return WorkerResult(
329 issue_id=issue.issue_id,
330 success=False,
331 was_blocked=True,
332 branch_name=branch_name,
333 worktree_path=worktree_path,
334 duration=time.time() - start_time,
335 error="ready-issue verdict: BLOCKED - open dependency detected",
336 stdout=ready_result.stdout,
337 stderr=ready_result.stderr,
338 )
340 # Handle NOT_READY verdict
341 if not ready_parsed["is_ready"]:
342 concerns = ready_parsed.get("concerns", [])
343 if concerns:
344 concern_msg = "; ".join(concerns)
345 elif ready_parsed["verdict"] == "UNKNOWN":
346 # For UNKNOWN verdicts, show a snippet of output for debugging
347 raw_out = (ready_result.stdout or "")[:200].strip()
348 concern_msg = (
349 f"Could not parse verdict. Output: {raw_out}..."
350 if raw_out
351 else "No output from ready-issue"
352 )
353 else:
354 concern_msg = "Issue not ready"
355 return WorkerResult(
356 issue_id=issue.issue_id,
357 success=False,
358 branch_name=branch_name,
359 worktree_path=worktree_path,
360 duration=time.time() - start_time,
361 error=f"ready-issue verdict: {ready_parsed['verdict']} - {concern_msg}",
362 stdout=ready_result.stdout,
363 stderr=ready_result.stderr,
364 )
366 # Track if issue was corrected (corrections stay in worktree)
367 was_corrected = ready_parsed.get("was_corrected", False)
368 corrections = ready_parsed.get("corrections", [])
370 # Update stage for progress tracking (ENH-262)
371 self.set_worker_stage(issue.issue_id, WorkerStage.IMPLEMENTING)
373 # Step 4: Get action from BRConfig
374 action = self.br_config.get_category_action(issue.issue_type)
376 # Step 5: Run manage-issue implementation (with continuation support)
377 manage_cmd = self.parallel_config.get_manage_command(
378 issue.issue_type, action, issue.issue_id
379 )
380 manage_result = self._run_with_continuation(
381 manage_cmd,
382 worktree_path,
383 issue_id=issue.issue_id,
384 )
386 # Update stage for progress tracking (ENH-262)
387 self.set_worker_stage(issue.issue_id, WorkerStage.VERIFYING)
389 # Check if worker was terminated during shutdown (ENH-036)
390 if issue.issue_id in self._terminated_during_shutdown:
391 self.set_worker_stage(issue.issue_id, WorkerStage.INTERRUPTED)
392 return WorkerResult(
393 issue_id=issue.issue_id,
394 success=False,
395 interrupted=True,
396 branch_name=branch_name,
397 worktree_path=worktree_path,
398 duration=time.time() - start_time,
399 error="Interrupted during shutdown",
400 stdout=manage_result.stdout,
401 stderr=manage_result.stderr,
402 )
404 # Step 6: Get list of changed files in worktree
405 changed_files = self._get_changed_files(worktree_path)
407 # Step 8: Detect files leaked to main repo instead of worktree (unstaged)
408 leaked_files = self._detect_main_repo_leaks(issue.issue_id, baseline_status)
409 if leaked_files:
410 self.logger.warning(
411 f"{issue.issue_id} leaked {len(leaked_files)} file(s) to main repo: "
412 f"{leaked_files}"
413 )
414 # Clean up leaked files to prevent stash conflicts during merge.
415 # The actual work is preserved in the worktree branch.
416 self._cleanup_leaked_files(leaked_files)
418 # Step 8b: Detect commits made directly to main instead of worktree branch.
419 # If Claude committed to main (not the worktree), worktree will have no diff,
420 # causing work verification to fail. Attempt to recover by cherry-picking
421 # the leaked commits to the worktree and resetting main. (BUG-580)
422 committed_leaks = self._detect_committed_leaks(baseline_head_sha)
423 if committed_leaks:
424 self.logger.warning(
425 f"{issue.issue_id} committed {len(committed_leaks)} commit(s) directly "
426 f"to main instead of worktree: {[sha[:8] for sha in committed_leaks]}"
427 )
428 if not changed_files:
429 recovered = self._recover_committed_leaks(
430 committed_leaks, worktree_path, baseline_head_sha, issue.issue_id
431 )
432 if recovered:
433 changed_files = self._get_changed_files(worktree_path)
435 # Step 7: Verify actual work was done (after potential committed-leak recovery)
436 # Pass full filename for better doc-only keyword matching
437 issue_filename = issue.path.stem if issue.path else ""
438 work_verified, verification_error = self._verify_work_was_done(
439 changed_files, issue.issue_id, issue_filename
440 )
442 if manage_result.returncode != 0:
443 return WorkerResult(
444 issue_id=issue.issue_id,
445 success=False,
446 branch_name=branch_name,
447 worktree_path=worktree_path,
448 changed_files=changed_files,
449 leaked_files=leaked_files,
450 duration=time.time() - start_time,
451 error=f"manage-issue failed: {manage_result.stderr}",
452 stdout=manage_result.stdout,
453 stderr=manage_result.stderr,
454 )
456 if not work_verified:
457 return WorkerResult(
458 issue_id=issue.issue_id,
459 success=False,
460 branch_name=branch_name,
461 worktree_path=worktree_path,
462 changed_files=changed_files,
463 leaked_files=leaked_files,
464 duration=time.time() - start_time,
465 error=verification_error,
466 stdout=manage_result.stdout,
467 stderr=manage_result.stderr,
468 )
470 # Step 9: Update branch base before merge (BUG-180)
471 # Fetch origin/main and rebase to ensure branch is based on latest main
472 base_updated, base_error = self._update_branch_base(worktree_path, issue.issue_id)
474 # Update stage for progress tracking (ENH-262)
475 self.set_worker_stage(issue.issue_id, WorkerStage.MERGING)
477 if not base_updated:
478 return WorkerResult(
479 issue_id=issue.issue_id,
480 success=False,
481 branch_name=branch_name,
482 worktree_path=worktree_path,
483 changed_files=changed_files,
484 leaked_files=leaked_files,
485 duration=time.time() - start_time,
486 error=base_error,
487 stdout=manage_result.stdout,
488 stderr=manage_result.stderr,
489 )
491 return WorkerResult(
492 issue_id=issue.issue_id,
493 success=True,
494 branch_name=branch_name,
495 worktree_path=worktree_path,
496 changed_files=changed_files,
497 leaked_files=leaked_files,
498 duration=time.time() - start_time,
499 error=None,
500 stdout=manage_result.stdout,
501 stderr=manage_result.stderr,
502 was_corrected=was_corrected,
503 corrections=corrections,
504 )
506 except Exception as e:
507 return WorkerResult(
508 issue_id=issue.issue_id,
509 success=False,
510 branch_name=branch_name,
511 worktree_path=worktree_path,
512 duration=time.time() - start_time,
513 error=str(e),
514 )
515 finally:
516 # Unregister worktree as no longer active (BUG-142)
517 with self._process_lock:
518 self._active_worktrees.discard(worktree_path)
520 def _setup_worktree(self, worktree_path: Path, branch_name: str) -> None:
521 """Create a git worktree with a new branch.
523 Args:
524 worktree_path: Path for the new worktree
525 branch_name: Name of the new branch
526 """
527 # Remove existing worktree if present
528 if worktree_path.exists():
529 self._cleanup_worktree(worktree_path)
531 # Create new worktree with branch
532 result = self._git_lock.run(
533 ["worktree", "add", "-b", branch_name, str(worktree_path)],
534 cwd=self.repo_path,
535 timeout=60,
536 )
538 if result.returncode != 0:
539 raise RuntimeError(f"Failed to create worktree: {result.stderr}")
541 # Copy git identity from main repo
542 for config_key in ["user.email", "user.name"]:
543 value_result = self._git_lock.run(
544 ["config", config_key],
545 cwd=self.repo_path,
546 )
547 if value_result.returncode == 0 and value_result.stdout.strip():
548 # Worktree config operations don't need the main repo lock
549 subprocess.run(
550 ["git", "config", config_key, value_result.stdout.strip()],
551 cwd=worktree_path,
552 capture_output=True,
553 )
555 # Copy .claude/ directory to establish project root for Claude Code (BUG-007)
556 # Claude Code uses .claude/ directory as highest priority for project root detection.
557 # Without this, Claude may detect the main repo as project root in worktrees,
558 # causing file writes to leak to the main repository.
559 claude_dir = self.repo_path / ".claude"
560 if claude_dir.exists() and claude_dir.is_dir():
561 dest_claude_dir = worktree_path / ".claude"
562 if dest_claude_dir.exists():
563 shutil.rmtree(dest_claude_dir)
564 shutil.copytree(claude_dir, dest_claude_dir)
565 self.logger.info("Copied .claude/ directory to worktree")
567 # Copy additional configured files from main repo to worktree
568 for file_path in self.parallel_config.worktree_copy_files:
569 if file_path.startswith(".claude/"):
570 continue # Already copied with full .claude/ directory above
571 src = self.repo_path / file_path
572 if src.exists():
573 if src.is_dir():
574 self.logger.warning(
575 f"Skipping '{file_path}' in worktree_copy_files: "
576 "is a directory (use symlinks or copytree for directories)"
577 )
578 continue
579 dest = worktree_path / file_path
580 dest.parent.mkdir(parents=True, exist_ok=True)
581 shutil.copy2(src, dest)
582 self.logger.info(f"Copied {file_path} to worktree")
583 else:
584 self.logger.debug(f"Skipped {file_path} (not found in main repo)")
586 self.logger.info(f"Created worktree at {worktree_path} on branch {branch_name}")
588 # Write session marker so concurrent orchestrators can identify this process's
589 # worktrees and skip them during orphan cleanup (BUG-579)
590 if worktree_path.exists():
591 marker_path = worktree_path / f".ll-session-{os.getpid()}"
592 marker_path.write_text(str(os.getpid()))
594 # Verify model if --show-model flag is set (requires API call)
595 if self.parallel_config.show_model:
596 model = self._detect_worktree_model_via_api(worktree_path)
597 if model:
598 self.logger.info(f" Using model: {model}")
599 else:
600 self.logger.warning(" Could not detect Claude CLI model")
602 def _detect_worktree_model_via_api(self, worktree_path: Path) -> str | None:
603 """Detect the model Claude will use by making an API call.
605 Runs a minimal Claude command with JSON output and parses the modelUsage
606 field to verify settings.local.json is being respected.
608 Args:
609 worktree_path: Path to the worktree to test
611 Returns:
612 Model name (e.g., "claude-sonnet-4-20250514") or None if unable to detect
613 """
614 try:
615 # Set environment to keep Claude in the project working directory (BUG-007)
616 # This ensures the first Claude CLI invocation in the worktree has the same
617 # project root behavior as subsequent invocations via run_claude_command()
618 env = os.environ.copy()
619 env["CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR"] = "1"
621 # Use a minimal prompt that requires an API call to get modelUsage
622 result = subprocess.run(
623 [
624 "claude",
625 "-p",
626 "reply with just 'ok'",
627 "--output-format",
628 "json",
629 ],
630 cwd=worktree_path,
631 capture_output=True,
632 text=True,
633 timeout=30,
634 env=env,
635 )
636 if result.returncode == 0 and result.stdout.strip():
637 data: dict[str, Any] = json.loads(result.stdout.strip())
638 model_usage: dict[str, Any] = data.get("modelUsage", {})
639 # Return the first (primary) model from modelUsage
640 if model_usage:
641 return cast(str, next(iter(model_usage.keys())))
642 except (subprocess.TimeoutExpired, FileNotFoundError, json.JSONDecodeError):
643 pass
644 return None
646 def _cleanup_worktree(self, worktree_path: Path) -> None:
647 """Remove a git worktree and its associated branch.
649 Args:
650 worktree_path: Path to the worktree to remove
651 """
652 if not worktree_path.exists():
653 return
655 # Skip cleanup if worktree is actively in use by a running worker (BUG-142)
656 with self._process_lock:
657 if worktree_path in self._active_worktrees:
658 self.logger.warning(
659 f"Skipping cleanup of {worktree_path.name}: worktree is in active use"
660 )
661 return
663 # Get branch name before removing worktree (worktree operation, no lock needed)
664 branch_result = subprocess.run(
665 ["git", "rev-parse", "--abbrev-ref", "HEAD"],
666 cwd=worktree_path,
667 capture_output=True,
668 text=True,
669 )
670 branch_name = branch_result.stdout.strip() if branch_result.returncode == 0 else None
672 # Remove worktree (main repo operation)
673 self._git_lock.run(
674 ["worktree", "remove", "--force", str(worktree_path)],
675 cwd=self.repo_path,
676 timeout=30,
677 )
679 # If worktree removal failed, force delete directory
680 if worktree_path.exists():
681 shutil.rmtree(worktree_path, ignore_errors=True)
683 # Delete the branch if it was a parallel branch (main repo operation)
684 if branch_name and branch_name.startswith("parallel/"):
685 self._git_lock.run(
686 ["branch", "-D", branch_name],
687 cwd=self.repo_path,
688 timeout=10,
689 )
691 def _run_claude_command(
692 self,
693 command: str,
694 working_dir: Path,
695 issue_id: str | None = None,
696 ) -> subprocess.CompletedProcess[str]:
697 """Run a Claude CLI command with real-time output streaming.
699 Args:
700 command: The command to run (e.g., "/ll:ready-issue BUG-123")
701 working_dir: Directory to run the command in
702 issue_id: Optional issue ID for subprocess tracking
704 Returns:
705 CompletedProcess with stdout and stderr
706 """
707 stream_output = self.parallel_config.stream_subprocess_output
709 def stream_callback(line: str, is_stderr: bool) -> None:
710 if stream_output:
711 if is_stderr:
712 print(f" {line}", file=sys.stderr)
713 else:
714 self.logger.info(f" {line}")
716 def on_start(process: subprocess.Popen[str]) -> None:
717 if issue_id:
718 with self._process_lock:
719 self._active_processes[issue_id] = process
721 def on_end(process: subprocess.Popen[str]) -> None:
722 if issue_id:
723 with self._process_lock:
724 self._active_processes.pop(issue_id, None)
726 return _run_claude_base(
727 command=command,
728 timeout=self.parallel_config.timeout_per_issue,
729 working_dir=working_dir,
730 stream_callback=stream_callback if stream_output else None,
731 on_process_start=on_start if issue_id else None,
732 on_process_end=on_end if issue_id else None,
733 idle_timeout=self.parallel_config.idle_timeout_per_issue,
734 )
736 def _run_with_continuation(
737 self,
738 command: str,
739 working_dir: Path,
740 issue_id: str | None = None,
741 max_continuations: int = 3,
742 ) -> subprocess.CompletedProcess[str]:
743 """Run a Claude command with automatic continuation on context handoff.
745 If the command signals CONTEXT_HANDOFF, reads the continuation prompt
746 from the worktree and spawns a fresh Claude session to continue.
748 Args:
749 command: The command to run
750 working_dir: Directory (worktree) to run the command in
751 issue_id: Optional issue ID for subprocess tracking
752 max_continuations: Maximum number of continuation attempts
754 Returns:
755 Combined CompletedProcess with all session outputs
756 """
757 all_stdout: list[str] = []
758 all_stderr: list[str] = []
759 current_command = command
760 continuation_count = 0
761 result: subprocess.CompletedProcess[str] = subprocess.CompletedProcess(
762 args=[], returncode=1, stdout="", stderr=""
763 )
765 while continuation_count <= max_continuations:
766 result = self._run_claude_command(
767 current_command,
768 working_dir,
769 issue_id=issue_id,
770 )
772 all_stdout.append(result.stdout)
773 all_stderr.append(result.stderr)
775 # Check for context handoff signal
776 if detect_context_handoff(result.stdout):
777 self.logger.info(f"[{issue_id}] Detected CONTEXT_HANDOFF signal")
779 # Read continuation prompt from worktree
780 prompt_content = read_continuation_prompt(working_dir)
781 if not prompt_content:
782 self.logger.warning(
783 f"[{issue_id}] Context handoff signaled but no continuation prompt found"
784 )
785 all_stderr.append("Handoff detected but no continuation prompt found")
786 result = subprocess.CompletedProcess(
787 args=result.args, returncode=1, stdout=result.stdout, stderr=result.stderr
788 )
789 break
791 if continuation_count >= max_continuations:
792 self.logger.warning(
793 f"[{issue_id}] Reached max continuations ({max_continuations}), stopping"
794 )
795 break
797 continuation_count += 1
798 self.logger.info(
799 f"[{issue_id}] Starting continuation session #{continuation_count}"
800 )
802 # Re-invoke the original command with --resume flag so the skill
803 # lifecycle (including completion/file-move) runs in the new session.
804 current_command = f"{command} --resume"
805 continue
807 # No handoff signal, we're done
808 break
810 return subprocess.CompletedProcess(
811 args=result.args,
812 returncode=result.returncode,
813 stdout="\n---CONTINUATION---\n".join(all_stdout),
814 stderr="\n---CONTINUATION---\n".join(all_stderr),
815 )
817 def _get_changed_files(self, worktree_path: Path) -> list[str]:
818 """Get list of files changed in the worktree.
820 Args:
821 worktree_path: Path to the worktree
823 Returns:
824 List of changed file paths relative to repo root
825 """
826 result = subprocess.run(
827 ["git", "diff", "--name-only", self.parallel_config.base_branch, "HEAD"],
828 cwd=worktree_path,
829 capture_output=True,
830 text=True,
831 timeout=30,
832 )
834 if result.returncode != 0:
835 return []
837 return [f.strip() for f in result.stdout.strip().split("\n") if f.strip()]
839 def _update_branch_base(self, worktree_path: Path, issue_id: str) -> tuple[bool, str]:
840 """Fetch origin/main and rebase worker branch onto it.
842 This ensures the worker branch is based on the latest main before
843 merge coordination, preventing conflicts when main advances during
844 sprint execution (BUG-180).
846 Args:
847 worktree_path: Path to the worker's worktree
848 issue_id: Issue ID for logging
850 Returns:
851 Tuple of (success, error_message)
852 """
853 # Fetch latest base branch from configured remote (fall back to local if fetch fails)
854 base = self.parallel_config.base_branch
855 remote = self.parallel_config.remote_name
856 fetch_result = subprocess.run(
857 ["git", "fetch", remote, base],
858 cwd=worktree_path,
859 capture_output=True,
860 text=True,
861 timeout=60,
862 )
864 rebase_target = f"{remote}/{base}" if fetch_result.returncode == 0 else base
866 # Rebase current branch onto base (remote or local fallback)
867 rebase_result = subprocess.run(
868 ["git", "rebase", rebase_target],
869 cwd=worktree_path,
870 capture_output=True,
871 text=True,
872 timeout=120,
873 )
875 if rebase_result.returncode != 0:
876 # Abort the failed rebase
877 subprocess.run(
878 ["git", "rebase", "--abort"],
879 cwd=worktree_path,
880 capture_output=True,
881 timeout=10,
882 )
883 return False, f"Failed to rebase onto {rebase_target}: {rebase_result.stderr}"
885 self.logger.info(f"[{issue_id}] Rebased branch onto {rebase_target}")
886 return True, ""
888 def _verify_work_was_done(
889 self, changed_files: list[str], issue_id: str, issue_filename: str = ""
890 ) -> tuple[bool, str]:
891 """Verify that actual implementation work was done.
893 Uses the shared verify_work_was_done() function to check that changed
894 files include meaningful work, not just issue files or other artifacts.
896 Args:
897 changed_files: List of files changed during processing
898 issue_id: The issue ID being processed (unused, kept for compatibility)
899 issue_filename: Full issue filename (unused, kept for compatibility)
901 Returns:
902 Tuple of (success, error_message)
903 """
904 if not changed_files:
905 return False, "No files were changed during implementation"
907 # Check if code changes are required
908 if not self.parallel_config.require_code_changes:
909 return True, ""
911 # Use shared verification function
912 if verify_work_was_done(self.logger, changed_files):
913 return True, ""
915 # Generate descriptive error with actual excluded files
916 excluded_files = [
917 f
918 for f in changed_files
919 if f and any(f.startswith(excl) for excl in EXCLUDED_DIRECTORIES)
920 ]
921 if excluded_files:
922 files_preview = ", ".join(excluded_files[:5])
923 if len(excluded_files) > 5:
924 files_preview += f" (+{len(excluded_files) - 5} more)"
925 return False, f"Only excluded files modified: {files_preview}"
926 return False, "Only excluded files modified (e.g., .issues/, thoughts/)"
928 def _has_other_issue_id(self, file_lower: str, current_issue_id_lower: str) -> bool:
929 """Check if file contains a different issue ID than the current worker's.
931 This prevents cross-worker contamination where worker A detects worker B's
932 leaked file. When multiple workers run in parallel, their leaked files may
933 both appear in the main repo. Each worker should only clean up its own leaks.
935 Args:
936 file_lower: Lowercase file path to check
937 current_issue_id_lower: Lowercase issue ID of the current worker
939 Returns:
940 True if the file contains a different issue ID (belongs to another worker),
941 False if the file contains the current issue ID or no recognizable issue ID
942 """
943 # Pattern matches common issue ID formats: BUG-123, ENH-456, FEAT-789
944 # Use non-capturing group (?:...) so findall returns full match, not group
945 matches = re.findall(r"(?:bug|enh|feat)-\d+", file_lower)
947 if not matches:
948 # No issue ID found - file doesn't belong to any specific worker
949 return False
951 # Check if any of the found issue IDs match the current worker
952 for match in matches:
953 if match == current_issue_id_lower:
954 return False # File belongs to current worker
956 # File has issue ID(s) but none match current worker - belongs to another worker
957 return True
959 def _detect_main_repo_leaks(self, issue_id: str, baseline_status: set[str]) -> list[str]:
960 """Detect files incorrectly written to main repo instead of worktree.
962 Claude Code may write files to the main repository instead of the
963 worktree due to project root detection issues (see GitHub #8771).
964 This method detects such leaks by comparing main repo status before
965 and after worker execution.
967 Args:
968 issue_id: ID of the issue being processed (for pattern matching)
969 baseline_status: Set of file paths from git status before worker started
971 Returns:
972 List of file paths that were leaked to main repo
973 """
974 # Get current status of main repo
975 result = self._git_lock.run(
976 ["status", "--porcelain"],
977 cwd=self.repo_path,
978 timeout=30,
979 )
981 if result.returncode != 0:
982 return []
984 current_files: set[str] = set()
985 for line in result.stdout.strip().split("\n"):
986 if not line or len(line) < 3:
987 continue
988 # Extract file path (after status codes and space)
989 file_path = line[3:].strip()
990 # Handle renamed files (old -> new)
991 if " -> " in file_path:
992 file_path = file_path.split(" -> ")[-1]
993 current_files.add(file_path)
995 # Find new files that appeared during worker execution
996 new_files = current_files - baseline_status
998 # Filter to files likely related to this issue
999 issue_id_lower = issue_id.lower()
1000 leaked_files: list[str] = []
1002 # Build source prefix list: start with common fallbacks, then add configured dirs
1003 source_prefixes = ["backend/", "src/", "lib/", "tests/"]
1004 for dir_path in [self.br_config.project.src_dir, self.br_config.project.test_dir]:
1005 if dir_path:
1006 normalized = dir_path.rstrip("/") + "/"
1007 if normalized not in source_prefixes:
1008 source_prefixes.append(normalized)
1010 for file_path in new_files:
1011 # Skip state file (managed by orchestrator)
1012 if file_path.endswith(".parallel-manage-state.json"):
1013 continue
1014 # Skip .gitignore (may be modified by ll-parallel)
1015 if file_path == ".gitignore":
1016 continue
1018 # Check if file is related to this issue
1019 file_lower = file_path.lower()
1020 if issue_id_lower in file_lower:
1021 leaked_files.append(file_path)
1022 # Also catch source files that shouldn't be modified in main
1023 elif file_path.startswith(tuple(source_prefixes)):
1024 leaked_files.append(file_path)
1025 # Catch thoughts/plans files
1026 elif file_path.startswith("thoughts/"):
1027 leaked_files.append(file_path)
1028 # Catch issue files in any issue directory variant
1029 # Handles both .issues/ (with dot) and issues/ (without dot)
1030 # Only include files without a different issue ID - files WITH other issue IDs
1031 # belong to other workers running in parallel (cross-worker contamination)
1032 elif file_path.startswith((".issues/", "issues/")):
1033 if not self._has_other_issue_id(file_lower, issue_id_lower):
1034 leaked_files.append(file_path)
1036 return leaked_files
1038 def _cleanup_leaked_files(self, leaked_files: list[str]) -> int:
1039 """Discard leaked files from main repo working directory.
1041 Claude Code sometimes writes files to the main repo instead of the
1042 worktree. These files cause stash conflicts during merge operations.
1043 Since the actual work is preserved in the worktree branch, we can
1044 safely discard these leaked changes from the main repo.
1046 Args:
1047 leaked_files: List of file paths leaked to main repo
1049 Returns:
1050 Number of files successfully cleaned up
1051 """
1052 if not leaked_files:
1053 return 0
1055 cleaned = 0
1057 # Get status to determine which files are tracked vs untracked
1058 status_result = self._git_lock.run(
1059 ["status", "--porcelain", "--"] + leaked_files,
1060 cwd=self.repo_path,
1061 timeout=30,
1062 )
1064 tracked_files: list[str] = []
1065 untracked_files: list[str] = []
1067 for line in status_result.stdout.splitlines():
1068 if not line or len(line) < 3:
1069 continue
1070 status_code = line[:2]
1071 file_path = line[3:].split(" -> ")[-1].strip()
1073 if status_code.startswith("?"):
1074 # Untracked file - need to delete
1075 untracked_files.append(file_path)
1076 else:
1077 # Tracked file - can use git checkout to discard
1078 tracked_files.append(file_path)
1080 # Discard changes to tracked files
1081 if tracked_files:
1082 checkout_result = self._git_lock.run(
1083 ["checkout", "--"] + tracked_files,
1084 cwd=self.repo_path,
1085 timeout=30,
1086 )
1087 if checkout_result.returncode == 0:
1088 cleaned += len(tracked_files)
1089 else:
1090 self.logger.warning(
1091 f"Failed to discard tracked leaked files: {checkout_result.stderr}"
1092 )
1094 # Delete untracked files
1095 for file_path in untracked_files:
1096 full_path = self.repo_path / file_path
1097 try:
1098 if full_path.exists():
1099 full_path.unlink()
1100 cleaned += 1
1101 except OSError as e:
1102 self.logger.warning(f"Failed to delete leaked file {file_path}: {e}")
1104 # Fallback: directly delete files not reported by git status
1105 # This handles gitignored files that git status --porcelain doesn't show
1106 accounted_files = set(tracked_files + untracked_files)
1107 for file_path in leaked_files:
1108 if file_path not in accounted_files:
1109 full_path = self.repo_path / file_path
1110 if full_path.exists():
1111 try:
1112 full_path.unlink()
1113 cleaned += 1
1114 self.logger.info(f"Deleted gitignored leaked file: {file_path}")
1115 except OSError as e:
1116 self.logger.warning(
1117 f"Failed to delete gitignored leaked file {file_path}: {e}"
1118 )
1119 else:
1120 self.logger.debug(f"Leaked file not found (may have been moved): {file_path}")
1122 if cleaned > 0:
1123 self.logger.info(f"Cleaned up {cleaned} leaked file(s) from main repo")
1125 return cleaned
1127 def _get_main_repo_baseline(self) -> set[str]:
1128 """Get baseline of modified/untracked files in main repo.
1130 Returns:
1131 Set of file paths currently showing in git status
1132 """
1133 result = self._git_lock.run(
1134 ["status", "--porcelain"],
1135 cwd=self.repo_path,
1136 timeout=30,
1137 )
1139 if result.returncode != 0:
1140 return set()
1142 files: set[str] = set()
1143 for line in result.stdout.strip().split("\n"):
1144 if not line or len(line) < 3:
1145 continue
1146 file_path = line[3:].strip()
1147 if " -> " in file_path:
1148 file_path = file_path.split(" -> ")[-1]
1149 files.add(file_path)
1151 return files
1153 def _get_main_head_sha(self) -> str:
1154 """Get the current HEAD SHA of the main repo.
1156 Returns:
1157 HEAD SHA string, or empty string if unavailable
1158 """
1159 result = self._git_lock.run(
1160 ["rev-parse", "HEAD"],
1161 cwd=self.repo_path,
1162 timeout=10,
1163 )
1164 if result.returncode == 0:
1165 return result.stdout.strip()
1166 return ""
1168 def _detect_committed_leaks(self, baseline_head_sha: str) -> list[str]:
1169 """Detect commits made directly to main repo during worker execution.
1171 When Claude commits to the main repo instead of the worktree branch,
1172 the commits appear on main's history but the worktree has no changes.
1173 This method detects such leaked commits by comparing main's HEAD SHA
1174 before and after worker execution.
1176 Args:
1177 baseline_head_sha: HEAD SHA captured before worker started
1179 Returns:
1180 List of commit SHAs committed to main during worker execution,
1181 newest first. Empty list if no committed leaks detected.
1182 """
1183 if not baseline_head_sha:
1184 return []
1186 current_sha = self._get_main_head_sha()
1187 if not current_sha or current_sha == baseline_head_sha:
1188 return []
1190 # Get list of new commits on main since baseline
1191 result = self._git_lock.run(
1192 ["log", "--format=%H", f"{baseline_head_sha}..HEAD"],
1193 cwd=self.repo_path,
1194 timeout=30,
1195 )
1196 if result.returncode != 0:
1197 return []
1199 commits = [sha.strip() for sha in result.stdout.strip().split("\n") if sha.strip()]
1200 return commits
1202 def _recover_committed_leaks(
1203 self,
1204 leaked_commits: list[str],
1205 worktree_path: Path,
1206 baseline_head_sha: str,
1207 issue_id: str,
1208 ) -> bool:
1209 """Attempt to recover committed leaks by cherry-picking to worktree.
1211 When Claude commits directly to main instead of the worktree branch,
1212 we attempt to:
1213 1. Cherry-pick the leaked commits onto the worktree branch
1214 2. Reset main back to the baseline SHA (if safe to do so)
1216 This preserves the implementation work in the worktree while
1217 cleaning up the incorrect commits on main.
1219 Args:
1220 leaked_commits: Commit SHAs that leaked to main (newest first)
1221 worktree_path: Path to the worker's worktree
1222 baseline_head_sha: Main HEAD SHA before worker started
1223 issue_id: Issue ID for logging
1225 Returns:
1226 True if cherry-pick succeeded (main reset is attempted but
1227 not required for a True return value)
1228 """
1229 self.logger.info(
1230 f"[{issue_id}] Attempting recovery: cherry-picking {len(leaked_commits)} "
1231 f"commit(s) to worktree"
1232 )
1234 # Cherry-pick in chronological order (oldest first = reverse of log output)
1235 for sha in reversed(leaked_commits):
1236 result = subprocess.run(
1237 ["git", "cherry-pick", sha],
1238 cwd=worktree_path,
1239 capture_output=True,
1240 text=True,
1241 timeout=60,
1242 )
1243 if result.returncode != 0:
1244 subprocess.run(
1245 ["git", "cherry-pick", "--abort"],
1246 cwd=worktree_path,
1247 capture_output=True,
1248 timeout=10,
1249 )
1250 self.logger.warning(
1251 f"[{issue_id}] Cherry-pick of {sha[:8]} failed: {result.stderr.strip()}"
1252 )
1253 return False
1255 # Attempt to reset main to baseline (only if main hasn't advanced further)
1256 current_main_sha = self._get_main_head_sha()
1257 most_recent_leaked = leaked_commits[0] # Newest first
1258 if current_main_sha == most_recent_leaked:
1259 reset_result = self._git_lock.run(
1260 ["reset", "--hard", baseline_head_sha],
1261 cwd=self.repo_path,
1262 timeout=30,
1263 )
1264 if reset_result.returncode == 0:
1265 self.logger.info(f"[{issue_id}] Reset main to baseline {baseline_head_sha[:8]}")
1266 else:
1267 self.logger.warning(
1268 f"[{issue_id}] Cherry-pick succeeded but failed to reset main: "
1269 f"{reset_result.stderr.strip()}"
1270 )
1271 else:
1272 self.logger.warning(
1273 f"[{issue_id}] Main has additional commits beyond leaked ones "
1274 f"({current_main_sha[:8]} != {most_recent_leaked[:8]}) — "
1275 f"skipping main reset, manual cleanup may be needed"
1276 )
1278 self.logger.info(
1279 f"[{issue_id}] Recovered {len(leaked_commits)} commit(s): "
1280 f"cherry-picked to worktree branch"
1281 )
1282 return True
1284 @property
1285 def active_count(self) -> int:
1286 """Number of currently active workers.
1288 Includes both workers with running futures AND workers whose futures
1289 are done but callbacks haven't completed yet.
1290 """
1291 with self._process_lock:
1292 running_futures = sum(1 for f in self._active_workers.values() if not f.done())
1293 with self._callback_lock:
1294 pending_callback_count = len(self._pending_callbacks)
1295 return running_futures + pending_callback_count
1297 def set_worker_stage(self, issue_id: str, stage: WorkerStage) -> None:
1298 """Update the stage of a worker.
1300 Args:
1301 issue_id: Issue ID being processed
1302 stage: New stage value
1303 """
1304 with self._process_lock:
1305 self._worker_stages[issue_id] = stage
1307 def get_worker_stage(self, issue_id: str) -> WorkerStage | None:
1308 """Get the current stage of a worker.
1310 Args:
1311 issue_id: Issue ID being processed
1313 Returns:
1314 Current stage, or None if issue not being tracked
1315 """
1316 with self._process_lock:
1317 return self._worker_stages.get(issue_id)
1319 def get_active_stages(self) -> dict[str, WorkerStage]:
1320 """Get all active worker stages.
1322 Returns:
1323 Dictionary mapping issue_id to current stage for active workers
1324 """
1325 with self._process_lock:
1326 # Only return workers that are actually active
1327 active_ids = set(self._active_workers.keys())
1328 return {
1329 issue_id: stage
1330 for issue_id, stage in self._worker_stages.items()
1331 if issue_id in active_ids
1332 }
1334 def remove_worker_stage(self, issue_id: str) -> None:
1335 """Remove a worker from stage tracking.
1337 Args:
1338 issue_id: Issue ID to remove
1339 """
1340 with self._process_lock:
1341 self._worker_stages.pop(issue_id, None)
1343 def cleanup_all_worktrees(self) -> None:
1344 """Clean up all worker worktrees."""
1345 worktree_base = self.repo_path / self.parallel_config.worktree_base
1346 if not worktree_base.exists():
1347 return
1349 for worktree_dir in worktree_base.iterdir():
1350 if worktree_dir.is_dir() and worktree_dir.name.startswith("worker-"):
1351 self._cleanup_worktree(worktree_dir)
1353 self.logger.info("Cleaned up all worker worktrees")