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

141 statements  

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

1"""SkillCapture — auto-capture successful workflows as reusable skills. 

2 

3When the agent completes a multi-step workflow successfully, this module 

4distills the sequence of tool calls, commands, and decisions into a 

5Skill with a SKILL.md contract and procedure.yaml. 

6 

7Usage: 

8 recorder = SkillRecorder() 

9 recorder.start("deploy psx to batocera within 60GB budget") 

10 

11 # ... agent does work, recording each step ... 

12 recorder.record_step(action="mcp_call", tool="farmhand_connect", ...) 

13 recorder.record_step(action="shell", command="romfarmer build psx ...", ...) 

14 

15 # On success, capture as a skill 

16 skill = recorder.capture( 

17 name="deploy-psx-budget", 

18 category=SkillCategory.DEPLOYMENT, 

19 tags=["deployment", "budget", "disc-based"], 

20 ) 

21 store.save(skill) 

22""" 

23 

24from __future__ import annotations 

25 

26import logging 

27from datetime import datetime 

28from typing import Any 

29 

30from romfarmer.farmhand.skills.models import ( 

31 Skill, 

32 SkillArtifact, 

33 SkillCategory, 

34 SkillMeta, 

35 SkillParam, 

36 SkillStep, 

37 StepAction, 

38) 

39 

40logger = logging.getLogger(__name__) 

41 

42 

43# --------------------------------------------------------------------------- 

44# Step recording 

45# --------------------------------------------------------------------------- 

46 

47 

48class RecordedStep: 

49 """A single step captured during workflow execution.""" 

50 

51 def __init__( 

52 self, 

53 action: str, 

54 description: str = "", 

55 tool: str = "", 

56 command: str = "", 

57 args: dict[str, Any] | None = None, 

58 result: Any = None, 

59 exit_code: int | None = None, 

60 success: bool = True, 

61 duration_ms: int = 0, 

62 ) -> None: 

63 self.action = action 

64 self.description = description 

65 self.tool = tool 

66 self.command = command 

67 self.args = args or {} 

68 self.result = result 

69 self.exit_code = exit_code 

70 self.success = success 

71 self.duration_ms = duration_ms 

72 self.timestamp = datetime.now() 

73 

74 

75# --------------------------------------------------------------------------- 

76# SkillRecorder 

77# --------------------------------------------------------------------------- 

78 

79 

80class SkillRecorder: 

81 """Records agent actions during a workflow for later skill capture. 

82 

83 This is the primary interface the agent uses to build up a skill 

84 from a successful workflow execution. 

85 """ 

86 

87 def __init__(self) -> None: 

88 self._task_description: str = "" 

89 self._steps: list[RecordedStep] = [] 

90 self._artifacts: list[tuple[str, str, str]] = [] # (filename, content, type) 

91 self._params_observed: dict[str, Any] = {} 

92 self._tools_used: set[str] = set() 

93 self._started: datetime | None = None 

94 self._active = False 

95 

96 @property 

97 def is_active(self) -> bool: 

98 return self._active 

99 

100 @property 

101 def step_count(self) -> int: 

102 return len(self._steps) 

103 

104 def start(self, task_description: str) -> None: 

105 """Begin recording a new workflow. 

106 

107 Parameters 

108 ---------- 

109 task_description 

110 Natural language description of what the agent is doing. 

111 """ 

112 self._task_description = task_description 

113 self._steps.clear() 

114 self._artifacts.clear() 

115 self._params_observed.clear() 

116 self._tools_used.clear() 

117 self._started = datetime.now() 

118 self._active = True 

119 logger.info("Skill recording started: %s", task_description) 

120 

121 def record_step( 

122 self, 

123 action: str, 

124 description: str = "", 

125 tool: str = "", 

126 command: str = "", 

127 args: dict[str, Any] | None = None, 

128 result: Any = None, 

129 exit_code: int | None = None, 

130 success: bool = True, 

131 duration_ms: int = 0, 

132 ) -> None: 

133 """Record a single step in the workflow. 

134 

135 Parameters 

136 ---------- 

137 action 

138 Step type: "mcp_call", "shell", "ssh", "python", "decision" 

139 description 

140 Human-readable explanation of what this step does. 

141 tool 

142 MCP tool name (for mcp_call actions). 

143 command 

144 Shell/SSH command (for shell/ssh actions). 

145 args 

146 Arguments passed to MCP tools. 

147 result 

148 The output/result of the step. 

149 exit_code 

150 Shell command exit code (None for non-shell steps). 

151 success 

152 Whether the step succeeded. 

153 duration_ms 

154 How long the step took in milliseconds. 

155 """ 

156 if not self._active: 

157 logger.warning("record_step called but recorder is not active") 

158 return 

159 

160 step = RecordedStep( 

161 action=action, 

162 description=description, 

163 tool=tool, 

164 command=command, 

165 args=args, 

166 result=result, 

167 exit_code=exit_code, 

168 success=success, 

169 duration_ms=duration_ms, 

170 ) 

171 self._steps.append(step) 

172 

173 if tool: 

174 self._tools_used.add(tool) 

175 

176 def record_param(self, name: str, value: Any) -> None: 

177 """Record a parameter value observed during the workflow. 

178 

179 These become template variables in the captured procedure. 

180 """ 

181 self._params_observed[name] = value 

182 

183 def record_artifact( 

184 self, 

185 filename: str, 

186 content: str, 

187 artifact_type: str = "file", 

188 description: str = "", 

189 ) -> None: 

190 """Record a file artifact created during the workflow. 

191 

192 Parameters 

193 ---------- 

194 filename 

195 Relative filename for the artifact. 

196 content 

197 File content as text. 

198 artifact_type 

199 Type: script, list, config, template, data. 

200 description 

201 What this artifact is for. 

202 """ 

203 self._artifacts.append((filename, content, artifact_type)) 

204 

205 def cancel(self) -> None: 

206 """Cancel the current recording without capturing.""" 

207 self._active = False 

208 self._steps.clear() 

209 self._artifacts.clear() 

210 logger.info("Skill recording cancelled") 

211 

212 # -- Capture --------------------------------------------------------------- 

213 

214 def capture( 

215 self, 

216 name: str, 

217 description: str = "", 

218 category: SkillCategory = SkillCategory.WORKFLOW, 

219 tags: list[str] | None = None, 

220 platforms: list[str] | None = None, 

221 targets: list[str] | None = None, 

222 preconditions: list[str] | None = None, 

223 ) -> Skill: 

224 """Distill the recorded workflow into a reusable Skill. 

225 

226 Analyzes the recorded steps to: 

227 - Extract template parameters from observed values 

228 - Build a procedure.yaml from the step sequence 

229 - Generate a SKILL.md body from step descriptions 

230 - Collect artifact metadata 

231 

232 Parameters 

233 ---------- 

234 name 

235 Skill slug (lowercase, hyphens). 

236 description 

237 One-line summary. Defaults to the task description. 

238 category 

239 Skill category. 

240 tags, platforms, targets, preconditions 

241 Optional metadata filters. 

242 

243 Returns 

244 ------- 

245 Skill 

246 The captured skill, ready to save via SkillStore.save(). 

247 """ 

248 if not self._active: 

249 raise RuntimeError("Cannot capture — recorder is not active") 

250 

251 if not description: 

252 description = self._task_description 

253 

254 # Build params from observed values 

255 params = self._extract_params() 

256 

257 # Build procedure steps 

258 steps = self._build_procedure(params) 

259 

260 # Build artifacts list 

261 artifacts = [ 

262 SkillArtifact( 

263 filename=fname, 

264 artifact_type=atype, 

265 description="", 

266 executable=atype == "script", 

267 ) 

268 for fname, _, atype in self._artifacts 

269 ] 

270 

271 # Generate markdown body 

272 body = self._generate_body() 

273 

274 meta = SkillMeta( 

275 name=name, 

276 description=description, 

277 category=category, 

278 author="agent", 

279 created=self._started or datetime.now(), 

280 updated=datetime.now(), 

281 tags=tags or [], 

282 platforms=platforms or [], 

283 targets=targets or [], 

284 params=params, 

285 preconditions=preconditions or [], 

286 tools_used=sorted(self._tools_used), 

287 artifacts=artifacts, 

288 ) 

289 

290 skill = Skill(meta=meta, body=body, steps=steps) 

291 

292 self._active = False 

293 logger.info( 

294 "Captured skill '%s' with %d steps and %d artifacts", 

295 name, 

296 len(steps), 

297 len(artifacts), 

298 ) 

299 return skill 

300 

301 # -- Internal helpers ------------------------------------------------------ 

302 

303 def _extract_params(self) -> list[SkillParam]: 

304 """Convert observed parameter values into SkillParam definitions.""" 

305 params: list[SkillParam] = [] 

306 for pname, pvalue in self._params_observed.items(): 

307 ptype = "string" 

308 if isinstance(pvalue, bool): 

309 ptype = "boolean" 

310 elif isinstance(pvalue, (int, float)): 

311 ptype = "number" 

312 elif isinstance(pvalue, list): 

313 ptype = "list" 

314 

315 params.append( 

316 SkillParam( 

317 name=pname, 

318 type=ptype, 

319 required=True, 

320 default=pvalue, 

321 ) 

322 ) 

323 return params 

324 

325 def _build_procedure(self, params: list[SkillParam]) -> list[SkillStep]: 

326 """Convert recorded steps into templatized SkillSteps. 

327 

328 Replaces observed parameter values with ``{{param_name}}`` 

329 template variables in commands and args. 

330 """ 

331 param_values = {p.name: self._params_observed[p.name] for p in params} 

332 steps: list[SkillStep] = [] 

333 

334 for i, recorded in enumerate(self._steps): 

335 if not recorded.success: 

336 continue # Skip failed steps 

337 

338 step_id = recorded.tool or f"step_{i + 1}" 

339 # Deduplicate step IDs 

340 existing_ids = {s.id for s in steps} 

341 if step_id in existing_ids: 

342 step_id = f"{step_id}_{i + 1}" 

343 

344 try: 

345 action = StepAction(recorded.action) 

346 except ValueError: 

347 action = StepAction.SHELL 

348 

349 # Templatize command 

350 command = self._templatize(recorded.command, param_values) 

351 

352 # Templatize args 

353 args = {} 

354 for k, v in recorded.args.items(): 

355 if isinstance(v, str): 

356 args[k] = self._templatize(v, param_values) 

357 else: 

358 args[k] = v 

359 

360 steps.append( 

361 SkillStep( 

362 id=step_id, 

363 description=recorded.description, 

364 action=action, 

365 tool=recorded.tool, 

366 command=command, 

367 args=args, 

368 expect_exit=recorded.exit_code 

369 if action in (StepAction.SHELL, StepAction.SSH) 

370 else None, 

371 ) 

372 ) 

373 

374 return steps 

375 

376 @staticmethod 

377 def _templatize(text: str, param_values: dict[str, Any]) -> str: 

378 """Replace concrete parameter values with {{param}} templates. 

379 

380 Longer values are replaced first to avoid partial matches. 

381 """ 

382 if not text or not param_values: 

383 return text 

384 

385 # Sort by value length descending (replace longer values first) 

386 sorted_params = sorted( 

387 param_values.items(), 

388 key=lambda kv: len(str(kv[1])), 

389 reverse=True, 

390 ) 

391 for pname, pvalue in sorted_params: 

392 str_val = str(pvalue) 

393 if str_val and str_val in text: 

394 text = text.replace(str_val, "{{" + pname + "}}") 

395 return text 

396 

397 def _generate_body(self) -> str: 

398 """Generate SKILL.md body markdown from recorded steps.""" 

399 lines: list[str] = [] 

400 

401 # Title 

402 clean_desc = self._task_description or "Untitled Workflow" 

403 lines.append(f"# {clean_desc}") 

404 lines.append("") 

405 

406 # When to use 

407 lines.append("## When to use") 

408 lines.append(f"Use this skill when you need to: {clean_desc.lower()}") 

409 lines.append("") 

410 

411 # Steps 

412 lines.append("## Steps") 

413 for i, step in enumerate(self._steps, 1): 

414 if not step.success: 

415 continue 

416 desc = step.description or step.tool or step.command[:60] 

417 lines.append(f"{i}. {desc}") 

418 lines.append("") 

419 

420 # Artifacts 

421 if self._artifacts: 

422 lines.append("## Artifacts") 

423 for fname, _, atype in self._artifacts: 

424 lines.append(f"- `{fname}` ({atype})") 

425 lines.append("") 

426 

427 # Known issues 

428 lines.append("## Known issues") 

429 lines.append("<!-- Add known issues and edge cases here -->") 

430 lines.append("") 

431 

432 return "\n".join(lines)