Coverage for src/romfarmer/ai/rescue_generator.py: 18%

297 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-05 02:19 -0700

1"""AI-powered rescue list generator for 1G1Gen cross-platform deduplication. 

2 

3Uses the GitHub Copilot SDK (via copilot Python package) to query a cheap model 

4(Claude Haiku 4.5) in batch to identify games where a lower-priority platform 

5has the definitively superior version. 

6 

7Architecture: 

8 1. Load cross-platform duplicate games from the build output 

9 2. Batch them into prompts (20-30 games per prompt for efficiency) 

10 3. Ask the model: "Which platform has the best version of each game?" 

11 4. Parse structured responses into rescue lists 

12 5. Save as YAML files that plug into FilterGenerationStage 

13 

14The rescue lists OVERRIDE the deterministic priority system. Without them, 

15gen6 would always keep the PS2 version. With rescue lists, we keep the 

16GameCube version of Soul Calibur II (has Link) and the Xbox version of 

17Splinter Cell (runs better). 

18 

19Usage: 

20 generator = RescueListGenerator() 

21 await generator.connect() 

22 rescue_lists = await generator.generate("gen6", duplicate_games) 

23 generator.save(rescue_lists, output_dir) 

24 

25 # Result: { 

26 # "gamecube": {"Soul Calibur II", "Resident Evil 4", ...}, 

27 # "xbox": {"Splinter Cell", "Half-Life 2", ...}, 

28 # "dreamcast": {"Marvel vs. Capcom 2", ...}, 

29 # } 

30""" 

31 

32from __future__ import annotations 

33 

34import asyncio 

35import json 

36import logging 

37import random 

38import re 

39import time 

40from dataclasses import dataclass, field 

41from pathlib import Path 

42from typing import Any 

43 

44import yaml 

45 

46logger = logging.getLogger(__name__) 

47 

48# Default model — cheapest Copilot model, good enough for game knowledge 

49DEFAULT_MODEL = "claude-haiku-4.5" 

50 

51# How many games to include per AI prompt batch 

52BATCH_SIZE = 50 

53 

54# Copilot Router endpoint (OpenAI-compatible) 

55COPILOT_ROUTER_URL = "http://localhost:7318/v1" 

56 

57# Max concurrent API batches (backoff handles rate limits) 

58MAX_CONCURRENT_BATCHES = 3 

59 

60# System prompt for rescue list generation 

61SYSTEM_PROMPT = """\ 

62You are a video game expert helping build a ROM collection. We are deduplicating \ 

63games that appear on multiple platforms within the same console generation. 

64 

65By default, we keep the PRIMARY platform's version of each cross-platform game \ 

66and remove the others. Your job is to identify EXCEPTIONS — games where a \ 

67NON-primary platform has a definitively superior version. 

68 

69Criteria for "rescue" (keeping a non-primary version): 

70- Exclusive content: Extra characters, levels, modes, weapons (e.g., GameCube \ 

71 Soul Calibur II has Link as exclusive character) 

72- Significantly better performance: Higher framerate, resolution, or stability \ 

73 (e.g., Xbox Splinter Cell runs at higher res than PS2) 

74- Different/enhanced game: Port is substantially reworked, not just a straight \ 

75 copy (e.g., Dreamcast Crazy Taxi has original soundtrack vs PS2) 

76- Definitive edition: Platform version widely considered the best way to play 

77 

78Do NOT rescue games just because of minor differences. The bar is HIGH — only \ 

79rescue when a gaming enthusiast would specifically seek out that platform's version. 

80 

81Respond in JSON format ONLY. No markdown, no explanation outside the JSON.\ 

82""" 

83 

84 

85@dataclass 

86class RescueDecision: 

87 """AI's decision about a single cross-platform game.""" 

88 

89 game_name: str 

90 platforms_available: list[str] 

91 primary_platform: str 

92 rescue_platform: str | None = None 

93 reason: str = "" 

94 confidence: str = "high" # high, medium, low 

95 

96 

97@dataclass 

98class RescueListResult: 

99 """Complete rescue list generation result for a generation.""" 

100 

101 generation: str 

102 model: str 

103 timestamp: float = 0.0 

104 decisions: list[RescueDecision] = field(default_factory=list) 

105 rescue_lists: dict[str, set[str]] = field(default_factory=dict) 

106 stats: dict[str, Any] = field(default_factory=dict) 

107 

108 def to_rescue_dict(self) -> dict[str, set[str]]: 

109 """Get rescue lists in the format FilterGenerationStage expects. 

110 

111 Returns: 

112 Dict of platform -> set of game names to protect from removal. 

113 """ 

114 return dict(self.rescue_lists) 

115 

116 def to_yaml(self) -> str: 

117 """Serialize to YAML for caching/review.""" 

118 data = { 

119 "generation": self.generation, 

120 "model": self.model, 

121 "timestamp": self.timestamp, 

122 "stats": self.stats, 

123 "rescue_lists": { 

124 platform: sorted(games) for platform, games in self.rescue_lists.items() 

125 }, 

126 "decisions": [ 

127 { 

128 "game": d.game_name, 

129 "platforms": d.platforms_available, 

130 "primary": d.primary_platform, 

131 "rescue_to": d.rescue_platform, 

132 "reason": d.reason, 

133 "confidence": d.confidence, 

134 } 

135 for d in self.decisions 

136 if d.rescue_platform # Only include actual rescues 

137 ], 

138 } 

139 return yaml.dump(data, default_flow_style=False, sort_keys=False, allow_unicode=True) 

140 

141 @classmethod 

142 def from_yaml(cls, yaml_str: str) -> RescueListResult: 

143 """Load from saved YAML.""" 

144 data = yaml.safe_load(yaml_str) 

145 result = cls( 

146 generation=data["generation"], 

147 model=data["model"], 

148 timestamp=data.get("timestamp", 0), 

149 stats=data.get("stats", {}), 

150 ) 

151 # Rebuild rescue lists 

152 for platform, games in data.get("rescue_lists", {}).items(): 

153 result.rescue_lists[platform] = set(games) 

154 # Rebuild decisions 

155 for d in data.get("decisions", []): 

156 result.decisions.append( 

157 RescueDecision( 

158 game_name=d["game"], 

159 platforms_available=d["platforms"], 

160 primary_platform=d["primary"], 

161 rescue_platform=d.get("rescue_to"), 

162 reason=d.get("reason", ""), 

163 confidence=d.get("confidence", "high"), 

164 ) 

165 ) 

166 return result 

167 

168 

169class RescueListGenerator: 

170 """Generate AI-powered rescue lists using the Copilot SDK. 

171 

172 Uses the `copilot` Python package (github-copilot-sdk) which communicates 

173 with the Copilot CLI subprocess via JSON-RPC. No HTTP server needed. 

174 """ 

175 

176 def __init__(self, model: str = DEFAULT_MODEL, batch_size: int = BATCH_SIZE): 

177 self.model = model 

178 self.batch_size = batch_size 

179 self._client = None 

180 self._session = None 

181 

182 async def connect(self) -> None: 

183 """Initialize the Copilot SDK client and create a session.""" 

184 try: 

185 import copilot 

186 except ImportError: 

187 raise ImportError( 

188 "github-copilot-sdk required: pip install github-copilot-sdk\n" 

189 "Also requires Copilot CLI: npm install -g @github/copilot" 

190 ) from None 

191 

192 logger.info(f"Connecting to Copilot SDK (model: {self.model})...") 

193 self._client = copilot.CopilotClient() 

194 await self._client.start() 

195 

196 state = self._client.get_state() 

197 if state != "connected": 

198 raise RuntimeError(f"Copilot SDK failed to connect: state={state}") 

199 

200 auth = await self._client.get_auth_status() 

201 if not auth.isAuthenticated: 

202 raise RuntimeError("Copilot SDK not authenticated. Run: copilot /login") 

203 

204 logger.info(f"Connected to Copilot SDK as {getattr(auth, 'user', 'unknown')}") 

205 

206 async def disconnect(self) -> None: 

207 """Shut down the SDK client.""" 

208 if self._client: 

209 try: 

210 await self._client.stop() 

211 except Exception as e: 

212 logger.warning(f"Error stopping Copilot client: {e}") 

213 self._client = None 

214 self._session = None 

215 

216 async def _send_prompt(self, prompt: str) -> str: 

217 """Send a prompt to the model and get the text response. 

218 

219 Creates a fresh session per prompt to avoid context contamination. 

220 """ 

221 if not self._client: 

222 raise RuntimeError("Not connected. Call connect() first.") 

223 

224 session = await self._client.create_session({"model": self.model}) 

225 try: 

226 result = await session.send_and_wait( 

227 {"prompt": prompt}, 

228 timeout=120, 

229 ) 

230 if result and result.data and result.data.content: 

231 return result.data.content.strip() 

232 return "" 

233 except Exception as e: 

234 logger.error(f"Prompt failed: {e}") 

235 return "" 

236 

237 def _build_batch_prompt( 

238 self, 

239 generation_name: str, 

240 primary_platform: str, 

241 platform_priority: list[str], 

242 games: list[dict[str, list[str]]], 

243 ) -> str: 

244 """Build a prompt for a batch of cross-platform games. 

245 

246 Args: 

247 generation_name: e.g. "gen6" 

248 primary_platform: e.g. "ps2" 

249 platform_priority: e.g. ["ps2", "gamecube", "xbox", "dreamcast"] 

250 games: List of {"name": str, "platforms": [str, ...]} 

251 

252 Returns: 

253 Complete prompt string. 

254 """ 

255 priority_str = " > ".join(platform_priority) 

256 games_block = "\n".join( 

257 f" {i + 1}. {g['name']} — available on: {', '.join(g['platforms'])}" 

258 for i, g in enumerate(games) 

259 ) 

260 

261 return f"""{SYSTEM_PROMPT} 

262 

263Generation: {generation_name} 

264Platform priority (highest first): {priority_str} 

265Primary (default keeper): {primary_platform} 

266 

267For each game below, decide: should we KEEP the {primary_platform} version \ 

268(default), or RESCUE a different platform's version because it's definitively better? 

269 

270Games to evaluate: 

271{games_block} 

272 

273Respond with a JSON array. For each game, include: 

274- "game": the game name exactly as listed 

275- "rescue": null if the {primary_platform} version is fine, or the platform name to rescue 

276- "reason": brief reason (only needed if rescuing) 

277 

278Example response: 

279[ 

280 {{"game": "Soul Calibur II", "rescue": "gamecube", "reason": "Exclusive Link character, best version"}}, 

281 {{"game": "Grand Theft Auto Vice City", "rescue": null}}, 

282 {{"game": "Splinter Cell", "rescue": "xbox", "reason": "Higher resolution, better lighting"}} 

283] 

284 

285Respond with ONLY the JSON array:\ 

286""" 

287 

288 def _parse_batch_response( 

289 self, 

290 response: str, 

291 primary_platform: str, 

292 games: list[dict[str, list[str]]], 

293 ) -> list[RescueDecision]: 

294 """Parse the model's JSON response into RescueDecision objects.""" 

295 decisions = [] 

296 

297 # Try to extract JSON from the response (model might wrap in markdown) 

298 json_match = re.search(r"\[.*\]", response, re.DOTALL) 

299 if not json_match: 

300 logger.warning(f"No JSON array found in response: {response[:200]}") 

301 # Fall back: no rescues for this batch 

302 for g in games: 

303 decisions.append( 

304 RescueDecision( 

305 game_name=g["name"], 

306 platforms_available=g["platforms"], 

307 primary_platform=primary_platform, 

308 rescue_platform=None, 

309 reason="(parse failure — defaulting to primary)", 

310 ) 

311 ) 

312 return decisions 

313 

314 try: 

315 parsed = json.loads(json_match.group()) 

316 except json.JSONDecodeError as e: 

317 logger.warning(f"JSON parse error: {e}") 

318 # Same fallback 

319 for g in games: 

320 decisions.append( 

321 RescueDecision( 

322 game_name=g["name"], 

323 platforms_available=g["platforms"], 

324 primary_platform=primary_platform, 

325 rescue_platform=None, 

326 reason="(parse failure — defaulting to primary)", 

327 ) 

328 ) 

329 return decisions 

330 

331 # Build lookup for quick matching 

332 game_lookup = {g["name"].lower(): g for g in games} 

333 

334 for item in parsed: 

335 game_name = item.get("game", "") 

336 rescue_platform = item.get("rescue") 

337 reason = item.get("reason", "") 

338 

339 # Find matching game from our input 

340 game_info = game_lookup.get(game_name.lower()) 

341 if not game_info: 

342 # Try fuzzy match 

343 for key, val in game_lookup.items(): 

344 if game_name.lower() in key or key in game_name.lower(): 

345 game_info = val 

346 break 

347 

348 if not game_info: 

349 logger.debug(f"Could not match response game: {game_name}") 

350 continue 

351 

352 # Validate rescue platform is in the available platforms 

353 if rescue_platform and rescue_platform not in game_info["platforms"]: 

354 logger.warning( 

355 f"Model suggested {rescue_platform} for {game_name}, " 

356 f"but only available on: {game_info['platforms']}" 

357 ) 

358 rescue_platform = None 

359 

360 decisions.append( 

361 RescueDecision( 

362 game_name=game_info["name"], 

363 platforms_available=game_info["platforms"], 

364 primary_platform=primary_platform, 

365 rescue_platform=rescue_platform if rescue_platform else None, 

366 reason=reason, 

367 ) 

368 ) 

369 

370 return decisions 

371 

372 async def generate( 

373 self, 

374 generation_name: str, 

375 platform_priority: list[str], 

376 duplicate_games: list[dict[str, list[str]]], 

377 ) -> RescueListResult: 

378 """Generate rescue lists for a generation's cross-platform duplicates. 

379 

380 Args: 

381 generation_name: e.g. "gen6" 

382 platform_priority: Platforms in priority order, e.g. ["ps2", "gamecube", "xbox"] 

383 duplicate_games: List of {"name": str, "platforms": [str, ...]} 

384 Each entry is a game that exists on 2+ platforms. 

385 

386 Returns: 

387 RescueListResult with platform -> set of rescued game names. 

388 """ 

389 if not duplicate_games: 

390 logger.info("No duplicate games to evaluate.") 

391 return RescueListResult( 

392 generation=generation_name, 

393 model=self.model, 

394 timestamp=time.time(), 

395 ) 

396 

397 primary = platform_priority[0] 

398 total = len(duplicate_games) 

399 logger.info( 

400 f"Generating rescue lists for {generation_name}: " 

401 f"{total} cross-platform games, primary={primary}" 

402 ) 

403 

404 # Split into batches 

405 batches = [ 

406 duplicate_games[i : i + self.batch_size] for i in range(0, total, self.batch_size) 

407 ] 

408 logger.info(f"Processing {len(batches)} batches of ~{self.batch_size} games") 

409 

410 all_decisions: list[RescueDecision] = [] 

411 

412 for batch_idx, batch in enumerate(batches): 

413 logger.info(f"Batch {batch_idx + 1}/{len(batches)} ({len(batch)} games)...") 

414 

415 prompt = self._build_batch_prompt(generation_name, primary, platform_priority, batch) 

416 

417 response = await self._send_prompt(prompt) 

418 if not response: 

419 logger.warning(f"Empty response for batch {batch_idx + 1}") 

420 continue 

421 

422 decisions = self._parse_batch_response(response, primary, batch) 

423 all_decisions.extend(decisions) 

424 

425 # Brief pause between batches to be respectful of rate limits 

426 if batch_idx < len(batches) - 1: 

427 await asyncio.sleep(1) 

428 

429 # Build rescue lists from decisions 

430 rescue_lists: dict[str, set[str]] = {} 

431 rescued_count = 0 

432 for d in all_decisions: 

433 if d.rescue_platform: 

434 if d.rescue_platform not in rescue_lists: 

435 rescue_lists[d.rescue_platform] = set() 

436 rescue_lists[d.rescue_platform].add(d.game_name) 

437 rescued_count += 1 

438 

439 result = RescueListResult( 

440 generation=generation_name, 

441 model=self.model, 

442 timestamp=time.time(), 

443 decisions=all_decisions, 

444 rescue_lists=rescue_lists, 

445 stats={ 

446 "total_duplicates": total, 

447 "batches": len(batches), 

448 "total_evaluated": len(all_decisions), 

449 "total_rescued": rescued_count, 

450 "rescue_rate": f"{rescued_count / max(len(all_decisions), 1) * 100:.1f}%", 

451 "by_platform": {p: len(games) for p, games in rescue_lists.items()}, 

452 }, 

453 ) 

454 

455 logger.info( 

456 f"Rescue generation complete: {rescued_count}/{len(all_decisions)} " 

457 f"games rescued ({result.stats['rescue_rate']})" 

458 ) 

459 for platform, games in rescue_lists.items(): 

460 logger.info(f" {platform}: {len(games)} rescued games") 

461 

462 return result 

463 

464 # ------------------------------------------------------------------ 

465 # OpenAI-compatible API path (via Copilot Router) 

466 # ------------------------------------------------------------------ 

467 

468 def _build_enriched_batch_prompt( 

469 self, 

470 generation_name: str, 

471 primary_platform: str, 

472 platform_priority: list[str], 

473 games: list[dict], 

474 ) -> str: 

475 """Build a prompt enriched with metadata for better LLM decisions. 

476 

477 Unlike _build_batch_prompt, this includes genre/rating/developer info 

478 from ScreenScraper so the model has concrete data to reason about. 

479 """ 

480 priority_str = " > ".join(platform_priority) 

481 lines = [] 

482 for i, g in enumerate(games): 

483 plats = ", ".join(g["platforms"]) 

484 line = f" {i + 1}. {g['name']} — on: {plats}" 

485 meta = g.get("metadata", {}) 

486 if meta: 

487 meta_parts = [] 

488 for p, m in meta.items(): 

489 parts = [] 

490 if m.get("genre"): 

491 parts.append(m["genre"]) 

492 if m.get("rating"): 

493 parts.append(f"rating={m['rating']:.1f}") 

494 if m.get("developer"): 

495 parts.append(f"dev={m['developer']}") 

496 if parts: 

497 meta_parts.append(f"{p}({', '.join(parts)})") 

498 if meta_parts: 

499 line += f" [{'; '.join(meta_parts)}]" 

500 lines.append(line) 

501 games_block = "\n".join(lines) 

502 

503 return f"""{SYSTEM_PROMPT} 

504 

505Generation: {generation_name} 

506Platform priority (highest first): {priority_str} 

507Primary (default keeper): {primary_platform} 

508 

509For each game below, decide: should we KEEP the {primary_platform} version \ 

510(default), or RESCUE a different platform's version because it's definitively better? 

511 

512Metadata is provided where available (genre, rating, developer) per platform. 

513 

514Games to evaluate: 

515{games_block} 

516 

517Respond with a JSON array. For each game, include: 

518- "game": the game name exactly as listed 

519- "rescue": null if the {primary_platform} version is fine, or the platform name to rescue 

520- "reason": brief reason (only needed if rescuing) 

521 

522Respond with ONLY the JSON array:\ 

523""" 

524 

525 async def _send_prompt_via_api(self, prompt: str) -> str: 

526 """Send a prompt via the OpenAI-compatible Copilot Router HTTP API. 

527 

528 Uses httpx for async HTTP. Falls back to urllib if httpx unavailable. 

529 """ 

530 import urllib.error 

531 import urllib.request 

532 

533 payload = json.dumps( 

534 { 

535 "model": self.model, 

536 "messages": [ 

537 {"role": "user", "content": prompt}, 

538 ], 

539 "temperature": 0.1, 

540 "max_tokens": 4096, 

541 } 

542 ) 

543 

544 req = urllib.request.Request( 

545 f"{COPILOT_ROUTER_URL}/chat/completions", 

546 data=payload.encode("utf-8"), 

547 headers={ 

548 "Content-Type": "application/json", 

549 "Authorization": "Bearer not-required", 

550 }, 

551 method="POST", 

552 ) 

553 

554 try: 

555 with urllib.request.urlopen(req, timeout=120) as resp: 

556 data = json.loads(resp.read().decode("utf-8")) 

557 return data["choices"][0]["message"]["content"].strip() 

558 except (urllib.error.URLError, urllib.error.HTTPError) as e: 

559 logger.error(f"API call failed: {e}") 

560 return "" 

561 except (KeyError, IndexError) as e: 

562 logger.error(f"Unexpected API response: {e}") 

563 return "" 

564 

565 async def _send_batch_concurrent( 

566 self, 

567 prompts: list[str], 

568 ) -> list[str]: 

569 """Send multiple prompts concurrently (up to MAX_CONCURRENT_BATCHES). 

570 

571 Uses asyncio.to_thread to run synchronous urllib calls concurrently. 

572 """ 

573 import asyncio 

574 

575 sem = asyncio.Semaphore(MAX_CONCURRENT_BATCHES) 

576 

577 async def _one(prompt: str) -> str: 

578 async with sem: 

579 return await asyncio.to_thread(self._send_prompt_sync, prompt) 

580 

581 return await asyncio.gather(*[_one(p) for p in prompts]) 

582 

583 def _send_prompt_sync(self, prompt: str, max_retries: int = 6) -> str: 

584 """Synchronous version of _send_prompt_via_api for use with to_thread. 

585 

586 Retries on failure with exponential backoff + jitter. 

587 Rate-limit (429) errors use longer backoff and respect Retry-After. 

588 """ 

589 import urllib.error 

590 import urllib.request 

591 

592 payload = json.dumps( 

593 { 

594 "model": self.model, 

595 "messages": [ 

596 {"role": "user", "content": prompt}, 

597 ], 

598 "temperature": 0.1, 

599 "max_tokens": 4096, 

600 } 

601 ) 

602 

603 base_delay = 5 # seconds 

604 

605 for attempt in range(max_retries + 1): 

606 req = urllib.request.Request( 

607 f"{COPILOT_ROUTER_URL}/chat/completions", 

608 data=payload.encode("utf-8"), 

609 headers={ 

610 "Content-Type": "application/json", 

611 "Authorization": "Bearer not-required", 

612 }, 

613 method="POST", 

614 ) 

615 

616 try: 

617 with urllib.request.urlopen(req, timeout=180) as resp: 

618 data = json.loads(resp.read().decode("utf-8")) 

619 content = data["choices"][0]["message"]["content"].strip() 

620 if content: 

621 return content 

622 logger.warning(f"Attempt {attempt + 1}: empty response from API") 

623 except urllib.error.HTTPError as e: 

624 if e.code == 429: 

625 retry_after = e.headers.get("Retry-After") 

626 if retry_after: 

627 wait = int(retry_after) 

628 else: 

629 wait = base_delay * (2**attempt) 

630 wait = min(wait, 120) 

631 jitter = random.uniform(0, wait * 0.25) 

632 logger.warning( 

633 f"Rate limited (429) on attempt {attempt + 1}. " 

634 f"Waiting {wait + jitter:.1f}s..." 

635 ) 

636 time.sleep(wait + jitter) 

637 continue 

638 logger.warning(f"HTTP {e.code} on attempt {attempt + 1}: {e.reason}") 

639 except Exception as e: 

640 logger.warning(f"API call attempt {attempt + 1} failed: {e}") 

641 

642 if attempt < max_retries: 

643 wait = base_delay * (2**attempt) 

644 wait = min(wait, 120) 

645 jitter = random.uniform(0, wait * 0.25) 

646 logger.info(f"Retrying in {wait + jitter:.1f}s...") 

647 time.sleep(wait + jitter) 

648 

649 logger.error(f"All {max_retries + 1} attempts exhausted") 

650 return "" 

651 

652 async def generate_via_api( 

653 self, 

654 generation_name: str, 

655 platform_priority: list[str], 

656 duplicate_games: list[dict], 

657 ) -> RescueListResult: 

658 """Generate rescue lists using the OpenAI-compatible Copilot Router API. 

659 

660 This is the optimized path: 

661 - Uses HTTP API instead of Copilot SDK subprocess 

662 - Supports metadata-enriched prompts 

663 - Sends concurrent batches for speed 

664 - Larger default batch size (50 vs 25) 

665 

666 Args: 

667 generation_name: e.g. "gen6" 

668 platform_priority: Platforms in priority order 

669 duplicate_games: List of {"name": str, "platforms": [str, ...], 

670 "metadata": {platform: {genre, rating, ...}}} 

671 

672 Returns: 

673 RescueListResult with rescue lists. 

674 """ 

675 if not duplicate_games: 

676 return RescueListResult( 

677 generation=generation_name, 

678 model=self.model, 

679 timestamp=time.time(), 

680 ) 

681 

682 primary = platform_priority[0] 

683 total = len(duplicate_games) 

684 logger.info( 

685 f"Generating rescue lists for {generation_name} via API: " 

686 f"{total} games, model={self.model}, batch_size={self.batch_size}" 

687 ) 

688 

689 # Build batched prompts 

690 batches = [ 

691 duplicate_games[i : i + self.batch_size] for i in range(0, total, self.batch_size) 

692 ] 

693 

694 prompts = [ 

695 self._build_enriched_batch_prompt(generation_name, primary, platform_priority, batch) 

696 for batch in batches 

697 ] 

698 

699 logger.info(f"Sending {len(prompts)} batches ({MAX_CONCURRENT_BATCHES} concurrent)") 

700 

701 # Send all batches (concurrent within limit) 

702 responses = await self._send_batch_concurrent(prompts) 

703 

704 # Parse all responses 

705 all_decisions: list[RescueDecision] = [] 

706 for batch_idx, (response, batch) in enumerate(zip(responses, batches, strict=False)): 

707 if not response: 

708 logger.warning(f"Empty response for batch {batch_idx + 1}") 

709 continue 

710 decisions = self._parse_batch_response(response, primary, batch) 

711 all_decisions.extend(decisions) 

712 logger.info( 

713 f"Batch {batch_idx + 1}/{len(batches)}: " 

714 f"{sum(1 for d in decisions if d.rescue_platform)} rescues" 

715 ) 

716 

717 # Build rescue lists 

718 rescue_lists: dict[str, set[str]] = {} 

719 rescued_count = 0 

720 for d in all_decisions: 

721 if d.rescue_platform: 

722 if d.rescue_platform not in rescue_lists: 

723 rescue_lists[d.rescue_platform] = set() 

724 rescue_lists[d.rescue_platform].add(d.game_name) 

725 rescued_count += 1 

726 

727 result = RescueListResult( 

728 generation=generation_name, 

729 model=self.model, 

730 timestamp=time.time(), 

731 decisions=all_decisions, 

732 rescue_lists=rescue_lists, 

733 stats={ 

734 "total_duplicates": total, 

735 "batches": len(batches), 

736 "total_evaluated": len(all_decisions), 

737 "total_rescued": rescued_count, 

738 "rescue_rate": f"{rescued_count / max(len(all_decisions), 1) * 100:.1f}%", 

739 "by_platform": {p: len(g) for p, g in rescue_lists.items()}, 

740 }, 

741 ) 

742 

743 logger.info(f"Rescue generation complete: {rescued_count}/{len(all_decisions)} rescued") 

744 return result 

745 

746 def save(self, result: RescueListResult, output_dir: Path) -> Path: 

747 """Save rescue lists to a YAML file. 

748 

749 Args: 

750 result: The generation result. 

751 output_dir: Directory to save in (e.g., config/curations/rescue/). 

752 

753 Returns: 

754 Path to the saved file. 

755 """ 

756 output_dir.mkdir(parents=True, exist_ok=True) 

757 filepath = output_dir / f"rescue-{result.generation}.yaml" 

758 filepath.write_text(result.to_yaml()) 

759 logger.info(f"Saved rescue lists to {filepath}") 

760 return filepath 

761 

762 @staticmethod 

763 def load(filepath: Path) -> RescueListResult: 

764 """Load previously generated rescue lists.""" 

765 return RescueListResult.from_yaml(filepath.read_text()) 

766 

767 

768# --------------------------------------------------------------------------- 

769# Convenience function for CLI / build integration 

770# --------------------------------------------------------------------------- 

771 

772 

773async def generate_rescue_lists( 

774 generation_name: str, 

775 platform_priority: list[str], 

776 duplicate_games: list[dict[str, list[str]]], 

777 model: str = DEFAULT_MODEL, 

778 cache_dir: Path | None = None, 

779 force_regenerate: bool = False, 

780) -> dict[str, set[str]]: 

781 """High-level function to generate or load cached rescue lists. 

782 

783 This is the main entry point for build integration. It: 

784 1. Checks for cached results (skip AI call if fresh enough) 

785 2. Generates new rescue lists via Copilot SDK 

786 3. Caches the results for future builds 

787 4. Returns the rescue dict for FilterGenerationStage 

788 

789 Args: 

790 generation_name: e.g. "gen6" 

791 platform_priority: Platforms in priority order 

792 duplicate_games: Cross-platform duplicate games to evaluate 

793 model: Copilot model to use 

794 cache_dir: Directory for cached results 

795 force_regenerate: Skip cache and regenerate 

796 

797 Returns: 

798 Dict of platform -> set of game names to rescue. 

799 """ 

800 if cache_dir is None: 

801 from romfarmer.core.paths import paths 

802 

803 cache_dir = paths.workspace_root / "config" / "curations" / "rescue" 

804 

805 # Check cache 

806 cache_file = cache_dir / f"rescue-{generation_name}.yaml" 

807 if cache_file.exists() and not force_regenerate: 

808 logger.info(f"Loading cached rescue lists from {cache_file}") 

809 result = RescueListResult.from_yaml(cache_file.read_text()) 

810 logger.info( 

811 f"Cached: {result.stats.get('total_rescued', '?')} rescues for {generation_name}" 

812 ) 

813 return result.to_rescue_dict() 

814 

815 # Generate fresh 

816 generator = RescueListGenerator(model=model) 

817 try: 

818 await generator.connect() 

819 result = await generator.generate(generation_name, platform_priority, duplicate_games) 

820 generator.save(result, cache_dir) 

821 return result.to_rescue_dict() 

822 finally: 

823 await generator.disconnect()