Coverage for src/romfarmer/new_orchestrator.py: 31%
741 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"""New declarative build orchestrator.
3Replaces the old BuildOrchestrator + PlatformProcessor (1,738 lines)
4with a streamlined orchestrator that uses the composition engine:
6 BuildSpec → ConfigResolver → [ResolvedPlatformConfig] → build_pipeline → execute
8Preserved features:
9 - State persistence and resume capability
10 - Budget tracking with tier-based prioritization
11 - Generation filter (cross-platform dedup)
12 - Post-build hooks (jdupes, etc.)
13 - Deployment (rsync)
14 - Logging and reporting
16What's gone:
17 - platform_overrides (replaced by recipe stacking)
18 - PlatformProcessor (replaced by resolver + builder)
19 - Fat BuildConfig (replaced by BuildSpec)
20 - 200-line if/elif pipeline assembly (replaced by lookup table)
21"""
23import logging
24import os
25import shutil
26from dataclasses import dataclass
27from datetime import datetime
28from pathlib import Path
29from typing import TYPE_CHECKING, Any
31import yaml
33if TYPE_CHECKING:
34 from romfarmer.driver.hooks import HookContext
35 from romfarmer.driver.resolve import ResolvedBuild
36 from romfarmer.ir.manifest import BuildManifest
38from romfarmer.build_models import BuildState, BuildStatus
39from romfarmer.config.build_spec import BuildSpec
40from romfarmer.config.new_loader import (
41 load_all_recipes,
42 load_build_spec,
43 load_slim_platform,
44)
45from romfarmer.config.recipe import RecipeSpec
46from romfarmer.config.resolver import ConfigResolver, ResolvedPlatformConfig
47from romfarmer.config.slim_platform import SlimPlatformConfig
48from romfarmer.config.target import ComposedTarget
49from romfarmer.core.paths import get_paths
50from romfarmer.driver.resolve import (
51 ResolvePaths,
52)
53from romfarmer.driver.resolve import (
54 parse_dat as _parse_dat,
55)
57logger = logging.getLogger(__name__)
60# ─────────────────────────────────────────────────────────────────────────────
61# Phase-boundary types
62#
63# The five phases are composed as typed pure functions rather than method calls
64# on a mutable orchestrator. The function signatures act as capability
65# starvation: each phase can only receive the data it is entitled to see.
66#
67# Hard rule: run_execute takes NO source paths and NO ResolvedPlatformConfig.
68# All data flows through PlannedPlatform → ExecutedPlatform.
69# ─────────────────────────────────────────────────────────────────────────────
72@dataclass(frozen=True)
73class PlannedPlatform:
74 """Result of CATALOG + PLAN phases — everything EXECUTE is entitled to see."""
76 platform: str
77 catalog: Any # romfarmer.ir.catalog.Catalog
78 build_plan: Any # romfarmer.ir.actions.BuildPlan
79 manifest: Any # romfarmer.ir.manifest.BuildManifest
80 traces: tuple[Any, ...] = () # PassTrace per pass — powers `plan run --explain`
81 chain: tuple[str, ...] = () # negotiated FormatChain the plan was lowered with
82 stages: tuple[tuple[str, Any], ...] = () # (pass name, Catalog entering it) — PlanSummary input
85@dataclass(frozen=True)
86class ExecEnv:
87 """Execution environment — the only external-world handles EXECUTE may use."""
89 cas_dir: Path
90 scratch_base: Path
91 db_path: Path
92 output_dir: Path # where terminal artifacts are hardlinked
93 transforms: Any # dict[str, Transform]
96@dataclass(frozen=True)
97class ExecutionReport:
98 """Post-EXECUTE summary, consumed by EMIT and by the driver."""
100 terminal_count: int
101 failed_units: tuple[tuple[str, str], ...] = () # (canonical_name, reason)
102 budget_stopped: tuple[str, ...] = () # unit_id strings skipped by stop-early
103 actual_bytes: int = 0 # cumulative terminal artifact bytes
106@dataclass(frozen=True)
107class ExecutedPlatform:
108 """Result of the EXECUTE phase — everything EMIT is entitled to see."""
110 planned: PlannedPlatform
111 layout: Any # romfarmer.ir.layout.LayoutPlan
112 report: ExecutionReport
115@dataclass(frozen=True)
116class PlatformRunReport:
117 """One platform's outcome from ``run_spec`` — the EMIT-time provenance line."""
119 platform: str
120 chain: tuple[str, ...]
121 terminal_count: int
122 actual_bytes: int
123 failed_units: tuple[tuple[str, str], ...] = ()
124 budget_stopped: int = 0
125 planned_only: bool = False # True under dry_run: PLAN ran, EXECUTE did not
128@dataclass(frozen=True)
129class SpecRunReport:
130 """Result of ``run_spec`` — one Spec, RESOLVE→EMIT, every platform.
132 ``write_provenance`` is the only thing in this module that writes outside
133 ``output_base``-relative paths, and it writes exactly one file: the
134 ``spec_hash`` this output was materialised from, so a card can later be
135 checked against the spec that produced it.
136 """
138 spec_hash: str
139 output_base: Path
140 dry_run: bool
141 platforms: tuple[PlatformRunReport, ...]
143 @property
144 def total_actual_bytes(self) -> int:
145 return sum(p.actual_bytes for p in self.platforms)
147 def write_provenance(self, spec: Any) -> Path:
148 import json
149 from datetime import timezone
151 path = self.output_base / "spec_manifest.json"
152 payload = {
153 "spec_hash": self.spec_hash,
154 "spec_version": spec.spec_version,
155 "intent": {
156 "text": spec.intent.text,
157 "authored_by": spec.intent.authored_by,
158 "authored_at": spec.intent.authored_at,
159 "allocation_note": spec.intent.allocation_note,
160 },
161 "target": {
162 "frontend": spec.target.frontend,
163 "device": spec.target.device,
164 "storage_bytes": spec.target.storage_bytes,
165 "reserve_bytes": spec.target.reserve_bytes,
166 },
167 "generated_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
168 "total_actual_bytes": self.total_actual_bytes,
169 "platforms": [
170 {
171 "platform": p.platform,
172 "chain": list(p.chain),
173 "terminal_count": p.terminal_count,
174 "actual_bytes": p.actual_bytes,
175 "failed_units": [list(f) for f in p.failed_units],
176 "budget_stopped": p.budget_stopped,
177 }
178 for p in self.platforms
179 ],
180 }
181 self.output_base.mkdir(parents=True, exist_ok=True)
182 path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n")
183 return path
186class PhaseError(Exception):
187 """Raised when a pipeline phase fails.
189 The driver (``_process_platform``) is the sole try/except site — it
190 catches ``PhaseError`` once per phase and applies per-phase policy:
191 CATALOG/PLAN/EXECUTE failures skip the platform; EMIT failures are
192 logged but do not mark outputs as invalid.
193 """
195 def __init__(self, phase: str, platform: str, cause: Exception) -> None:
196 self.phase = phase
197 self.platform = platform
198 self.cause = cause
199 super().__init__(f"{phase}({platform}): {cause}")
202class PlanValidationError(PhaseError):
203 """Raised by ``validate_plan`` when the BuildPlan references unregistered tools."""
206# ─────────────────────────────────────────────────────────────────────────────
207# Phase functions (module-level, not closures over `self`)
208# ─────────────────────────────────────────────────────────────────────────────
211def validate_plan(plan: Any, transforms: Any, platform: str = "") -> None:
212 """Raise PlanValidationError if any tool in *plan* lacks a Transform.
214 Called by the driver immediately before EXECUTE so that missing-tool
215 failures surface at plan time (bug-3 class prevention).
216 """
217 missing = {a.tool for up in plan.units for a in up.actions if a.tool not in transforms}
218 if missing:
219 raise PlanValidationError(
220 "PLAN",
221 platform,
222 ValueError(f"BuildPlan references unregistered tools: {sorted(missing)}"),
223 )
226def run_catalog(
227 resolved: "ResolvedPlatformConfig",
228 *,
229 source_dir: Path,
230 dat_file: Path | None,
231 kb: Any,
232 digest_db: Path | None = None,
233) -> Any:
234 """CATALOG phase: scan *source_dir* and return a ``Catalog``.
236 ``digest_db`` is the SQLite file for the FileDigestCache. ``None`` means
237 NO digest cache (a pure scan) — never an inferred workspace database, so
238 tests and MCP sessions cannot write into a workspace they did not name.
239 The driver and PlanSession pass their workspace's DB explicitly.
241 Raises ``PhaseError`` on failure so the driver can apply skip policy.
242 """
243 from romfarmer.analysis.catalog_builder import CatalogBuilder
244 from romfarmer.ir.catalog import PlatformId
246 platform_id = PlatformId(resolved.platform)
248 dat_parsed: Any = _parse_dat(dat_file) if dat_file else None
250 # Closed in `finally` — an open FileDigestCache connection left dangling
251 # past CATALOG is a live sqlite3 connection to the same db_path that
252 # PLAN's ActionCache and EXECUTE's ActionCache/UnitTelemetryStore also
253 # open; three live connections to one WAL database in one process is how
254 # a same-process wal_checkpoint self-deadlock happens (found 2026-09-04).
255 digest_cache = _open_digest_cache(resolved.platform, digest_db) if digest_db else None
256 try:
257 source_dirs = tuple(
258 (s.path, bool(s.recursive)) for s in (resolved.sources or ()) if s.path is not None
259 ) or ((source_dir, False),)
260 builder = CatalogBuilder(
261 platform=platform_id,
262 source_dir=source_dir,
263 knowledge_base=kb,
264 dat_file=dat_parsed,
265 file_digest_cache=digest_cache,
266 source_dirs=source_dirs,
267 )
268 return builder.build()
269 except Exception as exc:
270 raise PhaseError("CATALOG", resolved.platform, exc) from exc
271 finally:
272 if digest_cache is not None:
273 digest_cache.close()
276def run_plan(
277 catalog: Any,
278 manifest: Any,
279 *,
280 cost_model: Any,
281 kb: Any,
282 chain: "tuple[str, ...]" = (),
283 action_cache: Any | None = None,
284) -> PlannedPlatform:
285 """PLAN phase: apply passes then lower the catalog to a ``BuildPlan``.
287 Returns a ``PlannedPlatform`` carrying the post-pass catalog and the
288 full ``BuildPlan`` — everything EXECUTE needs without requiring access
289 to any ``ResolvedPlatformConfig``.
291 Raises ``PhaseError`` on failure.
292 """
293 from romfarmer.ir.actions import BuildPlan
294 from romfarmer.planner import PassRunner, passes
295 from romfarmer.planner.lowering.base import lower as lower_unit
297 platform_str = str(getattr(catalog, "platform", ""))
298 chain = tuple(chain) or tuple(getattr(manifest, "chain", ()) or ())
299 if not chain:
300 raise PhaseError(
301 "PLAN", platform_str, ValueError("no FormatChain: pass chain= or set manifest.chain")
302 )
304 try:
305 runner = PassRunner(
306 passes=list(passes.DEFAULT_PASSES),
307 manifest=manifest,
308 kb=kb,
309 cost_model=cost_model,
310 )
311 final_catalog, traces = runner.run(catalog)
312 stages = tuple(runner.stages)
314 total_removed = sum(len(t.removed) for t in traces)
315 logger.info(
316 "run_plan(%s): %d → %d units (%d removed by passes)",
317 platform_str,
318 len(catalog.units),
319 len(final_catalog.units),
320 total_removed,
321 )
323 if not final_catalog.units:
324 return PlannedPlatform(
325 platform=platform_str,
326 catalog=final_catalog,
327 build_plan=BuildPlan(units=()),
328 manifest=manifest,
329 traces=tuple(traces),
330 chain=chain,
331 stages=stages,
332 )
334 unit_plans = []
335 for unit in final_catalog.units:
336 try:
337 up = lower_unit(unit, chain, manifest, action_cache)
338 unit_plans.append(up)
339 except Exception as exc:
340 logger.warning(
341 "run_plan(%s): lowering failed for %s: %s",
342 platform_str,
343 unit.canonical_name,
344 exc,
345 )
347 return PlannedPlatform(
348 platform=platform_str,
349 catalog=final_catalog,
350 build_plan=BuildPlan(units=tuple(unit_plans)),
351 manifest=manifest,
352 traces=tuple(traces),
353 chain=chain,
354 stages=stages,
355 )
357 except PhaseError:
358 raise
359 except Exception as exc:
360 raise PhaseError("PLAN", platform_str, exc) from exc
363def run_execute(planned: PlannedPlatform, *, env: ExecEnv) -> ExecutedPlatform:
364 """EXECUTE phase: run the Executor against the BuildPlan in *planned*.
366 **Takes no source paths and no ResolvedPlatformConfig.** All data
367 flows through ``PlannedPlatform``. The (ArtifactDecl, Identity) zip
368 lives exclusively here — never in orchestrator glue.
370 Returns ``ExecutedPlatform`` with a ``LayoutPlan`` ready for EMIT.
371 Raises ``PhaseError`` on failure.
372 """
373 import os
375 from romfarmer.engine.actioncache import ActionCache
376 from romfarmer.engine.executor import Executor
377 from romfarmer.ir.actions import Retention
378 from romfarmer.ir.layout import LayoutEntry, LayoutPlan
380 try:
381 if not planned.build_plan.units:
382 return ExecutedPlatform(
383 planned=planned,
384 layout=LayoutPlan(root_name=planned.platform, entries=()),
385 report=ExecutionReport(terminal_count=0),
386 )
388 from romfarmer.engine.telemetry import UnitTelemetryStore
390 chain = tuple(planned.chain or getattr(planned.manifest, "chain", ()) or ())
391 tool_key = chain[0] if chain else "unknown"
393 with ActionCache(env.db_path) as action_cache, UnitTelemetryStore(env.db_path) as tele:
395 def _unit_telemetry(
396 unit_plan: Any, terminal: tuple[Any, ...], duration_seconds: float
397 ) -> None:
398 # CostModel feedback: (platform, chain tool) → source → output bytes → duration.
399 out_bytes = sum(int(i.size or 0) for i in terminal)
400 version = unit_plan.actions[-1].tool_version if unit_plan.actions else ""
401 tele.record(
402 planned.platform,
403 tool_key,
404 str(unit_plan.unit.unit_id),
405 int(unit_plan.unit.source_size),
406 out_bytes,
407 version,
408 duration_seconds,
409 )
411 executor = Executor(
412 action_cache=action_cache,
413 transforms=env.transforms,
414 cas_dir=env.cas_dir,
415 scratch_base=env.scratch_base,
416 budget_bytes=getattr(planned.manifest, "effective_budget_bytes", None),
417 unit_telemetry_cb=_unit_telemetry,
418 )
419 output_set = executor.run(planned.build_plan)
421 # Build LayoutPlan: zip terminal ArtifactDecls with output identities.
422 # This is the SOLE place this zip happens — never in orchestrator glue.
423 # Bug-2 prevention: logical_name from decl, NOT the CAS hash filename.
424 env.output_dir.mkdir(parents=True, exist_ok=True)
425 entries: list[LayoutEntry] = []
426 for unit_plan in planned.build_plan.units:
427 identities = output_set.unit_outputs.get(unit_plan.unit.unit_id)
428 if not identities:
429 continue
430 terminal_decls = [
431 decl
432 for action in unit_plan.actions
433 for decl in action.outputs
434 if decl.retention == Retention.TERMINAL
435 ]
436 for decl, ident in zip(terminal_decls, identities, strict=False):
437 if ident.sha256 is None:
438 continue
439 if decl.kind == "tree":
440 # Folder-shaped artifact (PS3 JB folder, etc.) — restore
441 # via the tree store's hardlink-per-file manifest, not
442 # the single-blob CAS path used for file artifacts.
443 from romfarmer.cas.store import ContentStore
444 from romfarmer.cas.tree import TreeStore
446 dest = env.output_dir / decl.logical_name
447 if not dest.exists():
448 try:
449 TreeStore(ContentStore(env.cas_dir)).restore(ident.sha256, dest)
450 except FileNotFoundError as exc:
451 logger.warning(
452 "run_execute(%s): tree restore failed for %s: %s",
453 planned.platform,
454 decl.logical_name,
455 exc,
456 )
457 continue
458 entries.append(
459 LayoutEntry(
460 artifact_sha256=ident.sha256,
461 relative_path=Path(decl.logical_name),
462 )
463 )
464 continue
465 blobs = list(env.cas_dir.glob(f"{ident.sha256[:2]}/{ident.sha256[2:]}*"))
466 if not blobs:
467 logger.warning(
468 "run_execute(%s): CAS blob missing for %s (%s)",
469 planned.platform,
470 decl.logical_name,
471 ident.sha256[:16],
472 )
473 continue
474 dest = env.output_dir / decl.logical_name
475 if not dest.exists():
476 try:
477 os.link(blobs[0], dest)
478 except OSError:
479 shutil.copy2(blobs[0], dest)
480 entries.append(
481 LayoutEntry(
482 artifact_sha256=ident.sha256,
483 relative_path=Path(decl.logical_name),
484 )
485 )
487 layout = LayoutPlan(root_name=planned.platform, entries=tuple(entries))
488 actual_bytes = sum(
489 ident.size or 0
490 for identities in output_set.unit_outputs.values()
491 for ident in identities
492 )
493 logger.info(
494 "run_execute(%s): complete, %d terminal files, %d bytes actual",
495 planned.platform,
496 len(entries),
497 actual_bytes,
498 )
499 if output_set.budget_stopped:
500 logger.info(
501 "run_execute(%s): %d unit(s) budget-stopped",
502 planned.platform,
503 len(output_set.budget_stopped),
504 )
505 return ExecutedPlatform(
506 planned=planned,
507 layout=layout,
508 report=ExecutionReport(
509 terminal_count=len(entries),
510 failed_units=(),
511 budget_stopped=tuple(output_set.budget_stopped),
512 actual_bytes=actual_bytes,
513 ),
514 )
516 except PhaseError:
517 raise
518 except Exception as exc:
519 raise PhaseError("EXECUTE", planned.platform, exc) from exc
522def run_emit(
523 executed: ExecutedPlatform,
524 *,
525 profile: Any | None,
526 output_dir: Path,
527) -> None:
528 """EMIT phase: organise output files and generate metadata.
530 Receives the ``ConcreteTargetProfile`` object loaded at RESOLVE time —
531 no string lookup happens here (bug-5 prevention).
533 Errors are propagated as ``PhaseError``. The driver treats EMIT
534 errors as non-fatal: terminal artifacts are already materialised by
535 EXECUTE.
536 """
537 from romfarmer.ir.layout import LayoutPlan
538 from romfarmer.targets.emitters.materializer import Materializer
540 try:
541 style = getattr(profile, "organisation_style", "flat") if profile else "flat"
542 materializer = Materializer(style=style, move=True)
544 layout = executed.layout
545 if isinstance(layout, LayoutPlan) and layout.entries:
546 files = [output_dir / e.relative_path for e in layout.entries]
547 shas: list[str] | None = [e.artifact_sha256 for e in layout.entries]
548 else:
549 files = [f for f in output_dir.iterdir() if f.is_file()] if output_dir.exists() else []
550 shas = None
552 placed = materializer.emit(files, output_dir)
554 # Re-anchor the layout to the organised locations.
555 if shas is not None and len(placed) == len(shas):
556 from romfarmer.ir.layout import LayoutEntry
558 layout = LayoutPlan(
559 root_name=output_dir.name,
560 entries=tuple(
561 LayoutEntry(
562 artifact_sha256=sha,
563 relative_path=p.relative_to(output_dir),
564 )
565 for sha, p in zip(shas, placed, strict=False)
566 ),
567 )
569 # Generate metadata (gamelist.xml) if the profile enables it.
570 if profile is not None and getattr(profile, "metadata_enabled", False):
571 from romfarmer.analysis.knowledge import KnowledgeBase
572 from romfarmer.targets.emitters.es_gamelist import ESGamelistEmitter
574 db_path = Path(get_paths().metadata_db)
575 kb = KnowledgeBase(db_path if db_path.exists() else None)
576 emitter = ESGamelistEmitter()
577 if not isinstance(layout, LayoutPlan):
578 layout = emitter.plan_layout(output_dir, profile)
579 emitter.emit_metadata(layout, output_dir, kb, profile)
581 logger.info("run_emit(%s): EMIT complete", executed.planned.platform)
583 except PhaseError:
584 raise
585 except Exception as exc:
586 raise PhaseError("EMIT", executed.planned.platform, exc) from exc
589def run_spec(
590 spec: Any, # romfarmer.ir.spec.Spec
591 config_root: Path,
592 *,
593 workspace_root: Path | None = None,
594 output_base: Path | None = None,
595 dry_run: bool = False,
596) -> SpecRunReport:
597 """The EXECUTE door: a frozen ``Spec`` in, a ``SpecRunReport`` out.
599 RESOLVE → CATALOG → PLAN → EXECUTE → EMIT for every platform, driven
600 entirely by the phase functions above — no model call anywhere in this
601 path, and no ``ResolvedPlatformConfig``/state file/budget-tracker from
602 the legacy ``NewBuildOrchestrator`` (the Spec's own per-platform
603 ``passes.budget.max_bytes`` is already the constraint; ``validate_spec``
604 already checked the sum fits ``target.usable_bytes``).
606 ``dry_run`` stops after PLAN (mirrors ``build run --dry-run``): no
607 CATALOG-derived selection is executed and no bytes are written. Output
608 always lands under *output_base* (default ``output/spec-<hash12>``,
609 same default ``resolve_build`` uses) — a plain staging directory, never
610 a device. Getting it onto a card is the separate, explicitly gated
611 ``--deploy`` step (``driver.hooks.run_deployment``); this function never
612 calls it.
613 """
614 from romfarmer.analysis.knowledge import KnowledgeBase
615 from romfarmer.driver.spec_resolve import resolve_build
616 from romfarmer.engine.actioncache import ActionCache
617 from romfarmer.planner import CostModel
619 ws = workspace_root or config_root.parent
620 paths = get_paths()
621 out_base = output_base or ws / "output" / f"spec-{spec.spec_hash()[:12]}"
623 builds: tuple[ResolvedBuild, ...] = resolve_build(
624 spec, config_root, workspace_root=ws, output_base=out_base
625 )
627 db_path = Path(paths.metadata_db)
628 db_path.parent.mkdir(parents=True, exist_ok=True)
629 kb = KnowledgeBase(db_path if db_path.exists() else None)
630 sd_path = ws / "config" / "size_data.json"
631 cost_model = CostModel(size_data_path=sd_path if sd_path.exists() else None, knowledge_base=kb)
632 transforms = _build_default_transforms()
634 reports: list[PlatformRunReport] = []
635 for rb in builds:
636 catalog = run_catalog(
637 rb.resolved, source_dir=rb.source_dir, dat_file=rb.dat_file, kb=kb, digest_db=db_path
638 )
639 if not getattr(catalog, "units", ()):
640 reports.append(PlatformRunReport(rb.platform, rb.chain, 0, 0))
641 continue
643 # PLAN's ActionCache connection is scoped to PLAN alone and closed
644 # before EXECUTE opens its own (run_execute is self-contained and
645 # opens ActionCache + UnitTelemetryStore against the same db_path) —
646 # two live connections to one WAL database in one process is exactly
647 # the shape that produces a self-deadlock on wal_checkpoint (found
648 # 2026-09-04: a real 84-unit run hung with zero disk I/O and a fresh
649 # connection's `PRAGMA wal_checkpoint(PASSIVE)` timing out).
650 with ActionCache(db_path) as action_cache:
651 planned = run_plan(
652 catalog,
653 rb.manifest,
654 cost_model=cost_model,
655 kb=kb,
656 chain=rb.chain,
657 action_cache=action_cache,
658 )
660 if dry_run:
661 reports.append(
662 PlatformRunReport(
663 rb.platform,
664 planned.chain,
665 len(planned.build_plan.units),
666 0,
667 planned_only=True,
668 )
669 )
670 continue
672 validate_plan(planned.build_plan, transforms, rb.platform)
674 work_dir = paths.platform_temp_dir(rb.platform)
675 cas_dir = ws / "store" / "cas"
676 cas_dir.mkdir(parents=True, exist_ok=True)
677 scratch_base = work_dir / "scratch"
678 scratch_base.mkdir(parents=True, exist_ok=True)
679 env = ExecEnv(
680 cas_dir=cas_dir,
681 scratch_base=scratch_base,
682 db_path=db_path,
683 output_dir=rb.output_dir,
684 transforms=transforms,
685 )
686 executed = run_execute(planned, env=env)
688 run_emit(executed, profile=rb.profile, output_dir=rb.output_dir)
690 reports.append(
691 PlatformRunReport(
692 rb.platform,
693 planned.chain,
694 executed.report.terminal_count,
695 executed.report.actual_bytes,
696 executed.report.failed_units,
697 len(executed.report.budget_stopped),
698 )
699 )
701 return SpecRunReport(
702 spec_hash=spec.spec_hash(), output_base=out_base, dry_run=dry_run, platforms=tuple(reports)
703 )
706def _build_default_transforms() -> dict[str, Any]:
707 """Build the standard transform registry for the EXECUTE phase."""
708 from romfarmer.engine.transforms.archive import ArchiveTransform
709 from romfarmer.engine.transforms.chd import CHDTransform
710 from romfarmer.engine.transforms.m3u import M3UTransform
711 from romfarmer.engine.transforms.ps3 import (
712 PS3DecTransform,
713 Ps3DkeyLookupTransform,
714 Ps3ExtractTreeTransform,
715 )
716 from romfarmer.engine.transforms.rvz import RVZExtractTransform
717 from romfarmer.engine.transforms.source import (
718 PassthroughTransform,
719 SourceCopyTransform,
720 )
721 from romfarmer.engine.transforms.squashfs import SquashFSTransform
722 from romfarmer.engine.transforms.unzip import UnzipTransform
723 from romfarmer.engine.transforms.wux import WUXExtractTransform
724 from romfarmer.engine.transforms.xiso import XisoTransform
726 return {
727 "source-copy": SourceCopyTransform(),
728 "passthrough": PassthroughTransform(),
729 "unzip": UnzipTransform(),
730 "compress-7z": ArchiveTransform(),
731 "compress-zip": ArchiveTransform(),
732 "chdman": CHDTransform(),
733 "unzip-rvz": RVZExtractTransform(),
734 "unzip-wux": WUXExtractTransform(),
735 "extract-xiso": XisoTransform(),
736 "mksquashfs": SquashFSTransform(),
737 "ps3dec": PS3DecTransform(),
738 "ps3-dkey-lookup": Ps3DkeyLookupTransform(),
739 "ps3-extract-tree": Ps3ExtractTreeTransform(),
740 "m3u-create": M3UTransform(),
741 }
744def _open_digest_cache(platform: str, db_path: Path) -> Any | None:
745 """Open the FileDigestCache at ``db_path``; None (with a debug log) on error."""
746 try:
747 from romfarmer.analysis.file_digest_cache import FileDigestCache
749 db_path = Path(db_path)
750 db_path.parent.mkdir(parents=True, exist_ok=True)
751 return FileDigestCache(db_path)
752 except Exception as exc:
753 logger.debug("_open_digest_cache(%s): %s", platform, exc)
754 return None
757class NewBuildOrchestrator:
758 """Orchestrates declarative builds using the composition engine.
760 This is the Step 6 replacement for BuildOrchestrator + PlatformProcessor.
761 It's ~400 lines vs 1,738 lines, with the same feature set.
763 Usage:
764 orchestrator = NewBuildOrchestrator.from_config("batocera-1tb")
765 orchestrator.run()
766 """
768 def __init__(
769 self,
770 build_spec: BuildSpec,
771 composed_target: ComposedTarget,
772 resolved_configs: list[ResolvedPlatformConfig],
773 recipes: dict[str, RecipeSpec],
774 state_dir: Path | None = None,
775 ):
776 self.build_spec = build_spec
777 self.composed_target = composed_target
778 self.resolved_configs = resolved_configs
779 self.recipes = recipes
781 # In-memory build state. BuildState YAML persistence was removed in
782 # the Phase 5 cleanup: resume is now replan-plus-action-cache-hits.
783 # Re-running a completed platform is fast because every action is a
784 # cache hit; there is nothing to persist.
785 self.state_dir = state_dir or Path("state") # kept for compat
786 self.state = BuildState(
787 build_name=build_spec.name,
788 started_at=datetime.now(),
789 )
791 # Budget tracking
792 self.budget_tracker = None
793 self.platform_tiers = None
794 self._initialize_budget_tracking()
796 # Logging
797 self._setup_logging()
799 logger.info(f"Initialized new orchestrator: {build_spec.name}")
800 logger.info(f" Target: {composed_target.frontend.name} + {composed_target.device.name}")
801 logger.info(f" Platforms: {len(resolved_configs)}")
802 logger.info(f" Recipes: {', '.join(build_spec.recipes)}")
804 # ═══════════════════════════════════════════════════════════════════════════
805 # Factory
806 # ═══════════════════════════════════════════════════════════════════════════
808 @classmethod
809 def from_config(
810 cls,
811 build_name: str,
812 config_root: Path | None = None,
813 platform_filter: list[str] | None = None,
814 ) -> "NewBuildOrchestrator":
815 """Create orchestrator from a build name.
817 Loads the BuildSpec, composed target, all recipes, and all referenced
818 platform configs, then resolves everything.
820 Args:
821 build_name: Name of build config (without .yaml)
822 config_root: Config root directory (default: auto-detect)
823 platform_filter: If set, only load/validate configs for these platforms.
824 Equivalent to --platforms but applied early enough to skip source
825 path validation for unneeded platforms.
827 Returns:
828 Fully initialized NewBuildOrchestrator
829 """
830 if config_root is None:
831 config_root = get_paths().workspace_root / "config"
833 # 1. Load the build spec
834 build_spec = load_build_spec(build_name, config_root)
835 logger.info(f"Loaded build spec: {build_name}")
837 # 2. Load composed target
838 from romfarmer.config.target_loader import load_composed_target
840 composed_target = load_composed_target(build_spec.target, config_root)
841 logger.info(f"Loaded target: {build_spec.target}")
843 # 3. Load all recipes
844 recipes = load_all_recipes(config_root)
845 logger.info(f"Loaded {len(recipes)} recipes")
847 # 4. Load all platforms referenced by the build's recipes
848 platform_names = set()
849 for recipe_name in build_spec.recipes:
850 recipe = recipes.get(recipe_name)
851 if recipe is None:
852 raise ValueError(f"Recipe '{recipe_name}' not found")
853 if recipe.platforms:
854 platform_names.update(recipe.platforms)
856 # If build spec explicitly lists platforms, use those instead
857 if build_spec.platforms is not None:
858 platform_names = set(build_spec.platforms)
860 # Apply CLI --platforms filter early so we don't load/validate
861 # source paths for platforms we're not going to process.
862 if platform_filter is not None:
863 platform_names &= set(platform_filter)
865 # Remove excluded platforms before loading configs
866 if build_spec.exclude:
867 platform_names -= set(build_spec.exclude)
869 platforms: dict[str, SlimPlatformConfig] = {}
870 for name in platform_names:
871 try:
872 platforms[name] = load_slim_platform(name, config_root)
873 except FileNotFoundError:
874 logger.warning(f"Platform config not found: {name}")
876 logger.info(f"Loaded {len(platforms)} platform configs")
878 # 5. Resolve source roots
879 _resolve_all_source_roots(platforms, config_root)
881 # 6. Resolve the build
882 resolver = ConfigResolver(
883 platforms=platforms,
884 recipes=recipes,
885 composed_target=composed_target,
886 )
887 resolved = resolver.resolve(build_spec)
889 return cls(
890 build_spec=build_spec,
891 composed_target=composed_target,
892 resolved_configs=resolved,
893 recipes=recipes,
894 )
896 # ═══════════════════════════════════════════════════════════════════════════
897 # Initialization helpers
898 # ═══════════════════════════════════════════════════════════════════════════
900 def _initialize_budget_tracking(self):
901 """Initialize budget tracking for builds with storage budgets."""
902 if not self.build_spec.has_budget_constraint():
903 logger.info("No storage budget constraint — unlimited build")
904 return
906 try:
907 from romfarmer.config.tiers_loader import load_platform_tiers
908 from romfarmer.utils.storage_budget import BudgetTracker, compute_storage_budget
910 budget = compute_storage_budget(self.build_spec.storage_budget)
911 self.budget_tracker = BudgetTracker(budget)
912 self.platform_tiers = load_platform_tiers()
913 logger.info(f"Storage budget: {budget}")
914 except Exception as e:
915 logger.error(f"Failed to initialize budget tracking: {e}")
916 raise
918 def _setup_logging(self):
919 """Configure file logging for this build."""
920 logs_dir = get_paths().workspace_root / "logs"
921 logs_dir.mkdir(parents=True, exist_ok=True)
922 log_path = logs_dir / f"build_{self.build_spec.name}.log"
924 build_logger = logging.getLogger(f"romfarmer.build.{self.build_spec.name}")
925 build_logger.setLevel(logging.DEBUG)
927 fh = logging.FileHandler(log_path)
928 fh.setLevel(logging.DEBUG)
929 fh.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s"))
930 build_logger.addHandler(fh)
932 def _load_or_create_state(self) -> BuildState:
933 """Removed: BuildState YAML persistence deleted in Phase 5 cleanup.
935 Kept as a no-op stub so call-sites that were not updated yet don't
936 crash at runtime. Use ``self.state`` directly.
937 """
938 return self.state
940 def _save_state(self) -> None:
941 """Removed: BuildState YAML persistence deleted in Phase 5 cleanup.
943 Resume is now replan-plus-action-cache-hits: re-running a completed
944 platform is fast because every action is a cache hit. No YAML file
945 is written or read.
946 """
948 # ═══════════════════════════════════════════════════════════════════════════
949 # Validation
950 # ═══════════════════════════════════════════════════════════════════════════
952 def validate(self) -> bool:
953 """Validate that the build can proceed.
955 Checks:
956 - At least one resolved platform
957 - Source directories exist
958 - Output directory writable
959 """
960 errors: list[str] = []
962 if not self.resolved_configs:
963 errors.append("No platforms resolved for this build")
965 # Check source directories
966 for rc in self.resolved_configs:
967 for src in rc.sources:
968 if src.path and not src.path.exists():
969 errors.append(f"{rc.platform}: source path not found: {src.path}")
971 # Target profile must load (loud, not a silent None — G4 #6)
972 try:
973 self._load_target_profile()
974 except Exception as e:
975 errors.append(f"target profile: {e}")
977 # Check output base writable
978 output_base = self.build_spec.get_output_base()
979 try:
980 output_base.mkdir(parents=True, exist_ok=True)
981 except Exception as e:
982 errors.append(f"Cannot create output directory {output_base}: {e}")
984 if errors:
985 logger.error("Validation failed:")
986 for err in errors:
987 logger.error(f" - {err}")
988 return False
990 logger.info(f"✅ Validation passed ({len(self.resolved_configs)} platforms)")
991 return True
993 # ═══════════════════════════════════════════════════════════════════════════
994 # Main execution
995 # ═══════════════════════════════════════════════════════════════════════════
997 def run(self, resume: bool = False):
998 """Run the build.
1000 Args:
1001 resume: If True, skip already-completed platforms
1002 """
1003 if not resume and not self.validate():
1004 raise ValueError("Build validation failed")
1006 self.state.status = BuildStatus.RUNNING
1007 self._save_state()
1009 # Order and filter platforms
1010 platforms_to_process = self._get_platforms_to_process(resume)
1012 logger.info(f"Starting build: {self.build_spec.name}")
1013 logger.info(f" Description: {self.build_spec.description}")
1014 logger.info(f" Platforms: {', '.join(rc.platform for rc in platforms_to_process)}")
1016 if self.budget_tracker:
1017 from romfarmer.utils.storage_budget import format_size
1019 logger.info(f" Budget: {format_size(self.budget_tracker.budget.available_bytes)}")
1021 budget_skipped: list[str] = []
1023 for i, resolved in enumerate(platforms_to_process, 1):
1024 logger.info(f"\n{'=' * 60}")
1025 logger.info(f"[{i}/{len(platforms_to_process)}] Processing: {resolved.platform}")
1026 logger.info(f"{'=' * 60}\n")
1028 # Budget gate for lower-tier platforms
1029 if self.budget_tracker and resolved.tier and resolved.tier >= 3:
1030 estimated = self._estimate_platform_size(resolved)
1031 remaining = self.budget_tracker.remaining
1032 if estimated > remaining:
1033 from romfarmer.utils.storage_budget import format_size
1035 logger.warning(
1036 f"⚠ Skipping {resolved.platform} (Tier {resolved.tier}): "
1037 f"estimated {format_size(estimated)} > remaining {format_size(remaining)}"
1038 )
1039 budget_skipped.append(resolved.platform)
1040 continue
1042 try:
1043 self._process_platform(resolved)
1044 self.state.completed_platforms.append(resolved.platform)
1045 logger.info(f"✅ {resolved.platform} complete")
1046 except Exception as e:
1047 logger.error(f"❌ {resolved.platform} failed: {e}", exc_info=True)
1048 self.state.failed_platforms.append(resolved.platform)
1049 # Could add stop_on_error check here if needed
1050 finally:
1051 self.state.current_platform = None
1052 self._save_state()
1054 # Post-build steps
1055 self._run_generation_filter()
1056 self._run_post_build_hooks()
1058 self.state.status = BuildStatus.COMPLETED
1059 self._save_state()
1061 logger.info(f"\n{'=' * 60}")
1062 logger.info("✅ Build complete!")
1063 logger.info(f"{'=' * 60}\n")
1065 self._generate_report()
1066 self._run_deployment()
1068 def resume(self):
1069 """Resume an interrupted build."""
1070 logger.info(f"Resuming build: {self.build_spec.name}")
1071 self.run(resume=True)
1073 # ═══════════════════════════════════════════════════════════════════════════
1074 # Platform processing
1075 # ═══════════════════════════════════════════════════════════════════════════
1077 def _get_platforms_to_process(self, resume: bool) -> list[ResolvedPlatformConfig]:
1078 """Get ordered list of platforms to process.
1080 Applies:
1081 1. Tier ordering (lower tier = higher priority)
1082 2. Resume filtering (skip completed)
1083 """
1084 platforms = list(self.resolved_configs)
1086 # Apply tier ordering (ResolvedPlatformConfig is frozen — derive copies)
1087 if self.platform_tiers:
1088 from dataclasses import replace
1090 tiered: list[ResolvedPlatformConfig] = []
1091 for rc in platforms:
1092 tier = self.platform_tiers.get_platform_tier(rc.platform)
1093 tier_strategy = None
1094 if tier:
1095 strategy = self._get_tier_strategy(rc.platform)
1096 tier_strategy = strategy.value if strategy else None
1097 tiered.append(replace(rc, tier=tier, tier_strategy=tier_strategy))
1098 platforms = tiered
1099 self.resolved_configs = list(platforms)
1101 platforms.sort(key=lambda rc: (rc.tier or 99, rc.platform))
1103 # Log tier distribution
1104 tier_counts: dict[str, int] = {}
1105 for rc in platforms:
1106 key = f"Tier {rc.tier}" if rc.tier else "Unknown"
1107 tier_counts[key] = tier_counts.get(key, 0) + 1
1108 logger.info(f"Platform ordering by tier: {tier_counts}")
1110 # Resume: BuildState YAML removed (Phase 5). resume=True re-runs
1111 # all platforms — the action cache provides fast hits for already-
1112 # completed work, so no YAML-based skip logic is needed.
1113 if resume:
1114 logger.info(
1115 "resume=True: re-running all platforms; "
1116 "action cache provides fast hits for completed work"
1117 )
1119 return platforms
1121 def _get_tier_strategy(self, platform: str):
1122 """Get selection strategy for a platform based on its tier."""
1123 from romfarmer.config.models import TierStrategy
1125 if not self.platform_tiers:
1126 return None
1128 tier_num = self.platform_tiers.get_platform_tier(platform)
1129 if tier_num is None:
1130 return TierStrategy.BEST_OF
1132 profile_name = None # Could come from build spec in future
1133 profile = self.platform_tiers.get_profile(profile_name) if profile_name else None
1134 return self.platform_tiers.get_strategy_for_tier(tier_num, profile)
1136 def _process_platform(self, resolved: ResolvedPlatformConfig) -> None:
1137 """Drive the five compiler phases for one platform.
1139 This is the sole try/except site for per-phase error handling. It
1140 never accesses the phase results beyond what it needs to pass to the
1141 next phase — capability starvation is enforced by the phase-function
1142 signatures (T6, 2026-07-04 architect review).
1143 """
1144 self.state.current_platform = resolved.platform
1145 self._save_state()
1147 logger.info(f"Processing platform: {resolved.platform}")
1149 # ── RESOLVE (public, frozen product) ───────────────────────────
1150 paths = get_paths()
1151 work_dir = paths.platform_temp_dir(resolved.platform)
1152 rb = self.resolve(resolved)
1153 source_dir, output_dir, dat_file, profile, chain, manifest = (
1154 rb.source_dir,
1155 rb.output_dir,
1156 rb.dat_file,
1157 rb.profile,
1158 rb.chain,
1159 rb.manifest,
1160 )
1161 logger.info(f" Source: {source_dir}")
1162 logger.info(f" Output: {output_dir}")
1164 from pathlib import Path as _Path
1166 from romfarmer.analysis.knowledge import KnowledgeBase
1167 from romfarmer.planner import CostModel
1169 db_path = _Path(paths.metadata_db)
1170 kb = KnowledgeBase(db_path if db_path.exists() else None)
1171 sd_path = _Path(paths.workspace_root) / "config" / "size_data.json"
1172 cost_model = CostModel(
1173 size_data_path=sd_path if sd_path.exists() else None,
1174 knowledge_base=kb,
1175 )
1177 # ── CATALOG phase ──────────────────────────────────────────────
1178 try:
1179 catalog = run_catalog(
1180 resolved,
1181 source_dir=source_dir,
1182 dat_file=dat_file,
1183 kb=kb,
1184 digest_db=db_path,
1185 )
1186 except PhaseError as exc:
1187 logger.warning(
1188 "_process_platform(%s): CATALOG failed — %s",
1189 resolved.platform,
1190 exc.cause,
1191 exc_info=True,
1192 )
1193 return
1195 if not getattr(catalog, "units", ()):
1196 logger.debug("_process_platform(%s): empty catalog — skipping", resolved.platform)
1197 return
1199 # ── PLAN phase (passes + lowering) ────────────────────────────
1200 from romfarmer.engine.actioncache import ActionCache
1202 cache_db = _Path(paths.metadata_db)
1203 cache_db.parent.mkdir(parents=True, exist_ok=True)
1205 with ActionCache(cache_db) as action_cache:
1206 try:
1207 planned = run_plan(
1208 catalog,
1209 manifest,
1210 cost_model=cost_model,
1211 kb=kb,
1212 chain=chain,
1213 action_cache=action_cache,
1214 )
1215 except PhaseError as exc:
1216 logger.warning(
1217 "_process_platform(%s): PLAN failed — %s",
1218 resolved.platform,
1219 exc.cause,
1220 exc_info=True,
1221 )
1222 return
1224 # ── Dry-run exit ───────────────────────────────────────────
1225 dry_run = getattr(self, "_dry_run", False)
1226 if dry_run:
1227 logger.info(
1228 " [dry-run] %s: %d units, chain=%s",
1229 resolved.platform,
1230 len(planned.build_plan.units),
1231 chain,
1232 )
1233 for up in planned.build_plan.units:
1234 logger.info(
1235 " %s: %d actions (%s)",
1236 up.unit.canonical_name,
1237 len(up.actions),
1238 ", ".join(a.tool for a in up.actions),
1239 )
1240 return
1242 # ── Plan validation (bug-3 prevention) ────────────────────
1243 transforms = _build_default_transforms()
1244 try:
1245 validate_plan(planned.build_plan, transforms, resolved.platform)
1246 except PlanValidationError as exc:
1247 logger.warning(
1248 "_process_platform(%s): plan validation failed — %s",
1249 resolved.platform,
1250 exc.cause,
1251 )
1252 return
1254 # ── EXECUTE phase ──────────────────────────────────────────
1255 cas_dir = _Path(paths.workspace_root) / "store" / "cas"
1256 cas_dir.mkdir(parents=True, exist_ok=True)
1257 scratch_base = work_dir / "scratch"
1258 scratch_base.mkdir(parents=True, exist_ok=True)
1260 env = ExecEnv(
1261 cas_dir=cas_dir,
1262 scratch_base=scratch_base,
1263 db_path=cache_db,
1264 output_dir=output_dir,
1265 transforms=transforms,
1266 )
1268 try:
1269 executed = run_execute(planned, env=env)
1270 except PhaseError as exc:
1271 logger.warning(
1272 "_process_platform(%s): EXECUTE failed — %s",
1273 resolved.platform,
1274 exc.cause,
1275 exc_info=True,
1276 )
1277 return
1279 # Predicted-vs-actual report (T10 observability). Prediction comes
1280 # from the CostModel for the chain tool — NOT UnitPlan.predicted_output_bytes,
1281 # which every lowering rule sets to the source size (identity).
1282 stopped = set(executed.report.budget_stopped)
1283 source_bytes = sum(
1284 up.unit.source_size
1285 for up in planned.build_plan.units
1286 if str(up.unit.unit_id) not in stopped
1287 )
1288 actual_bytes = executed.report.actual_bytes
1289 try:
1290 predicted_bytes, pred_label = cost_model.predict_output_bytes(
1291 source_bytes, resolved.platform, chain[0] if chain else None
1292 )
1293 except Exception as exc:
1294 predicted_bytes, pred_label = source_bytes, f"fallback:source_size ({exc})"
1295 if predicted_bytes > 0:
1296 ratio = actual_bytes / predicted_bytes
1297 logger.info(
1298 " %s: %d MB actual vs %d MB predicted (%.2f×) [%s]",
1299 resolved.platform,
1300 actual_bytes // (1024 * 1024),
1301 predicted_bytes // (1024 * 1024),
1302 ratio,
1303 pred_label,
1304 )
1305 if executed.report.budget_stopped:
1306 logger.info(
1307 " %s: %d unit(s) stopped by budget",
1308 resolved.platform,
1309 len(executed.report.budget_stopped),
1310 )
1311 # Platform-level size record (size_data.json) — WITH input bytes, so the
1312 # CostModel prior layer that reads it is no longer fed zeros.
1313 executed_units = [
1314 up
1315 for up in planned.build_plan.units
1316 if str(up.unit.unit_id) not in set(executed.report.budget_stopped)
1317 ]
1318 self._record_size(
1319 resolved,
1320 actual_bytes,
1321 executed.report.terminal_count,
1322 input_size_bytes=sum(up.unit.source_size for up in executed_units),
1323 )
1325 # ── EMIT phase (non-fatal) ─────────────────────────────────────
1326 try:
1327 run_emit(executed, profile=profile, output_dir=output_dir)
1328 except PhaseError as exc:
1329 # Outputs are already materialised — EMIT errors are best-effort
1330 logger.warning(
1331 "_process_platform(%s): EMIT error (outputs intact) — %s",
1332 resolved.platform,
1333 exc.cause,
1334 exc_info=True,
1335 )
1337 # ─────────────────────────────────────────────────────────────────────────
1338 # Profile loading (instance method — needs self.composed_target)
1339 # ─────────────────────────────────────────────────────────────────────────
1341 def _resolve_paths(self) -> "ResolvePaths":
1342 paths = get_paths()
1343 root = Path(paths.workspace_root)
1344 return ResolvePaths(
1345 workspace_root=root,
1346 config_dir=root / "config",
1347 dats_dir=Path(getattr(paths, "dats_dir", root / "dats")),
1348 lists_dir=root / "lists",
1349 )
1351 def _get_dat_pattern(self, platform: str) -> str | None:
1352 """DAT search pattern from ``config/dat_patterns.yaml`` (kept as a patch point)."""
1353 from romfarmer.driver.resolve import _dat_pattern
1355 return _dat_pattern(platform, self._resolve_paths().config_dir)
1357 def resolve(self, resolved: ResolvedPlatformConfig) -> "ResolvedBuild":
1358 """RESOLVE one platform into a frozen ``ResolvedBuild`` (public API).
1360 ``cli/plan.py`` and ``cli/doctor.py`` use this so ``plan --explain``
1361 predicts exactly what ``build`` does. DAT discovery and profile
1362 loading go through the instance methods below so tests can patch them.
1363 """
1364 from romfarmer.driver.resolve import resolve_platform
1366 if not resolved.sources or resolved.sources[0].path is None:
1367 raise ValueError(f"No source directory for {resolved.platform}")
1368 return resolve_platform(
1369 resolved,
1370 self.composed_target,
1371 self._resolve_paths(),
1372 dat_file=self._find_dat_file(resolved),
1373 profile=self._load_target_profile(),
1374 sample_n=getattr(self, "_test_sample", None),
1375 sample_seed=getattr(self, "_test_seed", None) or 0,
1376 )
1378 def _load_target_profile(self) -> "object | None":
1379 """Load (and cache) the ``ConcreteTargetProfile`` for this build's target.
1381 Raises ``TargetProfileError`` — never returns a silent ``None`` for a
1382 misconfigured frontend/device (review G4 #6).
1383 """
1384 if hasattr(self, "_cached_target_profile"):
1385 return self._cached_target_profile
1386 from romfarmer.driver.resolve import load_target_profile
1388 profile = load_target_profile(self.composed_target, self._resolve_paths().config_dir)
1389 self._cached_target_profile = profile
1390 return profile
1392 def _load_curated_lists(self, platform: str) -> "tuple[frozenset[str], frozenset[str]]":
1393 from romfarmer.driver.resolve import load_curated_lists
1395 return load_curated_lists(platform, self._resolve_paths().lists_dir)
1397 def _build_manifest(
1398 self,
1399 resolved: "ResolvedPlatformConfig",
1400 platform: "object",
1401 dat_file: Path | None = None,
1402 chain: "tuple[str, ...]" = (),
1403 ) -> "BuildManifest":
1404 """Construct a ``BuildManifest`` (delegates to ``driver.resolve.build_manifest``)."""
1405 from romfarmer.driver.resolve import build_manifest, negotiate_format_chain
1406 from romfarmer.ir.catalog import PlatformId
1408 return build_manifest(
1409 resolved,
1410 PlatformId(str(platform)),
1411 chain=tuple(chain) or negotiate_format_chain(resolved),
1412 dat_file=dat_file,
1413 paths=self._resolve_paths(),
1414 sample_n=getattr(self, "_test_sample", None),
1415 sample_seed=getattr(self, "_test_seed", None) or 0,
1416 )
1418 def _find_dat_file(self, resolved: ResolvedPlatformConfig) -> Path | None:
1419 """Find the DAT file for a platform (delegates to ``driver.resolve.find_dat_file``)."""
1420 from romfarmer.driver.resolve import find_dat_file
1422 return find_dat_file(
1423 resolved, self._resolve_paths(), pattern=self._get_dat_pattern(resolved.platform)
1424 )
1426 def _measure_output_size(self, output_dir: Path) -> int:
1427 """Measure total output size in bytes."""
1428 if not output_dir.exists():
1429 return 0
1430 return sum(f.stat().st_size for f in output_dir.rglob("*") if f.is_file())
1432 def _record_size(
1433 self,
1434 resolved: ResolvedPlatformConfig,
1435 output_size: int,
1436 files_processed: int,
1437 input_size_bytes: int = 0,
1438 ):
1439 """Record output size (and input bytes) for future estimation."""
1440 try:
1441 from romfarmer.utils.size_tracking import record_platform_size
1443 record_platform_size(
1444 platform=resolved.platform,
1445 compression=resolved.compression.value,
1446 output_size_bytes=output_size,
1447 selection=resolved.tier_strategy or "all",
1448 output_files=files_processed,
1449 input_size_bytes=input_size_bytes,
1450 # Explicit path: never the cwd-relative default (tests patch get_paths)
1451 db_path=Path(get_paths().workspace_root) / "config" / "size_data.json",
1452 )
1453 except Exception as e:
1454 logger.warning(f"Failed to record size: {e}")
1456 def _estimate_platform_size(self, resolved: ResolvedPlatformConfig) -> int:
1457 """Estimate output size for budget pre-check."""
1458 from romfarmer.utils.size_tracking import estimate_platform_size
1460 compression = resolved.compression.value
1461 selection = resolved.tier_strategy or "all"
1463 historical = estimate_platform_size(resolved.platform, compression, selection)
1464 if historical:
1465 return historical
1467 # Tier-based fallback
1468 if self.platform_tiers and resolved.tier:
1469 tier = self.platform_tiers.get_tier(resolved.tier)
1470 if tier:
1471 if tier.estimated_per_platform_mb:
1472 estimate = tier.estimated_per_platform_mb * 1024 * 1024
1473 if selection == "best_of":
1474 estimate //= 10
1475 elif selection == "best_of_extended":
1476 estimate //= 5
1477 return estimate
1479 return 1024 * 1024 * 1024 # 1 GB fallback
1481 # ═══════════════════════════════════════════════════════════════════════════
1482 # Post-build steps
1483 # ═══════════════════════════════════════════════════════════════════════════
1485 def _run_generation_filter(self) -> None:
1486 """Run cross-platform generation deduplication (if configured).
1488 Phase 5 implementation: uses the pure ``generation`` planner pass
1489 instead of the legacy ``FilterGenerationStage``.
1490 """
1491 gen_filter = self.build_spec.generation_filter
1492 if not gen_filter or not gen_filter.enabled:
1493 return
1495 logger.info(f"\n{'=' * 60}")
1496 logger.info("Running generation-based cross-platform deduplication...")
1497 logger.info(f"{'=' * 60}\n")
1499 try:
1500 from romfarmer.analysis.knowledge import KnowledgeBase
1501 from romfarmer.config.generation_loader import load_generation
1502 from romfarmer.ir.catalog import Catalog, PlatformId
1503 from romfarmer.ir.manifest import BuildManifest
1504 from romfarmer.planner.costmodel import CostModel
1505 from romfarmer.planner.passes.generation import run as generation_pass
1507 generation_def = load_generation(gen_filter.generation)
1508 if not generation_def:
1509 logger.error(f"Generation not found: {gen_filter.generation}")
1510 return
1512 platform_order = tuple(generation_def.get_platform_names())
1513 logger.info(f"Generation: {generation_def.label}")
1514 logger.info(f" Priority: {' > '.join(platform_order)}")
1516 # Load rescue lists as curated_include
1517 curated_include: frozenset[str] = frozenset()
1518 if gen_filter.rescue_lists:
1519 include_set: set[str] = set()
1520 for games in gen_filter.rescue_lists.values():
1521 include_set.update(g.lower() for g in games)
1522 curated_include = frozenset(include_set)
1523 else:
1524 rescue_file = (
1525 Path(__file__).resolve().parent.parent.parent
1526 / "config"
1527 / "curations"
1528 / "rescue"
1529 / f"rescue-{gen_filter.generation}.yaml"
1530 )
1531 if rescue_file.exists():
1532 import yaml
1534 rescue_data = yaml.safe_load(rescue_file.read_text())
1535 if rescue_data and rescue_data.get("rescue_lists"):
1536 include_set = set()
1537 for games in rescue_data["rescue_lists"].values():
1538 include_set.update(g.lower() for g in games)
1539 curated_include = frozenset(include_set)
1540 logger.info(f" Auto-loaded {len(curated_include)} rescue entries")
1542 # Build a merged multi-platform catalog from output directories
1543 build_output = self.build_spec.get_output_base()
1544 if not build_output.is_absolute():
1545 build_output = get_paths().workspace_root / build_output
1547 from romfarmer.analysis.catalog_builder import CatalogBuilder
1549 kb = KnowledgeBase()
1550 merged: Catalog | None = None
1551 for plat_name in platform_order:
1552 plat_dir = build_output / plat_name
1553 if not plat_dir.exists():
1554 continue
1555 builder = CatalogBuilder(
1556 platform=PlatformId(plat_name),
1557 source_dir=plat_dir,
1558 knowledge_base=kb,
1559 )
1560 cat = builder.build()
1561 if merged is None:
1562 merged = cat
1563 else:
1564 try:
1565 merged = merged.merge(cat)
1566 except ValueError:
1567 pass # overlapping ids — skip this platform
1569 if merged is None or not merged.units:
1570 logger.info("Generation filter: no units found in output dirs, skipping")
1571 return
1573 manifest = BuildManifest(
1574 generation_name=generation_def.name,
1575 generation_platform_order=platform_order,
1576 curated_include=curated_include,
1577 )
1578 result = generation_pass(merged, manifest, kb, CostModel())
1579 removed = len(merged.units) - len(result.catalog.units)
1580 logger.info(
1581 f"✅ Generation filter complete: removed {removed} cross-platform duplicates"
1582 )
1584 except Exception as e:
1585 logger.error(f"Generation filter error: {e}", exc_info=True)
1586 logger.warning("Generation filter failed, but build will continue")
1587 logger.warning("Generation filter failed, but build will continue")
1589 def _hook_context(self, platforms: list[str] | None = None) -> "HookContext":
1590 from romfarmer.driver.hooks import HookContext
1592 output_base = Path(self.build_spec.get_output_base())
1593 if not output_base.is_absolute():
1594 output_base = get_paths().workspace_root / output_base
1595 return HookContext(
1596 build_name=self.build_spec.name,
1597 output_base=output_base,
1598 platforms=tuple(platforms if platforms is not None else self.state.completed_platforms),
1599 metadata_db=get_paths().metadata_db,
1600 workspace_root=Path(get_paths().workspace_root),
1601 )
1603 def _run_post_build_hooks(self):
1604 """Run post-build hooks through the ``driver.hooks`` registry (no shell)."""
1605 if not self.build_spec.post_build:
1606 return
1607 from romfarmer.driver.hooks import run_post_build_hooks
1609 logger.info(f"\n{'=' * 60}")
1610 logger.info("Running post-build hooks...")
1611 logger.info(f"{'=' * 60}\n")
1612 run_post_build_hooks(self.build_spec.post_build, self._hook_context())
1614 def _run_deployment(self):
1615 """Deploy via ``driver.hooks.run_deployment`` (argv, never a shell string)."""
1616 deploy = self.build_spec.deploy
1617 if not deploy:
1618 return
1619 from romfarmer.driver.hooks import run_deployment
1621 logger.info(f"\n{'=' * 60}")
1622 logger.info("Running deployment...")
1623 logger.info(f"{'=' * 60}\n")
1624 result = run_deployment(deploy, self._hook_context().output_base)
1625 if result is None:
1626 return
1627 if result.ok:
1628 logger.info(" ✅ Deployment complete")
1629 else:
1630 logger.error(f" ❌ Deployment failed: {result.summary}")
1632 def _generate_report(self):
1633 """Generate build completion report."""
1634 report_path = get_paths().build_report_file(self.build_spec.name)
1635 duration = datetime.now() - self.state.started_at
1637 total = len(self.resolved_configs)
1638 completed = len(self.state.completed_platforms)
1639 failed = len(self.state.failed_platforms)
1641 with open(report_path, "w") as f:
1642 f.write(f"Build Report: {self.build_spec.name}\n")
1643 f.write("=" * 60 + "\n\n")
1644 f.write(f"Description: {self.build_spec.description}\n")
1645 f.write(f"Target: {self.build_spec.target}\n")
1646 f.write(f"Recipes: {', '.join(self.build_spec.recipes)}\n\n")
1647 f.write(f"Started: {self.state.started_at}\n")
1648 f.write(f"Completed: {datetime.now()}\n")
1649 f.write(f"Duration: {duration}\n\n")
1650 f.write(f"Status: {self.state.status.value}\n\n")
1651 f.write("Platforms Summary:\n")
1652 f.write(f" Total: {total}\n")
1653 f.write(f" Completed: {completed}\n")
1654 f.write(f" Failed: {failed}\n")
1655 f.write(f" Success Rate: {completed / max(total, 1) * 100:.1f}%\n\n")
1657 if self.state.completed_platforms:
1658 f.write(f"Completed Platforms ({completed}):\n")
1659 for p in self.state.completed_platforms:
1660 f.write(f" ✅ {p}\n")
1661 f.write("\n")
1663 if self.state.failed_platforms:
1664 f.write(f"Failed Platforms ({failed}):\n")
1665 for p in self.state.failed_platforms:
1666 f.write(f" ❌ {p}\n")
1667 f.write("\n")
1669 f.write("=" * 60 + "\n")
1671 logger.info(f"Report saved: {report_path}")
1673 # ═══════════════════════════════════════════════════════════════════════════
1674 # Status
1675 # ═══════════════════════════════════════════════════════════════════════════
1677 def get_status(self) -> dict[str, Any]:
1678 """Get current build status."""
1679 total = len(self.resolved_configs)
1680 completed = len(self.state.completed_platforms)
1681 failed = len(self.state.failed_platforms)
1683 return {
1684 "build_name": self.build_spec.name,
1685 "description": self.build_spec.description,
1686 "target": self.build_spec.target,
1687 "recipes": self.build_spec.recipes,
1688 "status": self.state.status.value,
1689 "current_platform": self.state.current_platform,
1690 "started_at": self.state.started_at.isoformat(),
1691 "last_updated": self.state.last_updated.isoformat()
1692 if self.state.last_updated
1693 else None,
1694 "progress": {
1695 "total": total,
1696 "completed": completed,
1697 "failed": failed,
1698 "remaining": total - completed - failed,
1699 "percent": (completed / total * 100) if total > 0 else 0,
1700 },
1701 "completed_platforms": self.state.completed_platforms,
1702 "failed_platforms": self.state.failed_platforms,
1703 }
1706# ═══════════════════════════════════════════════════════════════════════════════
1707# Helpers
1708# ═══════════════════════════════════════════════════════════════════════════════
1711def _resolve_all_source_roots(
1712 platforms: dict[str, SlimPlatformConfig],
1713 config_root: Path,
1714):
1715 """Resolve source root references in all platform configs.
1717 Reads config/sources.yaml and replaces root/subdir references
1718 with absolute paths in each platform's SourceConfig.
1719 """
1720 sources_path = config_root / "sources.yaml"
1721 if not sources_path.exists():
1722 return
1724 try:
1725 with open(sources_path) as f:
1726 roots = yaml.safe_load(os.path.expandvars(f.read())).get("roots", {})
1727 except Exception as e:
1728 logger.error(f"Failed to load sources.yaml: {e}")
1729 return
1731 for platform in platforms.values():
1732 for source in platform.sources:
1733 if source.root and source.root in roots:
1734 root_path = Path(roots[source.root])
1735 source.path = root_path / source.subdir if source.subdir else root_path
1736 if not source.path.exists():
1737 logger.warning(f"{platform.name}: source path not found: {source.path}")
1739 # Also resolve chd_sources
1740 if platform.chd_sources:
1741 for source in platform.chd_sources:
1742 if source.root and source.root in roots:
1743 root_path = Path(roots[source.root])
1744 source.path = root_path / source.subdir if source.subdir else root_path