Skip to content

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.

17.7 KB
Raw Blame
"""Tests for the skills REST endpoints touched by the on/off + delete + reorder work.

Covered:
- ``POST /{name}/enable|disable`` now persist the choice to the prefs sidecar so
  it survives a registry reload (the old in-memory flip was wiped on reload).
- ``DELETE /{name}`` removes a user skill and prunes its prefs; builtins are
  refused (they would be re-copied on next boot anyway).
- ``PUT /order`` persists a custom list order; ``GET /api/skills`` reflects it,
  appending any skill not in the order after the ordered ones, by name.

The registry is wired with ``prefs.load_state_overrides`` as its loader so the
enable/disable → reload persistence is exercised end-to-end. ``LOCALAPPDATA`` is
redirected so the prefs file lands in a tmp sandbox.
"""
from __future__ import annotations

from pathlib import Path

import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient

from dodaios.skills import prefs
from dodaios.skills.registry import SkillRegistry
from dodaios.skills.schema import SkillLifecycleState


@pytest.fixture(autouse=True)
def _isolate_data_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv("LOCALAPPDATA", str(tmp_path))


def _make_skill(root: Path, name: str, *, state: str | None = None) -> None:
    d = root / name
    d.mkdir(parents=True, exist_ok=True)
    fm = (
        "---\n"
        'schema_version: "1"\n'
        f"name: {name}\n"
        "description: test skill\n"
    )
    if state:
        fm += f"state: {state}\n"
    fm += "---\n\n## Body\n"
    (d / "SKILL.md").write_text(fm, encoding="utf-8")


def _client(skills_root: Path) -> tuple[TestClient, SkillRegistry]:
    from dodaios.ui.web.skills_routes import router

    reg = SkillRegistry(
        skills_root, bus=None, state_prefs_loader=prefs.load_state_overrides
    )
    reg.reload_sync()
    app = FastAPI()
    app.state.skill_registry = reg
    app.include_router(router)
    return TestClient(app), reg


@pytest.fixture
def skills_root(tmp_path: Path) -> Path:
    # NB: distinct from the LOCALAPPDATA sandbox so deletes never touch prefs dir.
    root = tmp_path / "skills_src"
    root.mkdir()
    return root


# ----------------------------------------------------------------------
# enable / disable persistence
# ----------------------------------------------------------------------


def test_disable_persists_and_survives_reload(skills_root: Path) -> None:
    _make_skill(skills_root, "alpha")  # VALIDATED = "on"
    client, reg = _client(skills_root)

    res = client.post("/api/skills/alpha/disable")
    assert res.status_code == 200, res.text

    assert prefs.load_state_overrides() == {"alpha": "disabled"}
    assert reg.get("alpha").state == SkillLifecycleState.DISABLED

    reg.reload_sync()  # the old bug reverted here
    assert reg.get("alpha").state == SkillLifecycleState.DISABLED


def test_enable_after_disable_records_active(skills_root: Path) -> None:
    _make_skill(skills_root, "alpha")
    client, reg = _client(skills_root)

    client.post("/api/skills/alpha/disable")
    res = client.post("/api/skills/alpha/enable")
    assert res.status_code == 200, res.text

    assert prefs.load_state_overrides()["alpha"] == "active"
    assert reg.get("alpha").state == SkillLifecycleState.ACTIVE


def test_enable_promotes_healthy_draft(skills_root: Path) -> None:
    """Voice/AI-authored skills land as ``state: draft`` (AP-15). Enable is
    the human promotion the Skills view and ``skill-enable`` already advertise.
    """
    _make_skill(skills_root, "alpha", state="draft")
    client, reg = _client(skills_root)

    assert reg.get("alpha").state == SkillLifecycleState.DRAFT
    assert reg.get("alpha").error is None

    res = client.post("/api/skills/alpha/enable")
    assert res.status_code == 200, res.text
    assert res.json()["state"] == "active"
    assert reg.get("alpha").state == SkillLifecycleState.ACTIVE
    text = (skills_root / "alpha" / "SKILL.md").read_text(encoding="utf-8")
    assert "state: active" in text
    assert prefs.load_state_overrides()["alpha"] == "active"


def test_enable_refuses_broken_draft(skills_root: Path) -> None:
    folder = skills_root / "broken"
    folder.mkdir()
    (folder / "SKILL.md").write_text(
        '---\nschema_version: "1"\nname: broken\ntriggers:\n  - type: voice\n---\n\n## Body\n',
        encoding="utf-8",
    )
    client, reg = _client(skills_root)

    assert reg.get("broken").state == SkillLifecycleState.DRAFT
    assert reg.get("broken").error

    res = client.post("/api/skills/broken/enable")
    assert res.status_code == 409, res.text
    assert reg.get("broken").state == SkillLifecycleState.DRAFT


def test_enable_refuses_unsafe_draft(skills_root: Path) -> None:
    folder = skills_root / "unsafe"
    folder.mkdir()
    (folder / "SKILL.md").write_text(
        '---\nschema_version: "1"\nname: unsafe\nstate: draft\n---\n\n'
        "```python\neval('boom')\n```\n",
        encoding="utf-8",
    )
    client, _reg = _client(skills_root)

    res = client.post("/api/skills/unsafe/enable")
    assert res.status_code == 409, res.text
    detail = res.json()["detail"].lower()
    assert "eval" in detail or "unsafe" in detail


def test_disable_refuses_draft(skills_root: Path) -> None:
    _make_skill(skills_root, "alpha", state="draft")
    client, reg = _client(skills_root)

    res = client.post("/api/skills/alpha/disable")
    assert res.status_code == 409, res.text
    assert reg.get("alpha").state == SkillLifecycleState.DRAFT


# ----------------------------------------------------------------------
# delete
# ----------------------------------------------------------------------


def test_delete_removes_user_skill(skills_root: Path) -> None:
    _make_skill(skills_root, "alpha")
    client, _reg = _client(skills_root)

    res = client.delete("/api/skills/alpha")
    assert res.status_code == 200, res.text
    assert res.json()["removed"] is True
    assert not (skills_root / "alpha").exists()

    names = [s["name"] for s in client.get("/api/skills").json()["skills"]]
    assert "alpha" not in names


def test_delete_prunes_prefs(skills_root: Path) -> None:
    _make_skill(skills_root, "alpha")
    client, _reg = _client(skills_root)

    client.post("/api/skills/alpha/disable")
    client.delete("/api/skills/alpha")

    assert "alpha" not in prefs.load_state_overrides()


def test_delete_builtin_is_refused(skills_root: Path) -> None:
    from dodaios.skills.builtin import BUILTIN_SKILL_NAMES

    builtin_name = sorted(BUILTIN_SKILL_NAMES)[0]
    _make_skill(skills_root, builtin_name)
    client, _reg = _client(skills_root)

    res = client.delete(f"/api/skills/{builtin_name}")
    assert res.status_code == 409, res.text
    assert (skills_root / builtin_name).exists()


# ----------------------------------------------------------------------
# bulk delete
# ----------------------------------------------------------------------


def test_bulk_delete_removes_multiple_user_skills(skills_root: Path) -> None:
    for n in ("alpha", "beta", "gamma"):
        _make_skill(skills_root, n)
    client, _reg = _client(skills_root)

    res = client.post("/api/skills/bulk-delete", json={"names": ["alpha", "gamma"]})
    assert res.status_code == 200, res.text
    body = res.json()
    assert sorted(body["deleted"]) == ["alpha", "gamma"]
    assert body["failed"] == []
    assert not (skills_root / "alpha").exists()
    assert not (skills_root / "gamma").exists()
    assert (skills_root / "beta").exists()

    names = [s["name"] for s in client.get("/api/skills").json()["skills"]]
    assert names == ["beta"]


def test_bulk_delete_refuses_builtins_but_deletes_the_rest(skills_root: Path) -> None:
    from dodaios.skills.builtin import BUILTIN_SKILL_NAMES

    builtin_name = sorted(BUILTIN_SKILL_NAMES)[0]
    _make_skill(skills_root, builtin_name)
    _make_skill(skills_root, "alpha")
    client, _reg = _client(skills_root)

    res = client.post(
        "/api/skills/bulk-delete", json={"names": [builtin_name, "alpha"]}
    )
    assert res.status_code == 200, res.text
    body = res.json()
    assert body["deleted"] == ["alpha"]
    assert [f["name"] for f in body["failed"]] == [builtin_name]
    # The protected built-in is untouched; the user skill is gone.
    assert (skills_root / builtin_name).exists()
    assert not (skills_root / "alpha").exists()


def test_bulk_delete_reports_missing_skill(skills_root: Path) -> None:
    _make_skill(skills_root, "alpha")
    client, _reg = _client(skills_root)

    res = client.post("/api/skills/bulk-delete", json={"names": ["alpha", "ghost"]})
    assert res.status_code == 200, res.text
    body = res.json()
    assert body["deleted"] == ["alpha"]
    assert [f["name"] for f in body["failed"]] == ["ghost"]


def test_bulk_delete_dedupes_repeated_names(skills_root: Path) -> None:
    _make_skill(skills_root, "alpha")
    client, _reg = _client(skills_root)

    res = client.post(
        "/api/skills/bulk-delete", json={"names": ["alpha", "alpha"]}
    )
    assert res.status_code == 200, res.text
    body = res.json()
    # A doubled name is deleted once, not reported as a failure on the second pass.
    assert body["deleted"] == ["alpha"]
    assert body["failed"] == []


def test_bulk_delete_prunes_prefs(skills_root: Path) -> None:
    _make_skill(skills_root, "alpha")
    _make_skill(skills_root, "beta")
    client, _reg = _client(skills_root)

    client.post("/api/skills/alpha/disable")
    client.post("/api/skills/bulk-delete", json={"names": ["alpha", "beta"]})

    overrides = prefs.load_state_overrides()
    assert "alpha" not in overrides
    assert "beta" not in overrides


# --- Skill Creator routes (deterministic, no brain in tests) ----------------
# ``dodaios.skills.creator_service`` is now shipped, so the creator routes work.
# With no brain wired on ``app.state`` they return the deterministic skeleton
# draft (``brain_used`` False) — the cloud-first fallback that must always work.
# The ``link-health`` route still 501s while its optional module is absent.


def test_creator_draft_returns_valid_skeleton_without_brain(
    skills_root: Path,
) -> None:
    client, _reg = _client(skills_root)
    res = client.post(
        "/api/skills/creator/draft",
        json={"intent": "pause spotify when I talk", "name_hint": "Spotify Pause"},
    )
    assert res.status_code == 200, res.text
    body = res.json()
    assert body["brain_used"] is False
    assert body["draft"]["name"]
    assert body["validation"]["ok"] is True


def test_creator_validate_checks_skill_md(skills_root: Path) -> None:
    client, _reg = _client(skills_root)
    ok = client.post(
        "/api/skills/creator/validate",
        json={"skill_md": '---\nschema_version: "1"\nname: X\n---\n\n## B\n'},
    )
    assert ok.status_code == 200, ok.text
    assert ok.json()["validation"]["ok"] is True

    bad = client.post(
        "/api/skills/creator/validate",
        json={"skill_md": "no frontmatter here"},
    )
    assert bad.status_code == 200, bad.text
    assert bad.json()["validation"]["ok"] is False


def test_create_skill_endpoint_writes_and_lists(skills_root: Path) -> None:
    client, _reg = _client(skills_root)
    res = client.post(
        "/api/skills",
        json={
            "name": "Form Made Skill",
            "description": "from the form",
            "body": "## Form Made Skill\n\nReply politely when invoked.\n",
        },
    )
    assert res.status_code == 200, res.text
    assert res.json()["name"] == "Form Made Skill"
    names = [s["name"] for s in client.get("/api/skills").json()["skills"]]
    assert "Form Made Skill" in names


def test_create_skill_endpoint_rejects_empty_body(skills_root: Path) -> None:
    """A skill with only a heading / blank body is functionless — refuse it
    (the Hallo-Hallo-Hallo forensic) so no dead skill is ever persisted."""
    client, _reg = _client(skills_root)
    res = client.post("/api/skills", json={"name": "Hollow", "body": "## Hollow\n"})
    assert res.status_code == 400, res.text
    assert "instructions" in res.json()["detail"].lower()


def test_create_skill_endpoint_rejects_duplicate(skills_root: Path) -> None:
    client, _reg = _client(skills_root)
    client.post("/api/skills", json={"name": "Dup", "body": "## Dup\n\nDo a thing.\n"})
    res = client.post("/api/skills", json={"name": "Dup", "body": "## Dup\n\nDo another.\n"})
    assert res.status_code == 409, res.text


def test_creator_commit_persists_reviewed_draft(skills_root: Path) -> None:
    client, _reg = _client(skills_root)
    draft = {
        "name": "Committed Via Route",
        "description": "desc",
        "category": "general",
        "tags": [],
        "triggers": [],
        "requires_tools": [],
        "risk_policy": {"default_tier": "ask"},
        "body": "## Committed Via Route\n\nDo it.\n",
    }
    res = client.post("/api/skills/creator/commit", json={"draft": draft})
    assert res.status_code == 200, res.text
    assert res.json()["name"] == "Committed Via Route"
    names = [s["name"] for s in client.get("/api/skills").json()["skills"]]
    assert "Committed Via Route" in names


def test_creator_author_refuses_without_brain_and_writes_nothing(skills_root: Path) -> None:
    """One-shot authoring (voice / CLI parity) is brain-REQUIRED: with no brain
    on app.state it answers 503 and no skeleton lands on disk — a template
    with the sentence pasted in is not the skill the user asked for."""
    client, _reg = _client(skills_root)
    res = client.post(
        "/api/skills/creator/author",
        json={"intent": "jeden morgen um 6 meine mails vorlesen", "schedule_hint": "0 6 * * *"},  # i18n-allow: test input
    )
    assert res.status_code == 503, res.text
    assert not any(skills_root.iterdir())


def test_creator_author_writes_a_draft_skill_with_a_brain(skills_root: Path) -> None:
    from dodaios.core.protocols import BrainDelta

    class _Brain:
        def complete(self, request):  # noqa: ANN001, ANN202
            async def _gen():
                yield BrainDelta(
                    content=(
                        '{"name": "Mail Morgen", "description": "Liest morgens Mails vor.", '
                        '"category": "productivity", "tags": ["mail"], '
                        '"triggers": [{"type": "voice", "pattern": "(mail morgen)"}], '
                        '"requires_tools": [], "risk_policy": {"default_tier": "monitor"}, '
                        '"body": "Morgens Mails.\\n\\n## Schritte\\n\\n1. gmail: ungelesene Mails nennen.\\n"}'
                    ),
                    finish_reason="stop",
                )

            return _gen()

    from dodaios.ui.web.skills_routes import router

    reg = SkillRegistry(skills_root, bus=None, state_prefs_loader=prefs.load_state_overrides)
    reg.reload_sync()
    app = FastAPI()
    app.state.skill_registry = reg
    app.state.brain = _Brain()
    app.include_router(router)
    client = TestClient(app)
    res = client.post(
        "/api/skills/creator/author",
        json={"intent": "jeden morgen mails vorlesen", "schedule_hint": "0 6 * * *"},  # i18n-allow: test input
    )
    assert res.status_code == 200, res.text
    body = res.json()
    assert body["brain_used"] is True
    assert body["skill"]["name"] == "mail-morgen"
    assert body["skill"]["state"] == "draft"  # AP-15
    crons = [t["cron"] for t in body["draft"]["triggers"] if t["type"] == "schedule"]
    assert crons == ["0 6 * * *"]
    assert (skills_root / "mail-morgen" / "SKILL.md").exists()


def test_link_health_returns_clean_501_when_module_absent(skills_root: Path) -> None:
    _make_skill(skills_root, "alpha")
    client, _reg = _client(skills_root)
    res = client.get("/api/skills/alpha/link-health")
    assert res.status_code == 501, res.text
    assert "not available" in res.json()["detail"].lower()


# ----------------------------------------------------------------------
# reorder
# ----------------------------------------------------------------------


def test_reorder_persists_and_list_reflects(skills_root: Path) -> None:
    for n in ("alpha", "beta", "gamma"):
        _make_skill(skills_root, n)
    client, _reg = _client(skills_root)

    res = client.put("/api/skills/order", json={"order": ["gamma", "alpha", "beta"]})
    assert res.status_code == 200, res.text
    assert prefs.load_order() == ["gamma", "alpha", "beta"]

    names = [s["name"] for s in client.get("/api/skills").json()["skills"]]
    assert names == ["gamma", "alpha", "beta"]


def test_list_appends_unordered_skills_by_name(skills_root: Path) -> None:
    for n in ("alpha", "beta", "gamma"):
        _make_skill(skills_root, n)
    client, _reg = _client(skills_root)

    client.put("/api/skills/order", json={"order": ["gamma"]})

    names = [s["name"] for s in client.get("/api/skills").json()["skills"]]
    assert names[0] == "gamma"
    assert names[1:] == ["alpha", "beta"]  # unordered remainder, sorted by name


# ----------------------------------------------------------------------
# brief listing — what the brain reads for "which skills do I have"
# ----------------------------------------------------------------------


def test_brief_listing_carries_state_and_starts_only(skills_root: Path) -> None:
    """``skills-list`` (app-command) reads this: lean enough for the 8 000-char
    tool-result cap, and "brief" must never be read as a skill name."""
    _make_skill(skills_root, "alpha")
    _make_skill(skills_root, "beta", state="draft")
    client, _reg = _client(skills_root)
    res = client.get("/api/skills/brief")
    assert res.status_code == 200, res.text
    body = res.json()
    assert body["total"] == 2
    by_name = {s["name"]: s for s in body["skills"]}
    assert by_name["alpha"]["state"] == "validated"
    assert by_name["beta"]["state"] == "draft"
    assert set(by_name["alpha"]) == {"name", "state", "is_builtin", "description", "starts"}
    # /{name} still resolves real names, and "brief" is not one of them.
    assert client.get("/api/skills/alpha").status_code == 200