Coverage for src/romfarmer/intent/tools.py: 74%

94 statements  

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

1"""The five intent tools as plain functions (transport-agnostic). 

2 

3Inputs are what an agent authors — Spec YAML text — and outputs are 

4JSON-serialisable dicts. Errors come back as ``{"error": ...}`` so the loop 

5can revise instead of crashing. One ``PlanSession`` per ``IntentTools`` 

6instance holds the catalog cache for the session (INVENTORY once, replan 

7many). 

8""" 

9 

10from __future__ import annotations 

11 

12from pathlib import Path 

13from typing import Any 

14 

15import yaml 

16 

17from romfarmer.driver.capability import capabilities as _capabilities 

18from romfarmer.driver.curated import write_curated 

19from romfarmer.driver.session import PlanSession 

20from romfarmer.driver.spec_resolve import resolve_build 

21from romfarmer.ir.spec import Spec, SpecError 

22 

23INTENT_TOOL_NAMES: frozenset[str] = frozenset( 

24 {"inventory", "capabilities", "validate_spec", "dry_run", "write_curated_list"} 

25) 

26 

27 

28def _parse(spec_yaml: str) -> Spec: 

29 try: 

30 raw = yaml.safe_load(spec_yaml) 

31 except yaml.YAMLError as exc: 

32 raise SpecError(f"spec is not valid YAML: {exc}") from exc 

33 if not isinstance(raw, dict): 

34 raise SpecError("spec must be a YAML mapping") 

35 return Spec.from_dict(raw) 

36 

37 

38class IntentTools: 

39 def __init__( 

40 self, workspace_root: Path | str | None = None, config_root: Path | None = None 

41 ) -> None: 

42 from romfarmer.driver.workspace import Workspace 

43 

44 ws = Workspace.resolve( 

45 workspace_root 

46 ) # explicit root, else ROMFARMER_WORKSPACE — never the cwd 

47 self.workspace = ws 

48 self.workspace_root = ws.root 

49 self.config_root = Path(config_root) if config_root else ws.config_dir 

50 self.session = PlanSession(self.workspace_root, self.config_root) 

51 

52 # -- 1. inventory --------------------------------------------------- 

53 def inventory(self, spec_yaml: str) -> dict[str, Any]: 

54 """Catalog every platform in the spec (once per session); per-platform facts + digest.""" 

55 try: 

56 spec = _parse(spec_yaml) 

57 inv = self.session.inventory(spec) 

58 except SpecError as exc: 

59 return {"error": str(exc)} 

60 digest = inv.pop("_inventory_digest", "") 

61 return {"spec_hash": spec.spec_hash(), "inventory_digest": digest, "platforms": inv} 

62 

63 # -- 2. capabilities ------------------------------------------------ 

64 def capabilities(self, frontend: str, device: str | None = None) -> dict[str, Any]: 

65 """What this frontend × device can run (tiers, formats, reserve). Data, not guesses.""" 

66 try: 

67 caps = _capabilities(frontend, device, self.config_root) 

68 except Exception as exc: 

69 return {"error": str(exc)} 

70 d = caps.to_dict() 

71 d["capability_digest"] = caps.digest() 

72 d["shippable"] = list(caps.shippable()) 

73 return d 

74 

75 # -- 3. validate_spec ----------------------------------------------- 

76 def validate_spec( 

77 self, 

78 spec_yaml: str, 

79 previous_spec_yaml: str | None = None, 

80 previous_headroom_p50: int | None = None, 

81 previous_headroom_p90: int | None = None, 

82 ) -> dict[str, Any]: 

83 """Loud validation + RESOLVE every platform (no source scan). 

84 

85 When revising a spec, pass the previous spec and the previous 

86 dry-run's headroom (``headroom_p90`` when known — that is the binding 

87 one — else ``headroom_p50``): the deterministic guards reject a 

88 revision that *loosens* a threshold while the last plan overshot. 

89 """ 

90 try: 

91 spec = _parse(spec_yaml) 

92 builds = resolve_build(spec, self.config_root, workspace_root=self.workspace_root) 

93 except Exception as exc: # SpecError, FormatNegotiationError, TargetProfileError … 

94 return {"ok": False, "error": str(exc)} 

95 if previous_spec_yaml is not None: 

96 from romfarmer.intent.guards import guard_spec_revision 

97 

98 try: 

99 previous = _parse(previous_spec_yaml) 

100 except SpecError as exc: 

101 return {"ok": False, "error": f"previous_spec_yaml: {exc}"} 

102 headroom = ( 

103 previous_headroom_p90 

104 if previous_headroom_p90 is not None 

105 else previous_headroom_p50 

106 ) 

107 violations = guard_spec_revision(previous, spec, headroom) 

108 if violations: 

109 return { 

110 "ok": False, 

111 "error": "guard: " + "; ".join(violations), 

112 "guard_violations": violations, 

113 } 

114 from romfarmer.driver.summary import correctness_warnings 

115 

116 try: 

117 caps = _capabilities(spec.target.frontend, spec.target.device, self.config_root) 

118 except Exception as exc: 

119 return {"ok": False, "error": f"capabilities: {exc}"} 

120 

121 def _warn(rb: Any) -> list[str]: 

122 try: 

123 tier: str | None = caps.require(rb.platform).tier 

124 except KeyError: 

125 tier = None 

126 pref = (caps.formats.get(rb.platform) or (None,))[0] 

127 return list( 

128 correctness_warnings( 

129 rb.platform, 

130 tuple(rb.chain), 

131 tier=tier, 

132 preferred_chain=pref, 

133 resolve_notes=rb.notes, 

134 ) 

135 ) 

136 

137 return { 

138 "ok": True, 

139 "spec_hash": spec.spec_hash(), 

140 "platforms": [ 

141 { 

142 "platform": rb.platform, 

143 "extraction": rb.resolved.extraction_type.value, 

144 "compression": rb.resolved.compression.value, 

145 "chain": list(rb.chain), 

146 "dat": rb.dat_file.name if rb.dat_file else None, 

147 "one_g_one_r": ( 

148 "by-dat (Retool 1G1R DAT already chose one title per game)" 

149 if not rb.manifest.one_g_one_r 

150 else "by-name-pass (name heuristic + region.preferred; no Retool DAT)" 

151 ), 

152 "rating_min": rb.manifest.rating_min, 

153 "budget_bytes": rb.manifest.budget_bytes, 

154 "notes": list(rb.notes), 

155 "warnings": _warn(rb), 

156 } 

157 for rb in builds 

158 ], 

159 } 

160 

161 # -- 4. dry_run ----------------------------------------------------- 

162 def dry_run(self, spec_yaml: str, detail: list[str] | None = None) -> dict[str, Any]: 

163 """PLAN over cached catalogs → PlanSummary. Moves zero bytes. 

164 

165 ``detail``: platforms to expand with heaviest / top_dropped / 

166 bytes_kept_at_rating. Omitted → all expanded; ``[]`` → none. Ask for 

167 detail only on what you are tuning. 

168 """ 

169 try: 

170 spec = _parse(spec_yaml) 

171 summary = self.session.dry_run(spec) 

172 except Exception as exc: 

173 return {"error": str(exc)} 

174 return summary.to_dict(None if detail is None else set(detail)) 

175 

176 # -- 5. write_curated_list ------------------------------------------ 

177 def write_curated_list( 

178 self, 

179 name: str, 

180 entries: list[dict[str, str]], 

181 generated_by: str, 

182 basis: dict[str, Any] | None = None, 

183 ) -> dict[str, Any]: 

184 """Freeze a curated list into a hash-addressed artifact; returns its ref.""" 

185 try: 

186 art = write_curated( 

187 name, 

188 entries, 

189 self.workspace_root / "artifacts", 

190 generated_by=generated_by, 

191 basis=basis, 

192 ) 

193 except SpecError as exc: 

194 return {"error": str(exc)} 

195 return {"ref": art.ref, "include": len(art.include), "exclude": len(art.exclude)} 

196 

197 # -- dispatch ------------------------------------------------------- 

198 def call(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]: 

199 if name not in INTENT_TOOL_NAMES: 

200 return {"error": f"unknown tool {name!r}"} 

201 fn = getattr(self, name) 

202 try: 

203 result: dict[str, Any] = fn(**arguments) 

204 except TypeError as exc: 

205 return {"error": f"{name}: bad arguments: {exc}"} 

206 return result