Coverage for little_loops / dependency_mapper / analysis.py: 96%

162 statements  

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

1"""Dependency analysis functions. 

2 

3Functions for computing conflict scores, finding file overlaps, 

4validating dependency references, and orchestrating full dependency analysis. 

5""" 

6 

7from __future__ import annotations 

8 

9import logging 

10import re 

11from typing import TYPE_CHECKING 

12 

13from little_loops.dependency_graph import DependencyGraph 

14from little_loops.dependency_mapper.models import ( 

15 DependencyProposal, 

16 DependencyReport, 

17 ParallelSafePair, 

18 ValidationResult, 

19) 

20from little_loops.text_utils import extract_file_paths 

21 

22if TYPE_CHECKING: 

23 from little_loops.config import DependencyMappingConfig 

24 from little_loops.issue_parser import IssueInfo 

25 

26logger = logging.getLogger(__name__) 

27 

28_CODE_FENCE = re.compile(r"```[\s\S]*?```", re.MULTILINE) 

29 

30# Semantic target extraction patterns 

31_PASCAL_CASE = re.compile(r"\b([A-Z][a-z]+(?:[A-Z][a-z]+)+)\b") 

32_FUNCTION_REF = re.compile(r"`(\w+)\(\)`") 

33_COMPONENT_SCOPE = re.compile( 

34 r"(?:component|module|class|widget|section)[:\s]+[`\"']?([a-zA-Z0-9_./\-]{3,})[`\"']?", 

35 re.IGNORECASE, 

36) 

37 

38# UI region / section keywords mapped to canonical names 

39_SECTION_KEYWORDS: dict[str, frozenset[str]] = { 

40 "header": frozenset({"header", "navbar", "toolbar", "top bar"}), 

41 "body": frozenset({"droppable"}), 

42 "footer": frozenset({"footer", "status bar", "action bar"}), 

43 "sidebar": frozenset({"sidebar", "side panel", "drawer"}), 

44 "card": frozenset({"card", "tile"}), 

45 "modal": frozenset({"modal", "dialog", "popup", "overlay"}), 

46 "form": frozenset({"form"}), 

47} 

48 

49# Modification type classification keywords 

50_MODIFICATION_TYPES: dict[str, frozenset[str]] = { 

51 "structural": frozenset( 

52 { 

53 "extract", 

54 "split", 

55 "refactor", 

56 "restructure", 

57 "reorganize", 

58 "create new component", 

59 "break out", 

60 "separate", 

61 "decompose", 

62 } 

63 ), 

64 "infrastructure": frozenset( 

65 { 

66 "listener", 

67 "provider", 

68 "state management", 

69 "routing", 

70 "middleware", 

71 "dragging", 

72 "drag", 

73 "drop", 

74 "dnd", 

75 } 

76 ), 

77 "enhancement": frozenset( 

78 { 

79 "add button", 

80 "add field", 

81 "add column", 

82 "add stats", 

83 "add icon", 

84 "add toggle", 

85 "empty state", 

86 "placeholder", 

87 "tooltip", 

88 "badge", 

89 } 

90 ), 

91} 

92 

93 

94def _extract_semantic_targets(content: str) -> set[str]: 

95 """Extract component and function references from issue content. 

96 

97 Identifies PascalCase component names, function references, 

98 and explicitly mentioned component/module scopes. 

99 

100 Args: 

101 content: Issue file content 

102 

103 Returns: 

104 Set of normalized semantic target names 

105 """ 

106 if not content: 

107 return set() 

108 

109 stripped = _CODE_FENCE.sub("", content) 

110 targets: set[str] = set() 

111 

112 for match in _PASCAL_CASE.finditer(stripped): 

113 targets.add(match.group(1).lower()) 

114 

115 for match in _FUNCTION_REF.finditer(stripped): 

116 targets.add(match.group(1).lower()) 

117 

118 for match in _COMPONENT_SCOPE.finditer(stripped): 

119 targets.add(match.group(1).lower()) 

120 

121 return targets 

122 

123 

124def _extract_section_mentions(content: str) -> set[str]: 

125 """Extract UI region/section references from issue content. 

126 

127 Maps keywords like "header", "body", "sidebar" to canonical 

128 section names using word-boundary matching. 

129 

130 Args: 

131 content: Issue file content 

132 

133 Returns: 

134 Set of canonical section names mentioned 

135 """ 

136 if not content: 

137 return set() 

138 

139 content_lower = content.lower() 

140 sections: set[str] = set() 

141 

142 for section_name, keywords in _SECTION_KEYWORDS.items(): 

143 for keyword in keywords: 

144 # Use word boundary for single words, substring for multi-word phrases 

145 if " " in keyword: 

146 if keyword in content_lower: 

147 sections.add(section_name) 

148 break 

149 else: 

150 if re.search(rf"\b{re.escape(keyword)}\b", content_lower): 

151 sections.add(section_name) 

152 break 

153 

154 return sections 

155 

156 

157def _classify_modification_type(content: str) -> str: 

158 """Classify the modification type of an issue. 

159 

160 Returns one of: "structural", "infrastructure", "enhancement". 

161 Falls back to "enhancement" if no clear match. 

162 

163 Args: 

164 content: Issue file content 

165 

166 Returns: 

167 Modification type classification string 

168 """ 

169 if not content: 

170 return "enhancement" 

171 

172 content_lower = content.lower() 

173 

174 for mod_type in ("structural", "infrastructure", "enhancement"): 

175 keywords = _MODIFICATION_TYPES[mod_type] 

176 for keyword in keywords: 

177 if keyword in content_lower: 

178 return mod_type 

179 

180 return "enhancement" 

181 

182 

183def compute_conflict_score( 

184 content_a: str, 

185 content_b: str, 

186 *, 

187 config: DependencyMappingConfig | None = None, 

188) -> float: 

189 """Compute semantic conflict score between two issues. 

190 

191 Combines three signals with configurable weights: 

192 - Semantic target overlap (component/function names) 

193 - Section mention overlap (UI regions) 

194 - Modification type match 

195 

196 Args: 

197 content_a: First issue's file content 

198 content_b: Second issue's file content 

199 config: Optional dependency mapping config for custom scoring weights. 

200 Falls back to default weights (0.5/0.3/0.2) when not provided. 

201 

202 Returns: 

203 Conflict score from 0.0 (parallel-safe) to 1.0 (definite conflict) 

204 """ 

205 targets_a = _extract_semantic_targets(content_a) 

206 targets_b = _extract_semantic_targets(content_b) 

207 

208 sections_a = _extract_section_mentions(content_a) 

209 sections_b = _extract_section_mentions(content_b) 

210 

211 type_a = _classify_modification_type(content_a) 

212 type_b = _classify_modification_type(content_b) 

213 

214 # Resolve scoring weights from config or defaults 

215 w_semantic = config.scoring_weights.semantic if config else 0.5 

216 w_section = config.scoring_weights.section if config else 0.3 

217 w_type = config.scoring_weights.type if config else 0.2 

218 

219 # Signal 1: Semantic target overlap (0.0 - 1.0) 

220 if targets_a and targets_b: 

221 target_union = len(targets_a | targets_b) 

222 target_score = len(targets_a & targets_b) / target_union if target_union > 0 else 0.0 

223 else: 

224 target_score = 0.5 # Unknown — default to moderate 

225 

226 # Signal 2: Section overlap (0.0 or 1.0) 

227 if sections_a and sections_b: 

228 section_score = 1.0 if sections_a & sections_b else 0.0 

229 else: 

230 section_score = 0.5 # Unknown 

231 

232 # Signal 3: Modification type match (0.0 or 1.0) 

233 type_score = 1.0 if type_a == type_b else 0.0 

234 

235 return round(target_score * w_semantic + section_score * w_section + type_score * w_type, 2) 

236 

237 

238def find_file_overlaps( 

239 issues: list[IssueInfo], 

240 issue_contents: dict[str, str], 

241 *, 

242 config: DependencyMappingConfig | None = None, 

243) -> tuple[list[DependencyProposal], list[ParallelSafePair]]: 

244 """Find issues that reference overlapping files and propose dependencies. 

245 

246 For each pair of issues where both reference the same file(s), computes 

247 a semantic conflict score. High-conflict pairs get dependency proposals; 

248 low-conflict pairs are reported as parallel-safe. 

249 

250 Pairs that already have a dependency relationship are skipped. 

251 

252 Args: 

253 issues: List of parsed issue objects 

254 issue_contents: Mapping from issue_id to file content 

255 config: Optional dependency mapping config for custom thresholds. 

256 Falls back to hardcoded defaults when not provided. 

257 

258 Returns: 

259 Tuple of (proposed dependencies, parallel-safe pairs) 

260 """ 

261 # Build existing dependency set for skip check 

262 existing_deps: set[tuple[str, str]] = set() 

263 for issue in issues: 

264 for blocker_id in issue.blocked_by: 

265 existing_deps.add((issue.issue_id, blocker_id)) 

266 

267 # Extract file paths per issue 

268 issue_paths: dict[str, set[str]] = {} 

269 for issue in issues: 

270 content = issue_contents.get(issue.issue_id, "") 

271 paths = extract_file_paths(content) 

272 if paths: 

273 issue_paths[issue.issue_id] = paths 

274 

275 proposals: list[DependencyProposal] = [] 

276 parallel_safe: list[ParallelSafePair] = [] 

277 issue_ids = sorted(issue_paths.keys()) 

278 

279 _type_order = {"structural": 0, "infrastructure": 1, "enhancement": 2} 

280 

281 for i, id_a in enumerate(issue_ids): 

282 for id_b in issue_ids[i + 1 :]: 

283 overlap = issue_paths[id_a] & issue_paths[id_b] 

284 if not overlap: 

285 continue 

286 

287 # Skip if dependency already exists (in either direction) 

288 if (id_a, id_b) in existing_deps or (id_b, id_a) in existing_deps: 

289 continue 

290 

291 content_a = issue_contents.get(id_a, "") 

292 content_b = issue_contents.get(id_b, "") 

293 conflict = compute_conflict_score(content_a, content_b, config=config) 

294 

295 overlap_list = sorted(overlap) 

296 

297 # Resolve conflict threshold from config or default 

298 conflict_threshold = config.conflict_threshold if config else 0.4 

299 

300 # Low-conflict pairs are parallel-safe 

301 if conflict < conflict_threshold: 

302 sections_a = _extract_section_mentions(content_a) 

303 sections_b = _extract_section_mentions(content_b) 

304 if sections_a and sections_b: 

305 reason = ( 

306 f"Different sections ({', '.join(sorted(sections_a))}" 

307 f" vs {', '.join(sorted(sections_b))})" 

308 ) 

309 else: 

310 reason = "Low semantic conflict score" 

311 parallel_safe.append( 

312 ParallelSafePair( 

313 issue_a=id_a, 

314 issue_b=id_b, 

315 shared_files=overlap_list, 

316 conflict_score=conflict, 

317 reason=reason, 

318 ) 

319 ) 

320 continue 

321 

322 # Determine direction for high-conflict pairs 

323 issue_a = next(iss for iss in issues if iss.issue_id == id_a) 

324 issue_b = next(iss for iss in issues if iss.issue_id == id_b) 

325 

326 confidence_modifier = 1.0 

327 

328 if issue_a.priority_int != issue_b.priority_int: 

329 # Different priorities: higher priority blocks lower 

330 if issue_a.priority_int < issue_b.priority_int: 

331 target_id, source_id = id_a, id_b 

332 else: 

333 target_id, source_id = id_b, id_a 

334 else: 

335 # Same priority: use modification type ordering 

336 type_a = _classify_modification_type(content_a) 

337 type_b = _classify_modification_type(content_b) 

338 order_a = _type_order.get(type_a, 2) 

339 order_b = _type_order.get(type_b, 2) 

340 

341 if order_a != order_b: 

342 if order_a < order_b: 

343 target_id, source_id = id_a, id_b 

344 else: 

345 target_id, source_id = id_b, id_a 

346 else: 

347 # Fall back to ID ordering with reduced confidence 

348 if id_a < id_b: 

349 target_id, source_id = id_a, id_b 

350 else: 

351 target_id, source_id = id_b, id_a 

352 confidence_modifier = config.confidence_modifier if config else 0.5 

353 

354 min_paths = min(len(issue_paths[id_a]), len(issue_paths[id_b])) 

355 confidence = len(overlap) / min_paths if min_paths > 0 else 0.0 

356 confidence *= confidence_modifier 

357 

358 rationale = ( 

359 f"{source_id} and {target_id} both reference " 

360 f"{', '.join(overlap_list[:3])}" 

361 f"{' and more' if len(overlap_list) > 3 else ''}. " 

362 f"{target_id} has higher priority and should be completed first." 

363 ) 

364 

365 proposals.append( 

366 DependencyProposal( 

367 source_id=source_id, 

368 target_id=target_id, 

369 reason="file_overlap", 

370 confidence=round(confidence, 2), 

371 rationale=rationale, 

372 overlapping_files=overlap_list, 

373 conflict_score=conflict, 

374 ) 

375 ) 

376 

377 # Sort by confidence descending 

378 proposals.sort(key=lambda p: -p.confidence) 

379 return proposals, parallel_safe 

380 

381 

382def validate_dependencies( 

383 issues: list[IssueInfo], 

384 completed_ids: set[str] | None = None, 

385 all_known_ids: set[str] | None = None, 

386) -> ValidationResult: 

387 """Validate existing dependency references for integrity. 

388 

389 Checks: 

390 - Broken refs: blocked_by entries referencing nonexistent issues 

391 - Missing backlinks: A blocks B but B doesn't list A in blocked_by 

392 - Cycles: circular dependency chains 

393 - Stale completed refs: blocked_by entries referencing completed issues 

394 

395 Args: 

396 issues: List of parsed issue objects 

397 completed_ids: Set of completed issue IDs 

398 all_known_ids: Set of all issue IDs that exist on disk (across all 

399 categories and completed). When provided, references to issues 

400 in this set are not flagged as broken even if they are not in 

401 the working ``issues`` list. 

402 

403 Returns: 

404 ValidationResult with all detected problems 

405 """ 

406 completed = completed_ids or set() 

407 result = ValidationResult() 

408 

409 active_ids = {issue.issue_id for issue in issues} 

410 all_known = active_ids | completed 

411 if all_known_ids: 

412 all_known = all_known | all_known_ids 

413 

414 # Build lookup maps 

415 blocked_by_map: dict[str, set[str]] = {} 

416 blocks_map: dict[str, set[str]] = {} 

417 for issue in issues: 

418 blocked_by_map[issue.issue_id] = set(issue.blocked_by) 

419 blocks_map[issue.issue_id] = set(issue.blocks) 

420 

421 for issue in issues: 

422 for ref_id in issue.blocked_by: 

423 if ref_id not in all_known: 

424 result.broken_refs.append((issue.issue_id, ref_id)) 

425 elif ref_id in completed: 

426 result.stale_completed_refs.append((issue.issue_id, ref_id)) 

427 

428 # Check backlinks: if A.blocked_by contains B, then B.blocks should contain A 

429 for ref_id in issue.blocked_by: 

430 if ref_id in active_ids: 

431 target_blocks = blocks_map.get(ref_id, set()) 

432 if issue.issue_id not in target_blocks: 

433 result.missing_backlinks.append((issue.issue_id, ref_id)) 

434 

435 # Cycle detection using DependencyGraph 

436 graph = DependencyGraph.from_issues(issues, completed, all_known_ids=all_known_ids) 

437 result.cycles = graph.detect_cycles() 

438 

439 return result 

440 

441 

442def analyze_dependencies( 

443 issues: list[IssueInfo], 

444 issue_contents: dict[str, str], 

445 completed_ids: set[str] | None = None, 

446 all_known_ids: set[str] | None = None, 

447 *, 

448 config: DependencyMappingConfig | None = None, 

449) -> DependencyReport: 

450 """Run full dependency analysis: discovery and validation. 

451 

452 Args: 

453 issues: List of parsed issue objects 

454 issue_contents: Mapping from issue_id to file content 

455 completed_ids: Set of completed issue IDs 

456 all_known_ids: Set of all issue IDs that exist on disk 

457 config: Optional dependency mapping config for custom thresholds. 

458 

459 Returns: 

460 Comprehensive dependency report 

461 """ 

462 proposals, parallel_safe = find_file_overlaps(issues, issue_contents, config=config) 

463 validation = validate_dependencies(issues, completed_ids, all_known_ids) 

464 

465 existing_dep_count = sum(len(issue.blocked_by) for issue in issues) 

466 

467 return DependencyReport( 

468 proposals=proposals, 

469 parallel_safe=parallel_safe, 

470 validation=validation, 

471 issue_count=len(issues), 

472 existing_dep_count=existing_dep_count, 

473 )