Coverage for src/romfarmer/cli/plan.py: 0%
105 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-04 16:33 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-04 16:33 -0700
1"""romfarmer plan — RESOLVE + CATALOG + PLAN for a build, with --explain.
3Usage::
5 romfarmer plan run smoke-nes-7z --explain
6 romfarmer plan run config/builds/redump-1g1r-eng-chd-retrobat.yaml --platform psx --explain
8Runs exactly the RESOLVE / CATALOG / PLAN phases that ``romfarmer build run``
9would (same passes, same manifest, same format negotiation), so the
10``--explain`` table is a faithful prediction of the build. Read-only: no
11transforms are executed and no output files are written.
12"""
14from __future__ import annotations
16import logging
17from pathlib import Path
19import click
20from rich import box
21from rich.console import Console
22from rich.table import Table
24logger = logging.getLogger(__name__)
25console = Console()
28@click.group("plan")
29def plan_group() -> None:
30 """Inspect and explain the planner's selection decisions."""
33@plan_group.command("run")
34@click.argument("build")
35@click.option("--platform", "platform_name", default=None, help="Limit to one platform (e.g. psx).")
36@click.option("--explain", is_flag=True, help="Show per-pass removal counts and sample reasons.")
37@click.option("--max-reasons", default=5, show_default=True, help="Sample reasons per pass.")
38@click.option(
39 "--test-sample", type=int, default=None, help="Apply the seeded sample pass a test build would."
40)
41@click.option("--seed", type=int, default=0, show_default=True, help="Seed for --test-sample.")
42def plan_run(
43 build: str,
44 platform_name: str | None,
45 explain: bool,
46 max_reasons: int,
47 test_sample: int | None,
48 seed: int,
49) -> None:
50 """Plan BUILD — a name in config/builds/ or a path to a build YAML."""
51 from romfarmer.analysis.knowledge import KnowledgeBase
52 from romfarmer.core.paths import get_paths
53 from romfarmer.new_orchestrator import NewBuildOrchestrator, run_catalog, run_plan
54 from romfarmer.planner import CostModel
56 ws = Path(get_paths().workspace_root)
57 build_path = Path(build)
58 is_spec = build_path.suffix in (".yaml", ".yml") and _is_spec_file(build_path)
59 build_name = build_path.stem if build_path.suffix in (".yaml", ".yml") else build
61 # Two front doors, one RESOLVE: a legacy build name/YAML, or a Spec YAML.
62 builds: list = []
63 target_label: str
64 if is_spec:
65 import dataclasses
67 from romfarmer.driver.spec_io import load_spec
68 from romfarmer.driver.spec_resolve import resolve_build
69 from romfarmer.ir.spec import SpecError, SpecSample
71 try:
72 spec = load_spec(build_path)
73 if test_sample:
74 spec = dataclasses.replace(
75 spec,
76 platforms=tuple(
77 dataclasses.replace(
78 p,
79 passes=dataclasses.replace(
80 p.passes, sample=SpecSample(n=test_sample, seed=seed)
81 ),
82 )
83 for p in spec.platforms
84 ),
85 )
86 builds = list(resolve_build(spec, ws / "config", workspace_root=ws))
87 except SpecError as exc:
88 console.print(f"[red]{exc}[/red]")
89 raise SystemExit(1) from exc
90 target_label = (
91 f"{spec.target.frontend}/{spec.target.device} spec_hash={spec.spec_hash()[:12]}"
92 )
93 build_name = f"spec:{spec.spec_hash()[:12]}"
94 else:
95 try:
96 orchestrator = NewBuildOrchestrator.from_config(
97 build_name, platform_filter=[platform_name] if platform_name else None
98 )
99 except FileNotFoundError as exc:
100 console.print(f"[red]{exc}[/red]")
101 raise SystemExit(1) from exc
102 if test_sample:
103 orchestrator._test_sample = test_sample
104 orchestrator._test_seed = seed
105 target_label = orchestrator.build_spec.target
106 for resolved in orchestrator.resolved_configs:
107 try:
108 builds.append(orchestrator.resolve(resolved))
109 except ValueError as exc: # no source directory
110 console.print(f"[yellow]{resolved.platform}: {exc} — skipped[/yellow]")
112 if platform_name:
113 builds = [rb for rb in builds if rb.platform == platform_name]
114 if not builds:
115 console.print(f"[red]Platform {platform_name!r} is not in {build_name!r}[/red]")
116 raise SystemExit(1)
118 db_path = Path(get_paths().metadata_db)
119 kb = KnowledgeBase(db_path if db_path.exists() else None)
120 sd_path = ws / "config" / "size_data.json"
121 cost_model = CostModel(size_data_path=sd_path if sd_path.exists() else None, knowledge_base=kb)
122 console.print(
123 f"[cyan]Build:[/cyan] {build_name} [cyan]Target:[/cyan] {target_label} "
124 f"[cyan]Platforms:[/cyan] {len(builds)}"
125 )
127 total_in = total_out = 0
128 for rb in builds:
129 resolved = rb.resolved
130 dat_file, chain, manifest = rb.dat_file, rb.chain, rb.manifest
132 with console.status(f"Cataloging {resolved.platform}..."):
133 catalog = run_catalog(
134 resolved, source_dir=rb.source_dir, dat_file=dat_file, kb=kb, digest_db=db_path
135 )
136 planned = run_plan(catalog, manifest, cost_model=cost_model, kb=kb, chain=chain)
138 n_in, n_out = len(catalog.units), len(planned.catalog.units)
139 total_in += n_in
140 total_out += n_out
141 dat_note = "" if dat_file else " [yellow](no DAT)[/yellow]"
142 console.print(
143 f"\n[bold]{resolved.platform}[/bold] chain={'→'.join(chain)} "
144 f"[green]{n_out}[/green] / {n_in} units{dat_note}"
145 )
146 if explain:
147 _render_explain(list(planned.traces), max_reasons)
149 if len(builds) > 1:
150 console.print(f"\n[bold]Total:[/bold] {total_out} / {total_in} units selected")
153def _render_explain(traces: list, max_reasons: int) -> None:
154 """Render the --explain table."""
155 table = Table(box=box.ROUNDED, show_lines=True)
156 table.add_column("Pass", style="cyan", no_wrap=True)
157 table.add_column("Removed", justify="right", style="red")
158 table.add_column("Sample reasons", overflow="fold")
160 for trace in traces:
161 n = len(trace.removed)
162 if n == 0:
163 sample = "[dim](no-op)[/dim]"
164 else:
165 lines = [f"• {reason}" for _, reason in trace.removed[:max_reasons]]
166 if n > max_reasons:
167 lines.append(f" [dim]... and {n - max_reasons} more[/dim]")
168 sample = "\n".join(lines)
169 table.add_row(trace.pass_name, str(n) if n else "—", sample)
171 console.print(table)
174def _is_spec_file(path: Path) -> bool:
175 """True when *path* is a Spec YAML (has ``spec_version``), not a legacy build."""
176 try:
177 import yaml
179 raw = yaml.safe_load(path.read_text())
180 except Exception:
181 return False
182 return isinstance(raw, dict) and "spec_version" in raw