Coverage for src/romfarmer/farmhand/planner.py: 0%

159 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-01 23:08 -0700

1"""Space optimization planner for Farm-Hand. 

2 

3Given a target profile (with volume info) and rom-farmer's platform size data, 

4produces a DeploymentPlan that maximizes game coverage within available storage. 

5 

6The planner implements a greedy bin-packing strategy: 

71. Classify every platform by output size tier (tiny → massive) 

82. Always include tiny/small platforms (they cost almost nothing) 

93. Include medium platforms if space allows 

104. For large/massive platforms, propose rating_budget selections sized to fit 

115. Spread platforms across volumes intelligently 

12""" 

13 

14from __future__ import annotations 

15 

16import json 

17import logging 

18from pathlib import Path 

19from typing import Any 

20 

21from romfarmer.farmhand.models import ( 

22 DeploymentPlan, 

23 DeploymentStatus, 

24 PlatformAllocation, 

25 PlatformSizeInfo, 

26 PlatformTier, 

27 SelectionAction, 

28 TargetProfile, 

29 VolumeInfo, 

30 VolumeRole, 

31) 

32 

33logger = logging.getLogger(__name__) 

34 

35# Tier thresholds in bytes 

36TIER_THRESHOLDS = { 

37 PlatformTier.TINY: 1 * 1024**3, # < 1 GB 

38 PlatformTier.SMALL: 10 * 1024**3, # 1–10 GB 

39 PlatformTier.MEDIUM: 100 * 1024**3, # 10–100 GB 

40 PlatformTier.LARGE: 500 * 1024**3, # 100–500 GB 

41 # anything above is MASSIVE 

42} 

43 

44# Default budget allocations for large platforms (as percentage of remaining space) 

45# These are starting points — the AI agent can override any of them 

46DEFAULT_LARGE_BUDGET_GB = { 

47 "ps2": 80, # Top ~200 games 

48 "psx": 60, # Top ~300 games 

49 "psp": 40, # Top ~150 games 

50 "xbox": 40, # Top ~100 games 

51 "xbox360": 0, # Skip by default (5.87 TB full set) 

52 "3ds": 40, # Top ~200 games 

53 "dreamcast": 60, # Top ~400 games 

54 "pcenginecd": 30, # Top ~200 games 

55} 

56 

57# Default space reservation for saves, BIOS, metadata, screenshots, etc. 

58DEFAULT_RESERVED_GB = 30 

59 

60 

61def classify_tier(size_bytes: int) -> PlatformTier: 

62 """Classify a platform into a size tier based on its full output size.""" 

63 if size_bytes < TIER_THRESHOLDS[PlatformTier.TINY]: 

64 return PlatformTier.TINY 

65 elif size_bytes < TIER_THRESHOLDS[PlatformTier.SMALL]: 

66 return PlatformTier.SMALL 

67 elif size_bytes < TIER_THRESHOLDS[PlatformTier.MEDIUM]: 

68 return PlatformTier.MEDIUM 

69 elif size_bytes < TIER_THRESHOLDS[PlatformTier.LARGE]: 

70 return PlatformTier.LARGE 

71 else: 

72 return PlatformTier.MASSIVE 

73 

74 

75class SpacePlanner: 

76 """Plans optimal ROM deployment for a target device. 

77 

78 Usage: 

79 planner = SpacePlanner(size_data_path="config/size_data.json") 

80 plan = planner.create_plan( 

81 target=target_profile, 

82 reserved_gb=30, 

83 exclude_platforms=["xbox360"], 

84 ) 

85 """ 

86 

87 def __init__( 

88 self, 

89 size_data_path: str | Path | None = None, 

90 workspace_root: Path | None = None, 

91 ) -> None: 

92 if workspace_root is None: 

93 from romfarmer.core.paths import get_paths 

94 

95 workspace_root = get_paths().workspace_root 

96 self.workspace_root = workspace_root 

97 

98 if size_data_path is None: 

99 size_data_path = self.workspace_root / "config" / "size_data.json" 

100 

101 self.size_data = self._load_size_data(Path(size_data_path)) 

102 

103 # ------------------------------------------------------------------ 

104 # Size data loading 

105 # ------------------------------------------------------------------ 

106 

107 def _load_size_data(self, path: Path) -> dict[str, PlatformSizeInfo]: 

108 """Load platform size data from rom-farmer's size_data.json.""" 

109 if not path.exists(): 

110 logger.warning("Size data not found at %s", path) 

111 return {} 

112 

113 with open(path) as f: 

114 raw = json.load(f) 

115 

116 platforms: dict[str, PlatformSizeInfo] = {} 

117 for platform_name, entries in raw.items(): 

118 if not entries: 

119 continue 

120 # Use the latest entry (last in the list) 

121 latest = entries[-1] 

122 size_bytes = latest.get("output_size_bytes", 0) 

123 platforms[platform_name] = PlatformSizeInfo( 

124 platform=platform_name, 

125 compression=latest.get("compression", ""), 

126 full_set_bytes=size_bytes, 

127 full_set_files=latest.get("output_files", 0), 

128 tier=classify_tier(size_bytes), 

129 ) 

130 

131 logger.info("Loaded size data for %d platforms", len(platforms)) 

132 return platforms 

133 

134 def get_platform_sizes(self) -> dict[str, PlatformSizeInfo]: 

135 """Return the loaded platform size data.""" 

136 return dict(self.size_data) 

137 

138 # ------------------------------------------------------------------ 

139 # Plan creation 

140 # ------------------------------------------------------------------ 

141 

142 def create_plan( 

143 self, 

144 target: TargetProfile, 

145 reserved_gb: float = DEFAULT_RESERVED_GB, 

146 exclude_platforms: list[str] | None = None, 

147 include_only: list[str] | None = None, 

148 budget_overrides: dict[str, float] | None = None, 

149 prefer_primary_for: list[str] | None = None, 

150 ) -> DeploymentPlan: 

151 """Create a deployment plan for the target. 

152 

153 Args: 

154 target: Scanned target profile with volume info. 

155 reserved_gb: Space to reserve for saves/BIOS/metadata per volume. 

156 exclude_platforms: Platforms to skip entirely. 

157 include_only: If set, only plan for these platforms. 

158 budget_overrides: Per-platform budget in GB (overrides defaults). 

159 prefer_primary_for: Platforms that should go on the primary volume. 

160 

161 Returns: 

162 A DeploymentPlan with per-platform allocations. 

163 """ 

164 exclude_platforms = set(exclude_platforms or []) 

165 budget_overrides = budget_overrides or {} 

166 prefer_primary_for = set(prefer_primary_for or []) 

167 

168 reserved_bytes = int(reserved_gb * 1024**3) 

169 

170 # Gather ROM volumes and compute available space 

171 rom_volumes = target.get_rom_volumes() 

172 if not rom_volumes: 

173 logger.error("No ROM volumes found on target") 

174 return DeploymentPlan( 

175 target_name=target.name, 

176 status=DeploymentStatus.FAILED, 

177 notes=["No ROM storage volumes found on target"], 

178 ) 

179 

180 # Compute per-volume available space (minus reservation) 

181 volume_budgets: dict[str, int] = {} 

182 for vol in rom_volumes: 

183 per_vol_reserve = reserved_bytes if vol.role == VolumeRole.PRIMARY else 0 

184 available = max(0, vol.available_bytes - per_vol_reserve) 

185 volume_budgets[vol.mount_point] = available 

186 

187 total_available = sum(volume_budgets.values()) 

188 

189 plan = DeploymentPlan( 

190 target_name=target.name, 

191 status=DeploymentStatus.PLANNING, 

192 reserved_bytes=reserved_bytes, 

193 total_available_bytes=total_available, 

194 ) 

195 

196 # Filter platforms 

197 candidate_platforms = dict(self.size_data) 

198 if include_only: 

199 candidate_platforms = { 

200 k: v for k, v in candidate_platforms.items() if k in include_only 

201 } 

202 for excluded in exclude_platforms: 

203 candidate_platforms.pop(excluded, None) 

204 

205 # Sort by tier (smallest first) so we fill guaranteed platforms first 

206 sorted_platforms = sorted( 

207 candidate_platforms.values(), 

208 key=lambda p: p.full_set_bytes, 

209 ) 

210 

211 # Track remaining space per volume 

212 remaining: dict[str, int] = dict(volume_budgets) 

213 

214 # Phase 1: Always include tiny and small platforms 

215 for pinfo in sorted_platforms: 

216 if pinfo.tier not in (PlatformTier.TINY, PlatformTier.SMALL): 

217 continue 

218 

219 volume = self._pick_volume( 

220 pinfo.platform, pinfo.full_set_bytes, rom_volumes, remaining, prefer_primary_for 

221 ) 

222 if volume is None: 

223 plan.notes.append( 

224 f"WARN: No space for {pinfo.platform} ({pinfo.full_set_bytes / 1024**3:.1f} GB)" 

225 ) 

226 continue 

227 

228 alloc = PlatformAllocation( 

229 platform=pinfo.platform, 

230 tier=pinfo.tier, 

231 action=SelectionAction.INCLUDE_ALL, 

232 full_set_bytes=pinfo.full_set_bytes, 

233 allocated_bytes=pinfo.full_set_bytes, 

234 target_volume=volume.mount_point, 

235 files_total=pinfo.full_set_files, 

236 ) 

237 plan.allocations.append(alloc) 

238 remaining[volume.mount_point] -= pinfo.full_set_bytes 

239 

240 # Phase 2: Include medium platforms if they fit 

241 for pinfo in sorted_platforms: 

242 if pinfo.tier != PlatformTier.MEDIUM: 

243 continue 

244 

245 volume = self._pick_volume( 

246 pinfo.platform, pinfo.full_set_bytes, rom_volumes, remaining, prefer_primary_for 

247 ) 

248 if volume is not None: 

249 alloc = PlatformAllocation( 

250 platform=pinfo.platform, 

251 tier=pinfo.tier, 

252 action=SelectionAction.INCLUDE_ALL, 

253 full_set_bytes=pinfo.full_set_bytes, 

254 allocated_bytes=pinfo.full_set_bytes, 

255 target_volume=volume.mount_point, 

256 files_total=pinfo.full_set_files, 

257 ) 

258 plan.allocations.append(alloc) 

259 remaining[volume.mount_point] -= pinfo.full_set_bytes 

260 else: 

261 # Medium platform doesn't fit in full — try budget 

262 budget_gb = budget_overrides.get( 

263 pinfo.platform, 

264 pinfo.full_set_bytes / (2 * 1024**3), # half as default 

265 ) 

266 budget_bytes = int(budget_gb * 1024**3) 

267 volume = self._pick_volume( 

268 pinfo.platform, budget_bytes, rom_volumes, remaining, prefer_primary_for 

269 ) 

270 if volume: 

271 alloc = PlatformAllocation( 

272 platform=pinfo.platform, 

273 tier=pinfo.tier, 

274 action=SelectionAction.BUDGET_SELECT, 

275 full_set_bytes=pinfo.full_set_bytes, 

276 allocated_bytes=budget_bytes, 

277 target_volume=volume.mount_point, 

278 selection_strategy="rating_budget", 

279 selection_max_gb=budget_gb, 

280 ) 

281 plan.allocations.append(alloc) 

282 remaining[volume.mount_point] -= budget_bytes 

283 plan.builds_needed.append(f"{pinfo.platform}-budget-{budget_gb:.0f}gb") 

284 else: 

285 self._add_skipped(plan, pinfo, "No space even for budget selection") 

286 

287 # Phase 3: Large and massive platforms — always use budget selection 

288 for pinfo in sorted_platforms: 

289 if pinfo.tier not in (PlatformTier.LARGE, PlatformTier.MASSIVE): 

290 continue 

291 

292 # Check if user explicitly budgeted this platform 

293 budget_gb = budget_overrides.get( 

294 pinfo.platform, 

295 DEFAULT_LARGE_BUDGET_GB.get(pinfo.platform, 0), 

296 ) 

297 

298 if budget_gb <= 0: 

299 self._add_skipped(plan, pinfo, "No budget assigned (massive platform)") 

300 continue 

301 

302 budget_bytes = int(budget_gb * 1024**3) 

303 volume = self._pick_volume( 

304 pinfo.platform, budget_bytes, rom_volumes, remaining, prefer_primary_for 

305 ) 

306 

307 if volume: 

308 alloc = PlatformAllocation( 

309 platform=pinfo.platform, 

310 tier=pinfo.tier, 

311 action=SelectionAction.BUDGET_SELECT, 

312 full_set_bytes=pinfo.full_set_bytes, 

313 allocated_bytes=budget_bytes, 

314 target_volume=volume.mount_point, 

315 selection_strategy="rating_budget", 

316 selection_max_gb=budget_gb, 

317 selection_min_rating=0.5, 

318 ) 

319 plan.allocations.append(alloc) 

320 remaining[volume.mount_point] -= budget_bytes 

321 plan.builds_needed.append(f"{pinfo.platform}-budget-{budget_gb:.0f}gb") 

322 else: 

323 self._add_skipped(plan, pinfo, f"No space for {budget_gb:.0f} GB budget") 

324 

325 # Compute summary stats 

326 included = [a for a in plan.allocations if a.action != SelectionAction.SKIP] 

327 skipped = [a for a in plan.allocations if a.action == SelectionAction.SKIP] 

328 plan.platforms_included = len(included) 

329 plan.platforms_skipped = len(skipped) 

330 plan.total_allocated_bytes = sum(a.allocated_bytes for a in included) 

331 plan.total_estimated_files = sum(a.files_total for a in included) 

332 

333 # Volume allocation summary 

334 for vol in rom_volumes: 

335 vol_allocs = plan.get_allocations_for_volume(vol.mount_point) 

336 plan.volume_allocations[vol.mount_point] = sum(a.allocated_bytes for a in vol_allocs) 

337 

338 plan.status = DeploymentStatus.PENDING 

339 plan.notes.append( 

340 f"Plan: {plan.platforms_included} platforms, " 

341 f"{plan.total_allocated_bytes / 1024**3:.1f} GB allocated, " 

342 f"{plan.headroom_gb:.1f} GB headroom" 

343 ) 

344 

345 logger.info(plan.summary()) 

346 return plan 

347 

348 # ------------------------------------------------------------------ 

349 # Volume assignment 

350 # ------------------------------------------------------------------ 

351 

352 def _pick_volume( 

353 self, 

354 platform: str, 

355 needed_bytes: int, 

356 volumes: list[VolumeInfo], 

357 remaining: dict[str, int], 

358 prefer_primary_for: set[str], 

359 ) -> VolumeInfo | None: 

360 """Pick the best volume for a platform allocation. 

361 

362 Strategy: 

363 - If platform is in prefer_primary_for, try primary first 

364 - Otherwise use best-fit: smallest volume with enough space 

365 - This naturally fills primary first (since it's usually smaller) 

366 and spills large platforms to secondary storage 

367 """ 

368 rom_volumes = [v for v in volumes if v.role in (VolumeRole.PRIMARY, VolumeRole.SECONDARY)] 

369 

370 if platform in prefer_primary_for: 

371 # Try primary first 

372 for vol in rom_volumes: 

373 if ( 

374 vol.role == VolumeRole.PRIMARY 

375 and remaining.get(vol.mount_point, 0) >= needed_bytes 

376 ): 

377 return vol 

378 

379 # Best-fit: pick volume with smallest remaining space that still fits 

380 candidates = [ 

381 vol for vol in rom_volumes if remaining.get(vol.mount_point, 0) >= needed_bytes 

382 ] 

383 

384 if not candidates: 

385 return None 

386 

387 # Sort by remaining space ascending (best fit) 

388 candidates.sort(key=lambda v: remaining[v.mount_point]) 

389 return candidates[0] 

390 

391 def _add_skipped( 

392 self, 

393 plan: DeploymentPlan, 

394 pinfo: PlatformSizeInfo, 

395 reason: str, 

396 ) -> None: 

397 """Add a skipped platform to the plan.""" 

398 alloc = PlatformAllocation( 

399 platform=pinfo.platform, 

400 tier=pinfo.tier, 

401 action=SelectionAction.SKIP, 

402 full_set_bytes=pinfo.full_set_bytes, 

403 ) 

404 plan.allocations.append(alloc) 

405 plan.notes.append(f"SKIP {pinfo.platform}: {reason} (full set: {pinfo.full_set_gb:.1f} GB)") 

406 

407 # ------------------------------------------------------------------ 

408 # Utility: what-if analysis 

409 # ------------------------------------------------------------------ 

410 

411 def estimate_platforms_count(self, available_gb: float) -> dict[str, Any]: 

412 """Quick estimate: how many platforms fit in this much space? 

413 

414 Returns a summary dict useful for MCP/CLI display. 

415 """ 

416 available_bytes = int(available_gb * 1024**3) 

417 

418 tiers: dict[str, list[dict]] = { 

419 "include_all": [], 

420 "budget_needed": [], 

421 "skip": [], 

422 } 

423 running_total = 0 

424 

425 sorted_platforms = sorted( 

426 self.size_data.values(), 

427 key=lambda p: p.full_set_bytes, 

428 ) 

429 

430 for pinfo in sorted_platforms: 

431 if pinfo.tier in (PlatformTier.TINY, PlatformTier.SMALL): 

432 running_total += pinfo.full_set_bytes 

433 tiers["include_all"].append( 

434 { 

435 "platform": pinfo.platform, 

436 "size_gb": round(pinfo.full_set_gb, 2), 

437 "files": pinfo.full_set_files, 

438 "tier": pinfo.tier.value, 

439 } 

440 ) 

441 elif pinfo.tier == PlatformTier.MEDIUM: 

442 if running_total + pinfo.full_set_bytes <= available_bytes: 

443 running_total += pinfo.full_set_bytes 

444 tiers["include_all"].append( 

445 { 

446 "platform": pinfo.platform, 

447 "size_gb": round(pinfo.full_set_gb, 2), 

448 "files": pinfo.full_set_files, 

449 "tier": pinfo.tier.value, 

450 } 

451 ) 

452 else: 

453 budget = DEFAULT_LARGE_BUDGET_GB.get(pinfo.platform, 20) 

454 tiers["budget_needed"].append( 

455 { 

456 "platform": pinfo.platform, 

457 "full_size_gb": round(pinfo.full_set_gb, 2), 

458 "suggested_budget_gb": budget, 

459 "tier": pinfo.tier.value, 

460 } 

461 ) 

462 else: 

463 budget = DEFAULT_LARGE_BUDGET_GB.get(pinfo.platform, 0) 

464 if budget > 0: 

465 tiers["budget_needed"].append( 

466 { 

467 "platform": pinfo.platform, 

468 "full_size_gb": round(pinfo.full_set_gb, 2), 

469 "suggested_budget_gb": budget, 

470 "tier": pinfo.tier.value, 

471 } 

472 ) 

473 else: 

474 tiers["skip"].append( 

475 { 

476 "platform": pinfo.platform, 

477 "full_size_gb": round(pinfo.full_set_gb, 2), 

478 "tier": pinfo.tier.value, 

479 } 

480 ) 

481 

482 return { 

483 "available_gb": available_gb, 

484 "guaranteed_gb": round(running_total / 1024**3, 2), 

485 "guaranteed_platforms": len(tiers["include_all"]), 

486 "budget_platforms": len(tiers["budget_needed"]), 

487 "skip_platforms": len(tiers["skip"]), 

488 **tiers, 

489 }