Coverage for little_loops / issue_lifecycle.py: 11%

269 statements  

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

1"""Issue lifecycle management for little-loops. 

2 

3Provides functions for closing, completing, and verifying issue completion, 

4as well as creating new issues from implementation failures. 

5 

6Also provides failure classification to distinguish transient errors 

7(API quota, network issues, timeouts) from real implementation failures. 

8""" 

9 

10from __future__ import annotations 

11 

12import re 

13import subprocess 

14from datetime import datetime 

15from enum import Enum 

16from pathlib import Path 

17 

18from little_loops.config import BRConfig 

19from little_loops.issue_parser import IssueInfo, IssueParser, get_next_issue_number, slugify 

20from little_loops.logger import Logger 

21from little_loops.session_log import append_session_log_entry 

22 

23# ============================================================================= 

24# Failure Classification 

25# ============================================================================= 

26 

27 

28class FailureType(Enum): 

29 """Classification of command failure types. 

30 

31 Used to distinguish between transient errors that should not 

32 create bug issues and real implementation failures that should. 

33 """ 

34 

35 TRANSIENT = "transient" # Temporary error, don't create issue 

36 REAL = "real" # Actual bug/error, create issue 

37 

38 

39def classify_failure(error_output: str, returncode: int) -> tuple[FailureType, str]: 

40 """Classify a command failure as transient or real. 

41 

42 Examines error output for patterns indicating transient failures 

43 (API quota, network errors, timeouts) vs real implementation failures. 

44 

45 Args: 

46 error_output: stderr or stdout from failed command 

47 returncode: Process exit code (available for future use) 

48 

49 Returns: 

50 Tuple of (failure_type, reason) where reason explains the classification 

51 """ 

52 error_lower = error_output.lower() 

53 

54 # API quota/rate limit patterns 

55 quota_patterns = [ 

56 "out of extra usage", 

57 "rate limit", 

58 "quota exceeded", 

59 "too many requests", 

60 "api limit", 

61 "usage limit", 

62 "429", # HTTP Too Many Requests 

63 "resource exhausted", 

64 "resourceexhausted", # No space variant (gRPC style) 

65 ] 

66 if any(pattern in error_lower for pattern in quota_patterns): 

67 return (FailureType.TRANSIENT, "API quota or rate limit exceeded") 

68 

69 # Network/connectivity patterns 

70 # Note: Use word boundaries where needed to avoid false positives 

71 # (e.g., "enotfound" shouldn't match "ModuleNotFoundError") 

72 network_patterns = [ 

73 "connection refused", 

74 "connection timeout", 

75 "network error", 

76 "dns resolution", 

77 "connection reset", 

78 "service unavailable", 

79 "502 bad gateway", 

80 "503 service unavailable", 

81 "504 gateway timeout", 

82 ] 

83 if any(pattern in error_lower for pattern in network_patterns): 

84 return (FailureType.TRANSIENT, "Network or connectivity error") 

85 

86 # Check for Node.js-style error codes with word boundary awareness 

87 # These are typically at word boundaries (e.g., "Error: ECONNREFUSED") 

88 if re.search(r"\beconnrefused\b", error_lower): 

89 return (FailureType.TRANSIENT, "Network or connectivity error") 

90 if re.search(r"\benotfound\b", error_lower): 

91 return (FailureType.TRANSIENT, "Network or connectivity error") 

92 if re.search(r"\betimedout\b", error_lower): 

93 return (FailureType.TRANSIENT, "Network or connectivity error") 

94 

95 # Timeout patterns 

96 timeout_patterns = [ 

97 "timeout", 

98 "timed out", 

99 "deadline exceeded", 

100 "operation timed out", 

101 ] 

102 if any(pattern in error_lower for pattern in timeout_patterns): 

103 return (FailureType.TRANSIENT, "Command timeout") 

104 

105 # Resource/system transient patterns 

106 resource_patterns = [ 

107 "disk full", 

108 "no space left", 

109 "resource temporarily unavailable", 

110 "too many open files", 

111 "memory allocation failed", 

112 "out of memory", 

113 ] 

114 if any(pattern in error_lower for pattern in resource_patterns): 

115 return (FailureType.TRANSIENT, "System resource error") 

116 

117 # Default: treat as real failure 

118 return (FailureType.REAL, "Implementation error") 

119 

120 

121# ============================================================================= 

122# Content Manipulation Helpers 

123# ============================================================================= 

124 

125 

126def _build_closure_resolution( 

127 close_status: str, 

128 close_reason: str, 

129 fix_commit: str | None = None, 

130 files_changed: list[str] | None = None, 

131) -> str: 

132 """Build resolution section for closed issues. 

133 

134 Args: 

135 close_status: Status text (e.g., "Closed - Already Fixed") 

136 close_reason: Reason code (e.g., "already_fixed", "invalid_ref") 

137 fix_commit: SHA of the commit that fixed the issue (for regression tracking) 

138 files_changed: List of files modified by the fix (for regression tracking) 

139 

140 Returns: 

141 Resolution section markdown string 

142 """ 

143 # Build fix commit line 

144 fix_commit_line = f"- **Fix Commit**: {fix_commit}\n" if fix_commit else "" 

145 

146 # Build files changed section 

147 if files_changed: 

148 files_list = "\n".join(f" - `{f}`" for f in files_changed) 

149 files_section = f""" 

150### Files Changed 

151{files_list} 

152""" 

153 else: 

154 files_section = "" 

155 

156 return f""" 

157 

158--- 

159 

160## Resolution 

161 

162- **Status**: {close_status} 

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

164- **Reason**: {close_reason} 

165- **Closure**: Automated (ready-issue validation) 

166{fix_commit_line} 

167### Closure Notes 

168Issue was automatically closed during validation. 

169The issue was determined to be invalid, already resolved, or not actionable. 

170{files_section}""" 

171 

172 

173def _build_completion_resolution( 

174 action: str, 

175 fix_commit: str | None = None, 

176 files_changed: list[str] | None = None, 

177) -> str: 

178 """Build resolution section for completed issues. 

179 

180 Args: 

181 action: Action verb (e.g., "fix", "implement") 

182 fix_commit: SHA of the commit that fixed the issue (for regression tracking) 

183 files_changed: List of files modified by the fix (for regression tracking) 

184 

185 Returns: 

186 Resolution section markdown string 

187 """ 

188 # Build fix commit line 

189 fix_commit_line = f"- **Fix Commit**: {fix_commit}" if fix_commit else "" 

190 

191 # Build files changed section 

192 if files_changed: 

193 files_list = "\n".join(f" - `{f}`" for f in files_changed) 

194 files_section = f""" 

195### Files Changed 

196{files_list}""" 

197 else: 

198 files_section = """ 

199### Files Changed 

200- See git history for details""" 

201 

202 return f""" 

203 

204--- 

205 

206## Resolution 

207 

208- **Action**: {action} 

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

210- **Status**: Completed (automated fallback) 

211- **Implementation**: Command exited early but issue was addressed 

212{fix_commit_line} 

213{files_section} 

214 

215### Verification Results 

216- Automated verification passed 

217 

218### Commits 

219- See git log for details 

220""" 

221 

222 

223def _prepare_issue_content(original_path: Path, resolution: str) -> str: 

224 """Read issue file and append resolution section if needed. 

225 

226 Args: 

227 original_path: Path to the original issue file 

228 resolution: Resolution section to append 

229 

230 Returns: 

231 Updated file content with resolution section 

232 """ 

233 content = original_path.read_text() 

234 if "## Resolution" not in content: 

235 content += resolution 

236 return content 

237 

238 

239# ============================================================================= 

240# Git Operations Helpers 

241# ============================================================================= 

242 

243 

244def _is_git_tracked(file_path: Path) -> bool: 

245 """Check if a file is under git version control. 

246 

247 Args: 

248 file_path: Path to the file to check 

249 

250 Returns: 

251 True if file is tracked by git, False otherwise 

252 """ 

253 try: 

254 result = subprocess.run( 

255 ["git", "ls-files", str(file_path)], 

256 capture_output=True, 

257 text=True, 

258 timeout=30, 

259 ) 

260 except subprocess.TimeoutExpired: 

261 return False 

262 return bool(result.stdout.strip()) 

263 

264 

265def _cleanup_stale_source(original_path: Path, issue_id: str, logger: Logger) -> None: 

266 """Remove orphaned source file and commit cleanup. 

267 

268 Args: 

269 original_path: Path to the stale source file 

270 issue_id: Issue identifier for commit message 

271 logger: Logger for output 

272 """ 

273 original_path.unlink() 

274 try: 

275 subprocess.run(["git", "add", "-A"], capture_output=True, text=True, timeout=30) 

276 subprocess.run( 

277 ["git", "commit", "-m", f"cleanup: remove stale {issue_id} from bugs/"], 

278 capture_output=True, 

279 text=True, 

280 timeout=30, 

281 ) 

282 except subprocess.TimeoutExpired: 

283 logger.warning(f"Git command timed out during cleanup of {issue_id}") 

284 

285 

286def _move_issue_to_completed( 

287 original_path: Path, 

288 completed_path: Path, 

289 content: str, 

290 logger: Logger, 

291) -> bool: 

292 """Move issue file to completed dir, preferring git mv for history. 

293 

294 Checks if source is under git version control before attempting git mv. 

295 If source is tracked, uses git mv for history preservation. 

296 If source is not tracked, uses manual copy + delete directly. 

297 

298 Args: 

299 original_path: Source path of issue file 

300 completed_path: Destination path in completed directory 

301 content: Updated file content to write 

302 logger: Logger for output 

303 

304 Returns: 

305 True if move succeeded 

306 """ 

307 # Handle pre-existing destination (e.g., from parallel worker or worktree leak) 

308 if completed_path.exists(): 

309 logger.info(f"Destination already exists: {completed_path.name}, updating content") 

310 completed_path.write_text(content) 

311 original_path.unlink(missing_ok=True) 

312 return True 

313 

314 # Check if source is under git version control before attempting git mv 

315 source_tracked = _is_git_tracked(original_path) 

316 

317 if source_tracked: 

318 # Source is tracked, use git mv for history preservation 

319 try: 

320 result = subprocess.run( 

321 ["git", "mv", str(original_path), str(completed_path)], 

322 capture_output=True, 

323 text=True, 

324 timeout=30, 

325 ) 

326 except subprocess.TimeoutExpired: 

327 logger.warning("git mv timed out, falling back to manual copy") 

328 completed_path.write_text(content) 

329 original_path.unlink(missing_ok=True) 

330 return True 

331 

332 if result.returncode != 0: 

333 # git mv failed, fall back to manual copy + delete 

334 logger.warning(f"git mv failed: {result.stderr}") 

335 completed_path.write_text(content) 

336 original_path.unlink(missing_ok=True) 

337 else: 

338 logger.success(f"Used git mv to move {original_path.stem}") 

339 # Write updated content to the moved file 

340 completed_path.write_text(content) 

341 else: 

342 # Source is not tracked, use manual copy + delete directly 

343 logger.info(f"Source not tracked by git, using manual copy: {original_path.name}") 

344 completed_path.write_text(content) 

345 original_path.unlink(missing_ok=True) 

346 

347 return True 

348 

349 

350def _commit_issue_completion( 

351 info: IssueInfo, 

352 commit_prefix: str, 

353 commit_body: str, 

354 logger: Logger, 

355) -> bool: 

356 """Stage all changes and create completion commit. 

357 

358 Args: 

359 info: Issue information 

360 commit_prefix: Prefix for commit message (e.g., "close" or action verb) 

361 commit_body: Body text for commit message 

362 logger: Logger for output 

363 

364 Returns: 

365 True if commit succeeded or nothing to commit 

366 """ 

367 # Stage all changes 

368 try: 

369 stage_result = subprocess.run( 

370 ["git", "add", "-A"], 

371 capture_output=True, 

372 text=True, 

373 timeout=30, 

374 ) 

375 if stage_result.returncode != 0: 

376 logger.warning(f"git add failed: {stage_result.stderr}") 

377 except subprocess.TimeoutExpired: 

378 logger.warning("git add timed out") 

379 

380 # Create commit 

381 commit_msg = f"{commit_prefix}({info.issue_type}): {commit_body}" 

382 try: 

383 commit_result = subprocess.run( 

384 ["git", "commit", "-m", commit_msg], 

385 capture_output=True, 

386 text=True, 

387 timeout=30, 

388 ) 

389 except subprocess.TimeoutExpired: 

390 logger.warning("git commit timed out") 

391 return True 

392 

393 if commit_result.returncode != 0: 

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

395 logger.info("No changes to commit (already committed)") 

396 else: 

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

398 else: 

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

400 if commit_hash_match: 

401 logger.success(f"Committed: {commit_hash_match.group(1)}") 

402 else: 

403 logger.success("Committed changes") 

404 

405 return True 

406 

407 

408def verify_issue_completed(info: IssueInfo, config: BRConfig, logger: Logger) -> bool: 

409 """Verify that an issue was moved to completed directory. 

410 

411 Args: 

412 info: Issue info 

413 config: Project configuration 

414 logger: Logger for output 

415 

416 Returns: 

417 True if issue is in completed directory 

418 """ 

419 completed_path = config.get_completed_dir() / info.path.name 

420 original_path = info.path 

421 

422 if completed_path.exists() and not original_path.exists(): 

423 logger.success(f"Verified: {info.issue_id} properly moved to completed") 

424 return True 

425 

426 if completed_path.exists() and original_path.exists(): 

427 logger.warning(f"Warning: {info.issue_id} exists in BOTH locations") 

428 

429 if not original_path.exists(): 

430 logger.warning(f"Warning: {info.issue_id} was deleted but not moved to completed") 

431 return True 

432 

433 logger.warning(f"Warning: {info.issue_id} was NOT moved to completed") 

434 return False 

435 

436 

437def create_issue_from_failure( 

438 error_output: str, 

439 parent_info: IssueInfo, 

440 config: BRConfig, 

441 logger: Logger, 

442) -> Path | None: 

443 """Create a new bug issue file when implementation fails. 

444 

445 Args: 

446 error_output: Error output from the failed command 

447 parent_info: Info about the issue that failed 

448 config: Project configuration 

449 logger: Logger for output 

450 

451 Returns: 

452 Path to new issue file, or None if creation failed 

453 """ 

454 bug_num = get_next_issue_number(config, "bugs") 

455 prefix = config.get_issue_prefix("bugs") 

456 bug_id = f"{prefix}-{bug_num:03d}" 

457 

458 # Try to extract meaningful error info 

459 error_lines = error_output.split("\n")[:20] # First 20 lines 

460 traceback = "\n".join(error_lines) 

461 

462 # Generate title from error 

463 title = f"Implementation failure in {parent_info.issue_id}" 

464 if "Error" in error_output: 

465 error_match = re.search(r"([A-Z]\w+Error[:\s]+[^\n]+)", error_output) 

466 if error_match: 

467 title = error_match.group(1) 

468 title_slug = slugify(title) 

469 

470 filename = f"P1-{bug_id}-{title_slug}.md" 

471 bugs_dir = config.get_issue_dir("bugs") 

472 new_issue_path = bugs_dir / filename 

473 

474 content = f"""# {bug_id}: Implementation Failure - {parent_info.issue_id} 

475 

476## Summary 

477Issue encountered during automated implementation of {parent_info.issue_id}. 

478 

479## Current Behavior 

480``` 

481{traceback} 

482``` 

483 

484## Expected Behavior 

485Implementation should complete without errors. 

486 

487## Root Cause 

488Discovered during automated processing of `{parent_info.path}`. 

489 

490## Steps to Reproduce 

4911. Run: `/ll:manage-issue {parent_info.issue_type} fix {parent_info.issue_id}` 

4922. Observe error 

493 

494## Proposed Solution 

495Investigate the error output above and address the root cause. 

496 

497## Impact 

498- **Severity**: High 

499- **Effort**: Unknown 

500- **Risk**: Medium 

501- **Breaking Change**: No 

502 

503## Labels 

504`bug`, `high-priority`, `auto-generated`, `implementation-failure` 

505 

506--- 

507 

508## Status 

509**Open** | Created: {datetime.now().isoformat()} | Priority: P1 

510 

511## Related Issues 

512- [{parent_info.issue_id}]({parent_info.path}) 

513""" 

514 

515 try: 

516 bugs_dir.mkdir(parents=True, exist_ok=True) 

517 new_issue_path.write_text(content) 

518 logger.success(f"Created new issue: {new_issue_path}") 

519 return new_issue_path 

520 except Exception as e: 

521 logger.error(f"Failed to create issue: {e}") 

522 return None 

523 

524 

525def close_issue( 

526 info: IssueInfo, 

527 config: BRConfig, 

528 logger: Logger, 

529 close_reason: str | None, 

530 close_status: str | None, 

531 fix_commit: str | None = None, 

532 files_changed: list[str] | None = None, 

533) -> bool: 

534 """Close an issue by moving it to completed with closure status. 

535 

536 Used when ready-issue determines an issue should not be implemented 

537 (e.g., already fixed, invalid, duplicate). 

538 

539 Args: 

540 info: Issue info 

541 config: Project configuration 

542 logger: Logger for output 

543 close_reason: Reason code (e.g., "already_fixed", "invalid_ref") 

544 close_status: Status text (e.g., "Closed - Already Fixed") 

545 fix_commit: SHA of the commit that fixed the issue (for regression tracking) 

546 files_changed: List of files modified by the fix (for regression tracking) 

547 

548 Returns: 

549 True if successful, False otherwise 

550 """ 

551 completed_dir = config.get_completed_dir() 

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

553 

554 original_path = info.path 

555 completed_path = completed_dir / original_path.name 

556 

557 # Safety checks - handle stale state gracefully 

558 if completed_path.exists(): 

559 logger.info(f"{info.issue_id} already in completed/ - cleaning up source") 

560 if original_path.exists(): 

561 _cleanup_stale_source(original_path, info.issue_id, logger) 

562 return True 

563 

564 if not original_path.exists(): 

565 logger.info(f"{info.issue_id} source already removed - nothing to close") 

566 return True 

567 

568 # Use defaults if not provided 

569 if not close_status: 

570 close_status = "Closed - Invalid" 

571 if not close_reason: 

572 close_reason = "unknown" 

573 

574 logger.info(f"Closing {info.issue_id}: {close_status} (reason: {close_reason})") 

575 

576 try: 

577 # Prepare content with resolution section 

578 resolution = _build_closure_resolution( 

579 close_status, close_reason, fix_commit, files_changed 

580 ) 

581 content = _prepare_issue_content(original_path, resolution) 

582 

583 # Move to completed directory 

584 _move_issue_to_completed(original_path, completed_path, content, logger) 

585 

586 # Commit the closure 

587 commit_body = f"""{info.issue_id} - {close_status} 

588 

589Automated closure - issue determined to be invalid or already resolved. 

590 

591Issue: {info.issue_id} 

592Reason: {close_reason} 

593Status: {close_status}""" 

594 _commit_issue_completion(info, "close", commit_body, logger) 

595 

596 logger.success(f"Closed {info.issue_id}: {close_status}") 

597 return True 

598 

599 except Exception as e: 

600 logger.error(f"Failed to close {info.issue_id}: {e}") 

601 return False 

602 

603 

604def complete_issue_lifecycle( 

605 info: IssueInfo, 

606 config: BRConfig, 

607 logger: Logger, 

608) -> bool: 

609 """Fallback: Complete the issue lifecycle when command exited early. 

610 

611 This moves the issue to completed and adds a resolution section. 

612 

613 Args: 

614 info: Issue info 

615 config: Project configuration 

616 logger: Logger for output 

617 

618 Returns: 

619 True if successful, False otherwise 

620 """ 

621 completed_dir = config.get_completed_dir() 

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

623 

624 original_path = info.path 

625 completed_path = completed_dir / original_path.name 

626 

627 # Safety checks - handle stale state gracefully 

628 if completed_path.exists(): 

629 logger.info(f"{info.issue_id} already in completed/ - cleaning up source") 

630 if original_path.exists(): 

631 _cleanup_stale_source(original_path, info.issue_id, logger) 

632 return True 

633 

634 if not original_path.exists(): 

635 logger.info(f"{info.issue_id} source already removed - nothing to complete") 

636 return True 

637 

638 logger.info(f"Completing lifecycle for {info.issue_id} (command may have exited early)...") 

639 

640 try: 

641 # Prepare content with resolution section 

642 action = config.get_category_action(info.issue_type) 

643 resolution = _build_completion_resolution(action) 

644 content = _prepare_issue_content(original_path, resolution) 

645 

646 # Move to completed directory 

647 _move_issue_to_completed(original_path, completed_path, content, logger) 

648 append_session_log_entry(completed_path, "ll-auto") 

649 

650 # Commit the completion 

651 commit_body = f"""implement {info.issue_id} 

652 

653Automated fallback commit - command exited before completion. 

654 

655Issue: {info.issue_id} 

656Action: {action} 

657Status: Completed via fallback lifecycle completion""" 

658 _commit_issue_completion(info, action, commit_body, logger) 

659 

660 logger.success(f"Completed lifecycle for {info.issue_id}") 

661 return True 

662 

663 except Exception as e: 

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

665 return False 

666 

667 

668# ============================================================================= 

669# Issue Deferral 

670# ============================================================================= 

671 

672 

673def _build_deferred_section(reason: str) -> str: 

674 """Build the ## Deferred section content.""" 

675 now = datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ") 

676 return f""" 

677 

678## Deferred 

679 

680- **Date**: {now} 

681- **Reason**: {reason} 

682""" 

683 

684 

685def _build_undeferred_section(reason: str) -> str: 

686 """Build the ## Undeferred section content.""" 

687 now = datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ") 

688 return f""" 

689 

690## Undeferred 

691 

692- **Date**: {now} 

693- **Reason**: {reason} 

694""" 

695 

696 

697def defer_issue( 

698 info: IssueInfo, 

699 config: BRConfig, 

700 logger: Logger, 

701 reason: str | None = None, 

702) -> bool: 

703 """Defer an issue by moving it from its active directory to deferred/. 

704 

705 Args: 

706 info: Issue info 

707 config: Project configuration 

708 logger: Logger for output 

709 reason: Reason for deferring 

710 

711 Returns: 

712 True if successful, False otherwise 

713 """ 

714 deferred_dir = config.get_deferred_dir() 

715 deferred_dir.mkdir(parents=True, exist_ok=True) 

716 

717 original_path = info.path 

718 deferred_path = deferred_dir / original_path.name 

719 

720 # Safety checks 

721 if deferred_path.exists(): 

722 logger.info(f"{info.issue_id} already in deferred/") 

723 return True 

724 

725 if not original_path.exists(): 

726 logger.info(f"{info.issue_id} source not found - nothing to defer") 

727 return True 

728 

729 if not reason: 

730 reason = "Intentionally set aside for later consideration" 

731 

732 logger.info(f"Deferring {info.issue_id}: {reason}") 

733 

734 try: 

735 # Prepare content with deferred section 

736 deferred_section = _build_deferred_section(reason) 

737 content = original_path.read_text(encoding="utf-8") + deferred_section 

738 

739 # Move to deferred directory (reuse the same move helper) 

740 _move_issue_to_completed(original_path, deferred_path, content, logger) 

741 

742 # Commit the deferral 

743 commit_body = f"""{info.issue_id} - Deferred 

744 

745Reason: {reason}""" 

746 _commit_issue_completion(info, "defer", commit_body, logger) 

747 

748 logger.success(f"Deferred {info.issue_id}") 

749 return True 

750 

751 except Exception as e: 

752 logger.error(f"Failed to defer {info.issue_id}: {e}") 

753 return False 

754 

755 

756def undefer_issue( 

757 config: BRConfig, 

758 deferred_issue_path: Path, 

759 logger: Logger, 

760 reason: str | None = None, 

761) -> Path | None: 

762 """Move an issue from deferred/ back to its original category directory. 

763 

764 Args: 

765 config: Project configuration 

766 deferred_issue_path: Path to issue in deferred/ 

767 logger: Logger for output 

768 reason: Reason for undeferring 

769 

770 Returns: 

771 New path to undeferred issue, or None if failed 

772 """ 

773 from little_loops.issue_discovery.search import _get_category_from_issue_path 

774 

775 if not deferred_issue_path.exists(): 

776 logger.error(f"Deferred issue not found: {deferred_issue_path}") 

777 return None 

778 

779 # Determine target category directory from filename 

780 category = _get_category_from_issue_path(deferred_issue_path, config) 

781 target_dir = config.get_issue_dir(category) 

782 target_dir.mkdir(parents=True, exist_ok=True) 

783 

784 target_path = target_dir / deferred_issue_path.name 

785 

786 # Safety check - don't overwrite existing active issue 

787 if target_path.exists(): 

788 logger.warning(f"Active issue already exists: {target_path}") 

789 return None 

790 

791 if not reason: 

792 reason = "Ready to resume active work" 

793 

794 logger.info(f"Undeferring {deferred_issue_path.name} -> {category}/") 

795 

796 try: 

797 content = deferred_issue_path.read_text(encoding="utf-8") 

798 content += _build_undeferred_section(reason) 

799 

800 # Parse IssueInfo before git mv so the path still exists 

801 info = IssueParser(config).parse_file(deferred_issue_path) 

802 

803 # Try git mv first for history preservation 

804 result = subprocess.run( 

805 ["git", "mv", str(deferred_issue_path), str(target_path)], 

806 capture_output=True, 

807 text=True, 

808 ) 

809 

810 if result.returncode != 0: 

811 logger.warning(f"git mv failed, using manual copy: {result.stderr}") 

812 target_path.write_text(content, encoding="utf-8") 

813 deferred_issue_path.unlink() 

814 else: 

815 target_path.write_text(content, encoding="utf-8") 

816 

817 commit_body = f"""{info.issue_id} - Undeferred 

818 

819Reason: {reason}""" 

820 _commit_issue_completion(info, "undefer", commit_body, logger) 

821 

822 logger.success(f"Undeferred: {target_path.name}") 

823 return target_path 

824 

825 except Exception as e: 

826 logger.error(f"Failed to undefer issue: {e}") 

827 return None