Coverage for src/romfarmer/cli/farmhand.py: 0%
717 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"""CLI commands for Farm-Hand deployment system.
3Provides: romfarmer farmhand connect|scan|plan|deploy|status|diff
4"""
6from __future__ import annotations
8from pathlib import Path
9from typing import TYPE_CHECKING
11import click
12from rich.console import Console
13from rich.panel import Panel
14from rich.table import Table
16if TYPE_CHECKING:
17 from romfarmer.farmhand.models import DeploymentPlan, TargetProfile
18 from romfarmer.farmhand.skills.store import SkillStore
21def _check_paramiko() -> None:
22 """Ensure paramiko is installed."""
23 try:
24 import paramiko # noqa: F401
25 except ImportError:
26 click.echo(
27 "Error: paramiko is required for Farm-Hand. "
28 "Install with: pip install 'romfarmer[farmhand]'",
29 err=True,
30 )
31 raise click.Abort() from None
34@click.group(name="farmhand")
35def farmhand_group() -> None:
36 """Farm-Hand: AI-driven ROM deployment to remote targets.
38 Connect to Batocera/RockNIX devices, analyze storage, plan optimal
39 ROM deployment, and transfer files via SSH.
41 Example workflow:
42 romfarmer farmhand connect batocera-nuc
43 romfarmer farmhand scan batocera-nuc
44 romfarmer farmhand plan --target batocera-nuc
45 romfarmer farmhand deploy --target batocera-nuc --dry-run
46 """
47 pass
50# ── Target management ────────────────────────────────────────────────────────
53@farmhand_group.group(name="target")
54def target_group() -> None:
55 """Manage target connection configs (config/farmhand/targets/).
57 Target configs are YAML files that store SSH connection details,
58 system identity, and volume hints. Create one per device.
60 Examples:
61 romfarmer farmhand target list
62 romfarmer farmhand target show batocera-nuc
63 """
64 pass
67@target_group.command(name="list")
68def target_list() -> None:
69 """List all configured targets."""
70 from romfarmer.core.paths import get_paths
71 from romfarmer.farmhand.config import get_targets_dir, list_profiles, list_targets
73 workspace = get_paths().workspace_root
74 targets = list_targets(workspace)
75 profiles = list_profiles(workspace)
76 console = Console()
78 if not targets:
79 console.print("[dim]No target configs found.[/dim]")
80 console.print(f"Create one at: {get_targets_dir(workspace)}/")
81 return
83 table = Table(title=f"Farm-Hand Targets ({len(targets)})")
84 table.add_column("Name", style="cyan bold")
85 table.add_column("Has Scan", style="green")
87 for name in targets:
88 has_profile = "yes" if name in profiles else "no"
89 table.add_row(name, has_profile)
91 console.print(table)
94@target_group.command(name="show")
95@click.argument("name")
96def target_show(name: str) -> None:
97 """Show details of a target config."""
98 from romfarmer.core.paths import get_paths
99 from romfarmer.farmhand.config import load_profile, load_target_config
101 workspace = get_paths().workspace_root
102 console = Console()
104 try:
105 config = load_target_config(workspace, name)
106 except Exception as exc:
107 console.print(f"[red]{exc}[/red]")
108 raise click.Abort() from exc
110 # Mask password in display
111 display_config = dict(config)
112 if display_config.get("password"):
113 display_config["password"] = "****"
115 import yaml
117 console.print(
118 Panel(
119 yaml.dump(display_config, default_flow_style=False, sort_keys=False).rstrip(),
120 title=f"Target: {name}",
121 )
122 )
124 # Show profile status
125 profile = load_profile(workspace, name)
126 if profile:
127 si = profile.system_info
128 console.print(
129 f"\n[bold green]Scan available[/bold green]"
130 f" (last: {profile.last_scanned:%Y-%m-%d %H:%M})"
131 )
132 if si:
133 console.print(f" {si.hostname} | {si.os_name} {si.os_version} | {si.architecture}")
134 console.print(
135 f" Volumes: {len(profile.volumes)} | "
136 f"Platforms: {len(profile.existing_roms)} | "
137 f"Available: {profile.total_available_gb():.1f} GB"
138 )
139 else:
140 console.print(f"\n[dim]No scan profile yet. Run: romfarmer farmhand scan {name}[/dim]")
143# ── Skill subcommands ────────────────────────────────────────────────────────
146@farmhand_group.group(name="skill")
147def skill_group() -> None:
148 """Manage Farm-Hand skills — reusable agent procedures and artifacts.
150 Skills are markdown contracts (SKILL.md) paired with machine-readable
151 procedures and artifacts (scripts, game lists, configs). The agent
152 auto-captures successful workflows and you can also create skills
153 by hand.
155 Examples:
156 romfarmer farmhand skill list
157 romfarmer farmhand skill show scan-and-plan
158 romfarmer farmhand skill search "deploy budget"
159 romfarmer farmhand skill cat scan-and-plan procedure.yaml
160 """
161 pass
164@skill_group.command(name="list")
165@click.option(
166 "--category",
167 "-c",
168 default=None,
169 help="Filter by category (deployment, build, target, curation, maintenance, scripting, workflow).",
170)
171@click.option("--tag", "-t", default=None, help="Filter by tag.")
172@click.option("--platform", "-p", default=None, help="Filter by ROM platform.")
173@click.option("--verbose", "-v", is_flag=True, help="Show full details.")
174def skill_list(
175 category: str | None,
176 tag: str | None,
177 platform: str | None,
178 verbose: bool,
179) -> None:
180 """List all available skills."""
181 from romfarmer.farmhand.skills import SkillCategory
183 store = _get_skill_store()
184 skills = store.search(
185 category=SkillCategory(category) if category else None,
186 tags=[tag] if tag else None,
187 platform=platform,
188 )
190 console = Console()
191 if not skills:
192 console.print("[dim]No skills found.[/dim]")
193 return
195 table = Table(title=f"Farm-Hand Skills ({len(skills)})", show_lines=verbose)
196 table.add_column("Name", style="cyan bold", min_width=24)
197 table.add_column("Category", style="yellow")
198 table.add_column("Description", min_width=40)
199 table.add_column("Tags", style="dim")
200 table.add_column("Source", style="dim")
202 for skill in sorted(skills, key=lambda s: (s.meta.category.value, s.meta.name)):
203 source = "builtin" if skill.is_builtin else "user"
204 tags_str = ", ".join(skill.meta.tags[:4])
205 if len(skill.meta.tags) > 4:
206 tags_str += f" +{len(skill.meta.tags) - 4}"
207 table.add_row(
208 skill.meta.name,
209 skill.meta.category.value,
210 skill.meta.description[:60],
211 tags_str,
212 source,
213 )
215 console.print(table)
218@skill_group.command(name="show")
219@click.argument("name")
220def skill_show(name: str) -> None:
221 """Show full details of a skill, including SKILL.md content."""
222 store = _get_skill_store()
223 skill = store.get(name)
224 console = Console()
226 if not skill:
227 console.print(f"[red]Skill '{name}' not found.[/red]")
228 raise click.Abort()
230 # Header panel
231 meta = skill.meta
232 header_lines = [
233 f"[bold cyan]{meta.name}[/bold cyan] v{meta.version}",
234 f"[yellow]{meta.category.value}[/yellow] | by {meta.author}",
235 f"Created: {meta.created:%Y-%m-%d} | Updated: {meta.updated:%Y-%m-%d}",
236 ]
237 if meta.tags:
238 header_lines.append(f"Tags: {', '.join(meta.tags)}")
239 if meta.platforms:
240 header_lines.append(f"Platforms: {', '.join(meta.platforms)}")
241 if meta.targets:
242 header_lines.append(f"Targets: {', '.join(meta.targets)}")
243 if meta.tools_used:
244 header_lines.append(f"Tools: {', '.join(meta.tools_used)}")
246 source_label = "builtin" if skill.is_builtin else str(skill.source_path)
247 header_lines.append(f"Source: {source_label}")
249 console.print(Panel("\n".join(header_lines), title="Skill Details"))
251 # Parameters
252 if meta.params:
253 ptable = Table(title="Parameters")
254 ptable.add_column("Name", style="green")
255 ptable.add_column("Type")
256 ptable.add_column("Required")
257 ptable.add_column("Default")
258 ptable.add_column("Description")
259 for p in meta.params:
260 ptable.add_row(
261 p.name,
262 p.type,
263 "yes" if p.required else "",
264 str(p.default) if p.default is not None else "",
265 p.description,
266 )
267 console.print(ptable)
269 # Artifacts
270 if meta.artifacts:
271 atable = Table(title="Artifacts")
272 atable.add_column("File", style="cyan")
273 atable.add_column("Type")
274 atable.add_column("Description")
275 for a in meta.artifacts:
276 atable.add_row(a.filename, a.artifact_type, a.description)
277 console.print(atable)
279 # Procedure steps
280 if skill.steps:
281 stable = Table(title="Procedure Steps")
282 stable.add_column("#", style="dim")
283 stable.add_column("ID", style="green")
284 stable.add_column("Action", style="yellow")
285 stable.add_column("Description")
286 for i, step in enumerate(skill.steps, 1):
287 stable.add_row(
288 str(i),
289 step.id,
290 step.action.value,
291 step.description[:60],
292 )
293 console.print(stable)
295 # Body
296 if skill.body.strip():
297 console.print(Panel(skill.body.strip(), title="SKILL.md Content"))
300@skill_group.command(name="search")
301@click.argument("query")
302@click.option("--category", "-c", default=None, help="Filter by category.")
303@click.option("--tag", "-t", default=None, help="Filter by tag.")
304def skill_search(query: str, category: str | None, tag: str | None) -> None:
305 """Search skills by text query."""
306 from romfarmer.farmhand.skills import SkillCategory
308 store = _get_skill_store()
309 results = store.search(
310 query=query,
311 category=SkillCategory(category) if category else None,
312 tags=[tag] if tag else None,
313 )
315 console = Console()
316 if not results:
317 console.print(f"[dim]No skills matching '{query}'.[/dim]")
318 return
320 console.print(f"[bold]Found {len(results)} skill(s):[/bold]")
321 for skill in results:
322 source = "builtin" if skill.is_builtin else "user"
323 console.print(f" [cyan]{skill.meta.name}[/cyan] [{source}] — {skill.meta.description}")
326@skill_group.command(name="cat")
327@click.argument("name")
328@click.argument("filename", default="SKILL.md")
329def skill_cat(name: str, filename: str) -> None:
330 """Display a file from a skill (default: SKILL.md).
332 Examples:
333 romfarmer farmhand skill cat scan-and-plan
334 romfarmer farmhand skill cat batocera-dual-volume-setup setup-rom-symlinks.sh
335 romfarmer farmhand skill cat curated-essentials-list essentials/saturn.yaml
336 """
337 store = _get_skill_store()
338 skill = store.get(name)
339 console = Console()
341 if not skill:
342 console.print(f"[red]Skill '{name}' not found.[/red]")
343 raise click.Abort()
345 if filename == "SKILL.md":
346 if skill.source_path:
347 md_path = skill.source_path / "SKILL.md"
348 if md_path.exists():
349 console.print(md_path.read_text(encoding="utf-8"))
350 return
351 # Fallback: reconstruct from model
352 console.print(skill.body)
353 return
355 content = store.get_artifact_content(name, filename)
356 if content is None:
357 console.print(f"[red]File '{filename}' not found in skill '{name}'.[/red]")
358 raise click.Abort()
359 console.print(content)
362@skill_group.command(name="delete")
363@click.argument("name")
364@click.option("--yes", "-y", is_flag=True, help="Skip confirmation.")
365def skill_delete(name: str, yes: bool) -> None:
366 """Delete a user-created skill."""
367 store = _get_skill_store()
368 skill = store.get(name)
369 console = Console()
371 if not skill:
372 console.print(f"[red]Skill '{name}' not found.[/red]")
373 raise click.Abort()
375 if skill.is_builtin:
376 console.print(f"[red]Cannot delete builtin skill '{name}'.[/red]")
377 raise click.Abort()
379 if not yes:
380 click.confirm(f"Delete skill '{name}'?", abort=True)
382 store.delete(name)
383 console.print(f"[green]Deleted skill '{name}'.[/green]")
386@skill_group.command(name="path")
387@click.argument("name")
388def skill_path(name: str) -> None:
389 """Print the filesystem path of a skill."""
390 store = _get_skill_store()
391 skill = store.get(name)
392 console = Console()
394 if not skill or not skill.source_path:
395 console.print(f"[red]Skill '{name}' not found.[/red]")
396 raise click.Abort()
398 console.print(str(skill.source_path))
401def _get_skill_store() -> SkillStore:
402 """Create a SkillStore with standard paths."""
403 from romfarmer.core.paths import get_paths
404 from romfarmer.farmhand.skills import SkillStore
406 paths = get_paths()
407 return SkillStore(workspace_root=paths.workspace_root)
410# ── Connect ──────────────────────────────────────────────────────────────────
413@farmhand_group.command()
414@click.argument("host_or_target")
415@click.option("--port", "-p", default=22, type=int, help="SSH port")
416@click.option("--user", "-u", default="root", help="SSH username")
417@click.option("--password", default=None, help="SSH password")
418@click.option("--key-file", default=None, type=click.Path(exists=True), help="SSH private key")
419@click.option("--name", "-n", default=None, help="Target profile name (default: auto-generated)")
420@click.option("--frontend", default="batocera", type=click.Choice(["batocera", "rocknix"]))
421def connect(
422 host_or_target: str,
423 port: int,
424 user: str,
425 password: str | None,
426 key_file: str | None,
427 name: str | None,
428 frontend: str,
429) -> None:
430 """Connect to a remote target and run a quick probe.
432 HOST_OR_TARGET can be an IP/hostname or a target config name
433 (from config/farmhand/targets/).
435 Examples:
436 romfarmer farmhand connect 192.0.2.10 --password linux
437 romfarmer farmhand connect batocera-nuc
438 """
439 _check_paramiko()
440 console = Console()
442 from romfarmer.farmhand.ssh import SSHClient
444 # Resolve target config or use direct args
445 ssh_kwargs, target_name, resolved_frontend = _resolve_target(
446 host_or_target,
447 port=port,
448 user=user,
449 password=password,
450 key_file=key_file,
451 name=name,
452 frontend=frontend,
453 )
455 if not ssh_kwargs.get("password") and not ssh_kwargs.get("key_file"):
456 ssh_kwargs["password"] = click.prompt("SSH password", hide_input=True)
458 with console.status(
459 f"Connecting to {ssh_kwargs['user']}@{ssh_kwargs['host']}:{ssh_kwargs['port']}..."
460 ):
461 client = SSHClient(**ssh_kwargs)
462 try:
463 client.connect()
464 except Exception as exc:
465 console.print(f"[red]Connection failed:[/red] {exc}")
466 raise click.Abort() from exc
468 probe = client.run("hostname").strip()
469 client.close()
471 profile_name = target_name or f"{resolved_frontend}-{probe.lower()}"
472 console.print(
473 Panel(
474 f"[green]Connected to {ssh_kwargs['host']}[/green]\n"
475 f"Hostname: {probe}\n"
476 f"Profile name: {profile_name}",
477 title="Farm-Hand Connect",
478 )
479 )
480 console.print(f"\nNext: [bold]romfarmer farmhand scan {host_or_target}[/bold]")
483# ── Scan ─────────────────────────────────────────────────────────────────────
486@farmhand_group.command()
487@click.argument("host_or_target")
488@click.option("--port", "-p", default=22, type=int, help="SSH port")
489@click.option("--user", "-u", default="root", help="SSH username")
490@click.option("--password", default=None, help="SSH password")
491@click.option("--key-file", default=None, type=click.Path(exists=True), help="SSH private key")
492@click.option("--name", "-n", default=None, help="Target profile name")
493@click.option("--frontend", default="batocera", type=click.Choice(["batocera", "rocknix"]))
494@click.option("--save/--no-save", default=True, help="Save target profile to config/")
495@click.option("--json-output", "output_json", is_flag=True, help="Output as JSON")
496def scan(
497 host_or_target: str,
498 port: int,
499 user: str,
500 password: str | None,
501 key_file: str | None,
502 name: str | None,
503 frontend: str,
504 save: bool,
505 output_json: bool,
506) -> None:
507 """Full scan of a remote target — volumes, ROMs, capabilities.
509 HOST_OR_TARGET can be an IP/hostname or a target config name
510 (from config/farmhand/targets/).
512 Examples:
513 romfarmer farmhand scan 192.0.2.10 --password linux
514 romfarmer farmhand scan batocera-nuc
515 """
516 _check_paramiko()
517 console = Console()
519 from romfarmer.farmhand.analyzer import TargetAnalyzer
520 from romfarmer.farmhand.config import save_profile
521 from romfarmer.farmhand.ssh import SSHClient
523 # Resolve target config or use direct args
524 ssh_kwargs, target_name, resolved_frontend = _resolve_target(
525 host_or_target,
526 port=port,
527 user=user,
528 password=password,
529 key_file=key_file,
530 name=name,
531 frontend=frontend,
532 )
534 if not ssh_kwargs.get("password") and not ssh_kwargs.get("key_file"):
535 ssh_kwargs["password"] = click.prompt("SSH password", hide_input=True)
537 client = SSHClient(**ssh_kwargs)
538 final_name = target_name or f"{resolved_frontend}-{ssh_kwargs['host'].replace('.', '-')}"
540 with console.status(f"Scanning {ssh_kwargs['host']}..."):
541 client.connect()
542 analyzer = TargetAnalyzer(client)
543 profile = analyzer.full_scan(
544 name=final_name,
545 frontend=resolved_frontend,
546 )
547 client.close()
549 if output_json:
550 click.echo(profile.model_dump_json(indent=2))
551 return
553 # Display results
554 _display_scan_results(console, profile)
556 # Save profile
557 if save:
558 from romfarmer.core.paths import get_paths
560 profile_path = save_profile(get_paths().workspace_root, profile)
561 console.print(f"\n[dim]Profile saved to {profile_path}[/dim]")
564def _display_scan_results(console: Console, profile: TargetProfile) -> None:
565 """Display scan results in a nice Rich table."""
566 # System info
567 si = profile.system_info
568 if si:
569 console.print(
570 Panel(
571 f"Hostname: {si.hostname}\n"
572 f"OS: {si.os_name} {si.os_version}\n"
573 f"Arch: {si.architecture}\n"
574 f"CPU: {si.cpu_model} ({si.cpu_cores}c/{si.cpu_threads}t)\n"
575 f"RAM: {si.memory_available_mb}/{si.memory_total_mb} MB",
576 title=f"System: {profile.name}",
577 )
578 )
580 # Volumes
581 vol_table = Table(title="Storage Volumes", show_header=True, header_style="bold cyan")
582 vol_table.add_column("Mount", style="green")
583 vol_table.add_column("Device")
584 vol_table.add_column("FS")
585 vol_table.add_column("Total", justify="right")
586 vol_table.add_column("Available", justify="right")
587 vol_table.add_column("Use%", justify="right")
588 vol_table.add_column("Role", style="yellow")
589 vol_table.add_column("ROM Path")
591 for vol in profile.volumes:
592 vol_table.add_row(
593 vol.mount_point,
594 vol.device,
595 vol.filesystem,
596 f"{vol.total_gb:.1f} GB",
597 f"{vol.available_gb:.1f} GB",
598 f"{vol.use_percent:.0f}%",
599 vol.role.value,
600 vol.rom_path or "-",
601 )
602 console.print(vol_table)
604 # Existing ROMs summary
605 if profile.existing_roms:
606 rom_table = Table(
607 title="Existing ROMs on Target",
608 show_header=True,
609 header_style="bold cyan",
610 )
611 rom_table.add_column("Platform", style="green")
612 rom_table.add_column("Files", justify="right")
614 for platform, files in sorted(profile.existing_roms.items(), key=lambda x: -len(x[1])):
615 rom_table.add_row(platform, str(len(files)))
616 console.print(rom_table)
618 # Capabilities
619 caps = profile.capabilities
620 if caps:
621 console.print(f"\n[bold]Binaries:[/bold] {', '.join(sorted(caps.binaries))}")
622 console.print(
623 f"[bold]7z support:[/bold] {'Yes' if caps.has_7z else 'No'} | "
624 f"[bold]chdman:[/bold] {'Yes' if caps.has_chdman else 'No'}"
625 )
627 # Summary
628 total_gb = profile.total_available_gb()
629 console.print(f"\n[bold green]Total ROM storage available: {total_gb:.1f} GB[/bold green]")
632# ── Plan ─────────────────────────────────────────────────────────────────────
635@farmhand_group.command()
636@click.option("--target", "-t", required=True, help="Target profile name")
637@click.option("--reserve", default=30.0, type=float, help="GB to reserve for saves/BIOS/etc")
638@click.option("--exclude", default=None, help="Comma-separated platforms to exclude")
639@click.option(
640 "--budget", default=None, multiple=True, help="Budget override: platform=GB (e.g., ps2=80)"
641)
642@click.option("--json-output", "output_json", is_flag=True, help="Output as JSON")
643def plan(
644 target: str,
645 reserve: float,
646 exclude: str | None,
647 budget: tuple[str, ...],
648 output_json: bool,
649) -> None:
650 """Generate a deployment plan for a target.
652 Analyzes available space and proposes optimal platform allocation.
654 Example:
655 romfarmer farmhand plan --target batocera-nuc --reserve 30 --exclude xbox360
656 romfarmer farmhand plan --target batocera-nuc --budget ps2=80 --budget psx=60
657 """
658 console = Console()
660 # Load target profile
661 profile = _load_profile(target)
662 if not profile:
663 console.print(f"[red]Target profile '{target}' not found[/red]")
664 console.print("Run: romfarmer farmhand scan <host> --name <target> first")
665 raise click.Abort()
667 exclude_platforms = [p.strip() for p in exclude.split(",")] if exclude else []
668 budget_overrides = {}
669 for b in budget:
670 if "=" in b:
671 k, v = b.split("=", 1)
672 budget_overrides[k.strip()] = float(v.strip())
674 from romfarmer.farmhand.planner import SpacePlanner
676 planner = SpacePlanner()
677 deployment_plan = planner.create_plan(
678 target=profile,
679 reserved_gb=reserve,
680 exclude_platforms=exclude_platforms,
681 budget_overrides=budget_overrides,
682 )
684 if output_json:
685 click.echo(deployment_plan.model_dump_json(indent=2))
686 return
688 _display_plan(console, deployment_plan)
691def _display_plan(console: Console, plan: DeploymentPlan) -> None:
692 """Display a deployment plan with Rich formatting."""
693 from romfarmer.farmhand.models import SelectionAction
695 console.print(
696 Panel(
697 plan.summary(),
698 title="Deployment Plan",
699 border_style="green",
700 )
701 )
703 # Allocation table
704 table = Table(
705 title="Platform Allocations",
706 show_header=True,
707 header_style="bold cyan",
708 )
709 table.add_column("Platform", style="green")
710 table.add_column("Tier")
711 table.add_column("Action", style="yellow")
712 table.add_column("Full Size", justify="right")
713 table.add_column("Allocated", justify="right")
714 table.add_column("Volume")
715 table.add_column("Strategy")
717 for alloc in sorted(plan.allocations, key=lambda a: a.allocated_bytes, reverse=True):
718 action_style = {
719 SelectionAction.INCLUDE_ALL: "green",
720 SelectionAction.BUDGET_SELECT: "yellow",
721 SelectionAction.SKIP: "red",
722 SelectionAction.CURATED_LIST: "cyan",
723 }.get(alloc.action, "white")
725 table.add_row(
726 alloc.platform,
727 alloc.tier.value,
728 f"[{action_style}]{alloc.action.value}[/{action_style}]",
729 f"{alloc.full_set_gb:.1f} GB" if alloc.full_set_bytes > 0 else "-",
730 f"{alloc.allocated_gb:.1f} GB" if alloc.allocated_bytes > 0 else "-",
731 alloc.target_volume or "-",
732 alloc.selection_strategy or "-",
733 )
735 console.print(table)
737 # Volume summary
738 if plan.volume_allocations:
739 vol_table = Table(title="Volume Usage", show_header=True, header_style="bold cyan")
740 vol_table.add_column("Volume", style="green")
741 vol_table.add_column("Allocated", justify="right")
742 for mount, allocated in plan.volume_allocations.items():
743 vol_table.add_row(mount, f"{allocated / 1024**3:.1f} GB")
744 console.print(vol_table)
746 # Notes
747 if plan.notes:
748 console.print("\n[bold]Notes:[/bold]")
749 for note in plan.notes:
750 console.print(f" {note}")
752 if plan.builds_needed:
753 console.print(f"\n[bold yellow]Builds needed:[/bold yellow] {len(plan.builds_needed)}")
754 for b in plan.builds_needed:
755 console.print(f" • {b}")
758# ── Deploy ───────────────────────────────────────────────────────────────────
761@farmhand_group.command()
762@click.option("--target", "-t", required=True, help="Target profile name")
763@click.option("--build", "-b", default=None, help="Build name (output dir under output/)")
764@click.option("--dry-run", is_flag=True, help="Show what would be transferred without doing it")
765@click.option("--no-delta", is_flag=True, help="Disable delta sync (transfer everything)")
766@click.option("--restart-es", is_flag=True, help="Restart EmulationStation after deploy")
767def deploy(
768 target: str,
769 build: str | None,
770 dry_run: bool,
771 no_delta: bool,
772 restart_es: bool,
773) -> None:
774 """Deploy ROMs to a remote target according to the deployment plan.
776 Example:
777 romfarmer farmhand deploy --target batocera-nuc --build nointro-1g1r-eng-7z-batocera-v2 --dry-run
778 """
779 _check_paramiko()
780 console = Console()
782 profile = _load_profile(target)
783 if not profile:
784 console.print(f"[red]Target profile '{target}' not found[/red]")
785 raise click.Abort()
787 if not build:
788 console.print("[red]--build is required (name of build output directory)[/red]")
789 raise click.Abort()
791 from romfarmer.core.paths import get_paths
792 from romfarmer.farmhand.deployer import Deployer
793 from romfarmer.farmhand.planner import SpacePlanner
794 from romfarmer.farmhand.ssh import SSHClient
796 output_root = get_paths().workspace_root / "output" / build
797 if not output_root.exists():
798 console.print(f"[red]Build output not found: {output_root}[/red]")
799 raise click.Abort()
801 # Create a basic plan from size data
802 planner = SpacePlanner()
803 plan = planner.create_plan(target=profile)
805 # Connect and deploy
806 password = click.prompt(f"SSH password for {profile.user}@{profile.host}", hide_input=True)
807 client = SSHClient(profile.host, port=profile.port, user=profile.user, password=password)
808 client.connect()
810 def on_event(event: str, data: dict) -> None:
811 if event == "platform_done":
812 console.print(
813 f" [green]✓[/green] {data['platform']}: "
814 f"{data['files']} files, {data['bytes'] / 1024**3:.1f} GB"
815 )
816 elif event == "file_done" and data.get("progress", 0) % 10 < 1:
817 console.print(f" {data['file']} ({data['progress']:.0f}%)", style="dim")
819 deployer = Deployer(ssh=client, output_root=output_root, on_event=on_event)
821 try:
822 if dry_run:
823 console.print("[yellow]DRY RUN — no files will be transferred[/yellow]\n")
825 result = deployer.deploy(plan, dry_run=dry_run, delta_sync=not no_delta)
827 console.print(
828 Panel(
829 "\n".join(result.notes[-3:]),
830 title=f"Deployment {result.status.value}",
831 border_style="green" if result.status.value == "completed" else "red",
832 )
833 )
835 if restart_es and not dry_run:
836 with console.status("Restarting EmulationStation..."):
837 deployer.restart_emulationstation()
838 console.print("[green]EmulationStation restarted[/green]")
839 finally:
840 client.close()
843# ── Status ───────────────────────────────────────────────────────────────────
846@farmhand_group.command()
847@click.option("--target", "-t", required=True, help="Target profile name")
848def status(target: str) -> None:
849 """Show current state of a target — what's deployed and available space."""
850 console = Console()
851 profile = _load_profile(target)
852 if not profile:
853 console.print(f"[red]Target profile '{target}' not found[/red]")
854 raise click.Abort()
856 _display_scan_results(console, profile)
859# ── Estimate ─────────────────────────────────────────────────────────────────
862@farmhand_group.command()
863@click.argument("available_gb", type=float)
864def estimate(available_gb: float) -> None:
865 """Quick estimate: what platforms fit in N gigabytes?
867 Example:
868 romfarmer farmhand estimate 1100
869 """
870 console = Console()
872 from romfarmer.farmhand.planner import SpacePlanner
874 planner = SpacePlanner()
875 result = planner.estimate_platforms_count(available_gb)
877 console.print(
878 Panel(
879 f"Available: {result['available_gb']} GB\n"
880 f"Guaranteed (tiny+small+medium): {result['guaranteed_gb']} GB, "
881 f"{result['guaranteed_platforms']} platforms\n"
882 f"Need budget: {result['budget_platforms']} platforms\n"
883 f"Skip: {result['skip_platforms']} platforms",
884 title="Space Estimate",
885 )
886 )
888 if result["include_all"]:
889 table = Table(title="Include All", show_header=True, header_style="bold green")
890 table.add_column("Platform")
891 table.add_column("Size", justify="right")
892 table.add_column("Files", justify="right")
893 table.add_column("Tier")
894 for p in result["include_all"]:
895 table.add_row(p["platform"], f"{p['size_gb']} GB", str(p["files"]), p["tier"])
896 console.print(table)
898 if result["budget_needed"]:
899 table = Table(title="Budget Needed", show_header=True, header_style="bold yellow")
900 table.add_column("Platform")
901 table.add_column("Full Size", justify="right")
902 table.add_column("Suggested Budget", justify="right")
903 table.add_column("Tier")
904 for p in result["budget_needed"]:
905 table.add_row(
906 p["platform"],
907 f"{p['full_size_gb']} GB",
908 f"{p['suggested_budget_gb']} GB",
909 p["tier"],
910 )
911 console.print(table)
913 if result["skip"]:
914 table = Table(title="Skip (No Budget)", show_header=True, header_style="bold red")
915 table.add_column("Platform")
916 table.add_column("Full Size", justify="right")
917 for p in result["skip"]:
918 table.add_row(p["platform"], f"{p['full_size_gb']} GB")
919 console.print(table)
922# ── Optimize ─────────────────────────────────────────────────────────────────
925@farmhand_group.command()
926@click.argument("build_name")
927@click.option(
928 "--volume-gb",
929 required=True,
930 type=float,
931 help="Total volume capacity in GB (e.g. 1900 for a 1.9 TB card).",
932)
933@click.option(
934 "--headroom-gb",
935 default=30.0,
936 show_default=True,
937 type=float,
938 help="Desired free space left after the build (GB).",
939)
940@click.option(
941 "--tolerance-gb",
942 default=5.0,
943 show_default=True,
944 type=float,
945 help="Acceptable deviation from --headroom-gb on either side (GB).",
946)
947@click.option(
948 "--max-iter",
949 default=8,
950 show_default=True,
951 type=int,
952 help="Maximum critic-adjust iterations before giving up.",
953)
954@click.option(
955 "--collect-pool/--no-collect-pool",
956 default=False,
957 help="Re-collect pool manifests from the superset build output before optimizing.",
958)
959@click.option(
960 "--dry-run",
961 is_flag=True,
962 help="Run the optimizer loop against the pool (in-memory only). "
963 "Does not produce a final staged build.",
964)
965@click.option(
966 "--pool-root",
967 default=None,
968 type=click.Path(exists=True, file_okay=False),
969 help="Path to a directory containing .pool/*.json manifests. Overrides the "
970 "default output/BUILD_NAME/.pool/ location. Useful when combining pools "
971 "from multiple builds.",
972)
973def optimize(
974 build_name: str,
975 volume_gb: float,
976 headroom_gb: float,
977 tolerance_gb: float,
978 max_iter: int,
979 collect_pool: bool,
980 dry_run: bool,
981 pool_root: str | None,
982) -> None:
983 """Iteratively optimize rating thresholds to fill a storage target.
985 Reads the pool manifest for BUILD_NAME (run 'collect-pool' flag or
986 call collect_pool() after a superset build), then runs a LangGraph
987 evaluator-optimizer loop to find per-generation rating thresholds
988 that fit the build into the target volume with the desired headroom.
990 Requires: pip install 'romfarmer[optimizer]'
992 Example:
993 # After building a superset (min_rating=0.0) output:
994 romfarmer farmhand optimize nointro-1g1r-eng \\
995 --volume-gb 1900 --headroom-gb 30 --collect-pool
996 """
997 from romfarmer.farmhand.optimizer import LEGACY_RETIRE_AFTER, legacy_optimizer_status
999 status = legacy_optimizer_status()
1000 if status == "retired":
1001 click.echo(
1002 f"[retired] 'farmhand optimize' was retired on {LEGACY_RETIRE_AFTER}: the intent loop "
1003 "(romfarmer-intent-mcp: validate_spec + dry_run over a Spec) replaced it. "
1004 "See romfarmer.intent.",
1005 err=True,
1006 )
1007 raise SystemExit(2)
1008 click.echo(
1009 f"[deprecated] 'farmhand optimize' is the legacy in-process loop; it retires on "
1010 f"{LEGACY_RETIRE_AFTER} or when the psx pilot completes, whichever comes first. "
1011 "Use the intent loop (romfarmer-intent-mcp).",
1012 err=True,
1013 )
1014 try:
1015 from romfarmer.farmhand.optimizer import run_optimizer
1016 except ImportError:
1017 click.echo(
1018 "Error: the optimizer extra is required.\n"
1019 "Install with: pip install 'romfarmer[optimizer]'",
1020 err=True,
1021 )
1022 raise click.Abort() from None
1024 console = Console()
1026 target_total = int(volume_gb * 1024**3)
1027 target_free = int(headroom_gb * 1024**3)
1028 tolerance = int(tolerance_gb * 1024**3)
1030 success_low = headroom_gb - tolerance_gb
1031 success_high = headroom_gb + tolerance_gb
1032 console.print(
1033 Panel(
1034 f"[bold]Build:[/bold] {build_name}\n"
1035 f"[bold]Volume:[/bold] {volume_gb:.0f} GB\n"
1036 f"[bold]Target headroom:[/bold] {headroom_gb:.0f} GB ± {tolerance_gb:.0f} GB "
1037 f"(window: {success_low:.0f}–{success_high:.0f} GB free)\n"
1038 f"[bold]Max iterations:[/bold] {max_iter}\n"
1039 f"[bold]Mode:[/bold] {'dry-run (estimate only)' if dry_run else 'full'}",
1040 title="ROM Farmer Budget Optimizer",
1041 )
1042 )
1044 try:
1045 from pathlib import Path
1047 result = run_optimizer(
1048 build_name=build_name,
1049 target_total_bytes=target_total,
1050 target_free_bytes=target_free,
1051 tolerance_bytes=tolerance,
1052 max_iterations=max_iter,
1053 collect_pool_first=collect_pool,
1054 pool_root=Path(pool_root) if pool_root else None,
1055 )
1056 except FileNotFoundError as exc:
1057 console.print(f"[red]{exc}[/red]")
1058 console.print(
1059 "\n[yellow]Hint:[/yellow] Run with [bold]--collect-pool[/bold] to generate "
1060 "pool manifests from an existing superset build output, or run the build with "
1061 "min_rating=0.0 first."
1062 )
1063 raise click.Abort() from exc
1065 # ── Result table ─────────────────────────────────────────────────────────
1066 verdict_color = {"converged": "green", "exhausted": "yellow", "infeasible": "red"}.get(
1067 result.verdict, "white"
1068 )
1069 console.print(
1070 f"\n[bold {verdict_color}]Verdict: {result.verdict.upper()}[/bold {verdict_color}]"
1071 f" ({result.iterations_used} iterations)"
1072 )
1074 if result.final_report:
1075 r = result.final_report
1076 used_gb = r.total_size_bytes / 1024**3
1077 free_gb = (target_total - r.total_size_bytes) / 1024**3
1078 console.print(
1079 f"Used: [cyan]{used_gb:.1f} GB[/cyan] "
1080 f"Free: [green]{free_gb:.1f} GB[/green] "
1081 f"Games: {r.total_game_count}"
1082 )
1084 # Thresholds table
1085 if result.final_thresholds:
1086 t_table = Table(title="Final Thresholds", show_header=True)
1087 t_table.add_column("Generation", style="cyan")
1088 t_table.add_column("Threshold", style="bold")
1089 for gen, val in sorted(result.final_thresholds.items()):
1090 color = "green" if val == 0.0 else ("yellow" if val < 0.9 else "red")
1091 t_table.add_row(gen, f"[{color}]{val:.2f}[/{color}]")
1092 console.print(t_table)
1094 # History table
1095 if result.history:
1096 h_table = Table(title="Iteration History", show_lines=False)
1097 h_table.add_column("#", style="dim", width=4)
1098 h_table.add_column("Action", min_width=30)
1099 h_table.add_column("Used GB", justify="right")
1100 h_table.add_column("Free GB", justify="right")
1101 h_table.add_column("Delta GB", justify="right")
1102 h_table.add_column("Spike")
1103 for log in result.history:
1104 delta_gb = log.delta_bytes / 1024**3
1105 delta_str = f"{delta_gb:+.1f}"
1106 delta_color = "red" if delta_gb > 0 else "green"
1107 h_table.add_row(
1108 str(log.iteration),
1109 log.action[:40],
1110 f"{log.used_bytes / 1024**3:.1f}",
1111 f"{log.free_bytes / 1024**3:.1f}",
1112 f"[{delta_color}]{delta_str}[/{delta_color}]",
1113 "⚡" if log.is_spike else "",
1114 )
1115 console.print(h_table)
1117 if result.verdict == "converged" and not dry_run:
1118 console.print(
1119 "\n[bold green]✓ Optimization complete.[/bold green] "
1120 "Pass the final thresholds to your build config and run:\n"
1121 f" [dim]romfarmer build run --name {build_name}[/dim]"
1122 )
1123 elif result.verdict != "converged":
1124 console.print(
1125 "\n[yellow]Optimizer did not converge.[/yellow] "
1126 "Check the audit log at "
1127 f"[dim]output/{build_name}/optimizer.log.json[/dim] for details."
1128 )
1131@farmhand_group.command(name="collect-pool")
1132@click.argument("build_name")
1133@click.option(
1134 "--output-base",
1135 default="output",
1136 type=click.Path(),
1137 help="Base output directory containing the superset build.",
1138)
1139def collect_pool_cmd(build_name: str, output_base: str) -> None:
1140 """Collect pool manifests from an existing superset build output.
1142 Walks output/BUILD_NAME/{platform}/ directories, groups files by game,
1143 looks up ratings from romfarmer.db, and writes per-platform JSON manifests
1144 to output/BUILD_NAME/.pool/
1146 Run this once after a permissive (min_rating=0.0) build, then call
1147 'optimize' for fast in-memory iteration.
1149 Example:
1150 romfarmer farmhand collect-pool nointro-1g1r-eng
1151 """
1152 from romfarmer.farmhand.optimizer import collect_pool
1154 console = Console()
1155 console.print(f"Collecting pool manifests for [bold]{build_name}[/bold] …")
1157 try:
1158 pool_root = collect_pool(
1159 build_name=build_name,
1160 output_base=Path(output_base),
1161 )
1162 console.print(f"[green]Done.[/green] Pool manifests written to [dim]{pool_root}[/dim]")
1163 except FileNotFoundError as exc:
1164 console.print(f"[red]{exc}[/red]")
1165 raise click.Abort() from exc
1168# ── Merge-pools ───────────────────────────────────────────────────────────────
1171@farmhand_group.command(name="merge-pools")
1172@click.argument("build_names", nargs=-1, required=True)
1173@click.option(
1174 "--output",
1175 "-o",
1176 required=True,
1177 type=click.Path(file_okay=False),
1178 help="Destination directory for the merged pool manifests.",
1179)
1180@click.option(
1181 "--output-base",
1182 default="output",
1183 type=click.Path(),
1184 help="Base directory containing per-build output folders. Default: output/",
1185)
1186@click.option(
1187 "--no-overwrite",
1188 is_flag=True,
1189 default=False,
1190 help="Keep existing manifests in --output; only add new platforms.",
1191)
1192def merge_pools_cmd(
1193 build_names: tuple[str, ...],
1194 output: str,
1195 output_base: str,
1196 no_overwrite: bool,
1197) -> None:
1198 """Merge pool manifests from multiple builds into a single directory.
1200 Use this when you want the optimizer to reason across several builds at
1201 once (e.g., nointro cartridge + redump disc + nintendo-disc RVZ).
1203 Run 'collect-pool' for each source build first, then merge, then pass
1204 the merged directory to 'optimize --pool-root'.
1206 Example:
1207 romfarmer farmhand collect-pool nointro-1g1r-eng-7z-batocera-v2
1208 romfarmer farmhand collect-pool redump-1g1r-eng-chd-batocera-v2
1209 romfarmer farmhand merge-pools \\
1210 nointro-1g1r-eng-7z-batocera-v2 \\
1211 redump-1g1r-eng-chd-batocera-v2 \\
1212 --output /tmp/retrobat-pool
1213 romfarmer farmhand optimize retrobat \\
1214 --pool-root /tmp/retrobat-pool --volume-gb 1900 --headroom-gb 50
1215 """
1216 from romfarmer.farmhand.optimizer import merge_pools_from_builds
1218 console = Console()
1219 output_path = Path(output)
1220 names = list(build_names)
1222 console.print(
1223 Panel(
1224 f"Sources: {', '.join(names)}\nOutput: {output_path}\nBase: {output_base}",
1225 title="Merge Pools",
1226 )
1227 )
1229 try:
1230 result = merge_pools_from_builds(
1231 build_names=names,
1232 output=output_path,
1233 output_base=Path(output_base),
1234 overwrite=not no_overwrite,
1235 )
1236 except FileNotFoundError as exc:
1237 console.print(f"[red]{exc}[/red]")
1238 raise click.Abort() from exc
1240 table = Table(title="Source Breakdown", show_header=True, header_style="bold cyan")
1241 table.add_column("Build (Source)", style="green")
1242 table.add_column("Platforms", justify="right")
1243 for build_name, platforms in result.source_breakdown.items():
1244 table.add_row(build_name, str(len(platforms)))
1245 console.print(table)
1247 if result.conflicts_resolved:
1248 console.print(
1249 f"[yellow]{result.conflicts_resolved} platform conflict(s) resolved "
1250 "(entries merged, first-seen wins)[/yellow]"
1251 )
1253 console.print(
1254 f"\n[green]✓[/green] {result.platforms_merged} platforms, "
1255 f"{result.games_total} games → [dim]{output_path}[/dim]"
1256 )
1257 console.print(
1258 f"\nNext:\n"
1259 f" [dim]romfarmer farmhand optimize <name> "
1260 f"--pool-root {output_path} --volume-gb <N> --headroom-gb <N>[/dim]"
1261 )
1264# ── Apply-thresholds ──────────────────────────────────────────────────────────
1267@farmhand_group.command(name="apply-thresholds")
1268@click.argument("build_names", nargs=-1, required=True)
1269@click.option(
1270 "--from-log",
1271 "log_path",
1272 type=click.Path(exists=True, dir_okay=False),
1273 default=None,
1274 help="Read thresholds from an optimizer.log.json file.",
1275)
1276@click.option(
1277 "--threshold",
1278 "-t",
1279 multiple=True,
1280 help="Manual threshold: gen=value (e.g., gen6=0.85). Repeatable.",
1281)
1282@click.option(
1283 "--builds-dir",
1284 default=None,
1285 type=click.Path(exists=True, file_okay=False),
1286 help="Directory containing build YAML files. Default: config/builds/",
1287)
1288@click.option("--dry-run", is_flag=True, help="Show changes without writing.")
1289def apply_thresholds_cmd(
1290 build_names: tuple[str, ...],
1291 log_path: str | None,
1292 threshold: tuple[str, ...],
1293 builds_dir: str | None,
1294 dry_run: bool,
1295) -> None:
1296 """Write optimizer thresholds into build config YAML files.
1298 Thresholds are per-generation min_rating values (e.g., gen6=0.85).
1299 They are stored in the 'optimizer_thresholds' field and automatically
1300 applied per-platform when the build runs.
1302 Provide thresholds either from an optimizer log file (--from-log) or
1303 manually (--threshold gen=value).
1305 Examples:
1306 # From the optimizer audit log:
1307 romfarmer farmhand apply-thresholds \\
1308 nointro-1g1r-eng-7z-retrobat redump-1g1r-eng-chd-retrobat \\
1309 --from-log output/retrobat-1.9tb/optimizer.log.json
1311 # Manually:
1312 romfarmer farmhand apply-thresholds redump-1g1r-eng-chd-retrobat \\
1313 --threshold gen6=0.85 --threshold gen7=0.92
1314 """
1315 from romfarmer.farmhand.optimizer import (
1316 apply_thresholds_to_builds,
1317 load_thresholds_from_optimizer_log,
1318 )
1320 console = Console()
1322 # Build threshold dict from --from-log and/or --threshold args
1323 thresholds: dict[str, float] = {}
1325 if log_path:
1326 try:
1327 thresholds.update(load_thresholds_from_optimizer_log(Path(log_path)))
1328 console.print(f"[dim]Loaded thresholds from {log_path}[/dim]")
1329 except (FileNotFoundError, KeyError) as exc:
1330 console.print(f"[red]{exc}[/red]")
1331 raise click.Abort() from exc
1333 for t in threshold:
1334 if "=" not in t:
1335 console.print(f"[red]Invalid --threshold '{t}' — expected gen=value[/red]")
1336 raise click.Abort()
1337 gen, val = t.split("=", 1)
1338 try:
1339 thresholds[gen.strip()] = float(val.strip())
1340 except ValueError:
1341 console.print(f"[red]Invalid threshold value: {val!r}[/red]")
1342 raise click.Abort() from None
1344 if not thresholds:
1345 console.print("[red]No thresholds provided. Use --from-log or --threshold.[/red]")
1346 raise click.Abort()
1348 if dry_run:
1349 console.print("[yellow]DRY RUN — no files will be written[/yellow]")
1351 results = apply_thresholds_to_builds(
1352 build_names=list(build_names),
1353 thresholds=thresholds,
1354 builds_dir=Path(builds_dir) if builds_dir else None,
1355 dry_run=dry_run,
1356 )
1358 table = Table(title="Apply Results", show_header=True, header_style="bold cyan")
1359 table.add_column("Build", style="green")
1360 table.add_column("Changed")
1361 table.add_column("Previous", style="dim")
1362 table.add_column("New Thresholds")
1364 for r in results:
1365 prev_str = (
1366 ", ".join(f"{k}={v}" for k, v in sorted(r.previous_thresholds.items()))
1367 if r.previous_thresholds
1368 else "none"
1369 )
1370 new_str = ", ".join(f"{k}={v}" for k, v in sorted(r.thresholds_written.items()))
1371 changed_str = "[green]yes[/green]" if r.changed else "[dim]no[/dim]"
1372 table.add_row(r.build_name, changed_str, prev_str, new_str)
1374 console.print(table)
1376 if not dry_run:
1377 changed = sum(1 for r in results if r.changed)
1378 console.print(f"\n[green]✓[/green] Updated {changed}/{len(results)} build configs.")
1379 if changed:
1380 console.print(
1381 "\nNext: run each build to apply the thresholds:\n"
1382 + "\n".join(
1383 f" [dim]romfarmer build run --name {r.build_name}[/dim]"
1384 for r in results
1385 if r.changed
1386 )
1387 )
1390# ── Build-fill ────────────────────────────────────────────────────────────────
1393@farmhand_group.command(name="build-fill")
1394@click.option(
1395 "--volume-gb",
1396 required=True,
1397 type=float,
1398 help="Total target volume capacity in GB (e.g. 1900).",
1399)
1400@click.option(
1401 "--headroom-gb",
1402 default=50.0,
1403 show_default=True,
1404 type=float,
1405 help="Desired free space after the build (GB).",
1406)
1407@click.option(
1408 "--tolerance-gb",
1409 default=10.0,
1410 show_default=True,
1411 type=float,
1412 help="Acceptable deviation from --headroom-gb on either side.",
1413)
1414@click.option(
1415 "--pool-from",
1416 "pool_from",
1417 multiple=True,
1418 help=(
1419 "Build name to collect pool data from. "
1420 "Repeatable. These are typically broad 'batocera' proxy builds "
1421 "whose output already exists."
1422 ),
1423)
1424@click.option(
1425 "--apply-to",
1426 "apply_to",
1427 multiple=True,
1428 help=(
1429 "Build name to apply thresholds to and run. "
1430 "Repeatable. These are the actual target builds (e.g., retrobat variants)."
1431 ),
1432)
1433@click.option(
1434 "--collect-pools/--no-collect-pools",
1435 default=True,
1436 show_default=True,
1437 help="(Re-)collect pool manifests from each --pool-from build's output.",
1438)
1439@click.option(
1440 "--max-iter",
1441 default=8,
1442 show_default=True,
1443 type=int,
1444 help="Max optimizer iterations.",
1445)
1446@click.option(
1447 "--dry-run",
1448 is_flag=True,
1449 help="Run optimizer and show plan; skip writing build configs and running builds.",
1450)
1451@click.option(
1452 "--run-builds/--no-run-builds",
1453 default=False,
1454 show_default=True,
1455 help="After applying thresholds, run each build automatically.",
1456)
1457@click.option(
1458 "--output-base",
1459 default="output",
1460 type=click.Path(),
1461 help="Base directory for build outputs. Default: output/",
1462)
1463def build_fill(
1464 volume_gb: float,
1465 headroom_gb: float,
1466 tolerance_gb: float,
1467 pool_from: tuple[str, ...],
1468 apply_to: tuple[str, ...],
1469 collect_pools: bool,
1470 max_iter: int,
1471 dry_run: bool,
1472 run_builds: bool,
1473 output_base: str,
1474) -> None:
1475 """End-to-end: optimize rating thresholds for a storage target, apply to
1476 builds, and optionally run them.
1478 This is the full "fill a 1.9TB drive" pipeline in one command:
1480 1. Collect pool manifests from existing superset build outputs
1481 (--pool-from builds)
1482 2. Merge the pools into a combined manifest
1483 3. Run the LangGraph optimizer loop to find per-generation thresholds
1484 4. Apply thresholds to target build configs (--apply-to builds)
1485 5. Optionally run each build (--run-builds)
1487 Example:
1489 romfarmer farmhand build-fill \\
1490 --volume-gb 1900 --headroom-gb 50 \\
1491 --pool-from nointro-1g1r-eng-7z-batocera-v2 \\
1492 --pool-from redump-1g1r-eng-chd-batocera-v2 \\
1493 --apply-to nointro-1g1r-eng-7z-retrobat \\
1494 --apply-to redump-1g1r-eng-chd-retrobat \\
1495 --run-builds
1496 """
1497 try:
1498 from romfarmer.farmhand.optimizer import (
1499 apply_thresholds_to_builds,
1500 collect_pool,
1501 merge_pools_from_builds,
1502 run_optimizer,
1503 )
1504 except ImportError:
1505 click.echo(
1506 "Error: the optimizer extra is required.\n"
1507 "Install with: pip install 'romfarmer[optimizer]'",
1508 err=True,
1509 )
1510 raise click.Abort() from None
1512 from romfarmer.core.paths import get_paths
1514 console = Console()
1515 workspace = get_paths().workspace_root
1516 output_base_path = Path(output_base)
1518 if not pool_from or not apply_to:
1519 console.print(
1520 "[red]--pool-from and --apply-to are both required.[/red]\n"
1521 "Use --pool-from to name builds whose output to read for pool data,\n"
1522 "and --apply-to to name builds that will receive the thresholds."
1523 )
1524 raise click.Abort()
1526 console.print(
1527 Panel(
1528 f"[bold]Volume:[/bold] {volume_gb:.0f} GB\n"
1529 f"[bold]Target headroom:[/bold] {headroom_gb:.0f} GB ± {tolerance_gb:.0f} GB\n"
1530 f"[bold]Pool sources:[/bold] {', '.join(pool_from)}\n"
1531 f"[bold]Apply to:[/bold] {', '.join(apply_to)}\n"
1532 f"[bold]Mode:[/bold] {'dry-run' if dry_run else 'full'}"
1533 + (" + run builds" if run_builds and not dry_run else ""),
1534 title="ROM Farmer Build-Fill",
1535 )
1536 )
1538 # ── Step 1: Collect pools ─────────────────────────────────────────────
1539 if collect_pools:
1540 console.print("\n[bold cyan]Step 1:[/bold cyan] Collecting pool manifests…")
1541 for build_name in pool_from:
1542 build_output = output_base_path / build_name
1543 if not build_output.exists():
1544 console.print(
1545 f" [yellow]No output for '{build_name}' at {build_output} — skipping.[/yellow]"
1546 )
1547 continue
1548 with console.status(f" Collecting pool for {build_name}…"):
1549 collect_pool(
1550 build_name=build_name,
1551 output_base=output_base_path,
1552 workspace_root=workspace,
1553 )
1554 console.print(f" [green]✓[/green] {build_name}")
1555 else:
1556 console.print("\n[dim]Step 1: Pool collection skipped (--no-collect-pools)[/dim]")
1558 # ── Step 2: Merge pools ───────────────────────────────────────────────
1559 console.print("\n[bold cyan]Step 2:[/bold cyan] Merging pool manifests…")
1560 merged_pool_dir = workspace / "output" / ".build-fill-pool"
1561 try:
1562 merge_result = merge_pools_from_builds(
1563 build_names=list(pool_from),
1564 output=merged_pool_dir,
1565 output_base=output_base_path,
1566 )
1567 except FileNotFoundError as exc:
1568 console.print(f" [red]{exc}[/red]")
1569 raise click.Abort() from exc
1571 console.print(
1572 f" [green]✓[/green] {merge_result.platforms_merged} platforms, "
1573 f"{merge_result.games_total} games merged"
1574 )
1576 # ── Step 3: Optimize ─────────────────────────────────────────────────
1577 console.print("\n[bold cyan]Step 3:[/bold cyan] Running optimizer loop…")
1578 try:
1579 opt_result = run_optimizer(
1580 build_name="build-fill",
1581 target_total_bytes=int(volume_gb * 1024**3),
1582 target_free_bytes=int(headroom_gb * 1024**3),
1583 tolerance_bytes=int(tolerance_gb * 1024**3),
1584 max_iterations=max_iter,
1585 pool_root=merged_pool_dir,
1586 )
1587 except FileNotFoundError as exc:
1588 console.print(f" [red]{exc}[/red]")
1589 raise click.Abort() from exc
1591 verdict_color = {"converged": "green", "exhausted": "yellow", "infeasible": "red"}.get(
1592 opt_result.verdict, "white"
1593 )
1594 console.print(
1595 f" [{verdict_color}]{opt_result.verdict.upper()}[/{verdict_color}] "
1596 f"({opt_result.iterations_used} iterations)"
1597 )
1599 if opt_result.final_report:
1600 r = opt_result.final_report
1601 total_bytes = int(volume_gb * 1024**3)
1602 used_gb = r.total_size_bytes / 1024**3
1603 free_gb = (total_bytes - r.total_size_bytes) / 1024**3
1604 console.print(
1605 f" Used: [cyan]{used_gb:.1f} GB[/cyan] "
1606 f"Free: [green]{free_gb:.1f} GB[/green] "
1607 f"Games: {r.total_game_count}"
1608 )
1610 if opt_result.final_thresholds:
1611 t_table = Table(title="Converged Thresholds", show_header=True, box=None)
1612 t_table.add_column("Generation", style="cyan")
1613 t_table.add_column("min_rating", style="bold")
1614 for gen, val in sorted(opt_result.final_thresholds.items()):
1615 if val > 0.0:
1616 color = "yellow" if val < 0.9 else "red"
1617 t_table.add_row(gen, f"[{color}]{val:.2f}[/{color}]")
1618 else:
1619 t_table.add_row(gen, "[green]0.00 (include all)[/green]")
1620 console.print(t_table)
1622 if opt_result.verdict == "infeasible":
1623 console.print(
1624 "\n[red]Optimizer could not find a feasible solution.[/red] "
1625 "Try increasing --volume-gb or relaxing --headroom-gb."
1626 )
1627 raise click.Abort()
1629 # ── Step 4: Apply thresholds ──────────────────────────────────────────
1630 console.print(
1631 f"\n[bold cyan]Step 4:[/bold cyan] Applying thresholds to {len(apply_to)} build config(s)…"
1632 )
1633 apply_results = apply_thresholds_to_builds(
1634 build_names=list(apply_to),
1635 thresholds=opt_result.final_thresholds,
1636 dry_run=dry_run,
1637 )
1639 for r in apply_results:
1640 status = (
1641 "[yellow](dry-run)[/yellow]"
1642 if dry_run
1643 else ("[green]updated[/green]" if r.changed else "[dim]no change[/dim]")
1644 )
1645 console.print(f" {r.build_name}: {status}")
1647 # ── Step 5: Run builds ────────────────────────────────────────────────
1648 if run_builds and not dry_run:
1649 console.print("\n[bold cyan]Step 5:[/bold cyan] Running builds…")
1650 import subprocess
1651 import sys
1653 for build_name in apply_to:
1654 console.print(f"\n [bold]{build_name}[/bold]")
1655 ret = subprocess.call(
1656 [sys.executable, "-m", "romfarmer", "build", "run", "--name", build_name]
1657 )
1658 if ret != 0:
1659 console.print(f" [red]Build '{build_name}' exited with code {ret}[/red]")
1660 console.print(" Continuing with remaining builds…")
1661 else:
1662 console.print(f" [green]✓[/green] {build_name} complete")
1663 elif run_builds and dry_run:
1664 console.print("\n[dim]Step 5: Build run skipped (dry-run)[/dim]")
1665 else:
1666 console.print(
1667 "\n[dim]Builds not run automatically. Use --run-builds or run manually:[/dim]"
1668 )
1669 for name in apply_to:
1670 console.print(f" [dim]romfarmer build run --name {name}[/dim]")
1672 console.print(
1673 f"\n[bold {'green' if opt_result.verdict == 'converged' else 'yellow'}]"
1674 f"Build-fill complete.[/bold {'green' if opt_result.verdict == 'converged' else 'yellow'}]"
1675 )
1678# ── Helpers ──────────────────────────────────────────────────────────────────
1681def _resolve_target(
1682 host_or_target: str,
1683 *,
1684 port: int = 22,
1685 user: str = "root",
1686 password: str | None = None,
1687 key_file: str | None = None,
1688 name: str | None = None,
1689 frontend: str = "batocera",
1690) -> tuple[dict, str | None, str]:
1691 """Resolve a host-or-target-name into SSH kwargs + target name + frontend.
1693 If host_or_target looks like an IP/hostname, use CLI args directly.
1694 Otherwise, try to load it as a target config name.
1696 Returns:
1697 (ssh_kwargs, target_name, frontend)
1698 """
1699 from romfarmer.core.paths import get_paths
1700 from romfarmer.farmhand.config import (
1701 list_targets,
1702 load_target_config,
1703 target_config_to_ssh_kwargs,
1704 )
1706 workspace = get_paths().workspace_root
1708 # Check if it's a target config name first
1709 available = list_targets(workspace)
1710 if host_or_target in available:
1711 config = load_target_config(workspace, host_or_target)
1712 ssh_kwargs = target_config_to_ssh_kwargs(config)
1713 target_name = name or config.get("name", host_or_target)
1714 resolved_frontend = config.get("frontend", frontend)
1715 return ssh_kwargs, target_name, resolved_frontend
1717 # It's a direct host — use CLI args
1718 ssh_kwargs = {
1719 "host": host_or_target,
1720 "port": port,
1721 "user": user,
1722 }
1723 if password:
1724 ssh_kwargs["password"] = password
1725 if key_file:
1726 ssh_kwargs["key_file"] = key_file
1727 return ssh_kwargs, name, frontend
1730def _load_profile(name: str) -> TargetProfile | None:
1731 """Load a saved target profile by name."""
1732 from romfarmer.core.paths import get_paths
1733 from romfarmer.farmhand.config import load_profile
1735 return load_profile(get_paths().workspace_root, name)