Coverage for little_loops / cli / parallel.py: 12%

96 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2026-06-26 17:38 -0500

1"""ll-parallel: Process issues concurrently using isolated git worktrees.""" 

2 

3from __future__ import annotations 

4 

5import argparse 

6import os 

7import subprocess 

8import sys 

9from pathlib import Path 

10 

11from little_loops.cli.output import configure_output, use_color_enabled 

12from little_loops.cli_args import ( 

13 add_context_limit_arg, 

14 add_dry_run_arg, 

15 add_handoff_threshold_arg, 

16 add_idle_timeout_arg, 

17 add_label_arg, 

18 add_max_issues_arg, 

19 add_only_arg, 

20 add_quiet_arg, 

21 add_resume_arg, 

22 add_skip_arg, 

23 add_skip_learning_gate_arg, 

24 add_timeout_arg, 

25 add_type_arg, 

26 parse_issue_ids, 

27 parse_issue_types, 

28 parse_labels, 

29 parse_priorities, 

30) 

31from little_loops.config import BRConfig 

32from little_loops.logger import Logger 

33from little_loops.session_store import DEFAULT_DB_PATH, cli_event_context 

34 

35 

36def main_parallel() -> int: 

37 """Entry point for ll-parallel command. 

38 

39 Process issues concurrently using isolated git worktrees. 

40 

41 Returns: 

42 Exit code (0 = success) 

43 """ 

44 with cli_event_context(DEFAULT_DB_PATH, "ll-parallel", sys.argv[1:]): 

45 parser = argparse.ArgumentParser( 

46 description="Process issues concurrently using isolated git worktrees", 

47 formatter_class=argparse.RawDescriptionHelpFormatter, 

48 epilog=""" 

49Examples: 

50 %(prog)s # Process with default workers 

51 %(prog)s --workers 3 # Use 3 parallel workers 

52 %(prog)s --dry-run # Preview what would be processed 

53 %(prog)s --priority P1,P2 # Only process P1 and P2 issues 

54 %(prog)s --cleanup # Clean up worktrees and exit 

55 %(prog)s --prune-merged-branches # Delete merged feature/* branches 

56 %(prog)s --prune-merged-branches --dry-run # Preview what would be pruned 

57 %(prog)s --stream-output # Stream Claude CLI output in real-time 

58 %(prog)s --only BUG-001,BUG-002 # Process only specific issues 

59 %(prog)s --skip BUG-003 # Skip specific issues 

60 %(prog)s --type BUG # Process only bugs 

61 %(prog)s --type BUG,ENH # Process bugs and enhancements 

62""", 

63 ) 

64 

65 # Parallel-specific arguments (--workers, not --max-workers) 

66 parser.add_argument( 

67 "--workers", 

68 "-w", 

69 type=int, 

70 default=None, 

71 help="Number of parallel workers (default: from config or 2)", 

72 ) 

73 parser.add_argument( 

74 "--priority", 

75 "-p", 

76 type=str, 

77 default=None, 

78 help="Comma-separated priorities to process (default: all)", 

79 ) 

80 parser.add_argument( 

81 "--worktree-base", 

82 type=Path, 

83 default=None, 

84 help="Base directory for git worktrees", 

85 ) 

86 parser.add_argument( 

87 "--cleanup", 

88 "-c", 

89 action="store_true", 

90 help="Clean up all worktrees and exit", 

91 ) 

92 parser.add_argument( 

93 "--prune-merged-branches", 

94 action="store_true", 

95 help=( 

96 "Delete local feature/* branches already merged into the base branch. " 

97 "Use --dry-run to preview. " 

98 "Squash/rebase-merged branches require gh CLI for detection." 

99 ), 

100 ) 

101 parser.add_argument( 

102 "--merge-pending", 

103 action="store_true", 

104 help="Attempt to merge pending work from previous interrupted runs", 

105 ) 

106 parser.add_argument( 

107 "--clean-start", 

108 action="store_true", 

109 help="Remove all worktrees and start fresh (skip pending work check)", 

110 ) 

111 parser.add_argument( 

112 "--ignore-pending", 

113 action="store_true", 

114 help="Report pending work but continue without merging", 

115 ) 

116 parser.add_argument( 

117 "--stream-output", 

118 action="store_true", 

119 help="Stream Claude CLI subprocess output to console", 

120 ) 

121 parser.add_argument( 

122 "--show-model", 

123 action="store_true", 

124 help="Make API call to verify and display model on worktree setup", 

125 ) 

126 parser.add_argument( 

127 "--feature-branches", 

128 action=argparse.BooleanOptionalAction, 

129 default=None, 

130 help="Enable/disable feature-branch mode for this run (overrides config)", 

131 ) 

132 parser.add_argument( 

133 "--overlap-detection", 

134 action="store_true", 

135 help="Enable pre-flight overlap detection to reduce merge conflicts (ENH-143)", 

136 ) 

137 parser.add_argument( 

138 "--warn-only", 

139 action="store_true", 

140 help="With --overlap-detection, warn about overlaps instead of serializing", 

141 ) 

142 

143 parser.add_argument( 

144 "--verbose", 

145 "-v", 

146 action="store_true", 

147 help="Enable verbose output (default when --quiet is not set)", 

148 ) 

149 

150 # Add common arguments from shared module 

151 add_dry_run_arg(parser) 

152 add_resume_arg(parser) 

153 add_timeout_arg(parser) 

154 add_idle_timeout_arg(parser) 

155 add_handoff_threshold_arg(parser) 

156 add_context_limit_arg(parser) 

157 add_quiet_arg(parser) 

158 add_only_arg(parser) 

159 add_skip_arg(parser) 

160 add_type_arg(parser) 

161 add_label_arg(parser) 

162 add_skip_learning_gate_arg(parser) 

163 

164 # Add max-issues and config individually (different help text needed) 

165 add_max_issues_arg(parser) 

166 parser.add_argument( 

167 "--config", 

168 "-C", 

169 type=Path, 

170 default=None, 

171 help="Path to project root", 

172 ) 

173 

174 args = parser.parse_args() 

175 

176 project_root = args.config or Path.cwd() 

177 config = BRConfig(project_root) 

178 configure_output(config.cli) 

179 

180 logger = Logger(verbose=args.verbose or not args.quiet, use_color=use_color_enabled()) 

181 

182 # Handle cleanup mode 

183 if args.cleanup: 

184 from little_loops.parallel import WorkerPool 

185 

186 parallel_config = config.create_parallel_config() 

187 pool = WorkerPool(parallel_config, config, logger, project_root) 

188 pool.cleanup_all_worktrees() 

189 logger.success("Cleanup complete") 

190 return 0 

191 

192 # Build priority filter (validates against VALID_PRIORITIES) 

193 priority_filter = parse_priorities(args.priority) 

194 

195 if args.handoff_threshold is not None: 

196 if not (1 <= args.handoff_threshold <= 100): 

197 parser.error("--handoff-threshold must be between 1 and 100") 

198 os.environ["LL_HANDOFF_THRESHOLD"] = str(args.handoff_threshold) 

199 

200 if args.context_limit is not None: 

201 if args.context_limit < 50000: 

202 parser.error("--context-limit must be at least 50000") 

203 os.environ["LL_CONTEXT_LIMIT"] = str(args.context_limit) 

204 

205 # Parse issue ID filters 

206 only_ids = parse_issue_ids(args.only) 

207 skip_ids = parse_issue_ids(args.skip) 

208 type_prefixes = parse_issue_types(args.type) 

209 label_filter = parse_labels(args.label) 

210 

211 # Detect current branch for rebase/merge operations (BUG-439) 

212 _branch_result = subprocess.run( 

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

214 capture_output=True, 

215 text=True, 

216 cwd=project_root, 

217 ) 

218 _base_branch = _branch_result.stdout.strip() if _branch_result.returncode == 0 else "main" 

219 

220 # Create parallel config with CLI overrides 

221 parallel_config = config.create_parallel_config( 

222 max_workers=args.workers, 

223 priority_filter=sorted(priority_filter) if priority_filter is not None else None, 

224 label_filter=label_filter, 

225 max_issues=args.max_issues, 

226 dry_run=args.dry_run, 

227 timeout_seconds=args.timeout, 

228 idle_timeout_per_issue=args.idle_timeout, 

229 stream_output=args.stream_output if args.stream_output else None, 

230 show_model=args.show_model if args.show_model else None, 

231 only_ids=only_ids, 

232 skip_ids=skip_ids, 

233 type_prefixes=type_prefixes, 

234 merge_pending=args.merge_pending, 

235 clean_start=args.clean_start, 

236 ignore_pending=args.ignore_pending, 

237 overlap_detection=args.overlap_detection, 

238 serialize_overlapping=not args.warn_only, 

239 base_branch=_base_branch, 

240 use_feature_branches=args.feature_branches, 

241 skip_learning_gate=args.skip_learning_gate, 

242 ) 

243 

244 # Handle prune mode 

245 if args.prune_merged_branches: 

246 from little_loops.parallel import WorkerPool 

247 

248 pool = WorkerPool(parallel_config, config, logger, project_root) 

249 if args.dry_run: 

250 logger.info("[DRY RUN] No branches will be deleted.") 

251 pruned, skipped = pool.prune_merged_feature_branches( 

252 base_branch=parallel_config.base_branch, 

253 dry_run=args.dry_run, 

254 ) 

255 if pruned: 

256 verb = "would delete" if args.dry_run else "deleted" 

257 logger.success( 

258 f"Pruned {len(pruned)} merged feature branch(es) ({verb}): {', '.join(pruned)}" 

259 ) 

260 else: 

261 logger.info("No merged feature branches found to prune.") 

262 if skipped: 

263 logger.warning(f"Could not delete {len(skipped)} branch(es): {', '.join(skipped)}") 

264 return 0 

265 

266 # Delete state file if not resuming 

267 if not args.resume: 

268 state_file = config.get_parallel_state_file() 

269 if state_file.exists(): 

270 state_file.unlink() 

271 

272 # Create and run orchestrator 

273 from little_loops.events import EventBus 

274 from little_loops.parallel import ParallelOrchestrator 

275 

276 event_bus = EventBus() 

277 from little_loops.extension import wire_extensions 

278 from little_loops.transport import wire_transports 

279 

280 wire_extensions(event_bus, config.extensions) 

281 wire_transports(event_bus, config.events) 

282 orchestrator = ParallelOrchestrator( 

283 parallel_config=parallel_config, 

284 br_config=config, 

285 repo_path=project_root, 

286 verbose=args.verbose or not args.quiet, 

287 event_bus=event_bus, 

288 ) 

289 

290 return orchestrator.run()