Coverage for little_loops / issue_manager.py: 12%
393 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"""Automated issue management for little-loops.
3Provides the AutoManager class for sequential issue processing with
4Claude CLI integration and state persistence for resume capability.
5"""
7from __future__ import annotations
9import signal
10import subprocess
11import sys
12import time
13from collections.abc import Callable, Generator
14from contextlib import contextmanager
15from dataclasses import dataclass, field
16from datetime import datetime
17from pathlib import Path
18from types import FrameType
20from little_loops.cli_args import _id_matches
21from little_loops.config import BRConfig
22from little_loops.dependency_graph import DependencyGraph
23from little_loops.git_operations import check_git_status, verify_work_was_done
24from little_loops.issue_lifecycle import (
25 FailureType,
26 classify_failure,
27 close_issue,
28 complete_issue_lifecycle,
29 create_issue_from_failure,
30 verify_issue_completed,
31)
32from little_loops.issue_parser import IssueInfo, IssueParser, find_issues
33from little_loops.logger import Logger, format_duration
34from little_loops.output_parsing import parse_ready_issue_output
35from little_loops.state import ProcessingState, StateManager
36from little_loops.subprocess_utils import (
37 detect_context_handoff,
38 read_continuation_prompt,
39)
40from little_loops.subprocess_utils import (
41 run_claude_command as _run_claude_base,
42)
45def _compute_relative_path(abs_path: Path, base_dir: Path | None = None) -> str:
46 """Compute relative path from base directory for command input.
48 Used for fallback retry when ready-issue resolves to wrong file -
49 allows retrying with explicit file path instead of ambiguous ID.
51 Args:
52 abs_path: Absolute path to the file
53 base_dir: Base directory (defaults to cwd)
55 Returns:
56 Relative path string suitable for ready-issue command
57 """
58 base = base_dir or Path.cwd()
59 try:
60 return str(abs_path.relative_to(base))
61 except ValueError:
62 # Path not relative to base, use absolute
63 return str(abs_path)
66@contextmanager
67def timed_phase(
68 logger: Logger,
69 phase_name: str,
70) -> Generator[dict[str, float], None, None]:
71 """Context manager for timing phases.
73 Yields a dict that will be populated with 'elapsed' after the context exits.
75 Args:
76 logger: Logger for output
77 phase_name: Name of the phase being timed
79 Yields:
80 Dict that will contain 'elapsed' key after context exits
81 """
82 timing_result: dict[str, float] = {}
83 start = time.time()
84 try:
85 yield timing_result
86 finally:
87 elapsed = time.time() - start
88 timing_result["elapsed"] = elapsed
89 logger.timing(f"{phase_name} completed in {format_duration(elapsed)}")
92def run_claude_command(
93 command: str,
94 logger: Logger,
95 timeout: int = 3600,
96 stream_output: bool = True,
97 idle_timeout: int = 0,
98 on_model_detected: Callable[[str], None] | None = None,
99) -> subprocess.CompletedProcess[str]:
100 """Invoke Claude CLI command with real-time output streaming.
102 Args:
103 command: Command to pass to Claude CLI
104 logger: Logger for output
105 timeout: Timeout in seconds
106 stream_output: Whether to stream output to console
107 idle_timeout: Kill process if no output for this many seconds (0 to disable)
108 on_model_detected: Optional callback invoked with the model name from the
109 stream-json system/init event.
111 Returns:
112 CompletedProcess with stdout/stderr captured
113 """
114 logger.info(f"Running: claude --dangerously-skip-permissions -p {command!r}")
116 def stream_callback(line: str, is_stderr: bool) -> None:
117 if stream_output:
118 if is_stderr:
119 print(f" {line}", file=sys.stderr)
120 else:
121 print(f" {line}")
123 return _run_claude_base(
124 command=command,
125 timeout=timeout,
126 stream_callback=stream_callback if stream_output else None,
127 idle_timeout=idle_timeout,
128 on_model_detected=on_model_detected,
129 )
132def run_with_continuation(
133 initial_command: str,
134 logger: Logger,
135 timeout: int = 3600,
136 stream_output: bool = True,
137 max_continuations: int = 3,
138 repo_path: Path | None = None,
139 idle_timeout: int = 0,
140) -> subprocess.CompletedProcess[str]:
141 """Run a Claude command with automatic continuation on context handoff.
143 If the command signals CONTEXT_HANDOFF, reads the continuation prompt
144 and spawns a fresh Claude session to continue the work.
146 Args:
147 initial_command: Initial command to run
148 logger: Logger for output
149 timeout: Timeout per session in seconds
150 stream_output: Whether to stream output
151 max_continuations: Maximum number of continuation attempts
152 repo_path: Repository root path
153 idle_timeout: Kill process if no output for this many seconds (0 to disable)
155 Returns:
156 Final CompletedProcess result
157 """
158 all_stdout: list[str] = []
159 all_stderr: list[str] = []
160 current_command = initial_command
161 continuation_count = 0
162 result: subprocess.CompletedProcess[str] = subprocess.CompletedProcess(
163 args=[], returncode=1, stdout="", stderr=""
164 )
166 while continuation_count <= max_continuations:
167 result = run_claude_command(
168 current_command,
169 logger,
170 timeout=timeout,
171 stream_output=stream_output,
172 idle_timeout=idle_timeout,
173 )
175 all_stdout.append(result.stdout)
176 all_stderr.append(result.stderr)
178 # Check for context handoff signal
179 if detect_context_handoff(result.stdout):
180 logger.info("Detected CONTEXT_HANDOFF signal")
182 # Read continuation prompt
183 prompt_content = read_continuation_prompt(repo_path)
184 if not prompt_content:
185 logger.warning("Context handoff signaled but no continuation prompt found")
186 all_stderr.append("Handoff detected but no continuation prompt found")
187 result = subprocess.CompletedProcess(
188 args=result.args, returncode=1, stdout=result.stdout, stderr=result.stderr
189 )
190 break
192 if continuation_count >= max_continuations:
193 logger.warning(f"Reached max continuations ({max_continuations}), stopping")
194 break
196 continuation_count += 1
197 logger.info(f"Starting continuation session #{continuation_count}")
199 # Re-invoke the original command with --resume flag so the skill
200 # lifecycle (including completion/file-move) runs in the new session.
201 # The skill reads .ll/ll-continue-prompt.md for context.
202 current_command = f"{initial_command} --resume"
203 continue
205 # No handoff signal, we're done
206 break
208 return subprocess.CompletedProcess(
209 args=result.args,
210 returncode=result.returncode,
211 stdout="\n---CONTINUATION---\n".join(all_stdout),
212 stderr="\n---CONTINUATION---\n".join(all_stderr),
213 )
216def detect_plan_creation(output: str, issue_id: str) -> Path | None:
217 """Detect if manage-issue created a plan file awaiting approval.
219 Checks for plan file creation in thoughts/shared/plans/ matching the issue ID.
220 This happens when manage-issue creates a plan but waits for user approval.
222 Args:
223 output: Command stdout (unused, for future pattern matching)
224 issue_id: Issue ID (e.g., "BUG-280")
226 Returns:
227 Path to plan file if created, None otherwise
228 """
229 plans_dir = Path("thoughts/shared/plans")
230 if not plans_dir.exists():
231 return None
233 # Find plan files matching this issue ID (format: YYYY-MM-DD-ISSUE-ID-*.md)
234 # Use glob pattern with issue_id
235 pattern = f"*-{issue_id}-*.md"
236 matching_plans = list(plans_dir.glob(pattern))
238 if not matching_plans:
239 return None
241 # Return the most recently modified plan file
242 # (in case multiple exist, take the latest)
243 latest_plan = max(matching_plans, key=lambda p: p.stat().st_mtime)
244 return latest_plan
247def check_content_markers(issue_path: Path) -> bool:
248 """Check if issue file content contains implementation markers.
250 Looks for indicators that an implementation was completed, such as
251 Resolution sections or status markers added by manage-issue.
253 Args:
254 issue_path: Path to the issue file
256 Returns:
257 True if implementation markers found
258 """
259 try:
260 content = issue_path.read_text(encoding="utf-8")
261 except (OSError, UnicodeDecodeError):
262 return False
264 markers = [
265 "## Resolution",
266 "Status: Implemented",
267 "Status: Completed",
268 "**Completed**:",
269 ]
270 return any(marker in content for marker in markers)
273@dataclass
274class IssueProcessingResult:
275 """Result of processing a single issue in-place."""
277 success: bool
278 duration: float
279 issue_id: str
280 was_closed: bool = False
281 was_blocked: bool = False
282 failure_reason: str = ""
283 corrections: list[str] = field(default_factory=list)
284 plan_created: bool = False
285 plan_path: str = ""
288def process_issue_inplace(
289 info: IssueInfo,
290 config: BRConfig,
291 logger: Logger,
292 dry_run: bool = False,
293 on_model_detected: Callable[[str], None] | None = None,
294) -> IssueProcessingResult:
295 """Process a single issue through the 3-phase workflow in the current working tree.
297 This is the core processing logic extracted from AutoManager._process_issue(),
298 suitable for use outside of AutoManager (e.g., single-issue sprint waves).
300 Args:
301 info: Issue information
302 config: Project configuration
303 logger: Logger for output
304 dry_run: If True, only preview what would be done
305 on_model_detected: Optional callback invoked with the model name from the
306 first stream-json system/init event during this issue's processing.
308 Returns:
309 IssueProcessingResult with outcome details
310 """
311 issue_start_time = time.time()
312 corrections: list[str] = []
314 logger.header(f"Processing: {info.issue_id} - {info.title}")
316 issue_timing: dict[str, float] = {}
318 # Track whether we used fallback path resolution for ready-issue.
319 validated_via_fallback = False
321 # Phase 1: Ready/verify the issue
322 logger.info(f"Phase 1: Verifying issue {info.issue_id}...")
323 with timed_phase(logger, "Phase 1 (ready-issue)") as phase1_timing:
324 if not dry_run:
325 result = run_claude_command(
326 f"/ll:ready-issue {info.issue_id}",
327 logger,
328 timeout=config.automation.timeout_seconds,
329 stream_output=config.automation.stream_output,
330 idle_timeout=config.automation.idle_timeout_seconds,
331 on_model_detected=on_model_detected,
332 )
333 if result.returncode != 0:
334 logger.warning("ready-issue command failed to execute, continuing anyway...")
335 else:
336 # Parse the verdict from the output
337 parsed = parse_ready_issue_output(result.stdout)
338 logger.info(f"ready-issue verdict: {parsed['verdict']}")
340 # Validate that ready-issue analyzed the expected file
341 validated_path = parsed.get("validated_file_path")
342 if validated_path:
343 # Normalize paths for comparison (resolve to absolute)
344 expected_path = str(info.path.resolve())
345 # Handle both absolute and relative paths from ready_issue
346 validated_resolved = Path(validated_path).resolve()
347 if str(validated_resolved) != expected_path:
348 # Check if this is a legitimate rename (new file exists,
349 # old file doesn't) vs a mismatch error
350 old_file_exists = info.path.exists()
351 new_file_exists = validated_resolved.exists()
353 if new_file_exists and not old_file_exists:
354 # ready-issue renamed the file - update tracking
355 logger.info(
356 f"Issue file renamed: '{info.path.name}' -> "
357 f"'{validated_resolved.name}'"
358 )
359 info.path = validated_resolved
360 else:
361 # Genuine mismatch - attempt fallback with explicit path
362 logger.warning(
363 f"Path mismatch: ready-issue validated "
364 f"'{validated_path}' but expected '{info.path}'"
365 )
366 logger.info(
367 "Attempting fallback: retrying ready-issue "
368 "with explicit file path..."
369 )
371 # Compute relative path for the command
372 relative_path = _compute_relative_path(info.path)
374 # Retry with explicit path
375 retry_result = run_claude_command(
376 f"/ll:ready-issue {relative_path}",
377 logger,
378 timeout=config.automation.timeout_seconds,
379 stream_output=config.automation.stream_output,
380 idle_timeout=config.automation.idle_timeout_seconds,
381 on_model_detected=on_model_detected,
382 )
384 if retry_result.returncode != 0:
385 logger.error(f"Fallback ready-issue failed for {info.issue_id}")
386 return IssueProcessingResult(
387 success=False,
388 duration=time.time() - issue_start_time,
389 issue_id=info.issue_id,
390 failure_reason="Fallback failed after path mismatch",
391 )
393 # Re-parse and validate retry output
394 retry_parsed = parse_ready_issue_output(retry_result.stdout)
395 retry_validated_path = retry_parsed.get("validated_file_path")
397 if retry_validated_path:
398 retry_resolved = Path(retry_validated_path).resolve()
399 if str(retry_resolved) != str(info.path.resolve()):
400 logger.error(
401 f"Fallback still mismatched: "
402 f"got '{retry_validated_path}', "
403 f"expected '{info.path}'"
404 )
405 return IssueProcessingResult(
406 success=False,
407 duration=time.time() - issue_start_time,
408 issue_id=info.issue_id,
409 failure_reason="Path mismatch persisted after fallback",
410 )
412 # Fallback succeeded - use retry result
413 logger.info("Fallback succeeded: validated correct file")
414 parsed = retry_parsed
415 validated_via_fallback = True
417 # Log and store any corrections made
418 if parsed.get("was_corrected"):
419 logger.info(f"Issue {info.issue_id} was auto-corrected")
420 phase_corrections = parsed.get("corrections", [])
421 for correction in phase_corrections:
422 logger.info(f" Correction: {correction}")
423 if phase_corrections:
424 corrections.extend(phase_corrections)
426 # Log any concerns found
427 if parsed["concerns"]:
428 for concern in parsed["concerns"]:
429 logger.warning(f" Concern: {concern}")
431 # Handle CLOSE verdict - issue should not be implemented
432 if parsed.get("should_close"):
433 close_reason = parsed.get("close_reason", "unknown")
434 logger.info(f"Issue {info.issue_id} should be closed (reason: {close_reason})")
436 # CRITICAL: Skip file operations for invalid references
437 if close_reason == "invalid_ref":
438 logger.warning(
439 f"Skipping {info.issue_id}: invalid reference - "
440 "no matching issue file exists"
441 )
442 return IssueProcessingResult(
443 success=False,
444 duration=time.time() - issue_start_time,
445 issue_id=info.issue_id,
446 failure_reason=f"Invalid reference: {close_reason}",
447 corrections=corrections,
448 )
450 # Also require validated_file_path to match before closing
451 close_validated_path = parsed.get("validated_file_path")
452 if not close_validated_path:
453 logger.warning(
454 f"Skipping close for {info.issue_id}: "
455 "ready-issue did not return validated file path"
456 )
457 return IssueProcessingResult(
458 success=False,
459 duration=time.time() - issue_start_time,
460 issue_id=info.issue_id,
461 failure_reason="CLOSE without validated file path",
462 corrections=corrections,
463 )
465 if close_issue(
466 info,
467 config,
468 logger,
469 close_reason,
470 parsed.get("close_status"),
471 ):
472 return IssueProcessingResult(
473 success=True,
474 duration=time.time() - issue_start_time,
475 issue_id=info.issue_id,
476 was_closed=True,
477 corrections=corrections,
478 )
479 else:
480 return IssueProcessingResult(
481 success=False,
482 duration=time.time() - issue_start_time,
483 issue_id=info.issue_id,
484 failure_reason=f"CLOSE failed: {parsed.get('close_status', 'unknown')}",
485 corrections=corrections,
486 )
488 # Handle BLOCKED verdict - issue has open dependencies
489 if parsed.get("is_blocked"):
490 logger.warning(
491 f"Issue {info.issue_id} blocked — open dependency detected by ready-issue"
492 )
493 return IssueProcessingResult(
494 success=False,
495 was_blocked=True,
496 duration=time.time() - issue_start_time,
497 issue_id=info.issue_id,
498 failure_reason=f"BLOCKED: {parsed.get('concerns', [])}",
499 corrections=corrections,
500 )
502 # Check if issue is NOT READY (and not closeable)
503 if not parsed["is_ready"]:
504 logger.error(
505 f"Issue {info.issue_id} is NOT READY for implementation "
506 f"(verdict: {parsed['verdict']})"
507 )
508 return IssueProcessingResult(
509 success=False,
510 duration=time.time() - issue_start_time,
511 issue_id=info.issue_id,
512 failure_reason=(
513 f"NOT READY: {parsed['verdict']} - {len(parsed['concerns'])} concern(s)"
514 ),
515 corrections=corrections,
516 )
518 # Log if proceeding with corrected issue
519 if parsed.get("was_corrected"):
520 logger.success(f"Issue {info.issue_id} corrected and ready for implementation")
521 else:
522 logger.info(f"Would run: /ll:ready-issue {info.issue_id}")
523 issue_timing["ready"] = phase1_timing.get("elapsed", 0.0)
525 # Phase 2: Implement the issue (with automatic continuation on context handoff)
526 action = config.get_category_action(info.issue_type)
527 logger.info(f"Phase 2: Implementing {info.issue_id}...")
528 with timed_phase(logger, "Phase 2 (implement)") as phase2_timing:
529 if not dry_run:
530 # Build manage-issue command
531 type_name = info.issue_type.rstrip("s") # bugs -> bug
533 # Use relative path if fallback was used, otherwise use issue_id
534 if validated_via_fallback:
535 issue_arg = _compute_relative_path(info.path)
536 else:
537 issue_arg = info.issue_id
539 # Use run_with_continuation to handle context exhaustion
540 result = run_with_continuation(
541 f"/ll:manage-issue {type_name} {action} {issue_arg}",
542 logger,
543 timeout=config.automation.timeout_seconds,
544 stream_output=config.automation.stream_output,
545 max_continuations=config.automation.max_continuations,
546 repo_path=config.repo_path,
547 idle_timeout=config.automation.idle_timeout_seconds,
548 )
549 else:
550 logger.info(f"Would run: /ll:manage-issue {info.issue_type} {action} {info.issue_id}")
551 result = subprocess.CompletedProcess(args=[], returncode=0)
552 issue_timing["implement"] = phase2_timing.get("elapsed", 0.0)
554 # Handle implementation failure
555 if result.returncode != 0:
556 error_output = result.stderr or result.stdout or "Unknown error"
557 failure_type, failure_reason_text = classify_failure(error_output, result.returncode)
559 if failure_type == FailureType.TRANSIENT:
560 # Transient failure - log but don't create bug issue
561 logger.warning(f"Transient failure for {info.issue_id}: {failure_reason_text}")
562 logger.warning("Not creating bug issue - this is a temporary error")
563 logger.info("Error output (first 500 chars):")
564 logger.info(error_output[:500])
566 return IssueProcessingResult(
567 success=False,
568 duration=time.time() - issue_start_time,
569 issue_id=info.issue_id,
570 failure_reason=f"Transient: {failure_reason_text}",
571 corrections=corrections,
572 )
574 # Real failure - create issue as before
575 logger.error(f"Implementation failed for {info.issue_id}")
577 failure_reason = ""
578 if not dry_run:
579 # Create new issue for the failure
580 new_issue = create_issue_from_failure(
581 error_output,
582 info,
583 config,
584 logger,
585 )
586 failure_reason = str(new_issue) if new_issue else error_output
587 else:
588 logger.info("Would create new bug issue for this failure")
590 return IssueProcessingResult(
591 success=False,
592 duration=time.time() - issue_start_time,
593 issue_id=info.issue_id,
594 failure_reason=failure_reason,
595 corrections=corrections,
596 )
598 # Phase 3: Verify completion
599 logger.info(f"Phase 3: Verifying {info.issue_id} completion...")
600 verified = False
601 with timed_phase(logger, "Phase 3 (verify)") as phase3_timing:
602 if not dry_run:
603 verified = verify_issue_completed(info, config, logger)
605 # Fallback: Only complete lifecycle if:
606 # 1. Command returned success (returncode 0)
607 # 2. File wasn't moved to completed
608 # 3. There's EVIDENCE of actual work being done (code changes)
609 if not verified and result.returncode == 0:
610 # Check if a plan was created awaiting approval
611 plan_path = detect_plan_creation(result.stdout, info.issue_id)
612 if plan_path is not None:
613 logger.info(
614 f"Plan created at {plan_path}, awaiting approval - "
615 "issue will remain incomplete until plan is approved and implemented"
616 )
617 return IssueProcessingResult(
618 success=False,
619 duration=time.time() - issue_start_time,
620 issue_id=info.issue_id,
621 plan_created=True,
622 plan_path=str(plan_path),
623 failure_reason="", # Not a failure - plan awaiting approval
624 corrections=corrections,
625 )
627 logger.info(
628 "Command returned success but issue not moved - "
629 "checking for evidence of work..."
630 )
632 # Check issue file content for implementation markers
633 if check_content_markers(info.path):
634 logger.info(
635 "Implementation markers found in issue file - completing lifecycle..."
636 )
637 verified = complete_issue_lifecycle(info, config, logger)
638 if verified:
639 logger.success(f"Content marker completion succeeded for {info.issue_id}")
640 else:
641 logger.warning(f"Content marker completion failed for {info.issue_id}")
642 else:
643 # CRITICAL: Verify actual implementation work was done
644 work_done = verify_work_was_done(logger)
645 if work_done:
646 logger.info("Evidence of code changes found - completing lifecycle...")
647 verified = complete_issue_lifecycle(info, config, logger)
648 if verified:
649 logger.success(f"Fallback completion succeeded for {info.issue_id}")
650 else:
651 logger.warning(f"Fallback completion failed for {info.issue_id}")
652 else:
653 # NO work was done - do NOT mark as completed
654 logger.error(
655 f"REFUSING to mark {info.issue_id} as completed: "
656 "no code changes detected despite returncode 0"
657 )
658 logger.error(
659 "This likely indicates the command was not executed "
660 "properly. Check command invocation and Claude CLI "
661 "output."
662 )
663 verified = False
664 else:
665 logger.info("Would verify issue moved to completed")
666 verified = True # In dry run, assume success
667 issue_timing["verify"] = phase3_timing.get("elapsed", 0.0)
669 # Record timing
670 total_issue_time = time.time() - issue_start_time
671 issue_timing["total"] = total_issue_time
672 logger.timing(f"Total processing time: {format_duration(total_issue_time)}")
674 if verified:
675 logger.success(f"Completed: {info.issue_id}")
676 else:
677 logger.warning(f"Issue {info.issue_id} was attempted but verification failed")
678 logger.info("This issue will be skipped on future runs (check logs above for details)")
680 return IssueProcessingResult(
681 success=verified,
682 duration=total_issue_time,
683 issue_id=info.issue_id,
684 corrections=corrections,
685 )
688class AutoManager:
689 """Automated issue manager for sequential processing.
691 Processes issues in priority order using Claude CLI commands,
692 with state persistence for resume capability.
693 """
695 def __init__(
696 self,
697 config: BRConfig,
698 dry_run: bool = False,
699 max_issues: int = 0,
700 resume: bool = False,
701 category: str | None = None,
702 only_ids: list[str] | set[str] | None = None,
703 skip_ids: set[str] | None = None,
704 type_prefixes: set[str] | None = None,
705 priority_filter: set[str] | None = None,
706 verbose: bool = True,
707 ) -> None:
708 """Initialize the auto manager.
710 Args:
711 config: Project configuration
712 dry_run: If True, only preview what would be done
713 max_issues: Maximum issues to process (0 = unlimited)
714 resume: Whether to resume from previous state
715 category: Optional category to filter (e.g., "bugs")
716 only_ids: If provided, only process these issue IDs. When a list,
717 issues are processed in list order (input sequence preserved).
718 skip_ids: Issue IDs to skip (in addition to attempted issues)
719 type_prefixes: If provided, only process issues with these type prefixes
720 priority_filter: If provided, only process issues with these priority levels
721 verbose: Whether to output progress messages
722 """
723 self.config = config
724 self.dry_run = dry_run
725 self.max_issues = max_issues
726 self.resume = resume
727 self.category = category
728 self.only_ids = only_ids
729 self.skip_ids = skip_ids or set()
730 self.type_prefixes = type_prefixes
731 self.priority_filter = priority_filter
733 self.logger = Logger(verbose=verbose)
734 self.state_manager = StateManager(config.get_state_file(), self.logger)
735 self.parser = IssueParser(config)
736 self._detected_model: list[str] = []
738 # Build dependency graph for dependency-aware sequencing (ENH-016)
739 # Note: don't filter by type here — we need all issues for dependency resolution
740 all_issues = find_issues(self.config, self.category)
741 all_known_ids: set[str] | None = None
742 try:
743 from little_loops.dependency_mapper import gather_all_issue_ids
745 issues_dir = config.project_root / config.issues.base_dir
746 all_known_ids = gather_all_issue_ids(issues_dir, config=config)
747 except Exception:
748 self.logger.debug("Dependency mapping unavailable — skipping")
749 self.dep_graph = DependencyGraph.from_issues(all_issues, all_known_ids=all_known_ids)
751 # Warn about any cycles
752 if self.dep_graph.has_cycles():
753 cycles = self.dep_graph.detect_cycles()
754 for cycle in cycles:
755 self.logger.warning(f"Dependency cycle detected: {' -> '.join(cycle)}")
757 self.processed_count = 0
758 self._shutdown_requested = False
760 signal.signal(signal.SIGINT, self._signal_handler)
761 signal.signal(signal.SIGTERM, self._signal_handler)
763 def _signal_handler(self, signum: int, frame: FrameType | None) -> None:
764 """Handle shutdown signals gracefully."""
765 self._shutdown_requested = True
766 self.logger.warning(f"Received signal {signum}, shutting down gracefully...")
768 def _get_next_issue(self) -> IssueInfo | None:
769 """Get next issue respecting dependencies.
771 Returns the highest priority issue whose blockers have all been
772 completed. If no ready issues exist but blocked issues remain,
773 logs warnings about what is blocking progress.
775 Returns:
776 Next IssueInfo to process, or None if no ready issues
777 """
778 # Get completed issues from state
779 completed = set(self.state_manager.state.completed_issues)
781 # Combine skip_ids from state and CLI argument
782 skip_ids = self.state_manager.state.attempted_issues | self.skip_ids
784 # Get issues that are ready (blockers satisfied)
785 ready_issues = self.dep_graph.get_ready_issues(completed)
787 # Filter by skip_ids, only_ids, type_prefixes, priority_filter
788 candidates = [
789 i
790 for i in ready_issues
791 if i.issue_id not in skip_ids
792 and (self.only_ids is None or any(_id_matches(i.issue_id, p) for p in self.only_ids))
793 and (self.type_prefixes is None or i.issue_id.split("-", 1)[0] in self.type_prefixes)
794 and (self.priority_filter is None or i.priority in self.priority_filter)
795 ]
797 if candidates:
798 # When only_ids is a list, respect input order; otherwise use priority order
799 only_ids = self.only_ids
800 if isinstance(only_ids, list):
801 candidates.sort(
802 key=lambda x: next(
803 (i for i, p in enumerate(only_ids) if _id_matches(x.issue_id, p)),
804 len(only_ids),
805 )
806 )
807 return candidates[0]
809 # No ready candidates - check if there are blocked issues remaining
810 all_in_graph = set(self.dep_graph.issues.keys())
811 remaining = all_in_graph - completed - skip_ids
812 if self.only_ids is not None:
813 remaining = {r for r in remaining if any(_id_matches(r, p) for p in self.only_ids)}
814 if self.type_prefixes is not None:
815 remaining = {r for r in remaining if r.split("-", 1)[0] in self.type_prefixes}
816 if self.priority_filter is not None:
817 remaining = {
818 r for r in remaining if self.dep_graph.issues[r].priority in self.priority_filter
819 }
821 if remaining:
822 self._log_blocked_issues(remaining, completed)
824 return None
826 def _log_blocked_issues(self, remaining: set[str], completed: set[str]) -> None:
827 """Log information about blocked issues when processing stalls.
829 Args:
830 remaining: Set of issue IDs that haven't been processed
831 completed: Set of completed issue IDs
832 """
833 blocked_count = 0
834 for issue_id in sorted(remaining):
835 blockers = self.dep_graph.get_blocking_issues(issue_id, completed)
836 if blockers:
837 blocked_count += 1
838 self.logger.info(f" {issue_id} blocked by: {', '.join(sorted(blockers))}")
840 if blocked_count > 0:
841 self.logger.warning(f"{blocked_count} issue(s) remain blocked - check dependencies")
843 def run(self) -> int:
844 """Run the automation loop.
846 Returns:
847 Exit code (0 = success)
848 """
849 run_start_time = time.time()
850 self.logger.info("Starting automated issue management...")
852 if self.dry_run:
853 self.logger.info("DRY RUN MODE - No actual changes will be made")
855 if not self.dry_run:
856 has_changes = check_git_status(self.logger)
857 if has_changes:
858 self.logger.warning("Proceeding anyway...")
860 # Load or initialize state
861 if self.resume:
862 state = self.state_manager.load()
863 if state:
864 self.logger.info(f"Resuming from: {state.current_issue}")
865 self.processed_count = len(state.completed_issues)
866 else:
867 # Fresh start
868 self.state_manager._state = ProcessingState(timestamp=datetime.now().isoformat())
870 try:
871 while not self._shutdown_requested:
872 if self.max_issues > 0 and self.processed_count >= self.max_issues:
873 self.logger.info(f"Reached max issues limit: {self.max_issues}")
874 break
876 info = self._get_next_issue()
877 if not info:
878 self.logger.success("No more issues to process!")
879 break
881 success = self._process_issue(info)
882 if success:
883 self.processed_count += 1
885 except Exception as e:
886 self.logger.error(f"Fatal error: {e}")
887 return 1
889 finally:
890 if not self._shutdown_requested:
891 self.state_manager.cleanup()
893 self._log_timing_summary(run_start_time)
894 self.logger.success(f"Processed {self.processed_count} issue(s)")
895 return 0
897 def _log_timing_summary(self, run_start_time: float) -> None:
898 """Log aggregate timing summary."""
899 total_run_time = time.time() - run_start_time
901 self.logger.info("")
902 self.logger.header("PROCESSING SUMMARY")
903 self.logger.timing(f"Total run time: {format_duration(total_run_time)}")
904 self.logger.timing(f"Issues processed: {self.processed_count}")
906 state = self.state_manager.state
907 if state.timing:
908 total_times = [t.get("total", 0) for t in state.timing.values()]
909 if total_times:
910 avg_time = sum(total_times) / len(total_times)
911 self.logger.timing(f"Average per issue: {format_duration(avg_time)}")
913 if state.failed_issues:
914 self.logger.warning(f"Failed issues: {len(state.failed_issues)}")
915 for issue_id, reason in state.failed_issues.items():
916 self.logger.warning(f" - {issue_id}: {reason[:50]}...")
918 # Log correction statistics for quality tracking
919 if state.corrections:
920 total_corrected = len(state.corrections)
921 total_issues = len(state.completed_issues) + len(state.failed_issues)
922 correction_rate = (total_corrected / total_issues * 100) if total_issues > 0 else 0
923 self.logger.info(
924 f"Auto-corrections: {total_corrected}/{total_issues} ({correction_rate:.1f}%)"
925 )
927 # Log most common correction types
928 from collections import Counter
930 all_corrections: list[str] = []
931 for corrections in state.corrections.values():
932 all_corrections.extend(corrections)
933 if all_corrections:
934 common = Counter(all_corrections).most_common(3)
935 self.logger.info("Most common corrections:")
936 for correction, count in common:
937 # Truncate long correction descriptions
938 display = correction[:60] + "..." if len(correction) > 60 else correction
939 self.logger.info(f" - {display}: {count}")
941 def _process_issue(self, info: IssueInfo) -> bool:
942 """Process a single issue through the workflow.
944 Delegates to process_issue_inplace() and maps the result back
945 to state manager calls.
947 Args:
948 info: Issue information
950 Returns:
951 True if processing succeeded
952 """
953 # Pre-processing state updates (before delegating)
954 self.state_manager.mark_attempted(info.issue_id, save=False)
955 self.state_manager.update_current(str(info.path), "processing")
957 on_model: Callable[[str], None] | None = None
958 if not self._detected_model:
960 def on_model(m: str) -> None:
961 self._detected_model.append(m)
962 self.logger.info(f"model: {m}")
964 result = process_issue_inplace(
965 info, self.config, self.logger, self.dry_run, on_model_detected=on_model
966 )
968 # Map result back to state tracking
969 if result.was_closed:
970 self.state_manager.mark_completed(info.issue_id)
971 elif result.was_blocked:
972 # Blocked issues are skipped, not failed — leave in pending state
973 self.logger.info(f"{info.issue_id} skipped — blocked by open dependency")
974 elif result.success:
975 self.state_manager.mark_completed(info.issue_id, {"total": result.duration})
976 elif result.plan_created:
977 # Don't mark as failed if a plan was created (awaiting approval)
978 self.logger.info(
979 f"{info.issue_id} has plan at {result.plan_path} - "
980 "leaving in pending state for manual approval"
981 )
982 # Issue remains in pending state (not marked as failed)
983 elif result.failure_reason:
984 self.state_manager.mark_failed(info.issue_id, result.failure_reason)
986 if result.corrections:
987 self.state_manager.record_corrections(info.issue_id, result.corrections)
989 return result.success