Coverage for little_loops / issue_manager.py: 90%

372 statements  

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

1"""Automated issue management for little-loops. 

2 

3Provides the AutoManager class for sequential issue processing with 

4Claude CLI integration and state persistence for resume capability. 

5""" 

6 

7from __future__ import annotations 

8 

9import signal 

10import subprocess 

11import sys 

12import time 

13from collections.abc import Generator 

14from contextlib import contextmanager 

15from dataclasses import dataclass, field 

16from datetime import datetime 

17from pathlib import Path 

18from types import FrameType 

19 

20from little_loops.config import BRConfig 

21from little_loops.dependency_graph import DependencyGraph 

22from little_loops.git_operations import check_git_status, verify_work_was_done 

23from little_loops.issue_lifecycle import ( 

24 FailureType, 

25 classify_failure, 

26 close_issue, 

27 complete_issue_lifecycle, 

28 create_issue_from_failure, 

29 verify_issue_completed, 

30) 

31from little_loops.issue_parser import IssueInfo, IssueParser, find_issues 

32from little_loops.logger import Logger, format_duration 

33from little_loops.output_parsing import parse_ready_issue_output 

34from little_loops.state import ProcessingState, StateManager 

35from little_loops.subprocess_utils import ( 

36 detect_context_handoff, 

37 read_continuation_prompt, 

38) 

39from little_loops.subprocess_utils import ( 

40 run_claude_command as _run_claude_base, 

41) 

42 

43 

44def _compute_relative_path(abs_path: Path, base_dir: Path | None = None) -> str: 

45 """Compute relative path from base directory for command input. 

46 

47 Used for fallback retry when ready-issue resolves to wrong file - 

48 allows retrying with explicit file path instead of ambiguous ID. 

49 

50 Args: 

51 abs_path: Absolute path to the file 

52 base_dir: Base directory (defaults to cwd) 

53 

54 Returns: 

55 Relative path string suitable for ready-issue command 

56 """ 

57 base = base_dir or Path.cwd() 

58 try: 

59 return str(abs_path.relative_to(base)) 

60 except ValueError: 

61 # Path not relative to base, use absolute 

62 return str(abs_path) 

63 

64 

65@contextmanager 

66def timed_phase( 

67 logger: Logger, 

68 phase_name: str, 

69) -> Generator[dict[str, float], None, None]: 

70 """Context manager for timing phases. 

71 

72 Yields a dict that will be populated with 'elapsed' after the context exits. 

73 

74 Args: 

75 logger: Logger for output 

76 phase_name: Name of the phase being timed 

77 

78 Yields: 

79 Dict that will contain 'elapsed' key after context exits 

80 """ 

81 timing_result: dict[str, float] = {} 

82 start = time.time() 

83 try: 

84 yield timing_result 

85 finally: 

86 elapsed = time.time() - start 

87 timing_result["elapsed"] = elapsed 

88 logger.timing(f"{phase_name} completed in {format_duration(elapsed)}") 

89 

90 

91def run_claude_command( 

92 command: str, 

93 logger: Logger, 

94 timeout: int = 3600, 

95 stream_output: bool = True, 

96 idle_timeout: int = 0, 

97) -> subprocess.CompletedProcess[str]: 

98 """Invoke Claude CLI command with real-time output streaming. 

99 

100 Args: 

101 command: Command to pass to Claude CLI 

102 logger: Logger for output 

103 timeout: Timeout in seconds 

104 stream_output: Whether to stream output to console 

105 idle_timeout: Kill process if no output for this many seconds (0 to disable) 

106 

107 Returns: 

108 CompletedProcess with stdout/stderr captured 

109 """ 

110 logger.info(f"Running: claude --dangerously-skip-permissions -p {command!r}") 

111 

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

113 if stream_output: 

114 if is_stderr: 

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

116 else: 

117 print(f" {line}") 

118 

119 return _run_claude_base( 

120 command=command, 

121 timeout=timeout, 

122 stream_callback=stream_callback if stream_output else None, 

123 idle_timeout=idle_timeout, 

124 ) 

125 

126 

127def run_with_continuation( 

128 initial_command: str, 

129 logger: Logger, 

130 timeout: int = 3600, 

131 stream_output: bool = True, 

132 max_continuations: int = 3, 

133 repo_path: Path | None = None, 

134 idle_timeout: int = 0, 

135) -> subprocess.CompletedProcess[str]: 

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

137 

138 If the command signals CONTEXT_HANDOFF, reads the continuation prompt 

139 and spawns a fresh Claude session to continue the work. 

140 

141 Args: 

142 initial_command: Initial command to run 

143 logger: Logger for output 

144 timeout: Timeout per session in seconds 

145 stream_output: Whether to stream output 

146 max_continuations: Maximum number of continuation attempts 

147 repo_path: Repository root path 

148 idle_timeout: Kill process if no output for this many seconds (0 to disable) 

149 

150 Returns: 

151 Final CompletedProcess result 

152 """ 

153 all_stdout: list[str] = [] 

154 all_stderr: list[str] = [] 

155 current_command = initial_command 

156 continuation_count = 0 

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

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

159 ) 

160 

161 while continuation_count <= max_continuations: 

162 result = run_claude_command( 

163 current_command, 

164 logger, 

165 timeout=timeout, 

166 stream_output=stream_output, 

167 idle_timeout=idle_timeout, 

168 ) 

169 

170 all_stdout.append(result.stdout) 

171 all_stderr.append(result.stderr) 

172 

173 # Check for context handoff signal 

174 if detect_context_handoff(result.stdout): 

175 logger.info("Detected CONTEXT_HANDOFF signal") 

176 

177 # Read continuation prompt 

178 prompt_content = read_continuation_prompt(repo_path) 

179 if not prompt_content: 

180 logger.warning("Context handoff signaled but no continuation prompt found") 

181 break 

182 

183 if continuation_count >= max_continuations: 

184 logger.warning(f"Reached max continuations ({max_continuations}), stopping") 

185 break 

186 

187 continuation_count += 1 

188 logger.info(f"Starting continuation session #{continuation_count}") 

189 

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

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

192 # The skill reads .claude/ll-continue-prompt.md for context. 

193 current_command = f"{initial_command} --resume" 

194 continue 

195 

196 # No handoff signal, we're done 

197 break 

198 

199 return subprocess.CompletedProcess( 

200 args=result.args, 

201 returncode=result.returncode, 

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

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

204 ) 

205 

206 

207def detect_plan_creation(output: str, issue_id: str) -> Path | None: 

208 """Detect if manage-issue created a plan file awaiting approval. 

209 

210 Checks for plan file creation in thoughts/shared/plans/ matching the issue ID. 

211 This happens when manage-issue creates a plan but waits for user approval. 

212 

213 Args: 

214 output: Command stdout (unused, for future pattern matching) 

215 issue_id: Issue ID (e.g., "BUG-280") 

216 

217 Returns: 

218 Path to plan file if created, None otherwise 

219 """ 

220 plans_dir = Path("thoughts/shared/plans") 

221 if not plans_dir.exists(): 

222 return None 

223 

224 # Find plan files matching this issue ID (format: YYYY-MM-DD-ISSUE-ID-*.md) 

225 # Use glob pattern with issue_id 

226 pattern = f"*-{issue_id}-*.md" 

227 matching_plans = list(plans_dir.glob(pattern)) 

228 

229 if not matching_plans: 

230 return None 

231 

232 # Return the most recently modified plan file 

233 # (in case multiple exist, take the latest) 

234 latest_plan = max(matching_plans, key=lambda p: p.stat().st_mtime) 

235 return latest_plan 

236 

237 

238def check_content_markers(issue_path: Path) -> bool: 

239 """Check if issue file content contains implementation markers. 

240 

241 Looks for indicators that an implementation was completed, such as 

242 Resolution sections or status markers added by manage-issue. 

243 

244 Args: 

245 issue_path: Path to the issue file 

246 

247 Returns: 

248 True if implementation markers found 

249 """ 

250 try: 

251 content = issue_path.read_text(encoding="utf-8") 

252 except (OSError, UnicodeDecodeError): 

253 return False 

254 

255 markers = [ 

256 "## Resolution", 

257 "Status: Implemented", 

258 "Status: Completed", 

259 "**Completed**:", 

260 ] 

261 return any(marker in content for marker in markers) 

262 

263 

264@dataclass 

265class IssueProcessingResult: 

266 """Result of processing a single issue in-place.""" 

267 

268 success: bool 

269 duration: float 

270 issue_id: str 

271 was_closed: bool = False 

272 failure_reason: str = "" 

273 corrections: list[str] = field(default_factory=list) 

274 plan_created: bool = False 

275 plan_path: str = "" 

276 

277 

278def process_issue_inplace( 

279 info: IssueInfo, 

280 config: BRConfig, 

281 logger: Logger, 

282 dry_run: bool = False, 

283) -> IssueProcessingResult: 

284 """Process a single issue through the 3-phase workflow in the current working tree. 

285 

286 This is the core processing logic extracted from AutoManager._process_issue(), 

287 suitable for use outside of AutoManager (e.g., single-issue sprint waves). 

288 

289 Args: 

290 info: Issue information 

291 config: Project configuration 

292 logger: Logger for output 

293 dry_run: If True, only preview what would be done 

294 

295 Returns: 

296 IssueProcessingResult with outcome details 

297 """ 

298 issue_start_time = time.time() 

299 corrections: list[str] = [] 

300 

301 logger.header(f"Processing: {info.issue_id} - {info.title}") 

302 

303 issue_timing: dict[str, float] = {} 

304 

305 # Track whether we used fallback path resolution for ready-issue. 

306 validated_via_fallback = False 

307 

308 # Phase 1: Ready/verify the issue 

309 logger.info(f"Phase 1: Verifying issue {info.issue_id}...") 

310 with timed_phase(logger, "Phase 1 (ready-issue)") as phase1_timing: 

311 if not dry_run: 

312 result = run_claude_command( 

313 f"/ll:ready-issue {info.issue_id}", 

314 logger, 

315 timeout=config.automation.timeout_seconds, 

316 stream_output=config.automation.stream_output, 

317 idle_timeout=config.automation.idle_timeout_seconds, 

318 ) 

319 if result.returncode != 0: 

320 logger.warning("ready-issue command failed to execute, continuing anyway...") 

321 else: 

322 # Parse the verdict from the output 

323 parsed = parse_ready_issue_output(result.stdout) 

324 logger.info(f"ready-issue verdict: {parsed['verdict']}") 

325 

326 # Validate that ready-issue analyzed the expected file 

327 validated_path = parsed.get("validated_file_path") 

328 if validated_path: 

329 # Normalize paths for comparison (resolve to absolute) 

330 expected_path = str(info.path.resolve()) 

331 # Handle both absolute and relative paths from ready_issue 

332 validated_resolved = Path(validated_path).resolve() 

333 if str(validated_resolved) != expected_path: 

334 # Check if this is a legitimate rename (new file exists, 

335 # old file doesn't) vs a mismatch error 

336 old_file_exists = info.path.exists() 

337 new_file_exists = validated_resolved.exists() 

338 

339 if new_file_exists and not old_file_exists: 

340 # ready-issue renamed the file - update tracking 

341 logger.info( 

342 f"Issue file renamed: '{info.path.name}' -> " 

343 f"'{validated_resolved.name}'" 

344 ) 

345 info.path = validated_resolved 

346 else: 

347 # Genuine mismatch - attempt fallback with explicit path 

348 logger.warning( 

349 f"Path mismatch: ready-issue validated " 

350 f"'{validated_path}' but expected '{info.path}'" 

351 ) 

352 logger.info( 

353 "Attempting fallback: retrying ready-issue " 

354 "with explicit file path..." 

355 ) 

356 

357 # Compute relative path for the command 

358 relative_path = _compute_relative_path(info.path) 

359 

360 # Retry with explicit path 

361 retry_result = run_claude_command( 

362 f"/ll:ready-issue {relative_path}", 

363 logger, 

364 timeout=config.automation.timeout_seconds, 

365 stream_output=config.automation.stream_output, 

366 idle_timeout=config.automation.idle_timeout_seconds, 

367 ) 

368 

369 if retry_result.returncode != 0: 

370 logger.error(f"Fallback ready-issue failed for {info.issue_id}") 

371 return IssueProcessingResult( 

372 success=False, 

373 duration=time.time() - issue_start_time, 

374 issue_id=info.issue_id, 

375 failure_reason="Fallback failed after path mismatch", 

376 ) 

377 

378 # Re-parse and validate retry output 

379 retry_parsed = parse_ready_issue_output(retry_result.stdout) 

380 retry_validated_path = retry_parsed.get("validated_file_path") 

381 

382 if retry_validated_path: 

383 retry_resolved = Path(retry_validated_path).resolve() 

384 if str(retry_resolved) != str(info.path.resolve()): 

385 logger.error( 

386 f"Fallback still mismatched: " 

387 f"got '{retry_validated_path}', " 

388 f"expected '{info.path}'" 

389 ) 

390 return IssueProcessingResult( 

391 success=False, 

392 duration=time.time() - issue_start_time, 

393 issue_id=info.issue_id, 

394 failure_reason="Path mismatch persisted after fallback", 

395 ) 

396 

397 # Fallback succeeded - use retry result 

398 logger.info("Fallback succeeded: validated correct file") 

399 parsed = retry_parsed 

400 validated_via_fallback = True 

401 

402 # Log and store any corrections made 

403 if parsed.get("was_corrected"): 

404 logger.info(f"Issue {info.issue_id} was auto-corrected") 

405 phase_corrections = parsed.get("corrections", []) 

406 for correction in phase_corrections: 

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

408 if phase_corrections: 

409 corrections.extend(phase_corrections) 

410 

411 # Log any concerns found 

412 if parsed["concerns"]: 

413 for concern in parsed["concerns"]: 

414 logger.warning(f" Concern: {concern}") 

415 

416 # Handle CLOSE verdict - issue should not be implemented 

417 if parsed.get("should_close"): 

418 close_reason = parsed.get("close_reason", "unknown") 

419 logger.info(f"Issue {info.issue_id} should be closed (reason: {close_reason})") 

420 

421 # CRITICAL: Skip file operations for invalid references 

422 if close_reason == "invalid_ref": 

423 logger.warning( 

424 f"Skipping {info.issue_id}: invalid reference - " 

425 "no matching issue file exists" 

426 ) 

427 return IssueProcessingResult( 

428 success=False, 

429 duration=time.time() - issue_start_time, 

430 issue_id=info.issue_id, 

431 failure_reason=f"Invalid reference: {close_reason}", 

432 corrections=corrections, 

433 ) 

434 

435 # Also require validated_file_path to match before closing 

436 close_validated_path = parsed.get("validated_file_path") 

437 if not close_validated_path: 

438 logger.warning( 

439 f"Skipping close for {info.issue_id}: " 

440 "ready-issue did not return validated file path" 

441 ) 

442 return IssueProcessingResult( 

443 success=False, 

444 duration=time.time() - issue_start_time, 

445 issue_id=info.issue_id, 

446 failure_reason="CLOSE without validated file path", 

447 corrections=corrections, 

448 ) 

449 

450 if close_issue( 

451 info, 

452 config, 

453 logger, 

454 close_reason, 

455 parsed.get("close_status"), 

456 ): 

457 return IssueProcessingResult( 

458 success=True, 

459 duration=time.time() - issue_start_time, 

460 issue_id=info.issue_id, 

461 was_closed=True, 

462 corrections=corrections, 

463 ) 

464 else: 

465 return IssueProcessingResult( 

466 success=False, 

467 duration=time.time() - issue_start_time, 

468 issue_id=info.issue_id, 

469 failure_reason=f"CLOSE failed: {parsed.get('close_status', 'unknown')}", 

470 corrections=corrections, 

471 ) 

472 

473 # Check if issue is NOT READY (and not closeable) 

474 if not parsed["is_ready"]: 

475 logger.error( 

476 f"Issue {info.issue_id} is NOT READY for implementation " 

477 f"(verdict: {parsed['verdict']})" 

478 ) 

479 return IssueProcessingResult( 

480 success=False, 

481 duration=time.time() - issue_start_time, 

482 issue_id=info.issue_id, 

483 failure_reason=( 

484 f"NOT READY: {parsed['verdict']} - {len(parsed['concerns'])} concern(s)" 

485 ), 

486 corrections=corrections, 

487 ) 

488 

489 # Log if proceeding with corrected issue 

490 if parsed.get("was_corrected"): 

491 logger.success(f"Issue {info.issue_id} corrected and ready for implementation") 

492 else: 

493 logger.info(f"Would run: /ll:ready-issue {info.issue_id}") 

494 issue_timing["ready"] = phase1_timing.get("elapsed", 0.0) 

495 

496 # Phase 2: Implement the issue (with automatic continuation on context handoff) 

497 action = config.get_category_action(info.issue_type) 

498 logger.info(f"Phase 2: Implementing {info.issue_id}...") 

499 with timed_phase(logger, "Phase 2 (implement)") as phase2_timing: 

500 if not dry_run: 

501 # Build manage-issue command 

502 type_name = info.issue_type.rstrip("s") # bugs -> bug 

503 

504 # Use relative path if fallback was used, otherwise use issue_id 

505 if validated_via_fallback: 

506 issue_arg = _compute_relative_path(info.path) 

507 else: 

508 issue_arg = info.issue_id 

509 

510 # Use run_with_continuation to handle context exhaustion 

511 result = run_with_continuation( 

512 f"/ll:manage-issue {type_name} {action} {issue_arg}", 

513 logger, 

514 timeout=config.automation.timeout_seconds, 

515 stream_output=config.automation.stream_output, 

516 max_continuations=config.automation.max_continuations, 

517 repo_path=config.repo_path, 

518 idle_timeout=config.automation.idle_timeout_seconds, 

519 ) 

520 else: 

521 logger.info(f"Would run: /ll:manage-issue {info.issue_type} {action} {info.issue_id}") 

522 result = subprocess.CompletedProcess(args=[], returncode=0) 

523 issue_timing["implement"] = phase2_timing.get("elapsed", 0.0) 

524 

525 # Handle implementation failure 

526 if result.returncode != 0: 

527 error_output = result.stderr or result.stdout or "Unknown error" 

528 failure_type, failure_reason_text = classify_failure(error_output, result.returncode) 

529 

530 if failure_type == FailureType.TRANSIENT: 

531 # Transient failure - log but don't create bug issue 

532 logger.warning(f"Transient failure for {info.issue_id}: {failure_reason_text}") 

533 logger.warning("Not creating bug issue - this is a temporary error") 

534 logger.info("Error output (first 500 chars):") 

535 logger.info(error_output[:500]) 

536 

537 return IssueProcessingResult( 

538 success=False, 

539 duration=time.time() - issue_start_time, 

540 issue_id=info.issue_id, 

541 failure_reason=f"Transient: {failure_reason_text}", 

542 corrections=corrections, 

543 ) 

544 

545 # Real failure - create issue as before 

546 logger.error(f"Implementation failed for {info.issue_id}") 

547 

548 failure_reason = "" 

549 if not dry_run: 

550 # Create new issue for the failure 

551 new_issue = create_issue_from_failure( 

552 error_output, 

553 info, 

554 config, 

555 logger, 

556 ) 

557 failure_reason = str(new_issue) if new_issue else error_output 

558 else: 

559 logger.info("Would create new bug issue for this failure") 

560 

561 return IssueProcessingResult( 

562 success=False, 

563 duration=time.time() - issue_start_time, 

564 issue_id=info.issue_id, 

565 failure_reason=failure_reason, 

566 corrections=corrections, 

567 ) 

568 

569 # Phase 3: Verify completion 

570 logger.info(f"Phase 3: Verifying {info.issue_id} completion...") 

571 verified = False 

572 with timed_phase(logger, "Phase 3 (verify)") as phase3_timing: 

573 if not dry_run: 

574 verified = verify_issue_completed(info, config, logger) 

575 

576 # Fallback: Only complete lifecycle if: 

577 # 1. Command returned success (returncode 0) 

578 # 2. File wasn't moved to completed 

579 # 3. There's EVIDENCE of actual work being done (code changes) 

580 if not verified and result.returncode == 0: 

581 # Check if a plan was created awaiting approval 

582 plan_path = detect_plan_creation(result.stdout, info.issue_id) 

583 if plan_path is not None: 

584 logger.info( 

585 f"Plan created at {plan_path}, awaiting approval - " 

586 "issue will remain incomplete until plan is approved and implemented" 

587 ) 

588 return IssueProcessingResult( 

589 success=False, 

590 duration=time.time() - issue_start_time, 

591 issue_id=info.issue_id, 

592 plan_created=True, 

593 plan_path=str(plan_path), 

594 failure_reason="", # Not a failure - plan awaiting approval 

595 corrections=corrections, 

596 ) 

597 

598 logger.info( 

599 "Command returned success but issue not moved - " 

600 "checking for evidence of work..." 

601 ) 

602 

603 # Check issue file content for implementation markers 

604 if check_content_markers(info.path): 

605 logger.info( 

606 "Implementation markers found in issue file - completing lifecycle..." 

607 ) 

608 verified = complete_issue_lifecycle(info, config, logger) 

609 if verified: 

610 logger.success(f"Content marker completion succeeded for {info.issue_id}") 

611 else: 

612 logger.warning(f"Content marker completion failed for {info.issue_id}") 

613 else: 

614 # CRITICAL: Verify actual implementation work was done 

615 work_done = verify_work_was_done(logger) 

616 if work_done: 

617 logger.info("Evidence of code changes found - completing lifecycle...") 

618 verified = complete_issue_lifecycle(info, config, logger) 

619 if verified: 

620 logger.success(f"Fallback completion succeeded for {info.issue_id}") 

621 else: 

622 logger.warning(f"Fallback completion failed for {info.issue_id}") 

623 else: 

624 # NO work was done - do NOT mark as completed 

625 logger.error( 

626 f"REFUSING to mark {info.issue_id} as completed: " 

627 "no code changes detected despite returncode 0" 

628 ) 

629 logger.error( 

630 "This likely indicates the command was not executed " 

631 "properly. Check command invocation and Claude CLI " 

632 "output." 

633 ) 

634 verified = False 

635 else: 

636 logger.info("Would verify issue moved to completed") 

637 verified = True # In dry run, assume success 

638 issue_timing["verify"] = phase3_timing.get("elapsed", 0.0) 

639 

640 # Record timing 

641 total_issue_time = time.time() - issue_start_time 

642 issue_timing["total"] = total_issue_time 

643 logger.timing(f"Total processing time: {format_duration(total_issue_time)}") 

644 

645 if verified: 

646 logger.success(f"Completed: {info.issue_id}") 

647 else: 

648 logger.warning(f"Issue {info.issue_id} was attempted but verification failed") 

649 logger.info("This issue will be skipped on future runs (check logs above for details)") 

650 

651 return IssueProcessingResult( 

652 success=verified, 

653 duration=total_issue_time, 

654 issue_id=info.issue_id, 

655 corrections=corrections, 

656 ) 

657 

658 

659class AutoManager: 

660 """Automated issue manager for sequential processing. 

661 

662 Processes issues in priority order using Claude CLI commands, 

663 with state persistence for resume capability. 

664 """ 

665 

666 def __init__( 

667 self, 

668 config: BRConfig, 

669 dry_run: bool = False, 

670 max_issues: int = 0, 

671 resume: bool = False, 

672 category: str | None = None, 

673 only_ids: set[str] | None = None, 

674 skip_ids: set[str] | None = None, 

675 type_prefixes: set[str] | None = None, 

676 verbose: bool = True, 

677 ) -> None: 

678 """Initialize the auto manager. 

679 

680 Args: 

681 config: Project configuration 

682 dry_run: If True, only preview what would be done 

683 max_issues: Maximum issues to process (0 = unlimited) 

684 resume: Whether to resume from previous state 

685 category: Optional category to filter (e.g., "bugs") 

686 only_ids: If provided, only process these issue IDs 

687 skip_ids: Issue IDs to skip (in addition to attempted issues) 

688 type_prefixes: If provided, only process issues with these type prefixes 

689 verbose: Whether to output progress messages 

690 """ 

691 self.config = config 

692 self.dry_run = dry_run 

693 self.max_issues = max_issues 

694 self.resume = resume 

695 self.category = category 

696 self.only_ids = only_ids 

697 self.skip_ids = skip_ids or set() 

698 self.type_prefixes = type_prefixes 

699 

700 self.logger = Logger(verbose=verbose) 

701 self.state_manager = StateManager(config.get_state_file(), self.logger) 

702 self.parser = IssueParser(config) 

703 

704 # Build dependency graph for dependency-aware sequencing (ENH-016) 

705 # Note: don't filter by type here — we need all issues for dependency resolution 

706 all_issues = find_issues(self.config, self.category) 

707 all_known_ids: set[str] | None = None 

708 try: 

709 from little_loops.dependency_mapper import gather_all_issue_ids 

710 

711 issues_dir = config.project_root / config.issues.base_dir 

712 all_known_ids = gather_all_issue_ids(issues_dir, config=config) 

713 except (AttributeError, TypeError): 

714 pass 

715 self.dep_graph = DependencyGraph.from_issues(all_issues, all_known_ids=all_known_ids) 

716 

717 # Warn about any cycles 

718 if self.dep_graph.has_cycles(): 

719 cycles = self.dep_graph.detect_cycles() 

720 for cycle in cycles: 

721 self.logger.warning(f"Dependency cycle detected: {' -> '.join(cycle)}") 

722 

723 self.processed_count = 0 

724 self._shutdown_requested = False 

725 

726 signal.signal(signal.SIGINT, self._signal_handler) 

727 signal.signal(signal.SIGTERM, self._signal_handler) 

728 

729 def _signal_handler(self, signum: int, frame: FrameType | None) -> None: 

730 """Handle shutdown signals gracefully.""" 

731 self._shutdown_requested = True 

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

733 

734 def _get_next_issue(self) -> IssueInfo | None: 

735 """Get next issue respecting dependencies. 

736 

737 Returns the highest priority issue whose blockers have all been 

738 completed. If no ready issues exist but blocked issues remain, 

739 logs warnings about what is blocking progress. 

740 

741 Returns: 

742 Next IssueInfo to process, or None if no ready issues 

743 """ 

744 # Get completed issues from state 

745 completed = set(self.state_manager.state.completed_issues) 

746 

747 # Combine skip_ids from state and CLI argument 

748 skip_ids = self.state_manager.state.attempted_issues | self.skip_ids 

749 

750 # Get issues that are ready (blockers satisfied) 

751 ready_issues = self.dep_graph.get_ready_issues(completed) 

752 

753 # Filter by skip_ids, only_ids, type_prefixes 

754 candidates = [ 

755 i 

756 for i in ready_issues 

757 if i.issue_id not in skip_ids 

758 and (self.only_ids is None or i.issue_id in self.only_ids) 

759 and (self.type_prefixes is None or i.issue_id.split("-", 1)[0] in self.type_prefixes) 

760 ] 

761 

762 if candidates: 

763 return candidates[0] # Already sorted by priority in get_ready_issues() 

764 

765 # No ready candidates - check if there are blocked issues remaining 

766 all_in_graph = set(self.dep_graph.issues.keys()) 

767 remaining = all_in_graph - completed - skip_ids 

768 if self.only_ids is not None: 

769 remaining = remaining & self.only_ids 

770 if self.type_prefixes is not None: 

771 remaining = {r for r in remaining if r.split("-", 1)[0] in self.type_prefixes} 

772 

773 if remaining: 

774 self._log_blocked_issues(remaining, completed) 

775 

776 return None 

777 

778 def _log_blocked_issues(self, remaining: set[str], completed: set[str]) -> None: 

779 """Log information about blocked issues when processing stalls. 

780 

781 Args: 

782 remaining: Set of issue IDs that haven't been processed 

783 completed: Set of completed issue IDs 

784 """ 

785 blocked_count = 0 

786 for issue_id in sorted(remaining): 

787 blockers = self.dep_graph.get_blocking_issues(issue_id, completed) 

788 if blockers: 

789 blocked_count += 1 

790 self.logger.info(f" {issue_id} blocked by: {', '.join(sorted(blockers))}") 

791 

792 if blocked_count > 0: 

793 self.logger.warning(f"{blocked_count} issue(s) remain blocked - check dependencies") 

794 

795 def run(self) -> int: 

796 """Run the automation loop. 

797 

798 Returns: 

799 Exit code (0 = success) 

800 """ 

801 run_start_time = time.time() 

802 self.logger.info("Starting automated issue management...") 

803 

804 if self.dry_run: 

805 self.logger.info("DRY RUN MODE - No actual changes will be made") 

806 

807 if not self.dry_run: 

808 has_changes = check_git_status(self.logger) 

809 if has_changes: 

810 self.logger.warning("Proceeding anyway...") 

811 

812 # Load or initialize state 

813 if self.resume: 

814 state = self.state_manager.load() 

815 if state: 

816 self.logger.info(f"Resuming from: {state.current_issue}") 

817 self.processed_count = len(state.completed_issues) 

818 else: 

819 # Fresh start 

820 self.state_manager._state = ProcessingState(timestamp=datetime.now().isoformat()) 

821 

822 try: 

823 while not self._shutdown_requested: 

824 if self.max_issues > 0 and self.processed_count >= self.max_issues: 

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

826 break 

827 

828 info = self._get_next_issue() 

829 if not info: 

830 self.logger.success("No more issues to process!") 

831 break 

832 

833 success = self._process_issue(info) 

834 if success: 

835 self.processed_count += 1 

836 

837 except Exception as e: 

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

839 return 1 

840 

841 finally: 

842 if not self._shutdown_requested: 

843 self.state_manager.cleanup() 

844 

845 self._log_timing_summary(run_start_time) 

846 self.logger.success(f"Processed {self.processed_count} issue(s)") 

847 return 0 

848 

849 def _log_timing_summary(self, run_start_time: float) -> None: 

850 """Log aggregate timing summary.""" 

851 total_run_time = time.time() - run_start_time 

852 

853 self.logger.info("") 

854 self.logger.header("PROCESSING SUMMARY") 

855 self.logger.timing(f"Total run time: {format_duration(total_run_time)}") 

856 self.logger.timing(f"Issues processed: {self.processed_count}") 

857 

858 state = self.state_manager.state 

859 if state.timing: 

860 total_times = [t.get("total", 0) for t in state.timing.values()] 

861 if total_times: 

862 avg_time = sum(total_times) / len(total_times) 

863 self.logger.timing(f"Average per issue: {format_duration(avg_time)}") 

864 

865 if state.failed_issues: 

866 self.logger.warning(f"Failed issues: {len(state.failed_issues)}") 

867 for issue_id, reason in state.failed_issues.items(): 

868 self.logger.warning(f" - {issue_id}: {reason[:50]}...") 

869 

870 # Log correction statistics for quality tracking 

871 if state.corrections: 

872 total_corrected = len(state.corrections) 

873 total_issues = len(state.completed_issues) + len(state.failed_issues) 

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

875 self.logger.info( 

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

877 ) 

878 

879 # Log most common correction types 

880 from collections import Counter 

881 

882 all_corrections: list[str] = [] 

883 for corrections in state.corrections.values(): 

884 all_corrections.extend(corrections) 

885 if all_corrections: 

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

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

888 for correction, count in common: 

889 # Truncate long correction descriptions 

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

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

892 

893 def _process_issue(self, info: IssueInfo) -> bool: 

894 """Process a single issue through the workflow. 

895 

896 Delegates to process_issue_inplace() and maps the result back 

897 to state manager calls. 

898 

899 Args: 

900 info: Issue information 

901 

902 Returns: 

903 True if processing succeeded 

904 """ 

905 # Pre-processing state updates (before delegating) 

906 self.state_manager.mark_attempted(info.issue_id, save=False) 

907 self.state_manager.update_current(str(info.path), "processing") 

908 

909 result = process_issue_inplace(info, self.config, self.logger, self.dry_run) 

910 

911 # Map result back to state tracking 

912 if result.was_closed: 

913 self.state_manager.mark_completed(info.issue_id) 

914 elif result.success: 

915 self.state_manager.mark_completed(info.issue_id, {"total": result.duration}) 

916 elif result.plan_created: 

917 # Don't mark as failed if a plan was created (awaiting approval) 

918 self.logger.info( 

919 f"{info.issue_id} has plan at {result.plan_path} - " 

920 "leaving in pending state for manual approval" 

921 ) 

922 # Issue remains in pending state (not marked as failed) 

923 elif result.failure_reason: 

924 self.state_manager.mark_failed(info.issue_id, result.failure_reason) 

925 

926 if result.corrections: 

927 self.state_manager.record_corrections(info.issue_id, result.corrections) 

928 

929 return result.success