Coverage for little_loops / parallel / types.py: 100%
135 statements
« prev ^ index » next coverage.py v7.12.0, created at 2026-03-04 01:17 -0600
« prev ^ index » next coverage.py v7.12.0, created at 2026-03-04 01:17 -0600
1"""Type definitions for parallel issue processing.
3Provides dataclasses for worker results, merge requests, orchestrator state,
4and parallel configuration. Reuses IssueInfo from issue_parser.py.
5"""
7from __future__ import annotations
9import time
10from dataclasses import dataclass, field
11from enum import Enum
12from pathlib import Path
13from typing import TYPE_CHECKING, Any
15if TYPE_CHECKING:
16 from little_loops.issue_parser import IssueInfo
19@dataclass
20class QueuedIssue:
21 """Issue in priority queue with ordering support.
23 Uses __lt__ for priority queue comparison. Lower priority number = higher priority.
24 Within same priority level, earlier timestamp wins (FIFO).
26 Attributes:
27 priority: Numeric priority (0=P0, 1=P1, etc.)
28 issue_info: The parsed issue information
29 timestamp: When the issue was queued (for FIFO ordering)
30 """
32 priority: int
33 issue_info: IssueInfo
34 timestamp: float = field(default_factory=time.time)
36 def __lt__(self, other: QueuedIssue) -> bool:
37 """Compare issues for priority queue ordering."""
38 if self.priority != other.priority:
39 return self.priority < other.priority
40 return self.timestamp < other.timestamp
42 def to_dict(self) -> dict[str, Any]:
43 """Convert to dictionary for JSON serialization."""
44 return {
45 "priority": self.priority,
46 "issue_info": self.issue_info.to_dict(),
47 "timestamp": self.timestamp,
48 }
51@dataclass
52class WorkerResult:
53 """Result from a worker processing an issue.
55 Attributes:
56 issue_id: ID of the processed issue
57 success: Whether processing succeeded
58 branch_name: Git branch created for this issue
59 worktree_path: Path to the worker's git worktree
60 changed_files: List of files modified during processing
61 leaked_files: Files incorrectly written to main repo instead of worktree
62 duration: Processing time in seconds
63 error: Error message if processing failed
64 stdout: Captured standard output
65 stderr: Captured standard error
66 was_corrected: Whether the issue file was auto-corrected
67 corrections: List of corrections made during validation (for pattern analysis)
68 should_close: Whether the issue should be closed (e.g., already fixed, invalid)
69 close_reason: Reason code for closure (e.g., "already_fixed")
70 close_status: Status text for closure (e.g., "Closed - Already Fixed")
71 interrupted: Whether the worker was interrupted during shutdown
72 """
74 issue_id: str
75 success: bool
76 branch_name: str
77 worktree_path: Path
78 changed_files: list[str] = field(default_factory=list)
79 leaked_files: list[str] = field(default_factory=list)
80 duration: float = 0.0
81 error: str | None = None
82 stdout: str = ""
83 stderr: str = ""
84 was_corrected: bool = False
85 corrections: list[str] = field(default_factory=list)
86 should_close: bool = False
87 close_reason: str | None = None
88 close_status: str | None = None
89 interrupted: bool = False
91 def to_dict(self) -> dict[str, Any]:
92 """Convert to dictionary for JSON serialization."""
93 return {
94 "issue_id": self.issue_id,
95 "success": self.success,
96 "branch_name": self.branch_name,
97 "worktree_path": str(self.worktree_path),
98 "changed_files": self.changed_files,
99 "leaked_files": self.leaked_files,
100 "duration": self.duration,
101 "error": self.error,
102 "stdout": self.stdout,
103 "stderr": self.stderr,
104 "was_corrected": self.was_corrected,
105 "corrections": self.corrections,
106 "should_close": self.should_close,
107 "close_reason": self.close_reason,
108 "close_status": self.close_status,
109 "interrupted": self.interrupted,
110 }
112 @classmethod
113 def from_dict(cls, data: dict[str, Any]) -> WorkerResult:
114 """Create from dictionary (JSON deserialization)."""
115 return cls(
116 issue_id=data["issue_id"],
117 success=data["success"],
118 branch_name=data["branch_name"],
119 worktree_path=Path(data["worktree_path"]),
120 changed_files=data.get("changed_files", []),
121 leaked_files=data.get("leaked_files", []),
122 duration=data.get("duration", 0.0),
123 error=data.get("error"),
124 stdout=data.get("stdout", ""),
125 stderr=data.get("stderr", ""),
126 was_corrected=data.get("was_corrected", False),
127 corrections=data.get("corrections", []),
128 should_close=data.get("should_close", False),
129 close_reason=data.get("close_reason"),
130 close_status=data.get("close_status"),
131 interrupted=data.get("interrupted", False),
132 )
135class MergeStatus(Enum):
136 """Status of a merge operation."""
138 PENDING = "pending"
139 IN_PROGRESS = "in_progress"
140 SUCCESS = "success"
141 CONFLICT = "conflict"
142 FAILED = "failed"
143 RETRYING = "retrying"
146class WorkerStage(Enum):
147 """Processing stage of a worker.
149 Stages progress in order:
150 - SETUP: Creating git worktree and copying .claude/ directory
151 - VALIDATING: Running ready-issue command
152 - IMPLEMENTING: Running manage-issue command
153 - VERIFYING: Checking work was done and updating branch base
154 - MERGING: Awaiting merge coordination
155 - COMPLETED: Successfully finished
156 - FAILED: Failed at some stage
157 - INTERRUPTED: Interrupted during shutdown
158 """
160 SETUP = "setup"
161 VALIDATING = "validating"
162 IMPLEMENTING = "implementing"
163 VERIFYING = "verifying"
164 MERGING = "merging"
165 COMPLETED = "completed"
166 FAILED = "failed"
167 INTERRUPTED = "interrupted"
170@dataclass
171class MergeRequest:
172 """Request to merge a completed worker's changes.
174 Attributes:
175 worker_result: The result from the worker
176 status: Current merge status
177 retry_count: Number of merge/rebase attempts
178 error: Error message if merge failed
179 queued_at: When the merge was requested
180 """
182 worker_result: WorkerResult
183 status: MergeStatus = MergeStatus.PENDING
184 retry_count: int = 0
185 error: str | None = None
186 queued_at: float = field(default_factory=time.time)
188 def to_dict(self) -> dict[str, Any]:
189 """Convert to dictionary for JSON serialization."""
190 return {
191 "worker_result": self.worker_result.to_dict(),
192 "status": self.status.value,
193 "retry_count": self.retry_count,
194 "error": self.error,
195 "queued_at": self.queued_at,
196 }
199@dataclass
200class OrchestratorState:
201 """Persistent state for the parallel orchestrator.
203 Enables resume capability after interruption.
205 Attributes:
206 in_progress_issues: Issues currently being processed by workers
207 completed_issues: Successfully completed issue IDs
208 failed_issues: Mapping of issue ID to failure reason
209 pending_merges: Issues awaiting merge
210 timing: Per-issue timing breakdown
211 corrections: Mapping of issue ID to list of corrections made (for pattern analysis)
212 started_at: When orchestration started
213 last_checkpoint: Last state save timestamp
214 """
216 in_progress_issues: list[str] = field(default_factory=list)
217 completed_issues: list[str] = field(default_factory=list)
218 failed_issues: dict[str, str] = field(default_factory=dict)
219 pending_merges: list[str] = field(default_factory=list)
220 timing: dict[str, dict[str, float]] = field(default_factory=dict)
221 corrections: dict[str, list[str]] = field(default_factory=dict)
222 started_at: str = ""
223 last_checkpoint: str = ""
225 def to_dict(self) -> dict[str, Any]:
226 """Convert state to dictionary for JSON serialization."""
227 return {
228 "in_progress_issues": self.in_progress_issues,
229 "completed_issues": self.completed_issues,
230 "failed_issues": self.failed_issues,
231 "pending_merges": self.pending_merges,
232 "timing": self.timing,
233 "corrections": self.corrections,
234 "started_at": self.started_at,
235 "last_checkpoint": self.last_checkpoint,
236 }
238 @classmethod
239 def from_dict(cls, data: dict[str, Any]) -> OrchestratorState:
240 """Create state from dictionary (JSON deserialization)."""
241 return cls(
242 in_progress_issues=data.get("in_progress_issues", []),
243 completed_issues=data.get("completed_issues", []),
244 failed_issues=data.get("failed_issues", {}),
245 pending_merges=data.get("pending_merges", []),
246 timing=data.get("timing", {}),
247 corrections=data.get("corrections", {}),
248 started_at=data.get("started_at", ""),
249 last_checkpoint=data.get("last_checkpoint", ""),
250 )
253@dataclass
254class PendingWorktreeInfo:
255 """Information about a pending worktree from a previous run.
257 Attributes:
258 worktree_path: Path to the worktree directory
259 branch_name: Git branch name (parallel/<issue-id>-<timestamp>)
260 issue_id: Extracted issue ID (e.g., BUG-045)
261 commits_ahead: Number of commits ahead of main
262 has_uncommitted_changes: Whether there are uncommitted changes
263 changed_files: List of files with uncommitted changes
264 """
266 worktree_path: Path
267 branch_name: str
268 issue_id: str
269 commits_ahead: int
270 has_uncommitted_changes: bool
271 changed_files: list[str] = field(default_factory=list)
273 @property
274 def has_pending_work(self) -> bool:
275 """Return True if this worktree has work that could be merged."""
276 return self.commits_ahead > 0 or self.has_uncommitted_changes
279@dataclass
280class ParallelConfig:
281 """Configuration for the parallel issue manager.
283 Supports configurable command templates for different project setups.
284 Commands use placeholders: {{issue_id}}, {{issue_type}}, {{action}}
286 Attributes:
287 max_workers: Number of parallel workers (default: 2)
288 p0_sequential: Process P0 issues sequentially (default: True)
289 merge_interval: Seconds between merge attempts (default: 30.0)
290 worktree_base: Base directory for git worktrees
291 state_file: Path to state persistence file
292 max_merge_retries: Maximum rebase attempts before giving up (default: 2)
293 priority_filter: Which priority levels to process
294 max_issues: Maximum issues to process (0 = unlimited)
295 dry_run: Preview mode without actual processing
296 timeout_per_issue: Timeout in seconds for each issue (default: 7200)
297 orchestrator_timeout: Timeout for waiting on workers (default: 0 = auto)
298 stream_subprocess_output: Whether to stream subprocess output
299 show_model: Make API call to verify and display model on worktree setup
300 command_prefix: Prefix for slash commands (default: "/ll:")
301 ready_command: Template for ready-issue command
302 manage_command: Template for manage-issue command
303 only_ids: If provided, only process these issue IDs
304 skip_ids: Issue IDs to skip (in addition to completed/failed)
305 merge_pending: Attempt to merge pending worktrees from previous runs
306 clean_start: Remove all worktrees without checking for pending work
307 ignore_pending: Report pending work but continue without merging
308 """
310 max_workers: int = 2
311 p0_sequential: bool = True
312 merge_interval: float = 30.0
313 worktree_base: Path = field(default_factory=lambda: Path(".worktrees"))
314 state_file: Path = field(default_factory=lambda: Path(".parallel-manage-state.json"))
315 max_merge_retries: int = 2
316 priority_filter: list[str] = field(default_factory=lambda: ["P0", "P1", "P2", "P3", "P4", "P5"])
317 max_issues: int = 0
318 dry_run: bool = False
319 timeout_per_issue: int = 3600
320 idle_timeout_per_issue: int = 0 # Kill if no output for N seconds (0 to disable)
321 orchestrator_timeout: int = 0 # 0 = use timeout_per_issue * max_workers
322 stream_subprocess_output: bool = False
323 show_model: bool = False # Make API call to verify model on worktree setup
324 # Configurable command templates
325 command_prefix: str = "/ll:"
326 ready_command: str = "ready-issue {{issue_id}}"
327 manage_command: str = "manage-issue {{issue_type}} {{action}} {{issue_id}}"
328 # Issue ID filters
329 only_ids: set[str] | None = None
330 skip_ids: set[str] | None = None
331 type_prefixes: set[str] | None = None
332 # Validation settings
333 require_code_changes: bool = True # If False, allow changes to only excluded dirs
334 # Additional files to copy from main repo to worktrees
335 # Note: .claude/ directory is always copied automatically (see worker_pool.py)
336 worktree_copy_files: list[str] = field(default_factory=lambda: [".env"])
337 # Pending worktree handling flags
338 merge_pending: bool = False # Attempt to merge pending worktrees
339 clean_start: bool = False # Remove all worktrees without checking
340 ignore_pending: bool = False # Report pending work but continue
341 # Overlap detection settings (ENH-143)
342 overlap_detection: bool = False # Enable pre-flight overlap detection
343 serialize_overlapping: bool = True # If True, defer overlapping issues; if False, just warn
344 # Base branch for rebase/merge operations (auto-detected at startup)
345 base_branch: str = "main"
347 def get_ready_command(self, issue_id: str) -> str:
348 """Build the ready-issue command string.
350 Args:
351 issue_id: Issue identifier
353 Returns:
354 Complete command string
355 """
356 cmd = self.ready_command.replace("{{issue_id}}", issue_id)
357 return f"{self.command_prefix}{cmd}"
359 def get_manage_command(self, issue_type: str, action: str, issue_id: str) -> str:
360 """Build the manage-issue command string.
362 Args:
363 issue_type: Type of issue (bug, feature, enhancement)
364 action: Action to perform (fix, implement, improve)
365 issue_id: Issue identifier
367 Returns:
368 Complete command string
369 """
370 cmd = (
371 self.manage_command.replace("{{issue_type}}", issue_type)
372 .replace("{{action}}", action)
373 .replace("{{issue_id}}", issue_id)
374 )
375 return f"{self.command_prefix}{cmd}"
377 def to_dict(self) -> dict[str, Any]:
378 """Convert to dictionary for JSON serialization."""
379 return {
380 "max_workers": self.max_workers,
381 "p0_sequential": self.p0_sequential,
382 "merge_interval": self.merge_interval,
383 "worktree_base": str(self.worktree_base),
384 "state_file": str(self.state_file),
385 "max_merge_retries": self.max_merge_retries,
386 "priority_filter": self.priority_filter,
387 "max_issues": self.max_issues,
388 "dry_run": self.dry_run,
389 "timeout_per_issue": self.timeout_per_issue,
390 "idle_timeout_per_issue": self.idle_timeout_per_issue,
391 "orchestrator_timeout": self.orchestrator_timeout,
392 "stream_subprocess_output": self.stream_subprocess_output,
393 "show_model": self.show_model,
394 "command_prefix": self.command_prefix,
395 "ready_command": self.ready_command,
396 "manage_command": self.manage_command,
397 "only_ids": list(self.only_ids) if self.only_ids else None,
398 "skip_ids": list(self.skip_ids) if self.skip_ids else None,
399 "type_prefixes": list(self.type_prefixes) if self.type_prefixes else None,
400 "require_code_changes": self.require_code_changes,
401 "merge_pending": self.merge_pending,
402 "clean_start": self.clean_start,
403 "ignore_pending": self.ignore_pending,
404 "overlap_detection": self.overlap_detection,
405 "serialize_overlapping": self.serialize_overlapping,
406 "base_branch": self.base_branch,
407 }
409 @classmethod
410 def from_dict(cls, data: dict[str, Any]) -> ParallelConfig:
411 """Create from dictionary (JSON deserialization)."""
412 only_ids_data = data.get("only_ids")
413 skip_ids_data = data.get("skip_ids")
414 type_prefixes_data = data.get("type_prefixes")
415 return cls(
416 max_workers=data.get("max_workers", 2),
417 p0_sequential=data.get("p0_sequential", True),
418 merge_interval=data.get("merge_interval", 30.0),
419 worktree_base=Path(data.get("worktree_base", ".worktrees")),
420 state_file=Path(data.get("state_file", ".parallel-manage-state.json")),
421 max_merge_retries=data.get("max_merge_retries", 2),
422 priority_filter=data.get("priority_filter", ["P0", "P1", "P2", "P3", "P4", "P5"]),
423 max_issues=data.get("max_issues", 0),
424 dry_run=data.get("dry_run", False),
425 timeout_per_issue=data.get("timeout_per_issue", 7200),
426 idle_timeout_per_issue=data.get("idle_timeout_per_issue", 0),
427 orchestrator_timeout=data.get("orchestrator_timeout", 0),
428 stream_subprocess_output=data.get("stream_subprocess_output", False),
429 show_model=data.get("show_model", False),
430 command_prefix=data.get("command_prefix", "/ll:"),
431 ready_command=data.get("ready_command", "ready-issue {{issue_id}}"),
432 manage_command=data.get(
433 "manage_command", "manage-issue {{issue_type}} {{action}} {{issue_id}}"
434 ),
435 only_ids=set(only_ids_data) if only_ids_data else None,
436 skip_ids=set(skip_ids_data) if skip_ids_data else None,
437 type_prefixes=set(type_prefixes_data) if type_prefixes_data else None,
438 require_code_changes=data.get("require_code_changes", True),
439 merge_pending=data.get("merge_pending", False),
440 clean_start=data.get("clean_start", False),
441 ignore_pending=data.get("ignore_pending", False),
442 overlap_detection=data.get("overlap_detection", False),
443 serialize_overlapping=data.get("serialize_overlapping", True),
444 base_branch=data.get("base_branch", "main"),
445 )