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

250 statements  

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

1"""SkillStore — load, search, and manage Farm-Hand skills. 

2 

3Dual-path resolution: 

4 1. library/ — bundled seed skills shipped with farm-hand (read-only) 

5 2. config/farmhand/skills/ — agent-created / user-edited (read-write) 

6 

7Agent-created skills shadow bundled ones with the same name. 

8""" 

9 

10from __future__ import annotations 

11 

12import logging 

13import re 

14import shutil 

15from datetime import datetime 

16from pathlib import Path 

17from typing import Any 

18 

19import yaml 

20 

21from romfarmer.farmhand.skills.models import ( 

22 Skill, 

23 SkillArtifact, 

24 SkillCategory, 

25 SkillMeta, 

26 SkillParam, 

27 SkillStep, 

28) 

29 

30logger = logging.getLogger(__name__) 

31 

32# --------------------------------------------------------------------------- 

33# YAML frontmatter parsing 

34# --------------------------------------------------------------------------- 

35 

36_FRONTMATTER_RE = re.compile( 

37 r"^---\s*\n(.*?)\n---\s*\n?(.*)", 

38 re.DOTALL, 

39) 

40 

41 

42def _parse_skill_md(text: str) -> tuple[dict[str, Any], str]: 

43 """Parse SKILL.md into (frontmatter_dict, body_markdown).""" 

44 m = _FRONTMATTER_RE.match(text) 

45 if not m: 

46 return {}, text 

47 raw_fm = m.group(1) 

48 body = m.group(2) 

49 try: 

50 fm = yaml.safe_load(raw_fm) or {} 

51 except yaml.YAMLError as exc: 

52 logger.warning("Failed to parse SKILL.md frontmatter: %s", exc) 

53 fm = {} 

54 return fm, body 

55 

56 

57def _frontmatter_to_meta(fm: dict[str, Any]) -> SkillMeta: 

58 """Convert parsed frontmatter dict to a SkillMeta model.""" 

59 # Normalize params from dict-of-dicts to list-of-SkillParam 

60 raw_params = fm.pop("params", {}) 

61 params: list[SkillParam] = [] 

62 if isinstance(raw_params, dict): 

63 for pname, pdef in raw_params.items(): 

64 if isinstance(pdef, dict): 

65 params.append(SkillParam(name=pname, **pdef)) 

66 else: 

67 params.append(SkillParam(name=pname, default=pdef)) 

68 elif isinstance(raw_params, list): 

69 for item in raw_params: 

70 if isinstance(item, dict) and "name" in item: 

71 params.append(SkillParam(**item)) 

72 

73 # Normalize artifacts 

74 raw_artifacts = fm.pop("artifacts", []) 

75 artifacts: list[SkillArtifact] = [] 

76 for art in raw_artifacts: 

77 if isinstance(art, dict): 

78 artifacts.append(SkillArtifact(**art)) 

79 elif isinstance(art, str): 

80 artifacts.append(SkillArtifact(filename=art)) 

81 

82 # Normalize category 

83 raw_cat = fm.pop("category", "workflow") 

84 try: 

85 category = SkillCategory(raw_cat) 

86 except ValueError: 

87 category = SkillCategory.WORKFLOW 

88 

89 return SkillMeta( 

90 category=category, 

91 params=params, 

92 artifacts=artifacts, 

93 **{k: v for k, v in fm.items() if k in SkillMeta.model_fields}, 

94 ) 

95 

96 

97def _meta_to_frontmatter(meta: SkillMeta) -> str: 

98 """Serialize SkillMeta back to YAML frontmatter string.""" 

99 data: dict[str, Any] = { 

100 "name": meta.name, 

101 "description": meta.description, 

102 "version": meta.version, 

103 "category": meta.category.value, 

104 "author": meta.author, 

105 "created": meta.created.isoformat(), 

106 "updated": meta.updated.isoformat(), 

107 } 

108 if meta.tags: 

109 data["tags"] = meta.tags 

110 if meta.platforms: 

111 data["platforms"] = meta.platforms 

112 if meta.targets: 

113 data["targets"] = meta.targets 

114 if meta.preconditions: 

115 data["preconditions"] = meta.preconditions 

116 if meta.tools_used: 

117 data["tools_used"] = meta.tools_used 

118 

119 # Params as dict-of-dicts (compact frontmatter style) 

120 if meta.params: 

121 params_dict: dict[str, Any] = {} 

122 for p in meta.params: 

123 pdef: dict[str, Any] = {"type": p.type} 

124 if p.description: 

125 pdef["description"] = p.description 

126 if p.required: 

127 pdef["required"] = True 

128 if p.default is not None: 

129 pdef["default"] = p.default 

130 if p.enum: 

131 pdef["enum"] = p.enum 

132 params_dict[p.name] = pdef 

133 data["params"] = params_dict 

134 

135 # Artifacts 

136 if meta.artifacts: 

137 data["artifacts"] = [ 

138 { 

139 "filename": a.filename, 

140 "description": a.description, 

141 "artifact_type": a.artifact_type, 

142 **({"executable": True} if a.executable else {}), 

143 } 

144 for a in meta.artifacts 

145 ] 

146 

147 return yaml.dump(data, default_flow_style=False, sort_keys=False, width=120) 

148 

149 

150# --------------------------------------------------------------------------- 

151# Procedure YAML loading / saving 

152# --------------------------------------------------------------------------- 

153 

154 

155def _load_procedure(path: Path) -> list[SkillStep]: 

156 """Load procedure.yaml from a skill folder.""" 

157 proc_file = path / "procedure.yaml" 

158 if not proc_file.exists(): 

159 return [] 

160 try: 

161 raw = yaml.safe_load(proc_file.read_text(encoding="utf-8")) or {} 

162 except yaml.YAMLError as exc: 

163 logger.warning("Failed to parse procedure.yaml in %s: %s", path, exc) 

164 return [] 

165 

166 steps_raw = raw.get("steps", []) 

167 steps: list[SkillStep] = [] 

168 for step_dict in steps_raw: 

169 if isinstance(step_dict, dict): 

170 try: 

171 steps.append(SkillStep(**step_dict)) 

172 except Exception as exc: 

173 logger.warning("Skipping invalid step in %s: %s", path, exc) 

174 return steps 

175 

176 

177def _save_procedure(steps: list[SkillStep], path: Path) -> None: 

178 """Save procedure steps to procedure.yaml.""" 

179 if not steps: 

180 return 

181 proc_file = path / "procedure.yaml" 

182 data = { 

183 "steps": [{k: v for k, v in step.model_dump(mode="json").items() if v} for step in steps] 

184 } 

185 proc_file.write_text( 

186 yaml.dump(data, default_flow_style=False, sort_keys=False, width=120), 

187 encoding="utf-8", 

188 ) 

189 

190 

191# --------------------------------------------------------------------------- 

192# SkillStore 

193# --------------------------------------------------------------------------- 

194 

195 

196class SkillStore: 

197 """Load, search, and manage Farm-Hand skills. 

198 

199 Parameters 

200 ---------- 

201 workspace_root 

202 Root of the rom-farmer project (for resolving config/ paths). 

203 library_path 

204 Path to the bundled skill library (defaults to skills/library/ 

205 within the farmhand package). 

206 user_path 

207 Path to user/agent-created skills (defaults to 

208 config/farmhand/skills/ under workspace_root). 

209 """ 

210 

211 def __init__( 

212 self, 

213 workspace_root: Path | None = None, 

214 library_path: Path | None = None, 

215 user_path: Path | None = None, 

216 ) -> None: 

217 self._workspace_root = workspace_root or Path.cwd() 

218 

219 self._library_path = library_path or (Path(__file__).parent / "library") 

220 self._user_path = user_path or (self._workspace_root / "config" / "farmhand" / "skills") 

221 

222 # Lazy-loaded cache 

223 self._cache: dict[str, Skill] = {} 

224 self._loaded = False 

225 

226 @property 

227 def library_path(self) -> Path: 

228 return self._library_path 

229 

230 @property 

231 def user_path(self) -> Path: 

232 return self._user_path 

233 

234 # -- Loading --------------------------------------------------------------- 

235 

236 def _ensure_loaded(self) -> None: 

237 """Load all skills from both paths (lazy, on first access).""" 

238 if self._loaded: 

239 return 

240 self._cache.clear() 

241 

242 # Load bundled first (lower priority) 

243 if self._library_path.is_dir(): 

244 for skill_dir in sorted(self._library_path.iterdir()): 

245 if skill_dir.is_dir() and self._has_skill_md(skill_dir): 

246 skill = self._load_skill_from_dir(skill_dir, is_builtin=True) 

247 if skill: 

248 self._cache[skill.name] = skill 

249 

250 # Load user skills (higher priority — shadows bundled) 

251 if self._user_path.is_dir(): 

252 for skill_dir in sorted(self._user_path.iterdir()): 

253 if skill_dir.is_dir() and self._has_skill_md(skill_dir): 

254 skill = self._load_skill_from_dir(skill_dir, is_builtin=False) 

255 if skill: 

256 self._cache[skill.name] = skill 

257 

258 self._loaded = True 

259 logger.info( 

260 "Loaded %d skills (%d bundled, %d user)", 

261 len(self._cache), 

262 sum(1 for s in self._cache.values() if s.is_builtin), 

263 sum(1 for s in self._cache.values() if not s.is_builtin), 

264 ) 

265 

266 @staticmethod 

267 def _has_skill_md(path: Path) -> bool: 

268 """Check if a directory contains a SKILL.md.""" 

269 return (path / "SKILL.md").exists() or (path / "skill.md").exists() 

270 

271 @staticmethod 

272 def _find_skill_md(path: Path) -> Path | None: 

273 """Find the SKILL.md file in a directory (case-flexible).""" 

274 for name in ("SKILL.md", "skill.md"): 

275 p = path / name 

276 if p.exists(): 

277 return p 

278 return None 

279 

280 def _load_skill_from_dir(self, path: Path, is_builtin: bool = False) -> Skill | None: 

281 """Load a Skill from a directory.""" 

282 skill_md = self._find_skill_md(path) 

283 if not skill_md: 

284 return None 

285 try: 

286 text = skill_md.read_text(encoding="utf-8") 

287 fm, body = _parse_skill_md(text) 

288 if "name" not in fm: 

289 fm["name"] = path.name # Use folder name as fallback 

290 meta = _frontmatter_to_meta(fm) 

291 steps = _load_procedure(path) 

292 return Skill( 

293 meta=meta, 

294 body=body, 

295 steps=steps, 

296 source_path=path, 

297 is_builtin=is_builtin, 

298 ) 

299 except Exception as exc: 

300 logger.warning("Failed to load skill from %s: %s", path, exc) 

301 return None 

302 

303 def reload(self) -> None: 

304 """Force reload of all skills from disk.""" 

305 self._loaded = False 

306 self._ensure_loaded() 

307 

308 # -- Query ---------------------------------------------------------------- 

309 

310 def list_all(self) -> list[Skill]: 

311 """Return all loaded skills.""" 

312 self._ensure_loaded() 

313 return list(self._cache.values()) 

314 

315 def get(self, name: str) -> Skill | None: 

316 """Get a skill by exact name.""" 

317 self._ensure_loaded() 

318 return self._cache.get(name) 

319 

320 def search( 

321 self, 

322 query: str = "", 

323 category: SkillCategory | None = None, 

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

325 platform: str | None = None, 

326 target: str | None = None, 

327 ) -> list[Skill]: 

328 """Search skills by text query, category, tags, platform, target. 

329 

330 Text query matches against name, description, and tags (case-insensitive). 

331 All filters are AND-combined. 

332 """ 

333 self._ensure_loaded() 

334 results: list[Skill] = [] 

335 query_lower = query.lower() 

336 

337 for skill in self._cache.values(): 

338 # Text match 

339 if query_lower: 

340 searchable = " ".join( 

341 [ 

342 skill.meta.name, 

343 skill.meta.description, 

344 " ".join(skill.meta.tags), 

345 skill.meta.category.value, 

346 ] 

347 ).lower() 

348 if query_lower not in searchable: 

349 continue 

350 

351 # Category filter 

352 if category and skill.meta.category != category: 

353 continue 

354 

355 # Tag filter (any match) 

356 if tags: 

357 skill_tags = {t.lower() for t in skill.meta.tags} 

358 if not any(t.lower() in skill_tags for t in tags): 

359 continue 

360 

361 # Platform filter 

362 if platform: 

363 if skill.meta.platforms and platform.lower() not in [ 

364 p.lower() for p in skill.meta.platforms 

365 ]: 

366 continue 

367 

368 # Target frontend filter 

369 if target: 

370 if skill.meta.targets and target.lower() not in [ 

371 t.lower() for t in skill.meta.targets 

372 ]: 

373 continue 

374 

375 results.append(skill) 

376 

377 return results 

378 

379 def list_categories(self) -> dict[SkillCategory, int]: 

380 """Return category → count mapping.""" 

381 self._ensure_loaded() 

382 counts: dict[SkillCategory, int] = {} 

383 for skill in self._cache.values(): 

384 counts[skill.meta.category] = counts.get(skill.meta.category, 0) + 1 

385 return counts 

386 

387 def list_tags(self) -> dict[str, int]: 

388 """Return tag → count mapping across all skills.""" 

389 self._ensure_loaded() 

390 counts: dict[str, int] = {} 

391 for skill in self._cache.values(): 

392 for tag in skill.meta.tags: 

393 counts[tag] = counts.get(tag, 0) + 1 

394 return counts 

395 

396 # -- CRUD (user skills only) ----------------------------------------------- 

397 

398 def save(self, skill: Skill) -> Path: 

399 """Save a skill to the user skills directory. 

400 

401 Creates or updates the skill folder with SKILL.md, procedure.yaml, 

402 and any artifact files. 

403 

404 Returns the path to the saved skill folder. 

405 """ 

406 skill_dir = self._user_path / skill.meta.name 

407 skill_dir.mkdir(parents=True, exist_ok=True) 

408 

409 # Write SKILL.md 

410 skill.meta.updated = datetime.now() 

411 frontmatter = _meta_to_frontmatter(skill.meta) 

412 skill_md = f"---\n{frontmatter}---\n\n{skill.body}" 

413 (skill_dir / "SKILL.md").write_text(skill_md, encoding="utf-8") 

414 

415 # Write procedure.yaml 

416 if skill.steps: 

417 _save_procedure(skill.steps, skill_dir) 

418 

419 # Update cache 

420 saved_skill = skill.model_copy(update={"source_path": skill_dir, "is_builtin": False}) 

421 self._cache[skill.meta.name] = saved_skill 

422 

423 logger.info("Saved skill '%s' to %s", skill.meta.name, skill_dir) 

424 return skill_dir 

425 

426 def save_artifact(self, skill_name: str, filename: str, content: str | bytes) -> Path: 

427 """Save an artifact file to a skill's folder. 

428 

429 Parameters 

430 ---------- 

431 skill_name 

432 Name of the skill to add the artifact to. 

433 filename 

434 Relative filename within the skill folder. 

435 content 

436 File content (str for text, bytes for binary). 

437 

438 Returns the path to the saved artifact. 

439 """ 

440 skill_dir = self._user_path / skill_name 

441 skill_dir.mkdir(parents=True, exist_ok=True) 

442 artifact_path = skill_dir / filename 

443 

444 # Create subdirectories if needed 

445 artifact_path.parent.mkdir(parents=True, exist_ok=True) 

446 

447 if isinstance(content, bytes): 

448 artifact_path.write_bytes(content) 

449 else: 

450 artifact_path.write_text(content, encoding="utf-8") 

451 

452 logger.info("Saved artifact '%s' for skill '%s'", filename, skill_name) 

453 return artifact_path 

454 

455 def delete(self, name: str) -> bool: 

456 """Delete a user skill (cannot delete bundled skills). 

457 

458 Returns True if deleted, False if not found or is builtin. 

459 """ 

460 skill = self._cache.get(name) 

461 if not skill: 

462 return False 

463 if skill.is_builtin: 

464 logger.warning("Cannot delete bundled skill '%s'", name) 

465 return False 

466 if skill.source_path and skill.source_path.exists(): 

467 shutil.rmtree(skill.source_path) 

468 self._cache.pop(name, None) 

469 logger.info("Deleted skill '%s'", name) 

470 return True 

471 

472 def get_artifact_path(self, skill_name: str, filename: str) -> Path | None: 

473 """Resolve the full path to an artifact file in a skill. 

474 

475 Returns None if the skill or artifact doesn't exist. 

476 """ 

477 skill = self.get(skill_name) 

478 if not skill or not skill.source_path: 

479 return None 

480 artifact_path = skill.source_path / filename 

481 if artifact_path.exists(): 

482 return artifact_path 

483 return None 

484 

485 def get_artifact_content(self, skill_name: str, filename: str) -> str | None: 

486 """Read the text content of a skill artifact.""" 

487 path = self.get_artifact_path(skill_name, filename) 

488 if path: 

489 return path.read_text(encoding="utf-8") 

490 return None