Coverage for src/romfarmer/ai/curator.py: 50%
223 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-05 02:19 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-05 02:19 -0700
1"""AI-powered game curation engine.
3The AICurator generates intelligent, ranked game lists for ROM Farmer builds.
4It operates in multiple modes:
61. **Knowledge-based**: Uses pre-defined rankings from gaming expertise
7 (critical consensus, historical importance, genre diversity).
8 This is what the agent generates when creating curated lists.
102. **Metadata-enriched**: Combines knowledge rankings with the scraped_games
11 database (ratings, genres, descriptions) to validate and extend rankings.
133. **Embedding-powered** (future): Uses sentence-transformers to cluster
14 games by similarity, find hidden gems, and match cross-platform titles.
164. **LLM-live** (future): Queries a language model during build decisions
17 via Copilot SDK / API integration.
19Output format: YAML curated lists that integrate directly with ROM Farmer's
20ApplyListsStage and SelectionFilter pipeline stages.
21"""
23from __future__ import annotations
25import enum
26import json
27import logging
28import sqlite3
29from dataclasses import dataclass, field
30from pathlib import Path
31from typing import Any
33import yaml
35logger = logging.getLogger(__name__)
38# ---------------------------------------------------------------------------
39# Tier system
40# ---------------------------------------------------------------------------
43class GameTier(str, enum.Enum):
44 """Quality tiers for curated games.
46 Each tier represents a curatorial judgment, not just a rating threshold.
47 A tier-1 game is a game that DEFINES its platform — everyone should play it.
48 A tier-4 game is still good, but you'd only include it in a large collection.
49 """
51 ESSENTIAL = "essential" # Tier 1: Defines the platform. Must-play. (~5-15 per platform)
52 EXCELLENT = "excellent" # Tier 2: Outstanding games. (~15-50 per platform)
53 GREAT = "great" # Tier 3: Very good games. (~50-150 per platform)
54 NOTABLE = "notable" # Tier 4: Good games worth including. (~150-500)
55 COMPLETE = "complete" # Tier 5: The rest of the 1G1R set. Everything else.
57 @property
58 def rank(self) -> int:
59 """Numeric rank (lower = better). Essential=1, Complete=5."""
60 return list(GameTier).index(self) + 1
62 @property
63 def label(self) -> str:
64 """Human-friendly label with tier number."""
65 return f"Tier {self.rank}: {self.value.title()}"
68@dataclass
69class CuratedGame:
70 """A game with its curatorial assessment.
72 Attributes:
73 name: Game name as it appears in ROM filenames (No-Intro/Redump style)
74 tier: Quality tier assignment
75 score: Numeric score 0-100 for ordering within a tier
76 tags: Curatorial tags (hidden-gem, genre-defining, japan-exclusive, etc.)
77 note: Brief curatorial note explaining the ranking
78 genre: Game genre (from metadata or knowledge)
79 year: Release year
80 players: Player count info
81 cross_platform: True if this game exists on other platforms in same gen
82 best_platform: The single best platform to play this game on
83 """
85 name: str
86 tier: GameTier = GameTier.COMPLETE
87 score: int = 50
88 tags: list[str] = field(default_factory=list)
89 note: str = ""
90 genre: str = ""
91 year: str = ""
92 players: str = ""
93 cross_platform: bool = False
94 best_platform: str = ""
96 def to_dict(self) -> dict[str, Any]:
97 """Serialize for YAML output."""
98 d: dict[str, Any] = {"name": self.name, "tier": self.tier.value, "score": self.score}
99 if self.tags:
100 d["tags"] = self.tags
101 if self.note:
102 d["note"] = self.note
103 if self.genre:
104 d["genre"] = self.genre
105 if self.year:
106 d["year"] = self.year
107 if self.cross_platform:
108 d["cross_platform"] = True
109 if self.best_platform:
110 d["best_platform"] = self.best_platform
111 return d
113 @classmethod
114 def from_dict(cls, data: dict[str, Any]) -> CuratedGame:
115 """Deserialize from YAML."""
116 return cls(
117 name=data["name"],
118 tier=GameTier(data.get("tier", "complete")),
119 score=data.get("score", 50),
120 tags=data.get("tags", []),
121 note=data.get("note", ""),
122 genre=data.get("genre", ""),
123 year=data.get("year", ""),
124 players=data.get("players", ""),
125 cross_platform=data.get("cross_platform", False),
126 best_platform=data.get("best_platform", ""),
127 )
130@dataclass
131class PlatformCuration:
132 """Complete curated ranking for a platform.
134 Attributes:
135 platform: Platform identifier (psx, ps2, saturn, etc.)
136 version: Curation version (bumped when re-generated)
137 curator: Who/what generated this curation
138 games: All ranked games for this platform
139 generation: Console generation identifier
140 total_available: Total games in the 1G1R set for this platform
141 metadata: Additional curation metadata
142 """
144 platform: str
145 version: str = "1.0.0"
146 curator: str = "ai-frontier"
147 games: list[CuratedGame] = field(default_factory=list)
148 generation: str = ""
149 total_available: int = 0
150 metadata: dict[str, Any] = field(default_factory=dict)
152 # --- Tier queries ---
154 def by_tier(self, tier: GameTier) -> list[CuratedGame]:
155 """Get games at a specific tier."""
156 return [g for g in self.games if g.tier == tier]
158 def up_to_tier(self, tier: GameTier) -> list[CuratedGame]:
159 """Get games at or above a tier (Essential through the given tier)."""
160 return [g for g in self.games if g.tier.rank <= tier.rank]
162 def essentials(self) -> list[CuratedGame]:
163 return self.by_tier(GameTier.ESSENTIAL)
165 def top_n(self, n: int) -> list[CuratedGame]:
166 """Get top N games across all tiers, by score descending."""
167 return sorted(self.games, key=lambda g: (-g.tier.rank * -1, -g.score))[:n]
169 # --- List generation ---
171 def to_include_list(self, max_tier: GameTier = GameTier.GREAT) -> list[str]:
172 """Generate a ROM Farmer include list (just filenames).
174 This output format is directly consumable by ApplyListsStage.
175 One filename per line, no extensions (matched via fuzzy/stem).
176 """
177 games = self.up_to_tier(max_tier)
178 games.sort(key=lambda g: (-g.score, g.name))
179 return [g.name for g in games]
181 def to_rom_farmer_list(
182 self,
183 max_tier: GameTier = GameTier.GREAT,
184 header_comment: bool = True,
185 ) -> str:
186 """Generate a ROM Farmer list file compatible with ApplyListsStage.
188 Format: One filename per line, # comments for documentation.
189 """
190 lines = []
192 if header_comment:
193 lines.append(f"# AI-Curated {self.platform.upper()} Games")
194 lines.append(f"# Curator: {self.curator} v{self.version}")
195 tier_label = max_tier.label
196 count = len(self.up_to_tier(max_tier))
197 lines.append(f"# Tier: {tier_label} ({count} games)")
198 lines.append(f"# Total available: {self.total_available}")
199 lines.append("")
201 current_tier = None
202 for game in sorted(self.up_to_tier(max_tier), key=lambda g: (g.tier.rank, -g.score)):
203 if game.tier != current_tier:
204 current_tier = game.tier
205 if lines and lines[-1] != "":
206 lines.append("")
207 lines.append(f"# === {current_tier.label} ===")
209 lines.append(game.name)
211 return "\n".join(lines) + "\n"
213 # --- Serialization ---
215 def to_yaml(self) -> str:
216 """Serialize to YAML for storage."""
217 data = {
218 "platform": self.platform,
219 "version": self.version,
220 "curator": self.curator,
221 "generation": self.generation,
222 "total_available": self.total_available,
223 "metadata": self.metadata,
224 "tiers": {
225 tier.value: {
226 "count": len(self.by_tier(tier)),
227 "games": [
228 g.to_dict() for g in sorted(self.by_tier(tier), key=lambda g: -g.score)
229 ],
230 }
231 for tier in GameTier
232 if self.by_tier(tier)
233 },
234 }
235 return yaml.dump(data, default_flow_style=False, sort_keys=False, allow_unicode=True)
237 @classmethod
238 def from_yaml(cls, yaml_str: str) -> PlatformCuration:
239 """Deserialize from YAML."""
240 data = yaml.safe_load(yaml_str)
241 games = []
242 for _tier_name, tier_data in data.get("tiers", {}).items():
243 for game_data in tier_data.get("games", []):
244 games.append(CuratedGame.from_dict(game_data))
246 return cls(
247 platform=data["platform"],
248 version=data.get("version", "1.0.0"),
249 curator=data.get("curator", "unknown"),
250 games=games,
251 generation=data.get("generation", ""),
252 total_available=data.get("total_available", 0),
253 metadata=data.get("metadata", {}),
254 )
256 def save(self, directory: Path) -> Path:
257 """Save curation to a YAML file.
259 Args:
260 directory: Directory to save in
262 Returns:
263 Path to saved file
264 """
265 directory.mkdir(parents=True, exist_ok=True)
266 filepath = directory / f"{self.platform}.yaml"
267 filepath.write_text(self.to_yaml())
268 logger.info(f"Saved {self.platform} curation: {len(self.games)} games to {filepath}")
269 return filepath
271 @classmethod
272 def load(cls, filepath: Path) -> PlatformCuration:
273 """Load curation from a YAML file."""
274 return cls.from_yaml(filepath.read_text())
277# ---------------------------------------------------------------------------
278# AI Curator
279# ---------------------------------------------------------------------------
282class AICurator:
283 """Main curator engine.
285 The curator combines multiple data sources to produce intelligent
286 game rankings:
288 1. Agent knowledge (curated lists generated by the AI agent)
289 2. Metadata database (scraped_games: ratings, genres, descriptions)
290 3. Cross-platform data (generation configs for 1R1G dedup)
292 Future:
293 4. Embeddings (sentence-transformers for similarity/clustering)
294 5. Live LLM queries (Copilot SDK for build-time decisions)
295 """
297 def __init__(
298 self,
299 metadata_db: Path | None = None,
300 curations_dir: Path | None = None,
301 workspace_root: Path | None = None,
302 ):
303 """Initialize the curator.
305 Args:
306 metadata_db: Path to romfarmer.db with scraped_games
307 curations_dir: Directory for saved curations
308 workspace_root: ROM Farmer workspace root
309 """
310 if workspace_root is None:
311 from romfarmer.core.paths import paths
313 workspace_root = paths.workspace_root
314 self.workspace_root = workspace_root
315 self.metadata_db = (
316 metadata_db or self.workspace_root / "metadata" / "database" / "romfarmer.db"
317 )
318 self.curations_dir = curations_dir or self.workspace_root / "config" / "curations"
319 self._db: sqlite3.Connection | None = None
321 @property
322 def db(self) -> sqlite3.Connection:
323 """Lazy database connection."""
324 if self._db is None:
325 if not self.metadata_db.exists():
326 raise FileNotFoundError(f"Metadata DB not found: {self.metadata_db}")
327 self._db = sqlite3.connect(str(self.metadata_db))
328 self._db.row_factory = sqlite3.Row
329 return self._db
331 def close(self) -> None:
332 """Close database connection."""
333 if self._db:
334 self._db.close()
335 self._db = None
337 # --- Metadata queries ---
339 def get_platform_games(self, platform: str) -> list[dict[str, Any]]:
340 """Get all games for a platform from the metadata DB.
342 Returns list of dicts with: name, rating, genre, developer,
343 publisher, description, players, release_date, region.
344 """
345 cursor = self.db.execute(
346 """SELECT DISTINCT name, rating, genre, developer, publisher,
347 description, players, release_date, region
348 FROM scraped_games
349 WHERE system = ?
350 ORDER BY rating DESC, name ASC""",
351 (platform,),
352 )
353 return [dict(row) for row in cursor.fetchall()]
355 def get_platform_stats(self, platform: str) -> dict[str, Any]:
356 """Get statistical summary for a platform."""
357 cursor = self.db.execute(
358 """SELECT
359 COUNT(*) as total,
360 SUM(CASE WHEN rating > 0 THEN 1 ELSE 0 END) as has_rating,
361 AVG(CASE WHEN rating > 0 THEN rating END) as avg_rating,
362 MAX(rating) as max_rating,
363 COUNT(DISTINCT genre) as genre_count,
364 SUM(CASE WHEN description IS NOT NULL AND description != '' THEN 1 ELSE 0 END) as has_desc
365 FROM scraped_games WHERE system = ?""",
366 (platform,),
367 )
368 row = cursor.fetchone()
369 return dict(row) if row else {}
371 def find_cross_platform_games(
372 self,
373 platform: str,
374 other_platforms: list[str],
375 ) -> dict[str, list[str]]:
376 """Find games that exist on both this platform and others.
378 Uses a simplified name matching approach (strips parenthetical metadata).
379 Returns dict of normalized_name -> list of platforms that have it.
380 """
381 import re
383 def normalize(name: str) -> str:
384 """Strip region/disc markers for cross-platform matching."""
385 name = re.sub(r"\s*\(.*?\)", "", name) # Remove (USA), (Disc 1), etc.
386 name = re.sub(r"\s*\[.*?\]", "", name) # Remove [!], [b], etc.
387 name = re.sub(r"\s*-\s*", " ", name) # Normalize dashes
388 name = re.sub(r"\s+", " ", name).strip() # Collapse whitespace
389 return name.lower()
391 # Get all game names for our platform
392 our_games = {}
393 cursor = self.db.execute(
394 "SELECT DISTINCT name FROM scraped_games WHERE system = ?",
395 (platform,),
396 )
397 for row in cursor:
398 norm = normalize(row[0])
399 our_games[norm] = row[0]
401 # Check against other platforms
402 cross_platform: dict[str, list[str]] = {}
403 for other in other_platforms:
404 cursor = self.db.execute(
405 "SELECT DISTINCT name FROM scraped_games WHERE system = ?",
406 (other,),
407 )
408 for row in cursor:
409 norm = normalize(row[0])
410 if norm in our_games:
411 if norm not in cross_platform:
412 cross_platform[norm] = [platform]
413 cross_platform[norm].append(other)
415 return cross_platform
417 # --- Curation operations ---
419 def load_curation(self, platform: str) -> PlatformCuration | None:
420 """Load a saved curation for a platform."""
421 filepath = self.curations_dir / f"{platform}.yaml"
422 if filepath.exists():
423 return PlatformCuration.load(filepath)
424 return None
426 def save_curation(self, curation: PlatformCuration) -> Path:
427 """Save a platform curation."""
428 return curation.save(self.curations_dir)
430 def list_curations(self) -> list[str]:
431 """List all saved platform curations."""
432 if not self.curations_dir.exists():
433 return []
434 return sorted(p.stem for p in self.curations_dir.glob("*.yaml"))
436 def write_curated_artifact(
437 self,
438 platform: str,
439 max_tier: GameTier = GameTier.GREAT,
440 artifacts_dir: Path | None = None,
441 ) -> str | None:
442 """Freeze a saved curation into a hash-addressed artifact; return its ref.
444 This is the intent-layer path (brief v1 §4): the model's output becomes
445 bytes, the bytes get a hash, and the ``curated/<name>@sha256:<hex>``
446 ref goes into the Spec. Prefer this over ``generate_list_file``,
447 which writes a name-addressed ``lists/`` file with no provenance.
448 """
449 from romfarmer.driver.curated import write_curated
451 curation = self.load_curation(platform)
452 if not curation:
453 logger.warning(f"No curation found for {platform}")
454 return None
455 entries = [
456 {
457 "canonical_name": g.name,
458 "action": "include",
459 "reason": f"{g.tier.value}:{g.score} {g.note}".strip(),
460 }
461 for g in curation.up_to_tier(max_tier)
462 ]
463 art = write_curated(
464 f"{platform}-{max_tier.value}",
465 entries,
466 artifacts_dir or self.workspace_root / "artifacts",
467 generated_by=f"ai:{curation.curator}@{curation.version}",
468 basis={
469 "platform": platform,
470 "generation": curation.generation,
471 "total_available": curation.total_available,
472 **dict(curation.metadata),
473 },
474 )
475 logger.info(f"Curated artifact: {art.ref} ({len(entries)} entries)")
476 return art.ref
478 def generate_list_file(
479 self,
480 platform: str,
481 max_tier: GameTier = GameTier.GREAT,
482 output_dir: Path | None = None,
483 ) -> Path | None:
484 """Generate a legacy ROM Farmer list file from a saved curation.
486 DEPRECATED for intent-layer use: writes a name-addressed ``lists/``
487 file with no hash or basis. Use ``write_curated_artifact``.
489 Args:
490 platform: Platform name
491 max_tier: Maximum tier to include
492 output_dir: Output directory (default: lists/)
494 Returns:
495 Path to generated list file, or None if no curation exists
496 """
497 curation = self.load_curation(platform)
498 if not curation:
499 logger.warning(f"No curation found for {platform}")
500 return None
502 output_dir = output_dir or self.workspace_root / "lists"
503 output_dir.mkdir(parents=True, exist_ok=True)
505 tier_label = max_tier.value
506 filename = f"{platform}+AI-{tier_label.title()}"
507 filepath = output_dir / filename
509 content = curation.to_rom_farmer_list(max_tier=max_tier)
510 filepath.write_text(content)
512 count = len(curation.up_to_tier(max_tier))
513 logger.info(f"Generated list: {filepath} ({count} games)")
514 return filepath
516 # --- Future: Embedding-based operations ---
518 def compute_game_embeddings(self, platform: str) -> None:
519 """Compute sentence-transformer embeddings for game descriptions.
521 This enables:
522 - Semantic similarity search ("games like Castlevania")
523 - Clustering (find hidden genres/niches)
524 - Cross-platform matching (when names differ)
526 Requires: sentence-transformers, torch
527 """
528 try:
529 from sentence_transformers import SentenceTransformer
530 except ImportError:
531 raise ImportError(
532 "sentence-transformers required: pip install sentence-transformers"
533 ) from None
535 games = self.get_platform_games(platform)
536 texts = []
537 for g in games:
538 # Combine name + genre + description for rich embeddings
539 parts = [g["name"]]
540 if g.get("genre"):
541 parts.append(g["genre"])
542 if g.get("description"):
543 parts.append(g["description"][:500]) # Truncate long descriptions
544 texts.append(" | ".join(parts))
546 if not texts:
547 logger.warning(f"No games with text data for {platform}")
548 return
550 model = SentenceTransformer("all-MiniLM-L6-v2")
551 embeddings = model.encode(texts, show_progress_bar=True)
553 # Save embeddings
554 output_path = self.curations_dir / "embeddings" / f"{platform}.json"
555 output_path.parent.mkdir(parents=True, exist_ok=True)
557 embedding_data = {
558 "platform": platform,
559 "model": "all-MiniLM-L6-v2",
560 "count": len(texts),
561 "games": [
562 {"name": games[i]["name"], "embedding": embeddings[i].tolist()}
563 for i in range(len(texts))
564 ],
565 }
566 output_path.write_text(json.dumps(embedding_data))
567 logger.info(f"Saved {len(texts)} embeddings for {platform} to {output_path}")