Coverage for src/romfarmer/ir/spec.py: 81%

279 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-05 02:19 -0700

1"""Spec — the frozen, hash-addressed build specification (the SPEC seam). 

2 

3Everything above this type may be stochastic (an agent authoring it); 

4everything below is the deterministic compiler. ``Spec`` is the only thing 

5that crosses. It is the product of INTENT and the input of RESOLVE. 

6 

7Design (intent brief v4 §5): 

8 

9* ``intent`` is **provenance only** and is excluded from ``spec_hash`` — 

10 rewording the prompt must not invalidate a correct build. 

11* Semantic fields (``target``, ``platforms``) are canonicalised to compact, 

12 key-sorted JSON; ``spec_hash`` is the SHA-256 of that text. The canonical 

13 form is FROZEN — see ``tests/ir/test_spec_golden.py``. 

14* Sources are ``{root, subpath}`` aliases into ``config/sources.yaml`` — a Spec 

15 never embeds an absolute path, so it is portable and hashes the same on 

16 every host (resolution is RESOLVE's job). 

17* Curated-list references are ``curated/<name>@sha256:<hex>`` and bind to the 

18 spec hash only — never to ``Action.params`` (selection determinism and 

19 transform determinism are distinct layers). 

20* Ratings are on the unit interval (0.0–1.0). ``rating.min > 1`` is an 

21 error at construction; ``unrated`` is *required* whenever ``min`` is set. 

22* ``dat.retool_1g1r`` is THE one-game-one-region lever; there is no 

23 ``passes.1g1r``. ``region.preferred`` must be empty under a Retool DAT. 

24 

25This module is stdlib-only (IR contract). YAML I/O lives in 

26``romfarmer.driver.spec_io``. 

27""" 

28 

29from __future__ import annotations 

30 

31import hashlib 

32import json 

33import re 

34from collections.abc import Mapping 

35from dataclasses import dataclass, field, fields 

36from typing import Any 

37 

38SPEC_VERSION = 2 

39 

40_CURATED_REF = re.compile(r"^curated/[A-Za-z0-9._-]+@sha256:[0-9a-f]{64}$") 

41_UNRATED = ("keep", "drop") 

42_UNRATED_AS = ("median", "worst", "best") 

43_RATING_SCALE = "unit_interval" 

44 

45 

46class SpecError(ValueError): 

47 """The spec is malformed or violates a validation rule. Always loud.""" 

48 

49 

50# --------------------------------------------------------------------------- 

51# Leaf types 

52# --------------------------------------------------------------------------- 

53 

54 

55@dataclass(frozen=True, slots=True) 

56class SpecIntent: 

57 """Provenance. EXCLUDED from ``spec_hash``.""" 

58 

59 text: str = "" 

60 authored_by: str = "" 

61 authored_at: str = "" 

62 inventory_digest: str = "" 

63 capability_digest: str = "" 

64 allocation_note: str = "" 

65 

66 

67@dataclass(frozen=True, slots=True) 

68class SpecTarget: 

69 frontend: str 

70 device: str | None = None 

71 storage_bytes: int | None = None 

72 reserve_bytes: int | None = None 

73 

74 @property 

75 def usable_bytes(self) -> int | None: 

76 if self.storage_bytes is None: 

77 return None 

78 return self.storage_bytes - (self.reserve_bytes or 0) 

79 

80 

81@dataclass(frozen=True, slots=True) 

82class SpecSource: 

83 """A source directory named by root alias, never by absolute path. 

84 

85 ``root`` is a key of ``config/sources.yaml`` ``roots:``; the host maps it 

86 to a mount point. Keeps the Spec portable and its hash stable across 

87 hosts and remounts. 

88 """ 

89 

90 root: str 

91 subpath: str = "" 

92 recursive: bool = False 

93 

94 

95@dataclass(frozen=True, slots=True) 

96class SpecDat: 

97 """Which DAT defines the platform's collection. 

98 

99 ``retool_1g1r`` is the one-game-one-region lever: when true the DAT has 

100 already chosen one title per game and the name-heuristic 1g1r pass is off. 

101 ``source`` is the ``DATSource`` key (``retool_1g1r_eng`` …) or ``None`` to 

102 take the platform config's intrinsic reference; ``file`` an explicit path. 

103 """ 

104 

105 retool_1g1r: bool = False 

106 source: str | None = None 

107 file: str | None = None 

108 

109 

110@dataclass(frozen=True, slots=True) 

111class SpecRegion: 

112 preferred: tuple[str, ...] = () 

113 

114 

115@dataclass(frozen=True, slots=True) 

116class SpecRating: 

117 scale: str = _RATING_SCALE 

118 min: float | None = None 

119 top_n: int | None = None 

120 unrated: str | None = None # REQUIRED when min is set: "keep" | "drop" 

121 

122 

123@dataclass(frozen=True, slots=True) 

124class SpecCuratedLists: 

125 ref: str | None = None # curated/<name>@sha256:<hex> 

126 

127 

128@dataclass(frozen=True, slots=True) 

129class SpecBudget: 

130 """``max_bytes`` binds at p50 inside the compiler; the card-level constraint 

131 is the aggregate **p90** headroom in ``PlanSummary`` (measured uncertainty), 

132 not a fixed safety margin. ``safety_margin`` was retired 2026-09-03.""" 

133 

134 max_bytes: int | None = None 

135 unrated_as: str = "median" # median | worst | best | "<float>" 

136 

137 

138@dataclass(frozen=True, slots=True) 

139class SpecSample: 

140 n: int | None = None 

141 seed: int = 0 

142 

143 

144@dataclass(frozen=True, slots=True) 

145class SpecPasses: 

146 dat_filter: bool = True 

147 region: SpecRegion = field(default_factory=SpecRegion) 

148 rating: SpecRating = field(default_factory=SpecRating) 

149 curated_lists: SpecCuratedLists = field(default_factory=SpecCuratedLists) 

150 budget: SpecBudget = field(default_factory=SpecBudget) 

151 sample: SpecSample = field(default_factory=SpecSample) 

152 

153 

154@dataclass(frozen=True, slots=True) 

155class SpecPlatform: 

156 platform: str 

157 sources: tuple[SpecSource, ...] 

158 # Both OPTIONAL: ``None`` = the platform config's intrinsic extraction and 

159 # the frontend's preferred format. The first cold run omitted them and a 

160 # silent ``none`` default produced a passthrough card; a stated 

161 # compression that resolves to passthrough is now an error. 

162 extraction: str | None = None # none | cartridge | disc | rvz | wux | ps3 | xiso 

163 compression: str | None = None # none | zip | 7z | chd | xiso | sqfs | … 

164 priority: int = 0 

165 dat: SpecDat = field(default_factory=SpecDat) 

166 passes: SpecPasses = field(default_factory=SpecPasses) 

167 

168 

169@dataclass(frozen=True, slots=True) 

170class Spec: 

171 target: SpecTarget 

172 platforms: tuple[SpecPlatform, ...] 

173 intent: SpecIntent = field(default_factory=SpecIntent) 

174 spec_version: int = SPEC_VERSION 

175 

176 # ------------------------------------------------------------------ 

177 # Canonical form + hash (FROZEN — golden test) 

178 # ------------------------------------------------------------------ 

179 

180 def semantic_dict(self) -> dict[str, Any]: 

181 """The hashed content: everything except ``intent``. Platforms sorted by id.""" 

182 return { 

183 "spec_version": self.spec_version, 

184 "target": _to_plain(self.target), 

185 "platforms": [_to_plain(p) for p in sorted(self.platforms, key=lambda p: p.platform)], 

186 } 

187 

188 def canonical_json(self) -> str: 

189 """Compact, key-sorted, ASCII JSON of ``semantic_dict``. FROZEN FOREVER.""" 

190 return json.dumps( 

191 self.semantic_dict(), sort_keys=True, separators=(",", ":"), ensure_ascii=True 

192 ) 

193 

194 def spec_hash(self) -> str: 

195 return hashlib.sha256(self.canonical_json().encode("utf-8")).hexdigest() 

196 

197 def to_dict(self) -> dict[str, Any]: 

198 """Full round-trippable form (includes ``intent``).""" 

199 d = self.semantic_dict() 

200 d["intent"] = _to_plain(self.intent) 

201 return d 

202 

203 # ------------------------------------------------------------------ 

204 # Construction 

205 # ------------------------------------------------------------------ 

206 

207 @classmethod 

208 def from_dict(cls, raw: Mapping[str, Any]) -> Spec: 

209 """Build and validate a ``Spec`` from a plain mapping. Unknown keys are errors.""" 

210 _check_keys(raw, {"spec_version", "intent", "target", "platforms", "policy"}, "spec") 

211 if "policy" in raw: 

212 raise SpecError( 

213 "'policy' was removed (v4): budget strategy is agent behaviour, not compiler " 

214 "behaviour — record the outcome as per-platform budget.max_bytes" 

215 ) 

216 raw = migrate_spec_dict(raw) 

217 version = raw.get("spec_version", SPEC_VERSION) 

218 if version != SPEC_VERSION: 

219 raise SpecError(f"unsupported spec_version {version!r} (expected {SPEC_VERSION})") 

220 target = _target_from(raw.get("target")) 

221 plats_raw = raw.get("platforms") 

222 if not isinstance(plats_raw, list) or not plats_raw: 

223 raise SpecError("'platforms' must be a non-empty list") 

224 platforms = tuple(_platform_from(p) for p in plats_raw) 

225 intent = _intent_from(raw.get("intent") or {}) 

226 spec = cls(target=target, platforms=platforms, intent=intent, spec_version=version) 

227 validate_spec(spec) 

228 return spec 

229 

230 

231# --------------------------------------------------------------------------- 

232# Schema migration — spec_version is load-bearing, not decorative 

233# --------------------------------------------------------------------------- 

234 

235 

236def migrate_spec_dict(raw: Mapping[str, Any]) -> dict[str, Any]: 

237 """Return *raw* upgraded to ``SPEC_VERSION``; unknown future versions are errors. 

238 

239 v1 → v2 (2026-09-03): ``passes.budget.safety_margin`` removed (the card 

240 binds on aggregate p90); ``extraction``/``compression`` became optional 

241 (a v1 spec that stated them keeps them verbatim). 

242 """ 

243 d: dict[str, Any] = dict(raw) 

244 version = d.get("spec_version", SPEC_VERSION) 

245 if not isinstance(version, int) or isinstance(version, bool): 

246 raise SpecError(f"spec_version must be an integer, got {version!r}") 

247 if version > SPEC_VERSION: 

248 raise SpecError( 

249 f"spec_version {version} is newer than this code understands ({SPEC_VERSION})" 

250 ) 

251 if version == 1: 

252 plats = [] 

253 for pl in d.get("platforms") or []: 

254 if isinstance(pl, Mapping): 

255 pl = dict(pl) 

256 passes = dict(pl.get("passes") or {}) 

257 if isinstance(passes.get("budget"), Mapping): 

258 b = dict(passes["budget"]) 

259 b.pop("safety_margin", None) 

260 passes["budget"] = b 

261 pl["passes"] = passes 

262 plats.append(pl) 

263 d["platforms"] = plats 

264 d["spec_version"] = 2 

265 return d 

266 

267 

268# --------------------------------------------------------------------------- 

269# Validation (pure; every rule from the briefs lives here) 

270# --------------------------------------------------------------------------- 

271 

272 

273def validate_spec(spec: Spec) -> None: 

274 """Raise ``SpecError`` on the first violated rule. 

275 

276 Rules (intent briefs v2–v4): 

277 - platform ids unique; sources non-empty 

278 - rating.scale == unit_interval; 0 ≤ min ≤ 1; top_n ≥ 1; unrated required with min 

279 - budget.max_bytes ≥ 0; unrated_as ∈ {median, worst, best, <float in [0,1]>} 

280 - region.preferred must be empty when dat.retool_1g1r (it would delete 

281 Retool's English picks) 

282 - curated_lists.ref must be hash-addressed 

283 - Σ budget.max_bytes ≤ target.storage_bytes − reserve_bytes 

284 """ 

285 t = spec.target 

286 if not t.frontend: 

287 raise SpecError("target.frontend is required") 

288 for name in ("storage_bytes", "reserve_bytes"): 

289 v = getattr(t, name) 

290 if v is not None and (not isinstance(v, int) or v < 0): 

291 raise SpecError(f"target.{name} must be a non-negative integer, got {v!r}") 

292 if ( 

293 t.storage_bytes is not None 

294 and t.reserve_bytes is not None 

295 and t.reserve_bytes > t.storage_bytes 

296 ): 

297 raise SpecError("target.reserve_bytes exceeds target.storage_bytes") 

298 

299 seen: set[str] = set() 

300 total_budget = 0 

301 for p in spec.platforms: 

302 where = f"platforms[{p.platform!r}]" 

303 if not p.platform: 

304 raise SpecError("platform id is required") 

305 if p.platform in seen: 

306 raise SpecError(f"duplicate platform {p.platform!r}") 

307 seen.add(p.platform) 

308 if not p.sources: 

309 raise SpecError(f"{where}.sources must be non-empty") 

310 r = p.passes.rating 

311 if r.scale != _RATING_SCALE: 

312 raise SpecError( 

313 f"{where}.passes.rating.scale must be {_RATING_SCALE!r}, got {r.scale!r}" 

314 ) 

315 if r.min is not None: 

316 if not (0.0 <= r.min <= 1.0): 

317 raise SpecError( 

318 f"{where}.passes.rating.min must be on the unit interval 0.0–1.0, got {r.min!r} " 

319 "(ratings are 0–1; 3.5 would remove every rated unit)" 

320 ) 

321 if r.unrated is None: 

322 raise SpecError( 

323 f"{where}.passes.rating.unrated is required when min is set (keep|drop)" 

324 ) 

325 if r.unrated is not None and r.unrated not in _UNRATED: 

326 raise SpecError(f"{where}.passes.rating.unrated must be keep|drop, got {r.unrated!r}") 

327 if r.top_n is not None and r.top_n < 1: 

328 raise SpecError(f"{where}.passes.rating.top_n must be >= 1") 

329 b = p.passes.budget 

330 if b.max_bytes is not None: 

331 if b.max_bytes < 0: 

332 raise SpecError(f"{where}.passes.budget.max_bytes must be >= 0") 

333 total_budget += b.max_bytes 

334 if b.unrated_as not in _UNRATED_AS: 

335 try: 

336 f = float(b.unrated_as) 

337 except ValueError: 

338 raise SpecError( 

339 f"{where}.passes.budget.unrated_as must be median|worst|best|<float>, got {b.unrated_as!r}" 

340 ) from None 

341 if not (0.0 <= f <= 1.0): 

342 raise SpecError(f"{where}.passes.budget.unrated_as float must be in [0, 1]") 

343 if p.dat.retool_1g1r and p.passes.region.preferred: 

344 raise SpecError( 

345 f"{where}.passes.region.preferred must be empty under a Retool 1G1R DAT — " 

346 "the DAT already chose one title per game and a region filter would delete " 

347 "its English picks (e.g. Japan-only English releases)" 

348 ) 

349 ref = p.passes.curated_lists.ref 

350 if ref is not None and not _CURATED_REF.match(ref): 

351 raise SpecError( 

352 f"{where}.passes.curated_lists.ref must be 'curated/<name>@sha256:<64 hex>', got {ref!r}" 

353 ) 

354 s = p.passes.sample 

355 if s.n is not None and s.n < 1: 

356 raise SpecError(f"{where}.passes.sample.n must be >= 1") 

357 

358 usable = t.usable_bytes 

359 if usable is not None and total_budget > usable: 

360 raise SpecError( 

361 f"sum of platform budget.max_bytes ({total_budget:,}) exceeds usable storage " 

362 f"({usable:,} = storage_bytes − reserve_bytes)" 

363 ) 

364 

365 

366# --------------------------------------------------------------------------- 

367# dict ↔ dataclass helpers 

368# --------------------------------------------------------------------------- 

369 

370 

371def Path_parts(sub: str) -> tuple[str, ...]: 

372 return tuple(part for part in sub.replace("\\", "/").split("/") if part) 

373 

374 

375def _to_plain(obj: Any) -> Any: 

376 if hasattr(obj, "__dataclass_fields__"): 

377 return {f.name: _to_plain(getattr(obj, f.name)) for f in fields(obj)} 

378 if isinstance(obj, tuple): 

379 return [_to_plain(x) for x in obj] 

380 return obj 

381 

382 

383def _check_keys(raw: Any, allowed: set[str], where: str) -> None: 

384 if not isinstance(raw, Mapping): 

385 raise SpecError(f"{where} must be a mapping, got {type(raw).__name__}") 

386 unknown = set(raw) - allowed 

387 if unknown: 

388 raise SpecError(f"{where}: unknown key(s) {sorted(unknown)} (allowed: {sorted(allowed)})") 

389 

390 

391def _opt_int(raw: Mapping[str, Any], key: str, where: str) -> int | None: 

392 v = raw.get(key) 

393 if v is None: 

394 return None 

395 if isinstance(v, bool) or not isinstance(v, int): 

396 raise SpecError(f"{where}.{key} must be an integer, got {v!r}") 

397 return v 

398 

399 

400def _opt_float(raw: Mapping[str, Any], key: str, where: str) -> float | None: 

401 v = raw.get(key) 

402 if v is None: 

403 return None 

404 if isinstance(v, bool) or not isinstance(v, (int, float)): 

405 raise SpecError(f"{where}.{key} must be a number, got {v!r}") 

406 return float(v) 

407 

408 

409def _intent_from(raw: Mapping[str, Any]) -> SpecIntent: 

410 _check_keys(raw, {f.name for f in fields(SpecIntent)}, "intent") 

411 return SpecIntent(**{k: str(v) for k, v in raw.items()}) 

412 

413 

414def _target_from(raw: Any) -> SpecTarget: 

415 _check_keys(raw, {"frontend", "device", "storage_bytes", "reserve_bytes"}, "target") 

416 if not raw.get("frontend"): 

417 raise SpecError("target.frontend is required") 

418 return SpecTarget( 

419 frontend=str(raw["frontend"]), 

420 device=str(raw["device"]) if raw.get("device") is not None else None, 

421 storage_bytes=_opt_int(raw, "storage_bytes", "target"), 

422 reserve_bytes=_opt_int(raw, "reserve_bytes", "target"), 

423 ) 

424 

425 

426def _passes_from(raw: Any, where: str) -> SpecPasses: 

427 raw = raw or {} 

428 _check_keys( 

429 raw, {"dat_filter", "region", "rating", "curated_lists", "budget", "sample", "1g1r"}, where 

430 ) 

431 if "1g1r" in raw: 

432 raise SpecError( 

433 f"{where}.1g1r was removed (v4): use dat.retool_1g1r — the DAT is the 1g1r lever" 

434 ) 

435 df = raw.get("dat_filter", True) 

436 if not isinstance(df, bool): 

437 raise SpecError(f"{where}.dat_filter must be a boolean (the gate is binary), got {df!r}") 

438 

439 reg_raw = raw.get("region") or {} 

440 _check_keys(reg_raw, {"preferred"}, f"{where}.region") 

441 region = SpecRegion(preferred=tuple(str(x) for x in (reg_raw.get("preferred") or []))) 

442 

443 rat_raw = raw.get("rating") 

444 if isinstance(rat_raw, bool): 

445 raise SpecError(f"{where}.rating must be a mapping (scale/min/top_n/unrated)") 

446 rat_raw = rat_raw or {} 

447 _check_keys(rat_raw, {"scale", "min", "top_n", "unrated"}, f"{where}.rating") 

448 rating = SpecRating( 

449 scale=str(rat_raw.get("scale", _RATING_SCALE)), 

450 min=_opt_float(rat_raw, "min", f"{where}.rating"), 

451 top_n=_opt_int(rat_raw, "top_n", f"{where}.rating"), 

452 unrated=str(rat_raw["unrated"]) if rat_raw.get("unrated") is not None else None, 

453 ) 

454 

455 cl_raw = raw.get("curated_lists") or {} 

456 _check_keys(cl_raw, {"ref"}, f"{where}.curated_lists") 

457 curated = SpecCuratedLists(ref=str(cl_raw["ref"]) if cl_raw.get("ref") is not None else None) 

458 

459 b_raw = raw.get("budget") or {} 

460 _check_keys(b_raw, {"max_bytes", "unrated_as", "safety_margin"}, f"{where}.budget") 

461 if "safety_margin" in b_raw: 

462 raise SpecError( 

463 f"{where}.budget.safety_margin was retired: the card-level constraint is the aggregate " 

464 "p90 headroom reported by dry_run (measured uncertainty), not a fixed margin" 

465 ) 

466 budget = SpecBudget( 

467 max_bytes=_opt_int(b_raw, "max_bytes", f"{where}.budget"), 

468 unrated_as=str(b_raw.get("unrated_as", "median")), 

469 ) 

470 

471 s_raw = raw.get("sample") or {} 

472 _check_keys(s_raw, {"n", "seed"}, f"{where}.sample") 

473 sample = SpecSample( 

474 n=_opt_int(s_raw, "n", f"{where}.sample"), 

475 seed=_opt_int(s_raw, "seed", f"{where}.sample") or 0, 

476 ) 

477 

478 return SpecPasses( 

479 dat_filter=df, 

480 region=region, 

481 rating=rating, 

482 curated_lists=curated, 

483 budget=budget, 

484 sample=sample, 

485 ) 

486 

487 

488def _platform_from(raw: Any) -> SpecPlatform: 

489 _check_keys( 

490 raw, 

491 {"platform", "priority", "sources", "extraction", "compression", "dat", "passes"}, 

492 "platform", 

493 ) 

494 pid = str(raw.get("platform") or "") 

495 where = f"platforms[{pid!r}]" 

496 srcs = raw.get("sources") 

497 if not isinstance(srcs, list): 

498 raise SpecError(f"{where}.sources must be a list of {{root, subpath}} entries") 

499 sources: list[SpecSource] = [] 

500 for i, entry in enumerate(srcs): 

501 if isinstance(entry, str): 

502 raise SpecError( 

503 f"{where}.sources[{i}]: absolute paths are not allowed — name a root alias from " 

504 f"config/sources.yaml: {{root: <alias>, subpath: <relative dir>}}" 

505 ) 

506 _check_keys(entry, {"root", "subpath", "recursive"}, f"{where}.sources[{i}]") 

507 if not entry.get("root"): 

508 raise SpecError(f"{where}.sources[{i}].root is required") 

509 sub = str(entry.get("subpath") or "") 

510 if sub.startswith("/") or ".." in Path_parts(sub): 

511 raise SpecError(f"{where}.sources[{i}].subpath must be relative and contain no '..'") 

512 sources.append( 

513 SpecSource( 

514 root=str(entry["root"]), subpath=sub, recursive=bool(entry.get("recursive", False)) 

515 ) 

516 ) 

517 dat_raw = raw.get("dat") or {} 

518 _check_keys(dat_raw, {"retool_1g1r", "source", "file"}, f"{where}.dat") 

519 dat = SpecDat( 

520 retool_1g1r=bool(dat_raw.get("retool_1g1r", False)), 

521 source=str(dat_raw["source"]) if dat_raw.get("source") is not None else None, 

522 file=str(dat_raw["file"]) if dat_raw.get("file") is not None else None, 

523 ) 

524 return SpecPlatform( 

525 platform=pid, 

526 sources=tuple(sources), 

527 extraction=str(raw["extraction"]) if raw.get("extraction") is not None else None, 

528 compression=str(raw["compression"]) if raw.get("compression") is not None else None, 

529 priority=_opt_int(raw, "priority", where) or 0, 

530 dat=dat, 

531 passes=_passes_from(raw.get("passes"), f"{where}.passes"), 

532 ) 

533 

534 

535__all__ = [ 

536 "SPEC_VERSION", 

537 "Spec", 

538 "SpecBudget", 

539 "SpecCuratedLists", 

540 "SpecDat", 

541 "SpecError", 

542 "SpecIntent", 

543 "SpecPasses", 

544 "SpecPlatform", 

545 "SpecRating", 

546 "SpecRegion", 

547 "SpecSample", 

548 "SpecSource", 

549 "SpecTarget", 

550 "migrate_spec_dict", 

551 "validate_spec", 

552]