Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(ide): add a skill library of saved Markdown prompts for terminal panes
rubenluetke10-beepf27be73befe4
diff --git a/jarvis/agentic_ide/skill_library.py b/jarvis/agentic_ide/skill_library.pynew file mode 100644index 0000000000..7fa2769003--- /dev/null+++ b/jarvis/agentic_ide/skill_library.py@@ -0,0 +1,397 @@+"""The Agentic IDE's skill library — saved Markdown prompts for terminal panes.++A skill here is a titled piece of Markdown the user keeps at hand: a review+checklist, a house style, a SKILL.md they collected somewhere. The IDE's+Skills tab lists them, and dragging one onto a terminal pane pastes its text+into that pane's prompt (never submitted — the user still says what to do).++This is deliberately NOT the assistant's skill system (``jarvis.skills``):+those are capabilities Jarvis itself runs, with lifecycle states and a+registry. These are inert text the user hands to whichever coding agent they+choose, so they live in their own small store and never enter a tool set.++Storage is one JSON sidecar under ``user_data_dir()/data/`` written atomically+(tempfile + ``os.replace``), the same discipline as the STT dictionary. The+order of the list is the user's order; new skills join at the top.+"""+from __future__ import annotations++import dataclasses+import json+import logging+import os+import re+import tempfile+import uuid+from dataclasses import dataclass+from datetime import UTC, datetime+from pathlib import Path+from typing import Any++from jarvis.core.paths import user_data_dir++log = logging.getLogger(__name__)++# Abuse guards, not product limits — generous for any real collection.+MAX_SKILLS = 500+MAX_TITLE_LEN = 120+MAX_DESCRIPTION_LEN = 280+MAX_CONTENT_CHARS = 200_000++#: The palette slots the UI paints a skill with. Names, not colours: the+#: frontend maps each onto its own theme tokens so both modes stay legible.+HUES: tuple[str, ...] = (+ "blue",+ "violet",+ "teal",+ "amber",+ "rose",+ "green",+ "magenta",+ "slate",+)++#: Glyph names the UI knows how to draw. Anything else falls back to "auto".+ICONS: tuple[str, ...] = (+ "auto",+ "sparkles",+ "code",+ "bug",+ "book",+ "shield",+ "rocket",+ "wand",+ "brain",+ "flask",+ "palette",+ "terminal",+ "git",+ "list",+)++_FRONTMATTER_RE = re.compile(r"\A?---[ \t]*\r?\n(.*?)\r?\n---[ \t]*(?:\r?\n|\Z)", re.DOTALL)+_HEADING_RE = re.compile(r"^\s{0,3}#{1,6}\s+(.+?)\s*#*\s*$")+++def skill_library_path() -> Path:+ """JSON sidecar holding the IDE's skill library."""+ return user_data_dir() / "data" / "ide_skills.json"+++def _now_iso() -> str:+ return datetime.now(UTC).isoformat(timespec="seconds")+++def _clean_line(value: str, limit: int) -> str:+ return " ".join(value.split())[:limit].strip()+++def _frontmatter_field(frontmatter: str, key: str) -> str:+ """One scalar field of a YAML frontmatter block, read without a YAML parser.++ Only ``key: value`` on one line (quotes stripped) is understood — enough for+ the ``name``/``description`` every SKILL.md carries, and nothing here ever+ executes or trusts what it reads.+ """+ match = re.search(rf"^{re.escape(key)}\s*:\s*(.+?)\s*$", frontmatter, re.MULTILINE)+ if not match:+ return ""+ value = match.group(1).strip()+ if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":+ value = value[1:-1]+ # A folded block scalar (`description: >-`) carries its text on the next lines.+ if value in {">", ">-", "|", "|-"}:+ rest = frontmatter[match.end():].splitlines()+ folded: list[str] = []+ for line in rest:+ if line.strip() and not line.startswith((" ", "\t")):+ break+ folded.append(line.strip())+ value = " ".join(part for part in folded if part)+ return value+++def derive_title(content: str, fallback: str = "") -> str:+ """The title a pasted or imported Markdown text suggests for itself.++ Frontmatter ``name`` first (a SKILL.md), then the first heading, then the+ caller's fallback (an imported file's name), then the first line.+ """+ match = _FRONTMATTER_RE.match(content)+ if match:+ name = _frontmatter_field(match.group(1), "name")+ if name:+ return _clean_line(name, MAX_TITLE_LEN)+ body = content[match.end():]+ else:+ body = content+ for line in body.splitlines():+ heading = _HEADING_RE.match(line)+ if heading:+ return _clean_line(heading.group(1), MAX_TITLE_LEN)+ if fallback.strip():+ return _clean_line(fallback, MAX_TITLE_LEN)+ for line in body.splitlines():+ if line.strip():+ return _clean_line(line.lstrip("#>-*` "), MAX_TITLE_LEN)+ return ""+++def derive_description(content: str) -> str:+ """A one-line summary: frontmatter ``description``, else the first prose line."""+ match = _FRONTMATTER_RE.match(content)+ if match:+ described = _frontmatter_field(match.group(1), "description")+ if described:+ return _clean_line(described, MAX_DESCRIPTION_LEN)+ body = content[match.end():]+ else:+ body = content+ in_fence = False+ for line in body.splitlines():+ stripped = line.strip()+ if stripped.startswith(("```", "~~~")):+ in_fence = not in_fence+ continue+ if in_fence or not stripped or _HEADING_RE.match(line):+ continue+ if stripped.startswith(("|", "---", "<!--")):+ continue+ plain = stripped.lstrip(">-*+ ").replace("**", "").replace("`", "")+ return _clean_line(plain, MAX_DESCRIPTION_LEN)+ return ""+++@dataclass(frozen=True)+class LibrarySkill:+ """One saved prompt. ``description`` is derived unless the user set one."""++ id: str+ title: str+ content: str+ description: str = ""+ hue: str = ""+ icon: str = "auto"+ created_at: str = ""+ updated_at: str = ""+ use_count: int = 0+ last_used_at: str | None = None++ def to_dict(self) -> dict[str, Any]:+ return dataclasses.asdict(self)++ @classmethod+ def from_dict(cls, raw: dict[str, Any]) -> LibrarySkill | None:+ try:+ skill_id = str(raw["id"]).strip()+ content = str(raw.get("content", ""))+ title = _clean_line(str(raw.get("title", "")), MAX_TITLE_LEN)+ except (KeyError, TypeError) as exc:+ # A hand-edited or half-migrated entry: skip it rather than lose the list.+ log.warning("IDE skill library: dropping unreadable entry (%s).", exc)+ return None+ if not skill_id or not title:+ return None+ hue = str(raw.get("hue") or "")+ icon = str(raw.get("icon") or "auto")+ try:+ uses = max(0, int(raw.get("use_count") or 0))+ except (TypeError, ValueError):+ uses = 0+ last_used = raw.get("last_used_at")+ return cls(+ id=skill_id,+ title=title,+ content=content[:MAX_CONTENT_CHARS],+ description=_clean_line(str(raw.get("description") or ""), MAX_DESCRIPTION_LEN),+ hue=hue if hue in HUES else _hue_for(skill_id),+ icon=icon if icon in ICONS else "auto",+ created_at=str(raw.get("created_at") or ""),+ updated_at=str(raw.get("updated_at") or ""),+ use_count=uses,+ last_used_at=str(last_used) if last_used else None,+ )+++def _hue_for(seed: str) -> str:+ """A stable palette slot for a skill that never picked one."""+ total = sum(ord(ch) for ch in seed)+ return HUES[total % len(HUES)]+++def _validated_content(content: str) -> str:+ if not content.strip():+ raise ValueError("A skill needs some Markdown text.")+ if len(content) > MAX_CONTENT_CHARS:+ raise ValueError(f"A skill can hold at most {MAX_CONTENT_CHARS:,} characters.")+ # Windows line endings would paste as doubled newlines into some CLIs.+ return content.replace("\r\n", "\n").replace("\r", "\n")+++def _validated_title(title: str) -> str:+ cleaned = _clean_line(title, MAX_TITLE_LEN)+ if not cleaned:+ raise ValueError("A skill needs a title.")+ return cleaned+++def _validated_choice(value: str | None, allowed: tuple[str, ...], field: str) -> str | None:+ if value is None:+ return None+ if value not in allowed:+ raise ValueError(f"Unknown {field} {value!r}.")+ return value+++class SkillLibrary:+ """Read-modify-write over the sidecar. Callers serialise with their own lock."""++ def __init__(self, path: Path | None = None) -> None:+ self._path = path or skill_library_path()++ def list_all(self) -> list[LibrarySkill]:+ try:+ raw = json.loads(self._path.read_text(encoding="utf-8"))+ except FileNotFoundError:+ return []+ except (OSError, ValueError) as exc:+ log.warning(+ "IDE skill library at %s is unreadable (%s); starting empty.", self._path, exc+ )+ return []+ entries = raw.get("skills", []) if isinstance(raw, dict) else []+ out: list[LibrarySkill] = []+ seen: set[str] = set()+ for entry in entries if isinstance(entries, list) else []:+ if not isinstance(entry, dict):+ continue+ skill = LibrarySkill.from_dict(entry)+ if skill is None or skill.id in seen:+ continue+ seen.add(skill.id)+ out.append(skill)+ return out++ def get(self, skill_id: str) -> LibrarySkill | None:+ return next((skill for skill in self.list_all() if skill.id == skill_id), None)++ def create(+ self,+ *,+ title: str,+ content: str,+ description: str | None = None,+ hue: str | None = None,+ icon: str | None = None,+ ) -> LibrarySkill:+ skills = self.list_all()+ if len(skills) >= MAX_SKILLS:+ raise ValueError(f"The library is full ({MAX_SKILLS} skills).")+ body = _validated_content(content)+ skill_id = uuid.uuid4().hex[:12]+ now = _now_iso()+ skill = LibrarySkill(+ id=skill_id,+ title=_validated_title(title),+ content=body,+ description=(+ _clean_line(description, MAX_DESCRIPTION_LEN)+ if description+ else derive_description(body)+ ),+ hue=_validated_choice(hue, HUES, "colour") or _hue_for(skill_id),+ icon=_validated_choice(icon, ICONS, "icon") or "auto",+ created_at=now,+ updated_at=now,+ )+ self._write([skill, *skills])+ return skill++ def update(+ self,+ skill_id: str,+ *,+ title: str | None = None,+ content: str | None = None,+ description: str | None = None,+ hue: str | None = None,+ icon: str | None = None,+ ) -> LibrarySkill | None:+ skills = self.list_all()+ for index, skill in enumerate(skills):+ if skill.id != skill_id:+ continue+ body = _validated_content(content) if content is not None else skill.content+ if description is not None:+ summary = _clean_line(description, MAX_DESCRIPTION_LEN)+ summary = summary or derive_description(body)+ elif content is not None:+ summary = derive_description(body)+ else:+ summary = skill.description+ updated = dataclasses.replace(+ skill,+ title=_validated_title(title) if title is not None else skill.title,+ content=body,+ description=summary,+ hue=_validated_choice(hue, HUES, "colour") or skill.hue,+ icon=_validated_choice(icon, ICONS, "icon") or skill.icon,+ updated_at=_now_iso(),+ )+ skills[index] = updated+ self._write(skills)+ return updated+ return None++ def mark_used(self, skill_id: str) -> LibrarySkill | None:+ """Count one paste into a terminal. Does not touch ``updated_at``."""+ skills = self.list_all()+ for index, skill in enumerate(skills):+ if skill.id != skill_id:+ continue+ used = dataclasses.replace(+ skill, use_count=skill.use_count + 1, last_used_at=_now_iso()+ )+ skills[index] = used+ self._write(skills)+ return used+ return None++ def reorder(self, ids: list[str]) -> list[LibrarySkill]:+ """Put the named skills first in the given order; the rest keep theirs."""+ skills = self.list_all()+ by_id = {skill.id: skill for skill in skills}+ ordered: list[LibrarySkill] = []+ for skill_id in ids:+ skill = by_id.pop(skill_id, None)+ if skill is not None:+ ordered.append(skill)+ ordered.extend(skill for skill in skills if skill.id in by_id)+ self._write(ordered)+ return ordered++ def delete(self, skill_id: str) -> bool:+ skills = self.list_all()+ kept = [skill for skill in skills if skill.id != skill_id]+ if len(kept) == len(skills):+ return False+ self._write(kept)+ return True++ def _write(self, skills: list[LibrarySkill]) -> None:+ payload = {"version": 1, "skills": [skill.to_dict() for skill in skills]}+ self._path.parent.mkdir(parents=True, exist_ok=True)+ # Atomic tempfile + os.replace: a crash mid-write never tears the list.+ fd, tmp_name = tempfile.mkstemp(+ dir=str(self._path.parent), prefix=".ide_skills_", suffix=".tmp"+ )+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as fh:+ json.dump(payload, fh, ensure_ascii=False, indent=2)+ os.replace(tmp_name, self._path)+ except Exception:+ try:+ os.unlink(tmp_name)+ except OSError:+ log.debug("IDE skill library: temp file %s already gone.", tmp_name)+ raisediff --git a/jarvis/ui/web/ide_skills_routes.py b/jarvis/ui/web/ide_skills_routes.pynew file mode 100644index 0000000000..7328fd4b7b--- /dev/null+++ b/jarvis/ui/web/ide_skills_routes.py@@ -0,0 +1,171 @@+"""REST API for the Agentic IDE's skill library (saved Markdown prompts).++Endpoints (mounted by the WebServer in ``_build_app()``):++ GET /api/agentic-ide/skills → {"skills": [...]} in the user's order.+ POST /api/agentic-ide/skills → save one; 201 (400 on bad input).+ POST /api/agentic-ide/skills/derive → title/description a text suggests.+ PUT /api/agentic-ide/skills/order → reorder by id.+ GET /api/agentic-ide/skills/{id} → one skill with its full text; 404.+ PATCH /api/agentic-ide/skills/{id} → partial edit; 404.+ POST /api/agentic-ide/skills/{id}/used → count one paste into a terminal.+ DELETE /api/agentic-ide/skills/{id} → remove (idempotent, {"removed": bool}).++The Skills tab of the IDE side panel drives these; pasting the text into a+pane happens in the browser (a bracketed paste into that pane's terminal), so+no route here ever writes to a PTY. No Brain dependency: works headless.+"""+from __future__ import annotations++import logging+import threading+from typing import Any++from fastapi import APIRouter, HTTPException+from pydantic import BaseModel, Field++from jarvis.agentic_ide.skill_library import (+ MAX_CONTENT_CHARS,+ SkillLibrary,+ derive_description,+ derive_title,+)++log = logging.getLogger(__name__)++router = APIRouter(prefix="/api/agentic-ide/skills", tags=["ide-skills"])++# Endpoints are sync ``def`` (FastAPI threadpool), so a threading.Lock+# serialises every read-modify-write of the sidecar.+_LOCK = threading.Lock()+++def _library() -> SkillLibrary:+ # Per request, so user_data_dir() is resolved at call time (test sandbox).+ return SkillLibrary()+++class SkillCreate(BaseModel):+ title: str = Field(max_length=400)+ content: str = Field(max_length=MAX_CONTENT_CHARS * 2)+ description: str | None = Field(default=None, max_length=2_000)+ hue: str | None = None+ icon: str | None = None+++class SkillUpdate(BaseModel):+ title: str | None = Field(default=None, max_length=400)+ content: str | None = Field(default=None, max_length=MAX_CONTENT_CHARS * 2)+ description: str | None = Field(default=None, max_length=2_000)+ hue: str | None = None+ icon: str | None = None+++class DeriveRequest(BaseModel):+ content: str = Field(max_length=MAX_CONTENT_CHARS * 2)+ filename: str = Field(default="", max_length=400)+++class OrderRequest(BaseModel):+ ids: list[str] = Field(max_length=2_000)+++def _not_found(skill_id: str) -> HTTPException:+ return HTTPException(status_code=404, detail=f"No skill with id {skill_id!r}.")++[email protected]("", openapi_extra={"x-jarvis-readonly": True})+def list_ide_skills() -> dict[str, Any]:+ """Every saved skill, in the order the user arranged them."""+ with _LOCK:+ skills = _library().list_all()+ return {"skills": [skill.to_dict() for skill in skills]}++[email protected]("", status_code=201)+def create_ide_skill(body: SkillCreate) -> dict[str, Any]:+ """Save a titled Markdown text as a new skill at the top of the library."""+ try:+ with _LOCK:+ skill = _library().create(+ title=body.title,+ content=body.content,+ description=body.description,+ hue=body.hue,+ icon=body.icon,+ )+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ log.info("IDE skill library: saved %r (%d chars).", skill.title, len(skill.content))+ return skill.to_dict()++[email protected]("/derive", openapi_extra={"x-jarvis-readonly": True})+def derive_ide_skill_fields(body: DeriveRequest) -> dict[str, Any]:+ """The title and summary a Markdown text suggests (frontmatter, heading, file name)."""+ stem = body.filename.rsplit("/", 1)[-1].rsplit("\\", 1)[-1]+ if "." in stem:+ stem = stem.rsplit(".", 1)[0]+ if stem.upper() == "SKILL":+ stem = ""+ return {+ "title": derive_title(body.content, stem.replace("-", " ").replace("_", " ")),+ "description": derive_description(body.content),+ }++[email protected]("/order")+def reorder_ide_skills(body: OrderRequest) -> dict[str, Any]:+ """Arrange the library: the given ids first, in this order."""+ with _LOCK:+ skills = _library().reorder(body.ids)+ return {"skills": [skill.to_dict() for skill in skills]}++[email protected]("/{skill_id}", openapi_extra={"x-jarvis-readonly": True})+def get_ide_skill(skill_id: str) -> dict[str, Any]:+ """One skill with its full Markdown text."""+ with _LOCK:+ skill = _library().get(skill_id)+ if skill is None:+ raise _not_found(skill_id)+ return skill.to_dict()++[email protected]("/{skill_id}")+def update_ide_skill(skill_id: str, body: SkillUpdate) -> dict[str, Any]:+ """Change a skill's title, text, summary, colour or icon."""+ fields = body.model_dump(exclude_unset=True)+ try:+ with _LOCK:+ skill = _library().update(+ skill_id,+ title=fields.get("title"),+ content=fields.get("content"),+ description=fields.get("description"),+ hue=fields.get("hue"),+ icon=fields.get("icon"),+ )+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ if skill is None:+ raise _not_found(skill_id)+ return skill.to_dict()++[email protected]("/{skill_id}/used")+def mark_ide_skill_used(skill_id: str) -> dict[str, Any]:+ """Count one paste of this skill into a terminal pane."""+ with _LOCK:+ skill = _library().mark_used(skill_id)+ if skill is None:+ raise _not_found(skill_id)+ return skill.to_dict()++[email protected]("/{skill_id}")+def delete_ide_skill(skill_id: str) -> dict[str, Any]:+ """Remove one skill from the library."""+ with _LOCK:+ removed = _library().delete(skill_id)+ return {"ok": True, "removed": removed}diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex ddb85d531c..ce6d3e15ef 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -485,6 +485,7 @@ class WebServer:from .friends_routes import router as friends_routerfrom .frontier_routes import router as frontier_routerfrom .grok_build_routes import router as grok_build_router+ from .ide_skills_routes import router as ide_skills_routerfrom .live_routes import router as live_routerfrom .local_models_assistant_routes import (router as local_models_assistant_router,@@ -654,6 +655,8 @@ class WebServer:# the focused coding mode.# Before the IDE router, so its /{…} paths never shadow /git/….app.include_router(agentic_ide_git_router)+ # The Skills tab's library of saved Markdown prompts (/api/agentic-ide/skills/*).+ app.include_router(ide_skills_router)app.include_router(agentic_ide_router)# The pane-activity sweep has no bus of its own (the registry is a plain# holder by design); this is the one place that holds one, so the sweepdiff --git a/tests/unit/ui/web/test_ide_skills_routes.py b/tests/unit/ui/web/test_ide_skills_routes.pynew file mode 100644index 0000000000..fc376e5014--- /dev/null+++ b/tests/unit/ui/web/test_ide_skills_routes.py@@ -0,0 +1,130 @@+"""REST route tests for the Agentic IDE skill library (saved Markdown prompts)."""+from __future__ import annotations++from pathlib import Path++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.agentic_ide.skill_library import (+ HUES,+ SkillLibrary,+ derive_description,+ derive_title,+ skill_library_path,+)+from jarvis.ui.web.ide_skills_routes import router as ide_skills_router++BASE = "/api/agentic-ide/skills"+++def client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient:+ # The library resolves user_data_dir() per request; sandbox it so the tests+ # never touch the real user profile.+ monkeypatch.setenv("LOCALAPPDATA", str(tmp_path))+ monkeypatch.setenv("HOME", str(tmp_path))+ app = FastAPI()+ app.include_router(ide_skills_router)+ return TestClient(app)+++def test_list_starts_empty(client: TestClient) -> None:+ r = client.get(BASE)+ assert r.status_code == 200+ assert r.json() == {"skills": []}+++def test_create_lists_newest_first_with_derived_summary(client: TestClient) -> None:+ first = client.post(BASE, json={"title": "Review", "content": "# Review\n\nCheck every diff."})+ assert first.status_code == 201+ body = first.json()+ assert body["title"] == "Review"+ assert body["description"] == "Check every diff."+ assert body["hue"] in HUES+ assert body["icon"] == "auto"+ assert body["use_count"] == 0++ client.post(BASE, json={"title": "Style", "content": "Short sentences."})+ titles = [skill["title"] for skill in client.get(BASE).json()["skills"]]+ assert titles == ["Style", "Review"]+++def test_create_rejects_empty_title_or_text_and_unknown_choices(client: TestClient) -> None:+ assert client.post(BASE, json={"title": " ", "content": "x"}).status_code == 400+ assert client.post(BASE, json={"title": "A", "content": " \n "}).status_code == 400+ assert client.post(BASE, json={"title": "A", "content": "x", "hue": "plaid"}).status_code == 400+ assert client.post(BASE, json={"title": "A", "content": "x", "icon": "nope"}).status_code == 400+++def test_windows_line_endings_are_normalised(client: TestClient) -> None:+ created = client.post(BASE, json={"title": "A", "content": "one\r\ntwo\rthree"}).json()+ assert created["content"] == "one\ntwo\nthree"+++def test_patch_get_and_delete(client: TestClient) -> None:+ skill = client.post(BASE, json={"title": "A", "content": "first text"}).json()+ r = client.patch(+ f"{BASE}/{skill['id']}",+ json={"title": "B", "content": "new body", "hue": "rose", "icon": "bug"},+ )+ assert r.status_code == 200+ updated = r.json()+ assert (updated["title"], updated["content"], updated["hue"], updated["icon"]) == (+ "B",+ "new body",+ "rose",+ "bug",+ )+ assert updated["description"] == "new body"+ assert client.get(f"{BASE}/{skill['id']}").json()["title"] == "B"++ assert client.delete(f"{BASE}/{skill['id']}").json() == {"ok": True, "removed": True}+ assert client.delete(f"{BASE}/{skill['id']}").json() == {"ok": True, "removed": False}+ assert client.get(f"{BASE}/{skill['id']}").status_code == 404+ assert client.patch(f"{BASE}/{skill['id']}", json={"title": "C"}).status_code == 404+++def test_used_counts_pastes_without_touching_updated_at(client: TestClient) -> None:+ skill = client.post(BASE, json={"title": "A", "content": "text"}).json()+ client.post(f"{BASE}/{skill['id']}/used")+ used = client.post(f"{BASE}/{skill['id']}/used").json()+ assert used["use_count"] == 2+ assert used["last_used_at"]+ assert used["updated_at"] == skill["updated_at"]+ assert client.post(f"{BASE}/missing/used").status_code == 404+++def test_order_puts_named_ids_first(client: TestClient) -> None:+ ids = [client.post(BASE, json={"title": t, "content": t}).json()["id"] for t in "abc"]+ # Library order is newest first: c, b, a.+ r = client.put(f"{BASE}/order", json={"ids": [ids[0], "unknown"]})+ assert [skill["title"] for skill in r.json()["skills"]] == ["a", "c", "b"]+++def test_derive_reads_frontmatter_heading_and_file_name(client: TestClient) -> None:+ skill_md = "---\nname: pr-review\ndescription: >-\n Review a pull\n request.\n---\n# Ignored"+ r = client.post(f"{BASE}/derive", json={"content": skill_md, "filename": "SKILL.md"})+ assert r.json() == {"title": "pr-review", "description": "Review a pull request."}++ plain = {"content": "plain words\n", "filename": "house_style.md"}+ r = client.post(f"{BASE}/derive", json=plain)+ assert r.json()["title"] == "house style"+++def test_unreadable_sidecar_degrades_to_empty(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setenv("LOCALAPPDATA", str(tmp_path))+ monkeypatch.setenv("HOME", str(tmp_path))+ path = skill_library_path()+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("{not json", encoding="utf-8")+ assert SkillLibrary().list_all() == []+++def test_derive_helpers_skip_fences_and_tables() -> None:+ text = "# Title\n\n```\ncode\n```\n| a | b |\n> Quoted *lead* line\n"+ assert derive_title(text) == "Title"+ assert derive_description(text) == "Quoted *lead* line"