Coverage for src/romfarmer/driver/capability.py: 100%

102 statements  

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

1"""Capability is data, not model knowledge (intent brief v1 §5, v4 §1). 

2 

3An agent asked what an R36S can run will confidently invent an answer. This 

4module is what it reads instead: the frontend × device profile, flattened 

5into a frozen ``Capabilities`` value with a digest the Spec records as 

6``intent.capability_digest``. 

7 

8``Capabilities.require(platform)`` raises for a platform the device profile 

9does not mention — an absent platform is an error, never a guess. 

10""" 

11 

12from __future__ import annotations 

13 

14import hashlib 

15import json 

16from dataclasses import dataclass 

17from pathlib import Path 

18from types import MappingProxyType 

19from typing import Any 

20 

21from romfarmer.ir.catalog import PlatformId 

22from romfarmer.ir.chain import FormatChain 

23from romfarmer.ir.layout import PlatformCapability 

24from romfarmer.targets.profiles.loader import ConcreteTargetProfile, TargetProfileLoader 

25 

26 

27@dataclass(frozen=True) 

28class Capabilities: 

29 frontend: str 

30 device: str | None 

31 reserve_bytes: int | None 

32 platforms: MappingProxyType[str, PlatformCapability] # listed platforms 

33 default: PlatformCapability | None # applies to unlisted platforms, if any 

34 formats: MappingProxyType[str, tuple[FormatChain, ...]] # frontend-accepted chains 

35 folder_names: MappingProxyType[str, str] 

36 platform_sources: MappingProxyType[str, tuple[dict[str, Any], ...]] = MappingProxyType( 

37 {} 

38 ) # platform → [{root, subpath, recursive}] 

39 spec_template: str = "" # a complete, valid Spec skeleton for this frontend/device 

40 

41 def require(self, platform: str) -> PlatformCapability: 

42 cap = self.platforms.get(platform) 

43 if cap is not None: 

44 return cap 

45 if self.default is not None: 

46 return self.default 

47 raise KeyError( 

48 f"device {self.device!r} has no capability entry for {platform!r} — add it to " 

49 f"config/devices/{self.device}.yaml (tier A/B/C/X); the intent layer does not guess" 

50 ) 

51 

52 def shippable(self) -> tuple[str, ...]: 

53 """Platforms with a tier other than X that the frontend can also load.""" 

54 out = [] 

55 for plat in sorted(set(self.platforms) | set(self.formats)): 

56 try: 

57 cap = self.require(plat) 

58 except KeyError: 

59 continue 

60 if cap.tier != "X" and plat in self.formats: 

61 out.append(plat) 

62 return tuple(out) 

63 

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

65 return { 

66 "frontend": self.frontend, 

67 "device": self.device, 

68 "reserve_bytes": self.reserve_bytes, 

69 "default": _cap_dict(self.default) if self.default else None, 

70 "platforms": { 

71 k: { 

72 **_cap_dict(v), 

73 "formats": [list(c) for c in self.formats.get(k, ())], 

74 "folder": self.folder_names.get(k, k), 

75 } 

76 for k, v in sorted(self.platforms.items()) 

77 }, 

78 "frontend_only": { 

79 k: [list(c) for c in v] 

80 for k, v in sorted(self.formats.items()) 

81 if k not in self.platforms 

82 }, 

83 "platform_sources": {k: list(v) for k, v in sorted(self.platform_sources.items())}, 

84 "spec_template": self.spec_template, 

85 } 

86 

87 def digest(self) -> str: 

88 """``sha256:<hex>`` of the canonical JSON — recorded as ``intent.capability_digest``.""" 

89 text = json.dumps(self.to_dict(), sort_keys=True, separators=(",", ":"), ensure_ascii=True) 

90 return "sha256:" + hashlib.sha256(text.encode("utf-8")).hexdigest() 

91 

92 

93def _cap_dict(c: PlatformCapability) -> dict[str, Any]: 

94 return { 

95 "tier": c.tier, 

96 "quality": c.quality, 

97 "playable_list": c.playable_list, 

98 "notes": c.notes, 

99 } 

100 

101 

102def capabilities_from_profile( 

103 profile: ConcreteTargetProfile, frontend: str, device: str | None 

104) -> Capabilities: 

105 return Capabilities( 

106 frontend=frontend, 

107 device=device, 

108 reserve_bytes=profile.reserve_bytes, 

109 platforms=MappingProxyType(dict(profile.capabilities)), 

110 default=profile.capability_default, 

111 formats=MappingProxyType({k: tuple(v) for k, v in profile.platform_preferences.items()}), 

112 folder_names=MappingProxyType( 

113 {k: profile.folder_name(PlatformId(k)) for k in profile.platform_preferences} 

114 ), 

115 ) 

116 

117 

118def _platform_sources( 

119 config_dir: Path, platforms: list[str] 

120) -> dict[str, tuple[dict[str, Any], ...]]: 

121 """``platform → [{root, subpath, recursive}]`` — the exact fragment a Spec needs. 

122 

123 Read from each supported platform's config and reverse-mapped through the 

124 named roots in ``config/sources.yaml``; platforms whose sources are under 

125 no named root are omitted (the Spec cannot express them). 

126 """ 

127 from romfarmer.config.new_loader import load_slim_platform 

128 from romfarmer.driver.sources import alias_path, load_source_roots 

129 

130 roots = load_source_roots(config_dir) # loud on a bad sources.yaml / unset ${VAR} 

131 out: dict[str, tuple[dict[str, Any], ...]] = {} 

132 for plat in platforms: 

133 try: 

134 slim = load_slim_platform(plat, config_dir, check_source_paths=False) 

135 except Exception as exc: 

136 out[plat] = ({"error": f"platform config unreadable: {exc}"},) 

137 continue 

138 frags = [] 

139 unaliased = [] 

140 for src in slim.sources or []: 

141 if src.path is None: 

142 continue 

143 a = alias_path(Path(src.path), roots, recursive=bool(src.recursive)) 

144 if a is not None: 

145 frags.append({"root": a.root, "subpath": a.subpath, "recursive": a.recursive}) 

146 else: 

147 unaliased.append(str(src.path)) 

148 if frags: 

149 out[plat] = tuple(frags) 

150 else: 

151 out[plat] = ( 

152 { 

153 "error": "no source under a named root in config/sources.yaml" 

154 + (f": {unaliased}" if unaliased else " (platform config lists no sources)") 

155 }, 

156 ) 

157 return out 

158 

159 

160def _spec_template( 

161 frontend: str, 

162 device: str | None, 

163 reserve: int | None, 

164 sources: dict[str, tuple[dict[str, Any], ...]], 

165 tiers: dict[str, str], 

166) -> str: 

167 """A complete Spec skeleton: every supported platform with its exact sources; policy fields commented.""" 

168 lines = [ 

169 "spec_version: 2", 

170 "intent:", 

171 ' text: "<the intent, verbatim>"', 

172 ' authored_by: "agent:<model-id>"', 

173 ' inventory_digest: "" # from inventory', 

174 ' capability_digest: "" # from capabilities', 

175 "target:", 

176 f" frontend: {frontend}", 

177 f" device: {device or 'pc'}", 

178 " storage_bytes: 512000000000", 

179 f" reserve_bytes: {reserve if reserve is not None else 0}", 

180 "platforms:", 

181 ] 

182 for plat in sorted(sources): 

183 if any("error" in f for f in sources[plat]): 

184 lines.append(f" # {plat}: NOT authorable — {sources[plat][0].get('error')}") 

185 continue 

186 lines.append(f" - platform: {plat} # tier {tiers.get(plat, '?')}") 

187 lines.append(" sources:") 

188 for f in sources[plat]: 

189 sub = f["subpath"].replace('"', '\\"') 

190 lines.append( 

191 f' - {{root: {f["root"]}, subpath: "{sub}", recursive: {str(f["recursive"]).lower()}}}' 

192 ) 

193 lines.append( 

194 " dat: {retool_1g1r: true} # true when the platform's DAT is a Retool 1G1R export (it is for No-Intro/Redump *_eng sources)" 

195 ) 

196 lines.append( 

197 " # extraction / compression: omit → platform intrinsic + frontend preferred format" 

198 ) 

199 lines.append(" passes:") 

200 lines.append(" dat_filter: true") 

201 lines.append( 

202 " # rating: {min: 0.70, unrated: keep} # unit interval 0–1; unrated REQUIRED with min" 

203 ) 

204 lines.append(" # budget: {max_bytes: 0, unrated_as: median}") 

205 lines.append( 

206 " # curated_lists: {ref: curated/<name>@sha256:<hex>} # from write_curated_list" 

207 ) 

208 return "\n".join(lines) + "\n" 

209 

210 

211def capabilities(frontend: str, device: str | None, config_dir: Path) -> Capabilities: 

212 """Read ``config/frontends/<frontend>.yaml`` + ``config/devices/<device>.yaml``. Loud. 

213 

214 Also returns ``platform_sources`` (each supported platform's exact 

215 ``{root, subpath}`` fragments) and a complete ``spec_template`` — the cold 

216 run showed an agent cannot author a Spec from directory names. 

217 """ 

218 key = f"{frontend}/{device}" if device else frontend 

219 profile = TargetProfileLoader(config_dir).load(key) 

220 caps = capabilities_from_profile(profile, frontend, device) 

221 fields = {f: getattr(caps, f) for f in caps.__dataclass_fields__} 

222 supported = list(caps.shippable()) 

223 sources = _platform_sources(config_dir, supported) 

224 tiers = {p: caps.require(p).tier for p in supported} 

225 fields["platform_sources"] = MappingProxyType(sources) 

226 fields["spec_template"] = _spec_template(frontend, device, caps.reserve_bytes, sources, tiers) 

227 return Capabilities(**fields)