Coverage for /Users/les/Projects/crackerjack/crackerjack/agents/documentation_agent.py: 0%

203 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-09-03 15:39 -0700

1import re 

2import subprocess 

3from contextlib import suppress 

4from datetime import datetime 

5from pathlib import Path 

6 

7from .base import ( 

8 FixResult, 

9 Issue, 

10 IssueType, 

11 SubAgent, 

12 agent_registry, 

13) 

14 

15 

16class DocumentationAgent(SubAgent): 

17 def get_supported_types(self) -> set[IssueType]: 

18 return {IssueType.DOCUMENTATION} 

19 

20 async def can_handle(self, issue: Issue) -> float: 

21 if issue.type == IssueType.DOCUMENTATION: 

22 return 0.8 

23 return 0.0 

24 

25 async def analyze_and_fix(self, issue: Issue) -> FixResult: 

26 self.log(f"Analyzing documentation issue: {issue.message}") 

27 

28 try: 

29 if "changelog" in issue.message.lower(): 

30 return await self._update_changelog(issue) 

31 if ( 

32 "agent count" in issue.message.lower() 

33 or "consistency" in issue.message.lower() 

34 ): 

35 return await self._fix_documentation_consistency(issue) 

36 if "api" in issue.message.lower() or "readme" in issue.message.lower(): 

37 return await self._update_api_documentation(issue) 

38 return await self._general_documentation_update(issue) 

39 

40 except Exception as e: 

41 return FixResult( 

42 success=False, 

43 confidence=0.0, 

44 remaining_issues=[f"Error processing documentation: {e}"], 

45 ) 

46 

47 async def _update_changelog(self, issue: Issue) -> FixResult: 

48 self.log("Updating changelog with recent changes") 

49 

50 changelog_path = Path("CHANGELOG.md") 

51 

52 recent_changes = self._get_recent_changes() 

53 

54 if not recent_changes: 

55 return FixResult( 

56 success=True, 

57 confidence=0.7, 

58 recommendations=["No recent changes to add to changelog"], 

59 ) 

60 

61 changelog_entry = self._generate_changelog_entry(recent_changes) 

62 

63 if changelog_path.exists(): 

64 content = self.context.get_file_content(changelog_path) 

65 if content is None: 

66 return FixResult( 

67 success=False, 

68 confidence=0.0, 

69 remaining_issues=[f"Failed to read {changelog_path}"], 

70 ) 

71 updated_content = self._insert_changelog_entry(content, changelog_entry) 

72 else: 

73 updated_content = self._create_initial_changelog(changelog_entry) 

74 

75 success = self.context.write_file_content(changelog_path, updated_content) 

76 

77 if success: 

78 return FixResult( 

79 success=True, 

80 confidence=0.9, 

81 fixes_applied=[ 

82 f"Updated CHANGELOG.md with {len(recent_changes)} recent changes", 

83 ], 

84 files_modified=[str(changelog_path)], 

85 ) 

86 

87 return FixResult( 

88 success=False, 

89 confidence=0.0, 

90 remaining_issues=["Failed to write changelog updates"], 

91 ) 

92 

93 async def _fix_documentation_consistency(self, issue: Issue) -> FixResult: 

94 self.log("Checking documentation consistency") 

95 

96 md_files = list(Path().glob("*.md")) + list(Path("docs").glob("*.md")) 

97 

98 agent_count_issues = self._check_agent_count_consistency(md_files) 

99 

100 files_modified: list[str] = [] 

101 fixes_applied: list[str] = [] 

102 

103 for file_path, current_count, expected_count in agent_count_issues: 

104 content = self.context.get_file_content(file_path) 

105 if content: 

106 updated_content = self._fix_agent_count_references( 

107 content, 

108 current_count, 

109 expected_count, 

110 ) 

111 if updated_content != content: 

112 success = self.context.write_file_content( 

113 file_path, 

114 updated_content, 

115 ) 

116 if success: 

117 files_modified.append(str(file_path)) 

118 fixes_applied.append(f"Updated agent count in {file_path.name}") 

119 

120 if files_modified: 

121 return FixResult( 

122 success=True, 

123 confidence=0.85, 

124 fixes_applied=fixes_applied, 

125 files_modified=files_modified, 

126 ) 

127 

128 return FixResult( 

129 success=True, 

130 confidence=0.8, 

131 recommendations=["Documentation is already consistent"], 

132 ) 

133 

134 async def _update_api_documentation(self, issue: Issue) -> FixResult: 

135 self.log("Updating API documentation") 

136 

137 api_changes = self._detect_api_changes() 

138 

139 if not api_changes: 

140 return FixResult( 

141 success=True, 

142 confidence=0.7, 

143 recommendations=[ 

144 "No API changes detected requiring documentation updates", 

145 ], 

146 ) 

147 

148 readme_path = Path("README.md") 

149 if readme_path.exists(): 

150 content = self.context.get_file_content(readme_path) 

151 if content is None: 

152 return FixResult( 

153 success=False, 

154 confidence=0.0, 

155 remaining_issues=[f"Failed to read {readme_path}"], 

156 ) 

157 updated_content = self._update_readme_examples(content, api_changes) 

158 

159 if updated_content != content: 

160 success = self.context.write_file_content(readme_path, updated_content) 

161 if success: 

162 return FixResult( 

163 success=True, 

164 confidence=0.8, 

165 fixes_applied=["Updated README.md examples for API changes"], 

166 files_modified=[str(readme_path)], 

167 ) 

168 

169 return FixResult( 

170 success=False, 

171 confidence=0.5, 

172 remaining_issues=["Could not update API documentation"], 

173 recommendations=["Manual review of API documentation may be needed"], 

174 ) 

175 

176 async def _general_documentation_update(self, issue: Issue) -> FixResult: 

177 self.log("Performing general documentation update") 

178 

179 return FixResult( 

180 success=True, 

181 confidence=0.6, 

182 recommendations=[ 

183 f"Documentation issue identified: {issue.message}", 

184 "Manual review recommended for optimal documentation updates", 

185 "Consider adding specific patterns to DocumentationAgent", 

186 ], 

187 ) 

188 

189 def _get_recent_changes(self) -> list[dict[str, str]]: 

190 try: 

191 commit_range = self._get_commit_range() 

192 if not commit_range: 

193 return [] 

194 

195 commit_messages = self._get_commit_messages(commit_range) 

196 return self._parse_commit_messages(commit_messages) 

197 

198 except Exception: 

199 return [] 

200 

201 def _get_commit_range(self) -> str: 

202 result = subprocess.run( 

203 ["git", "describe", "--tags", "--abbrev=0"], 

204 capture_output=True, 

205 text=True, 

206 check=False, 

207 ) 

208 

209 if result.returncode == 0: 

210 last_tag = result.stdout.strip() 

211 return f"{last_tag}..HEAD" 

212 

213 return "-10" 

214 

215 def _get_commit_messages(self, commit_range: str) -> str: 

216 result = subprocess.run( 

217 ["git", "log", commit_range, "--pretty=format:%s|%h|%an"], 

218 capture_output=True, 

219 text=True, 

220 check=False, 

221 ) 

222 

223 return result.stdout.strip() if result.returncode == 0 else "" 

224 

225 def _parse_commit_messages(self, commit_output: str) -> list[dict[str, str]]: 

226 changes: list[dict[str, str]] = [] 

227 

228 for line in commit_output.split("\n"): 

229 if line: 

230 parts = line.split("|") 

231 if len(parts) >= 2: 

232 change_info: dict[str, str] = { 

233 "message": parts[0], 

234 "hash": parts[1], 

235 "author": parts[2] if len(parts) > 2 else "Unknown", 

236 } 

237 changes.append(change_info) 

238 

239 return changes 

240 

241 def _generate_changelog_entry(self, changes: list[dict[str, str]]) -> str: 

242 date_str = datetime.now().strftime("%Y-%m-%d") 

243 entry_lines = [f"## [Unreleased] - {date_str}", ""] 

244 

245 categorized_changes = self._categorize_changes(changes) 

246 self._add_categorized_changes_to_entry(entry_lines, categorized_changes) 

247 

248 return "\n".join(entry_lines) 

249 

250 def _categorize_changes( 

251 self, 

252 changes: list[dict[str, str]], 

253 ) -> dict[str, list[str]]: 

254 categories: dict[str, list[str]] = { 

255 "features": [], 

256 "fixes": [], 

257 "refactors": [], 

258 "other": [], 

259 } 

260 

261 for change in changes: 

262 message = change["message"] 

263 category = self._get_change_category(message) 

264 categories[category].append(message) 

265 

266 return categories 

267 

268 def _get_change_category(self, message: str) -> str: 

269 if message.startswith(("feat:", "feature:")): 

270 return "features" 

271 if message.startswith("fix:"): 

272 return "fixes" 

273 if message.startswith(("refactor:", "refact:")): 

274 return "refactors" 

275 return "other" 

276 

277 def _add_categorized_changes_to_entry( 

278 self, 

279 entry_lines: list[str], 

280 categories: dict[str, list[str]], 

281 ) -> None: 

282 section_mappings = { 

283 "features": "### Added", 

284 "fixes": "### Fixed", 

285 "refactors": "### Changed", 

286 "other": "### Other", 

287 } 

288 

289 for category, section_title in section_mappings.items(): 

290 items = categories[category] 

291 if items: 

292 self._add_section_to_entry(entry_lines, section_title, items) 

293 

294 def _add_section_to_entry( 

295 self, 

296 entry_lines: list[str], 

297 section_title: str, 

298 items: list[str], 

299 ) -> None: 

300 entry_lines.append(section_title) 

301 for item in items: 

302 entry_lines.append(f"- {item}") 

303 entry_lines.append("") 

304 

305 def _insert_changelog_entry(self, content: str, entry: str) -> str: 

306 lines = content.split("\n") 

307 

308 insert_index = 0 

309 for i, line in enumerate(lines): 

310 if line.startswith(("# ", "## ")): 

311 if i > 0: 

312 insert_index = i 

313 break 

314 

315 new_lines = ( 

316 lines[:insert_index] + entry.split("\n") + [""] + lines[insert_index:] 

317 ) 

318 return "\n".join(new_lines) 

319 

320 def _create_initial_changelog(self, entry: str) -> str: 

321 return f"""# Changelog 

322 

323All notable changes to this project will be documented in this file. 

324 

325The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 

326and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 

327 

328{entry} 

329""" 

330 

331 def _check_agent_count_consistency( 

332 self, 

333 md_files: list[Path], 

334 ) -> list[tuple[Path, int, int]]: 

335 expected_count = 9 

336 issues: list[tuple[Path, int, int]] = [] 

337 patterns = self._get_agent_count_patterns() 

338 

339 for file_path in md_files: 

340 issue = self._check_file_agent_count(file_path, patterns, expected_count) 

341 if issue: 

342 issues.append(issue) 

343 

344 return issues 

345 

346 def _get_agent_count_patterns(self) -> list[str]: 

347 return [ 

348 r"(\d+)\s+agents", 

349 r"(\d+)\s+specialized\s+agents", 

350 r'total_agents["\']:\s*(\d+)', 

351 r"(\d+)\s+sub-agents", 

352 ] 

353 

354 def _check_file_agent_count( 

355 self, 

356 file_path: Path, 

357 patterns: list[str], 

358 expected_count: int, 

359 ) -> tuple[Path, int, int] | None: 

360 with suppress(Exception): 

361 content = self.context.get_file_content(file_path) 

362 if not content: 

363 return None 

364 

365 for pattern in patterns: 

366 matches = re.findall(pattern, content, re.IGNORECASE) 

367 for match in matches: 

368 count = int(match) 

369 if count != expected_count and count > 4: 

370 return (file_path, count, expected_count) 

371 

372 return None 

373 

374 def _fix_agent_count_references( 

375 self, 

376 content: str, 

377 current_count: int, 

378 expected_count: int, 

379 ) -> str: 

380 patterns_replacements = [ 

381 (rf"\b{current_count}\s+agents\b", f"{expected_count} agents"), 

382 ( 

383 rf"\b{current_count}\s+specialized\s+agents\b", 

384 f"{expected_count} specialized agents", 

385 ), 

386 ( 

387 rf'total_agents["\']:\s*{current_count}', 

388 f'total_agents": {expected_count}', 

389 ), 

390 (rf"\b{current_count}\s+sub-agents\b", f"{expected_count} sub-agents"), 

391 ] 

392 

393 updated_content = content 

394 for pattern, replacement in patterns_replacements: 

395 updated_content = re.sub( 

396 pattern, 

397 replacement, 

398 updated_content, 

399 flags=re.IGNORECASE, 

400 ) 

401 

402 return updated_content 

403 

404 def _detect_api_changes(self) -> list[dict[str, str]]: 

405 try: 

406 result = subprocess.run( 

407 ["git", "diff", "--name-only", "HEAD~5..HEAD", "*.py"], 

408 capture_output=True, 

409 text=True, 

410 check=False, 

411 ) 

412 

413 if result.returncode != 0: 

414 return [] 

415 

416 changed_files = result.stdout.strip().split("\n") 

417 api_changes: list[dict[str, str]] = [] 

418 

419 for file_path in changed_files: 

420 if file_path and ( 

421 "api" in file_path.lower() or "__init__" in file_path 

422 ): 

423 change_info: dict[str, str] = { 

424 "file": file_path, 

425 "type": "potential_api_change", 

426 } 

427 api_changes.append(change_info) 

428 

429 return api_changes 

430 

431 except Exception: 

432 return [] 

433 

434 def _update_readme_examples( 

435 self, 

436 content: str, 

437 api_changes: list[dict[str, str]], 

438 ) -> str: 

439 if api_changes and "TODO: Update examples" not in content: 

440 lines = content.split("\n") 

441 

442 for i, line in enumerate(lines): 

443 if line.startswith("# ") and i < len(lines) - 1: 

444 lines.insert( 

445 i + 2, 

446 "<!-- TODO: Update examples after recent API changes -->", 

447 ) 

448 break 

449 return "\n".join(lines) 

450 

451 return content 

452 

453 

454agent_registry.register(DocumentationAgent)