Coverage for src/romfarmer/driver/resolve.py: 74%
251 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"""RESOLVE phase — ``ResolvedPlatformConfig`` → frozen ``ResolvedBuild``.
3Everything the later phases need is decided here, once, and returned as a
4value:
6* the ``BuildManifest`` (selection policy, curated lists, arcade selection,
7 PS3 keys, format chain, budget),
8* the negotiated ``FormatChain`` (recipe ∩ target-profile preferences),
9* the DAT file, the ``ConcreteTargetProfile``, and the source/output dirs.
11``resolve_platform`` is pure apart from reading config/DAT/list files under
12the directories named in ``ResolvePaths``. It never touches source ROMs.
14History: these functions were private methods on ``NewBuildOrchestrator``
15(``_find_dat_file`` / ``_build_manifest`` / ``_load_target_profile`` /
16``_load_curated_lists``) plus ``planner/negotiation.py``; ``cli/plan.py`` and
17``cli/doctor.py`` reached into them. Moved here 2026-09-03 (review item 2.2).
18"""
20from __future__ import annotations
22import logging
23import re
24from dataclasses import dataclass
25from pathlib import Path
26from typing import TYPE_CHECKING, Any
28import yaml
30from romfarmer.ir.catalog import PlatformId
31from romfarmer.ir.chain import FormatChain
32from romfarmer.ir.manifest import BuildManifest
33from romfarmer.targets.profiles.loader import TargetProfileError
35if TYPE_CHECKING:
36 from romfarmer.config.resolver import ResolvedPlatformConfig
37 from romfarmer.config.target import ComposedTarget
38 from romfarmer.targets.profiles.loader import ConcreteTargetProfile
40logger = logging.getLogger(__name__)
42_UNSET: Any = object()
45# ---------------------------------------------------------------------------
46# Products
47# ---------------------------------------------------------------------------
50@dataclass(frozen=True)
51class ResolvePaths:
52 """Directories RESOLVE may read. Built from ``core.paths`` by the driver."""
54 workspace_root: Path
55 config_dir: Path
56 dats_dir: Path
57 lists_dir: Path
59 @classmethod
60 def from_workspace(cls, workspace_root: Path) -> ResolvePaths:
61 return cls(
62 workspace_root=workspace_root,
63 config_dir=workspace_root / "config",
64 dats_dir=workspace_root / "dats",
65 lists_dir=workspace_root / "lists",
66 )
69@dataclass(frozen=True)
70class ResolvedBuild:
71 """The RESOLVE product for one platform — everything CATALOG/PLAN/EMIT need."""
73 platform: str
74 resolved: ResolvedPlatformConfig
75 manifest: BuildManifest
76 chain: FormatChain
77 dat_file: Path | None
78 profile: ConcreteTargetProfile | None
79 source_dir: Path
80 source_dirs: tuple[tuple[Path, bool], ...] # (dir, recursive)
81 output_dir: Path
82 notes: tuple[str, ...] = () # human-readable RESOLVE facts an agent should see
85# ---------------------------------------------------------------------------
86# Format negotiation (moved from planner/negotiation.py)
87# ---------------------------------------------------------------------------
90class FormatNegotiationError(ValueError):
91 """Recipe and profile format preferences have no intersection.
93 Silent fallback was the pre-T11 behaviour and is exactly the bug-5 class:
94 a wrong profile key or a misconfigured recipe would produce unexpected
95 output with no warning. Hard failure forces the misconfiguration to
96 surface at RESOLVE time rather than silently producing the wrong format.
97 """
100def negotiate_format_chain(resolved: ResolvedPlatformConfig) -> FormatChain:
101 """Map ``(extraction_type, compression)`` to the lowering ``FormatChain``.
103 Raises:
104 ValueError: if the combination is unrecognised.
105 """
106 from romfarmer.config.models import CompressionFormat, ExtractionType
108 et = resolved.extraction_type
109 cf = resolved.compression
111 if et == ExtractionType.DISC:
112 if cf == CompressionFormat.CHD:
113 return ("chd",)
114 return ("cue_bin",) # passthrough — keep CUE/BIN
115 if et == ExtractionType.CARTRIDGE:
116 if cf == CompressionFormat.SEVENZ:
117 return ("7z",)
118 if cf == CompressionFormat.ZIP:
119 return ("zip",)
120 return ("passthrough",)
121 if et == ExtractionType.RVZ:
122 return ("rvz",)
123 if et == ExtractionType.WUX:
124 return ("wux",)
125 if et == ExtractionType.PS3:
126 return ("ps3",)
127 if et == ExtractionType.XISO:
128 if cf == CompressionFormat.SQUASHFS:
129 return ("xiso", "squashfs")
130 return ("xiso",)
131 if et == ExtractionType.NONE:
132 return ("passthrough",)
134 raise ValueError(
135 f"Unrecognised extraction_type={et!r} / compression={cf!r}. "
136 "Add a mapping in driver/resolve.py:negotiate_format_chain."
137 )
140def negotiate_with_profile(
141 resolved: ResolvedPlatformConfig,
142 profile: ConcreteTargetProfile,
143) -> FormatChain:
144 """Recipe chain ∩ profile preferences (blueprint §2.2 — intersection, not override).
146 1. Config default from ``negotiate_format_chain``.
147 2. If the profile lists no preferences for the platform, the default stands.
148 3. If the default is among the profile's supported chains, keep it.
149 4. Otherwise raise ``FormatNegotiationError`` — never silently substitute.
150 """
151 default_chain = negotiate_format_chain(resolved)
152 platform_prefs = profile.format_preferences(PlatformId(resolved.platform))
153 if not platform_prefs:
154 return default_chain
155 if default_chain in platform_prefs:
156 return default_chain
157 raise FormatNegotiationError(
158 f"Format negotiation failed for platform '{resolved.platform}': "
159 f"recipe chain {default_chain!r} is not in profile preferences "
160 f"{platform_prefs!r}. Check the target profile's format_preferences "
161 f"for this platform or update the recipe."
162 )
165# ---------------------------------------------------------------------------
166# Target profile
167# ---------------------------------------------------------------------------
170def load_target_profile(composed_target: ComposedTarget, config_dir: Path) -> ConcreteTargetProfile:
171 """Load the ``ConcreteTargetProfile`` for ``frontend[/device]``.
173 Fails loudly (``TargetProfileError``) when the frontend YAML is missing or
174 unparseable — a silent ``None`` here disables metadata and format
175 negotiation for the whole build with nothing above DEBUG level (review
176 G4 #6). The profile key is the frontend name (+ device), NOT the
177 build-spec target name (bug-5).
178 """
179 from romfarmer.targets.profiles.loader import TargetProfileLoader
181 fe = composed_target.frontend.name
182 dev = getattr(composed_target.device, "name", None)
183 key = f"{fe}/{dev}" if dev else str(fe)
184 try:
185 return TargetProfileLoader(config_dir).load(key)
186 except TargetProfileError:
187 raise
188 except Exception as exc:
189 raise TargetProfileError(f"cannot load target profile {key!r}: {exc}") from exc
192# ---------------------------------------------------------------------------
193# DAT discovery
194# ---------------------------------------------------------------------------
196_DAT_CACHE: dict[Path, Any] = {}
198_DAT_SOURCE_DIRS = {
199 "retool_1g1r_usa": "nointro.retool.1g1r.usa",
200 "retool_1g1r_all": "nointro.retool.1g1r.all",
201 "retool_1g1r_eng": None, # depends on extraction type
202 "redump_retool_1g1r_usa": "redump.retool.1g1r.usa",
203 "redump_retool_1g1r_eng": "redump.retool.1g1r.eng",
204 "nointro_retool_1g1r_eng": "nointro.retool.1g1r.eng",
205}
208def parse_dat(dat_file: Path) -> Any | None:
209 """Parse a DAT once per process (CATALOG and the manifest both need it)."""
210 if dat_file in _DAT_CACHE:
211 return _DAT_CACHE[dat_file]
212 parsed: Any = None
213 if dat_file.exists():
214 errors: list[str] = []
215 try:
216 from romfarmer.dat_parser import DATParser
218 parsed = DATParser().parse(dat_file) # type: ignore[no-untyped-call]
219 except Exception as exc:
220 errors.append(f"DATParser: {exc}")
221 try:
222 from romfarmer.dat_parser import RetoolDATParser
224 parsed = RetoolDATParser().parse(dat_file) # type: ignore[no-untyped-call]
225 except Exception as exc2:
226 errors.append(f"RetoolDATParser: {exc2}")
227 if parsed is None:
228 # Loud: a DAT that exists but cannot be parsed must not quietly
229 # become "no DAT" — that silently drops the collection gate.
230 raise ValueError(f"DAT {dat_file.name} could not be parsed ({'; '.join(errors)})")
231 _DAT_CACHE[dat_file] = parsed
232 return parsed
235def dat_is_retool_1g1r(resolved: ResolvedPlatformConfig) -> bool:
236 """True when the platform's DAT is a Retool 1G1R export (already deduplicated)."""
237 dat = getattr(resolved, "dat", None)
238 source = getattr(dat, "source", None)
239 value = getattr(source, "value", source)
240 return isinstance(value, str) and "1g1r" in value.lower()
243def _dat_pattern(platform: str, config_dir: Path) -> str | None:
244 patterns_path = config_dir / "dat_patterns.yaml"
245 if not patterns_path.exists():
246 return None
247 try:
248 with open(patterns_path) as f:
249 patterns = yaml.safe_load(f)
250 except yaml.YAMLError as exc:
251 raise ValueError(f"{patterns_path} is not valid YAML: {exc}") from exc
252 if patterns is None:
253 return None
254 if not isinstance(patterns, dict):
255 raise ValueError(f"{patterns_path} must map platform → search pattern")
256 value = patterns.get(platform.lower())
257 return str(value) if value is not None else None
260def find_dat_file(
261 resolved: ResolvedPlatformConfig,
262 paths: ResolvePaths,
263 *,
264 pattern: str | None = _UNSET,
265) -> Path | None:
266 """Locate the DAT for a platform from its ``dat`` reference; ``None`` if none applies.
268 ``pattern`` overrides the ``config/dat_patterns.yaml`` lookup (tests).
269 """
270 if not resolved.dat:
271 return None
272 from romfarmer.config.models import DATSource, ExtractionType
274 if resolved.dat.source == DATSource.NONE:
275 return None
277 if resolved.dat.file:
278 dat_path = Path(resolved.dat.file)
279 if dat_path.exists():
280 return dat_path
281 ws_path = paths.workspace_root / dat_path
282 if ws_path.exists():
283 return ws_path
285 source = resolved.dat.source
286 if source is None:
287 return None
288 source_str = source.value if hasattr(source, "value") else str(source)
289 dat_dir_name = _DAT_SOURCE_DIRS.get(source_str)
290 if dat_dir_name is None and source_str == "retool_1g1r_eng":
291 dat_dir_name = (
292 "nointro.retool.1g1r.eng"
293 if resolved.extraction_type == ExtractionType.CARTRIDGE
294 else "redump.retool.1g1r.eng"
295 )
296 if dat_dir_name is None:
297 dat_dir_name = source_str
299 dat_dir = paths.dats_dir / dat_dir_name
300 if not dat_dir.exists():
301 logger.warning("DAT directory not found: %s", dat_dir)
302 return None
304 # Variants in priority order; scan ALL files per variant before falling
305 # back so "xbox" cannot match "xbox 360".
306 platform_search = (
307 _dat_pattern(resolved.platform, paths.config_dir) if pattern is _UNSET else pattern
308 )
309 variants: list[str] = [platform_search] if platform_search else []
310 dat_platform_name = getattr(resolved.dat, "platform_name", None)
311 if dat_platform_name:
312 variants.append(f"{dat_platform_name} (".lower())
313 variants.append(str(dat_platform_name).lower())
314 variants.extend([resolved.platform.lower(), resolved.platform.split("-")[0].lower()])
316 dat_files = list(dat_dir.glob("*.dat"))
317 for variant in variants:
318 if not variant:
319 continue
320 for dat_file in dat_files:
321 if variant in dat_file.name.lower():
322 logger.info(" DAT: %s", dat_file.name)
323 return dat_file
325 logger.warning("No DAT file found for %s", resolved.platform)
326 return None
329# ---------------------------------------------------------------------------
330# Curated lists
331# ---------------------------------------------------------------------------
333_DISC_TAG = re.compile(r"\s*\((?:Disc|Disk|CD)\s*\d+\)", re.IGNORECASE)
336def _parse_list(path: Path) -> frozenset[str]:
337 if not path.exists():
338 return frozenset()
339 names: set[str] = set()
340 for raw_line in path.read_text(errors="replace").splitlines():
341 line = raw_line.strip()
342 if not line or line.startswith("#"):
343 continue
344 canonical = _DISC_TAG.sub("", Path(line).stem).strip()
345 if canonical:
346 names.add(canonical)
347 return frozenset(names)
350def load_curated_lists(platform: str, lists_dir: Path) -> tuple[frozenset[str], frozenset[str]]:
351 """``(curated_include, curated_exclude)`` from ``lists/{platform}+*`` and ``lists/{platform}-delete``.
353 Names are canonical (extension and disc tags stripped). Lines starting
354 with ``#`` are ignored.
355 """
356 curated_exclude = _parse_list(lists_dir / f"{platform}-delete")
357 curated_include: set[str] = set()
358 if lists_dir.exists():
359 for add_file in lists_dir.glob(f"{platform}+*"):
360 curated_include.update(_parse_list(add_file))
361 return frozenset(curated_include), curated_exclude
364# ---------------------------------------------------------------------------
365# Manifest
366# ---------------------------------------------------------------------------
369def build_manifest(
370 resolved: ResolvedPlatformConfig,
371 platform: PlatformId,
372 *,
373 chain: FormatChain,
374 dat_file: Path | None,
375 paths: ResolvePaths,
376 sample_n: int | None = None,
377 sample_seed: int = 0,
378 curated: tuple[frozenset[str], frozenset[str]] | None = None,
379 dat_filter: bool | None = None,
380) -> BuildManifest:
381 """Construct the frozen ``BuildManifest`` for one platform.
383 ``curated`` overrides the legacy ``lists/`` discovery (the Spec path
384 supplies hash-addressed artifacts); ``dat_filter`` overrides the
385 "gate iff a DAT was found" default.
386 """
387 sel = resolved.selection
388 preferred_regions: tuple[str, ...] = (
389 tuple(sel.preferred_regions) if sel and sel.preferred_regions else ()
390 )
391 rating_min = getattr(sel, "min_rating", None) if sel else None
392 rating_top_n = getattr(sel, "top_n", None) if sel else None
393 rating_unrated = getattr(sel, "unrated", "keep") if sel else "keep"
394 budget_unrated_as = getattr(sel, "unrated_as", "median") if sel else "median"
395 safety_margin = float(getattr(sel, "safety_margin", 0.0)) if sel else 0.0
397 budget_bytes = None
398 if sel:
399 max_gb = getattr(sel, "max_size_gb", None)
400 if max_gb:
401 budget_bytes = int(float(max_gb) * 1024**3)
403 gen_name = None
404 gen_order: tuple[str, ...] = ()
405 gen_cfg = getattr(resolved, "generation_filter", None)
406 if gen_cfg and getattr(gen_cfg, "enabled", False):
407 gen_name = getattr(gen_cfg, "generation", None)
408 if gen_name:
409 from romfarmer.config.generation_loader import load_generation
411 gen_def = load_generation(gen_name)
412 if gen_def:
413 gen_order = tuple(gen_def.get_platform_names())
414 else:
415 # Loud: an unknown generation would otherwise make the pass a silent no-op.
416 raise ValueError(f"generation_filter names unknown generation {gen_name!r}")
418 if curated is None:
419 curated_include, curated_exclude = load_curated_lists(str(platform), paths.lists_dir)
420 else:
421 curated_include, curated_exclude = curated
423 ps3_keys_directory = None
424 keys_dir = getattr(getattr(resolved, "extraction", None), "keys_directory", None)
425 if keys_dir:
426 ps3_keys_directory = str(keys_dir)
428 # Arcade: decide the selection here from DAT facts the catalog never sees
429 arcade_selected: frozenset[str] | None = None
430 arcade_rejections: tuple[tuple[str, str], ...] = ()
431 if resolved.arcade_filter is not None and dat_file is not None:
432 dat_parsed = parse_dat(dat_file)
433 if dat_parsed is not None:
434 from romfarmer.arcade.selection import select_arcade_games
436 arcade_selected, arcade_rejections = select_arcade_games(
437 dat_parsed, resolved.arcade_filter, resolved.dat
438 )
439 logger.info(
440 " arcade filter: %d of %d DAT entries selected",
441 len(arcade_selected),
442 len(dat_parsed.games),
443 )
445 return BuildManifest(
446 platform=platform,
447 chain=tuple(chain),
448 preferred_regions=preferred_regions,
449 rating_min=rating_min,
450 rating_top_n=rating_top_n,
451 rating_unrated=str(rating_unrated),
452 budget_bytes=budget_bytes,
453 budget_unrated_as=str(budget_unrated_as),
454 safety_margin=safety_margin,
455 generation_name=gen_name,
456 generation_platform_order=gen_order,
457 curated_include=curated_include,
458 curated_exclude=curated_exclude,
459 dat_filter=(dat_file is not None)
460 if dat_filter is None
461 else (dat_filter and dat_file is not None),
462 one_g_one_r=not dat_is_retool_1g1r(resolved) and arcade_selected is None,
463 arcade_selected=arcade_selected,
464 arcade_rejections=arcade_rejections,
465 sample_n=sample_n,
466 sample_seed=sample_seed,
467 ps3_keys_directory=ps3_keys_directory,
468 )
471# ---------------------------------------------------------------------------
472# Entry point
473# ---------------------------------------------------------------------------
476def resolve_platform(
477 resolved: ResolvedPlatformConfig,
478 composed_target: ComposedTarget | None,
479 paths: ResolvePaths,
480 *,
481 dat_file: Path | None = _UNSET,
482 profile: ConcreteTargetProfile | None = _UNSET,
483 sample_n: int | None = None,
484 sample_seed: int = 0,
485 curated: tuple[frozenset[str], frozenset[str]] | None = None,
486 dat_filter: bool | None = None,
487 extra_notes: tuple[str, ...] = (),
488) -> ResolvedBuild:
489 """RESOLVE one platform into a frozen ``ResolvedBuild``.
491 ``dat_file`` / ``profile`` may be supplied to skip discovery (tests,
492 ``doctor``). Raises ``ValueError`` when the platform has no source
493 directory, ``TargetProfileError`` when the profile cannot be loaded, and
494 ``FormatNegotiationError`` when recipe and profile disagree.
495 """
496 source_dir = resolved.sources[0].path if resolved.sources else None
497 if source_dir is None:
498 raise ValueError(f"No source directory for {resolved.platform}")
499 source_dirs = tuple(
500 (s.path, bool(s.recursive)) for s in (resolved.sources or ()) if s.path is not None
501 ) or ((source_dir, False),)
503 output_dir = resolved.output_dir or Path(f"output/{resolved.platform}")
504 if not output_dir.is_absolute():
505 output_dir = paths.workspace_root / output_dir
507 if profile is _UNSET:
508 profile = (
509 load_target_profile(composed_target, paths.config_dir) if composed_target else None
510 )
511 if dat_file is _UNSET:
512 dat_file = find_dat_file(resolved, paths)
514 chain = (
515 negotiate_with_profile(resolved, profile)
516 if profile is not None
517 else negotiate_format_chain(resolved)
518 )
519 platform_id = PlatformId(resolved.platform)
520 notes: list[str] = list(extra_notes)
521 dat_src = getattr(getattr(resolved, "dat", None), "source", None)
522 dat_src_value = getattr(dat_src, "value", dat_src)
523 if dat_src is None and dat_filter:
524 notes.append("platform config declares no DAT — dat_filter has nothing to gate")
525 if dat_src_value is not None and str(dat_src_value) != "none" and dat_file is None:
526 notes.append(
527 f"DAT expected (source={dat_src_value}) but no file found under {paths.dats_dir} — "
528 "dat_filter cannot gate; 1g1r falls back to the name heuristic"
529 )
530 if chain == ("passthrough",):
531 notes.append("chain=passthrough: source files are copied as-is (no compression)")
532 manifest = build_manifest(
533 resolved,
534 platform_id,
535 chain=chain,
536 dat_file=dat_file,
537 paths=paths,
538 sample_n=sample_n,
539 sample_seed=sample_seed,
540 curated=curated,
541 dat_filter=dat_filter,
542 )
543 return ResolvedBuild(
544 platform=resolved.platform,
545 resolved=resolved,
546 manifest=manifest,
547 chain=chain,
548 dat_file=dat_file,
549 profile=profile,
550 source_dir=source_dir,
551 source_dirs=source_dirs,
552 output_dir=output_dir,
553 notes=tuple(notes),
554 )