Coverage for little_loops / sprint.py: 97%

126 statements  

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

1"""Sprint and sequence management for issue execution.""" 

2 

3import logging 

4from dataclasses import dataclass, field 

5from datetime import UTC, datetime 

6from pathlib import Path 

7from typing import TYPE_CHECKING, Any 

8 

9import yaml 

10 

11logger = logging.getLogger(__name__) 

12 

13if TYPE_CHECKING: 

14 from little_loops.config import BRConfig 

15 from little_loops.issue_parser import IssueInfo 

16 

17 

18@dataclass 

19class SprintOptions: 

20 """Execution options for sprint runs. 

21 

22 Attributes: 

23 max_iterations: Maximum Claude iterations per issue 

24 timeout: Per-issue timeout in seconds 

25 max_workers: Worker count for parallel execution within waves 

26 """ 

27 

28 max_iterations: int = 100 

29 timeout: int = 3600 

30 max_workers: int = 2 

31 

32 def to_dict(self) -> dict: 

33 """Convert to dictionary for YAML serialization.""" 

34 return { 

35 "max_iterations": self.max_iterations, 

36 "timeout": self.timeout, 

37 "max_workers": self.max_workers, 

38 } 

39 

40 @classmethod 

41 def from_dict(cls, data: dict | None) -> "SprintOptions": 

42 """Create from dictionary (YAML deserialization). 

43 

44 Args: 

45 data: Dictionary from YAML file or None for defaults 

46 

47 Returns: 

48 SprintOptions instance 

49 """ 

50 if data is None: 

51 return cls() 

52 return cls( 

53 max_iterations=data.get("max_iterations", 100), 

54 timeout=data.get("timeout", 3600), 

55 max_workers=data.get("max_workers", 2), 

56 ) 

57 

58 

59@dataclass 

60class SprintState: 

61 """Persistent state for sprint execution. 

62 

63 Enables resume capability after interruption by tracking: 

64 - Sprint name being executed 

65 - Current wave number 

66 - Completed issues 

67 - Failed issues with reasons 

68 - Timing information 

69 

70 Attributes: 

71 sprint_name: Name of the sprint being executed 

72 current_wave: Wave number currently being processed (1-indexed) 

73 completed_issues: List of completed issue IDs 

74 failed_issues: Mapping of issue ID to failure reason 

75 timing: Per-issue timing breakdown 

76 started_at: ISO 8601 timestamp when sprint started 

77 last_checkpoint: ISO 8601 timestamp of last state save 

78 """ 

79 

80 sprint_name: str = "" 

81 current_wave: int = 0 

82 completed_issues: list[str] = field(default_factory=list) 

83 failed_issues: dict[str, str] = field(default_factory=dict) 

84 timing: dict[str, dict[str, float]] = field(default_factory=dict) 

85 started_at: str = "" 

86 last_checkpoint: str = "" 

87 

88 def to_dict(self) -> dict[str, Any]: 

89 """Convert state to dictionary for JSON serialization.""" 

90 return { 

91 "sprint_name": self.sprint_name, 

92 "current_wave": self.current_wave, 

93 "completed_issues": self.completed_issues, 

94 "failed_issues": self.failed_issues, 

95 "timing": self.timing, 

96 "started_at": self.started_at, 

97 "last_checkpoint": self.last_checkpoint, 

98 } 

99 

100 @classmethod 

101 def from_dict(cls, data: dict[str, Any]) -> "SprintState": 

102 """Create state from dictionary (JSON deserialization).""" 

103 return cls( 

104 sprint_name=data.get("sprint_name", ""), 

105 current_wave=data.get("current_wave", 0), 

106 completed_issues=data.get("completed_issues", []), 

107 failed_issues=data.get("failed_issues", {}), 

108 timing=data.get("timing", {}), 

109 started_at=data.get("started_at", ""), 

110 last_checkpoint=data.get("last_checkpoint", ""), 

111 ) 

112 

113 

114@dataclass 

115class Sprint: 

116 """A sprint is a named group of issues to execute together. 

117 

118 Sprints allow planning work in batches and executing them as a unit. 

119 Execution is always dependency-aware with parallel waves. 

120 

121 Attributes: 

122 name: Sprint identifier (used as filename) 

123 description: Human-readable purpose 

124 issues: List of issue IDs (e.g., BUG-001, FEAT-010) 

125 created: ISO 8601 timestamp of creation 

126 options: Execution options (timeout, max_workers, etc.) 

127 """ 

128 

129 name: str 

130 description: str 

131 issues: list[str] 

132 created: str 

133 options: SprintOptions | None = None 

134 

135 def to_dict(self) -> dict[str, str | list[str] | dict]: 

136 """Convert to dictionary for YAML serialization. 

137 

138 Returns: 

139 Dictionary representation suitable for yaml.dump() 

140 """ 

141 data: dict[str, str | list[str] | dict] = { 

142 "name": self.name, 

143 "description": self.description, 

144 "created": self.created, 

145 "issues": self.issues, 

146 } 

147 if self.options: 

148 data["options"] = self.options.to_dict() 

149 return data 

150 

151 @classmethod 

152 def from_dict(cls, data: dict) -> "Sprint": 

153 """Create from dictionary (YAML deserialization). 

154 

155 Args: 

156 data: Dictionary from YAML file 

157 

158 Returns: 

159 Sprint instance 

160 """ 

161 return cls( 

162 name=data["name"], 

163 description=data.get("description", ""), 

164 issues=data.get("issues", []), 

165 created=data.get("created", datetime.now(UTC).isoformat()), 

166 options=SprintOptions.from_dict(data.get("options")), 

167 ) 

168 

169 def save(self, sprints_dir: Path) -> Path: 

170 """Save sprint to YAML file. 

171 

172 Args: 

173 sprints_dir: Directory containing sprint definitions 

174 

175 Returns: 

176 Path to saved file 

177 """ 

178 sprints_dir.mkdir(parents=True, exist_ok=True) 

179 sprint_path = sprints_dir / f"{self.name}.yaml" 

180 with open(sprint_path, "w") as f: 

181 yaml.dump(self.to_dict(), f, default_flow_style=False, sort_keys=False) 

182 return sprint_path 

183 

184 @classmethod 

185 def load(cls, sprints_dir: Path, name: str) -> "Sprint | None": 

186 """Load sprint from YAML file. 

187 

188 Args: 

189 sprints_dir: Directory containing sprint definitions 

190 name: Sprint name (without .yaml extension) 

191 

192 Returns: 

193 Sprint instance or None if not found 

194 """ 

195 sprint_path = sprints_dir / f"{name}.yaml" 

196 if not sprint_path.exists(): 

197 return None 

198 with open(sprint_path) as f: 

199 data = yaml.safe_load(f) 

200 return cls.from_dict(data) 

201 

202 

203class SprintManager: 

204 """Manager for sprint CRUD operations. 

205 

206 Provides methods to create, load, list, and delete sprint definitions. 

207 Also validates that issue IDs exist before executing sprints. 

208 """ 

209 

210 def __init__(self, sprints_dir: Path | None = None, config: "BRConfig | None" = None) -> None: 

211 """Initialize SprintManager. 

212 

213 Args: 

214 sprints_dir: Directory for sprint definitions (overrides config) 

215 config: Project configuration for settings and issue validation 

216 """ 

217 self.config = config 

218 # Derive sprints_dir: explicit arg > config > default 

219 if sprints_dir is not None: 

220 self.sprints_dir = sprints_dir 

221 elif config is not None: 

222 self.sprints_dir = Path(config.sprints.sprints_dir) 

223 else: 

224 self.sprints_dir = Path(".sprints") 

225 self.sprints_dir.mkdir(parents=True, exist_ok=True) 

226 

227 def get_default_options(self) -> SprintOptions: 

228 """Get default SprintOptions from config or hardcoded defaults. 

229 

230 Returns: 

231 SprintOptions with values from config if available, else defaults 

232 """ 

233 if self.config is not None: 

234 return SprintOptions( 

235 timeout=self.config.sprints.default_timeout, 

236 max_workers=self.config.sprints.default_max_workers, 

237 ) 

238 return SprintOptions() 

239 

240 def create( 

241 self, 

242 name: str, 

243 issues: list[str], 

244 description: str = "", 

245 options: SprintOptions | None = None, 

246 ) -> Sprint: 

247 """Create a new sprint. 

248 

249 Args: 

250 name: Sprint identifier 

251 issues: List of issue IDs 

252 description: Human-readable description 

253 options: Optional execution options 

254 

255 Returns: 

256 Created Sprint instance 

257 """ 

258 sprint = Sprint( 

259 name=name, 

260 description=description, 

261 issues=[i.strip().upper() for i in issues], 

262 created=datetime.now(UTC).isoformat(), 

263 options=options, 

264 ) 

265 sprint.save(self.sprints_dir) 

266 return sprint 

267 

268 def load(self, name: str) -> Sprint | None: 

269 """Load a sprint by name. 

270 

271 Args: 

272 name: Sprint name 

273 

274 Returns: 

275 Sprint instance or None if not found 

276 """ 

277 return Sprint.load(self.sprints_dir, name) 

278 

279 def list_all(self) -> list[Sprint]: 

280 """List all sprints. 

281 

282 Returns: 

283 List of Sprint instances, sorted by name 

284 """ 

285 sprints = [] 

286 for path in sorted(self.sprints_dir.glob("*.yaml")): 

287 sprint = Sprint.load(self.sprints_dir, path.stem) 

288 if sprint: 

289 sprints.append(sprint) 

290 return sprints 

291 

292 def delete(self, name: str) -> bool: 

293 """Delete a sprint. 

294 

295 Args: 

296 name: Sprint name 

297 

298 Returns: 

299 True if deleted, False if not found 

300 """ 

301 sprint_path = self.sprints_dir / f"{name}.yaml" 

302 if not sprint_path.exists(): 

303 return False 

304 sprint_path.unlink() 

305 return True 

306 

307 def _find_issue_path(self, issue_id: str) -> Path | None: 

308 """Find the filesystem path for an issue ID. 

309 

310 Searches all configured issue categories for a file matching the issue ID. 

311 

312 Args: 

313 issue_id: Issue ID to locate (e.g. "BUG-001") 

314 

315 Returns: 

316 Path to the issue file, or None if not found 

317 """ 

318 if not self.config: 

319 return None 

320 for category in self.config.issue_categories: 

321 issue_dir = self.config.get_issue_dir(category) 

322 for path in issue_dir.glob(f"*-{issue_id}-*.md"): 

323 return path 

324 return None 

325 

326 def validate_issues(self, issues: list[str]) -> dict[str, Path]: 

327 """Validate that issue IDs exist. 

328 

329 Args: 

330 issues: List of issue IDs to validate 

331 

332 Returns: 

333 Dictionary mapping valid issue IDs to their file paths 

334 """ 

335 if not self.config: 

336 # No config provided, skip validation 

337 return {} 

338 

339 valid = {} 

340 for issue_id in issues: 

341 path = self._find_issue_path(issue_id) 

342 if path is not None: 

343 valid[issue_id] = path 

344 return valid 

345 

346 def load_issue_infos(self, issues: list[str]) -> list["IssueInfo"]: 

347 """Load IssueInfo objects for the given issue IDs. 

348 

349 Args: 

350 issues: List of issue IDs to load 

351 

352 Returns: 

353 List of IssueInfo objects (only for issues that exist) 

354 """ 

355 from little_loops.issue_parser import IssueParser 

356 

357 if not self.config: 

358 return [] 

359 

360 parser = IssueParser(self.config) 

361 result: list[IssueInfo] = [] 

362 for issue_id in issues: 

363 path = self._find_issue_path(issue_id) 

364 if path is not None: 

365 try: 

366 info = parser.parse_file(path) 

367 result.append(info) 

368 except Exception as e: 

369 logger.warning("Failed to parse issue file %s: %s", path, e) 

370 return result