Coverage for src/romfarmer/farmhand/skills/models.py: 0%

102 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-03 11:31 -0700

1"""Pydantic models for the Farm-Hand skill system. 

2 

3A Skill is a reusable unit of agent knowledge — a markdown contract 

4(SKILL.md) paired with a structured procedure (procedure.yaml) and 

5optional artifacts (scripts, curated lists, configs). 

6""" 

7 

8from __future__ import annotations 

9 

10import enum 

11from datetime import datetime 

12from pathlib import Path 

13from typing import Any 

14 

15from pydantic import BaseModel, Field 

16 

17# --------------------------------------------------------------------------- 

18# Enums 

19# --------------------------------------------------------------------------- 

20 

21 

22class SkillCategory(str, enum.Enum): 

23 """Broad classification of what a skill does.""" 

24 

25 DEPLOYMENT = "deployment" # Deploy ROMs to a target 

26 BUILD = "build" # Drive rom-farmer builds 

27 TARGET = "target" # Target management (setup, migrate, audit) 

28 CURATION = "curation" # Game lists, cultural picks, recommendations 

29 MAINTENANCE = "maintenance" # Cleanup, sync, verify, repair 

30 SCRIPTING = "scripting" # Reusable scripts / shell tools 

31 WORKFLOW = "workflow" # Multi-step orchestration across tools 

32 

33 

34class StepAction(str, enum.Enum): 

35 """What kind of action a procedure step performs.""" 

36 

37 MCP_CALL = "mcp_call" # Call an MCP tool 

38 SHELL = "shell" # Run a shell command (local or remote) 

39 SSH = "ssh" # Run a command on a remote target 

40 PYTHON = "python" # Execute a Python snippet 

41 SKILL = "skill" # Invoke another skill (composition) 

42 CONDITIONAL = "conditional" # Branch based on a condition 

43 PROMPT = "prompt" # Ask the agent to decide something 

44 

45 

46# --------------------------------------------------------------------------- 

47# Skill parameter definition 

48# --------------------------------------------------------------------------- 

49 

50 

51class SkillParam(BaseModel): 

52 """A parameter that a skill accepts. 

53 

54 Parameters use Jinja2-style template variables in procedures: 

55 ``{{platform}}``, ``{{budget_gb}}``, etc. 

56 """ 

57 

58 name: str = Field(description="Parameter name (used as template variable)") 

59 type: str = Field( 

60 default="string", 

61 description="Parameter type: string, number, boolean, list, path", 

62 ) 

63 description: str = Field(default="", description="What this parameter controls") 

64 required: bool = Field(default=False, description="Must be provided to run") 

65 default: Any = Field(default=None, description="Default value if not provided") 

66 enum: list[str] = Field( 

67 default_factory=list, 

68 description="Allowed values (empty = any)", 

69 ) 

70 

71 

72# --------------------------------------------------------------------------- 

73# Procedure step 

74# --------------------------------------------------------------------------- 

75 

76 

77class SkillStep(BaseModel): 

78 """A single step in a skill's procedure. 

79 

80 Steps form a linear sequence by default. Use ``depends_on`` to 

81 define DAG-style dependencies or ``condition`` for branches. 

82 """ 

83 

84 id: str = Field(description="Unique step identifier within the procedure") 

85 description: str = Field(default="", description="Human-readable explanation") 

86 action: StepAction = Field(description="What kind of action to perform") 

87 

88 # -- Action-specific fields (only relevant fields need to be set) -- 

89 tool: str = Field(default="", description="MCP tool name (for mcp_call actions)") 

90 command: str = Field( 

91 default="", 

92 description="Shell/SSH command template (for shell/ssh actions)", 

93 ) 

94 args: dict[str, Any] = Field( 

95 default_factory=dict, 

96 description="Arguments for MCP calls (supports {{param}} templates)", 

97 ) 

98 code: str = Field( 

99 default="", 

100 description="Python code snippet (for python actions)", 

101 ) 

102 skill_name: str = Field( 

103 default="", 

104 description="Name of skill to invoke (for skill actions)", 

105 ) 

106 skill_args: dict[str, Any] = Field( 

107 default_factory=dict, 

108 description="Arguments to pass to sub-skill", 

109 ) 

110 

111 # -- Control flow -- 

112 condition: str = Field( 

113 default="", 

114 description="Jinja2 expression; step runs only if truthy", 

115 ) 

116 depends_on: list[str] = Field( 

117 default_factory=list, 

118 description="Step IDs that must complete first", 

119 ) 

120 on_failure: str = Field( 

121 default="abort", 

122 description="What to do on failure: abort, skip, retry, rollback", 

123 ) 

124 retries: int = Field(default=0, description="Number of retry attempts") 

125 

126 # -- Output capture -- 

127 outputs: list[str] = Field( 

128 default_factory=list, 

129 description="Variable names to capture from step result", 

130 ) 

131 expect_exit: int | None = Field( 

132 default=None, 

133 description="Expected exit code (for shell/ssh; None = don't check)", 

134 ) 

135 

136 

137# --------------------------------------------------------------------------- 

138# Artifact — files bundled with the skill 

139# --------------------------------------------------------------------------- 

140 

141 

142class SkillArtifact(BaseModel): 

143 """A file bundled with a skill — a script, list, config, template, etc. 

144 

145 Artifacts live in the skill folder alongside SKILL.md and procedure.yaml. 

146 They can be referenced by procedure steps via relative path. 

147 """ 

148 

149 filename: str = Field(description="Filename relative to skill folder") 

150 description: str = Field(default="", description="What this artifact is for") 

151 artifact_type: str = Field( 

152 default="file", 

153 description="Type: script, list, config, template, data", 

154 ) 

155 executable: bool = Field( 

156 default=False, 

157 description="Whether this file should be chmod +x on deploy", 

158 ) 

159 

160 

161# --------------------------------------------------------------------------- 

162# Skill metadata (maps to SKILL.md frontmatter) 

163# --------------------------------------------------------------------------- 

164 

165 

166class SkillMeta(BaseModel): 

167 """Metadata extracted from / written to SKILL.md YAML frontmatter.""" 

168 

169 name: str = Field(description="Unique skill identifier (slug)") 

170 description: str = Field(description="One-line summary of what the skill does") 

171 version: str = Field(default="1.0.0", description="Semver version string") 

172 category: SkillCategory = Field( 

173 default=SkillCategory.WORKFLOW, 

174 description="Broad classification", 

175 ) 

176 author: str = Field( 

177 default="agent", 

178 description="Who created this: 'agent', 'user', or a name", 

179 ) 

180 created: datetime = Field( 

181 default_factory=datetime.now, 

182 description="When the skill was first created", 

183 ) 

184 updated: datetime = Field( 

185 default_factory=datetime.now, 

186 description="When the skill was last modified", 

187 ) 

188 

189 # -- Applicability -- 

190 tags: list[str] = Field( 

191 default_factory=list, 

192 description="Searchable tags: [deployment, budget, disc-based, ...]", 

193 ) 

194 platforms: list[str] = Field( 

195 default_factory=list, 

196 description="ROM platforms this skill applies to (empty = any)", 

197 ) 

198 targets: list[str] = Field( 

199 default_factory=list, 

200 description="Target frontends: [batocera, rocknix, ...] (empty = any)", 

201 ) 

202 

203 # -- Requirements -- 

204 params: list[SkillParam] = Field( 

205 default_factory=list, 

206 description="Parameters the skill accepts", 

207 ) 

208 preconditions: list[str] = Field( 

209 default_factory=list, 

210 description="Conditions that must be true before running", 

211 ) 

212 tools_used: list[str] = Field( 

213 default_factory=list, 

214 description="MCP tools / CLI commands this skill calls", 

215 ) 

216 artifacts: list[SkillArtifact] = Field( 

217 default_factory=list, 

218 description="Bundled files (scripts, lists, configs)", 

219 ) 

220 

221 

222# --------------------------------------------------------------------------- 

223# Full Skill — the loaded, ready-to-use object 

224# --------------------------------------------------------------------------- 

225 

226 

227class Skill(BaseModel): 

228 """A complete skill — metadata, procedure, and artifact info. 

229 

230 Loaded from a skill folder containing: 

231 SKILL.md — markdown contract with YAML frontmatter 

232 procedure.yaml — machine-readable steps 

233 (optional artifacts: scripts, lists, configs, etc.) 

234 """ 

235 

236 meta: SkillMeta = Field(description="Skill metadata from SKILL.md frontmatter") 

237 body: str = Field( 

238 default="", 

239 description="Markdown body from SKILL.md (after frontmatter)", 

240 ) 

241 steps: list[SkillStep] = Field( 

242 default_factory=list, 

243 description="Procedure steps from procedure.yaml", 

244 ) 

245 source_path: Path | None = Field( 

246 default=None, 

247 description="Filesystem path to the skill folder", 

248 ) 

249 is_builtin: bool = Field( 

250 default=False, 

251 description="True if loaded from bundled library (read-only)", 

252 ) 

253 

254 # -- Convenience -- 

255 

256 @property 

257 def name(self) -> str: 

258 return self.meta.name 

259 

260 @property 

261 def description(self) -> str: 

262 return self.meta.description 

263 

264 @property 

265 def category(self) -> SkillCategory: 

266 return self.meta.category 

267 

268 def get_required_params(self) -> list[SkillParam]: 

269 """Return parameters that must be provided.""" 

270 return [p for p in self.meta.params if p.required] 

271 

272 def get_param_defaults(self) -> dict[str, Any]: 

273 """Return a dict of param_name → default_value for all params with defaults.""" 

274 return {p.name: p.default for p in self.meta.params if p.default is not None} 

275 

276 def get_artifacts_by_type(self, artifact_type: str) -> list[SkillArtifact]: 

277 """Filter artifacts by type (script, list, config, etc.).""" 

278 return [a for a in self.meta.artifacts if a.artifact_type == artifact_type] 

279 

280 def has_procedure(self) -> bool: 

281 """Whether this skill has machine-readable steps.""" 

282 return len(self.steps) > 0 

283 

284 def summary(self) -> str: 

285 """One-line summary for display.""" 

286 parts = [f"[{self.meta.category.value}]", self.meta.name] 

287 if self.meta.description: 

288 parts.append(f"— {self.meta.description}") 

289 n_steps = len(self.steps) 

290 n_artifacts = len(self.meta.artifacts) 

291 extras = [] 

292 if n_steps: 

293 extras.append(f"{n_steps} steps") 

294 if n_artifacts: 

295 extras.append(f"{n_artifacts} artifacts") 

296 if extras: 

297 parts.append(f"({', '.join(extras)})") 

298 return " ".join(parts)