Personal AI, On Personal Devices
Python
fix(skills): wire CLI execution and reuse cached sources (#951)
Elliot Sluskyb39b27280379
diff --git a/docs/user-guide/skills.md b/docs/user-guide/skills.mdindex 9786fdc4..a676e874 100644--- a/docs/user-guide/skills.md+++ b/docs/user-guide/skills.md@@ -39,6 +39,13 @@ jarvis skill run math-solver -a expression="41 + 82"jarvis skill info research-and-summarize```+`jarvis skill run` executes structured tool steps, including nested skills. It+loads only the tools that the pipeline needs; a nonempty `tools.enabled` list+restricts that selection. Capability checks, rate limits, and audit events use+the `skill:cli` identity, and sensitive tools ask for confirmation. Instruction-only+skills have no executable pipeline and exit with an explanation instead of+reporting success. A failed step also produces a nonzero exit status.+## Skill Definition FormatA skill is a directory containing a `skill.toml`, a `SKILL.md`, or both.@@ -187,6 +194,11 @@ jarvis skill sourcesjarvis skill update```+If an upstream refresh fails but the source cache still contains skills,+installation can use that copy and prints a warning that it may be stale.+Initial clone failures and missing requested skills still fail. `skill update`+reports a stale-cache warning instead of claiming that the refresh succeeded.+## How Agents Use Skills### Skill Catalog in the System Promptdiff --git a/src/openjarvis/cli/skill_cmd.py b/src/openjarvis/cli/skill_cmd.pyindex 4dc46dfc..a8681ffd 100644--- a/src/openjarvis/cli/skill_cmd.py+++ b/src/openjarvis/cli/skill_cmd.py@@ -7,6 +7,7 @@ from typing import Listimport clickfrom rich.console import Console+from rich.markup import escapefrom rich.table import Tablefrom openjarvis.core.config import load_config@@ -47,8 +48,8 @@ def _get_skill_paths() -> List[Path]:return paths-def _get_manager() -> SkillManager:- mgr = SkillManager(bus=EventBus())+def _get_manager(bus: EventBus | None = None) -> SkillManager:+ mgr = SkillManager(bus=bus if bus is not None else EventBus())mgr.discover(paths=_get_skill_paths())return mgr@@ -112,31 +113,92 @@ def info(skill_name: str):)+def _skill_tool_names(mgr: SkillManager, skill_name: str) -> list[str]:+ """Collect only the tools needed by this pipeline and its nested skills."""+ names: list[str] = []+ visited: set[str] = set()++ def visit(name: str) -> None:+ if name in visited:+ return+ visited.add(name)+ try:+ manifest = mgr.resolve(name)+ except KeyError:+ raise click.ClickException(f"Skill '{name}' not found.") from None+ if not manifest.steps:+ raise click.ClickException(+ f"Skill '{name}' has no executable steps. Instruction-only skills "+ "can be used by an agent, but cannot be run as a tool pipeline."+ )+ for step in manifest.steps:+ if step.skill_name:+ visit(step.skill_name)+ elif step.tool_name and step.tool_name not in names:+ names.append(step.tool_name)++ visit(skill_name)+ return names++@skill.command("run")@click.argument("skill_name")@click.option("--arg", "-a", multiple=True, help="Arguments as key=value pairs.")def run(skill_name: str, arg: tuple):- """Execute a skill directly."""+ """Execute a stepped skill using configured security and tool permissions."""+ import openjarvis.tools # noqa: F401+ from openjarvis.cli._tool_names import resolve_tool_names+ from openjarvis.cli.ask import _build_tools+ from openjarvis.core.registry import ToolRegistry+ from openjarvis.security import setup_security+ from openjarvis.tools._stubs import ToolExecutor+console = Console()- mgr = _get_manager()+ bus = EventBus()+ mgr = _get_manager(bus)+ names = _skill_tool_names(mgr, skill_name)+ cfg = load_config()+ enabled = resolve_tool_names(None, cfg.tools.enabled)+ unavailable = [+ name+ for name in names+ if not ToolRegistry.contains(name) or (enabled and name not in enabled)+ ]+ if unavailable:+ raise click.ClickException(+ "Skill requires unavailable or disabled tools: " + ", ".join(unavailable)+ )context = {}for a in arg:if "=" in a:k, v = a.split("=", 1)context[k.strip()] = v.strip()+ sec = setup_security(cfg, None, bus)try:+ tools = _build_tools(names, cfg, None, "")+ mgr.set_tool_executor(+ ToolExecutor(+ tools,+ bus,+ capability_policy=sec.capability_policy,+ rate_limiter=sec.rate_limiter,+ agent_id="skill:cli",+ interactive=True,+ confirm_callback=lambda prompt: click.confirm(prompt, default=False),+ )+ )result = mgr.execute(skill_name, context)- except KeyError:- console.print(f"[red]Skill '{skill_name}' not found.[/red]")- raise SystemExit(1)+ finally:+ if sec.audit_logger is not None:+ sec.audit_logger.close()if result.success:console.print("[green]Success[/green]")- if result.step_results:- console.print(result.step_results[-1].content)else:console.print("[red]Failed[/red]")- if result.step_results:- console.print(result.step_results[-1].content)+ if result.step_results:+ console.print(result.step_results[-1].content, markup=False)+ if not result.success:+ raise SystemExit(1)def _parse_source_query(query: str) -> tuple[str, str]:@@ -183,6 +245,13 @@ def _get_resolver(source: str, url: str = ""):raise click.BadParameter(f"Unknown source: {source!r}")+def _sync_resolver(resolver, console: Console) -> None:+ resolver.sync()+ warning = getattr(resolver, "refresh_warning", "")+ if warning:+ console.print(warning, style="yellow", markup=False)++@skill.command("install")@click.argument("query")@click.option(@@ -218,7 +287,7 @@ def install(query: str, with_scripts: bool, force: bool, url: str, yes_dangerousresolver = _get_resolver(source, url=url)try:- resolver.sync()+ _sync_resolver(resolver, console)except Exception as exc:console.print(f"[red]Failed to sync source {source}: {exc}[/red]")raise SystemExit(1)@@ -324,7 +393,7 @@ def sync(if not source_configs:console.print("[yellow]No sources to sync. "- "Add sources to [skills.sources] in config.toml "+ f"Add sources to {escape('[skills.sources]')} in config.toml ""or pass a source name.[/yellow]")return@@ -340,7 +409,7 @@ def sync(console.print(f"[cyan]Syncing {src['source']}...[/cyan]")try:resolver = _get_resolver(src["source"], url=src["url"])- resolver.sync()+ _sync_resolver(resolver, console)except Exception as exc:console.print(f"[red]Failed to sync {src['source']}: {exc}[/red]")continue@@ -397,7 +466,7 @@ def sources():if not cfg.skills.sources:console.print("[dim]No skill sources configured. "- "Add entries to [skills.sources] in config.toml.[/dim]"+ f"Add entries to {escape('[skills.sources]')} in config.toml.[/dim]")return@@ -477,7 +546,7 @@ def search(query: str, source: str):if not cfg.skills.sources:console.print("[yellow]No skill sources configured. "- "Add entries to [skills.sources] in config.toml.[/yellow]"+ f"Add entries to {escape('[skills.sources]')} in config.toml.[/yellow]")raise SystemExit(1)@@ -493,7 +562,7 @@ def search(query: str, source: str):for src_cfg in sources_to_search:try:resolver = _get_resolver(src_cfg.source, url=src_cfg.url)- resolver.sync()+ _sync_resolver(resolver, console)except Exception as exc:console.print(f"[yellow]Skipped {src_cfg.source}: {exc}[/yellow]")continue@@ -548,8 +617,9 @@ def update():console.print(f"[cyan]Updating {src.source}...[/cyan]")try:resolver = _get_resolver(src.source, url=src.url)- resolver.sync()- console.print(" [green]OK[/green]")+ _sync_resolver(resolver, console)+ if not getattr(resolver, "refresh_warning", ""):+ console.print(" [green]OK[/green]")except Exception as exc:console.print(f" [red]Failed: {exc}[/red]")diff --git a/src/openjarvis/skills/sources/base.py b/src/openjarvis/skills/sources/base.pyindex 140f59b4..f9829425 100644--- a/src/openjarvis/skills/sources/base.py+++ b/src/openjarvis/skills/sources/base.py@@ -2,6 +2,8 @@from __future__ import annotations+import logging+import subprocessfrom abc import ABC, abstractmethodfrom dataclasses import dataclass, fieldfrom pathlib import Path@@ -34,6 +36,7 @@ class SourceResolver(ABC):"""name: str = ""+ refresh_warning: str = ""@abstractmethoddef cache_dir(self) -> Path:@@ -47,6 +50,30 @@ class SourceResolver(ABC):def list_skills(self) -> List[ResolvedSkill]:"""Walk the cache directory and return all discoverable skills."""+ def _sync_git_cache(self, repo_url: str) -> None:+ """Refresh a usable cache best-effort; an initial clone must succeed."""+ cache = self.cache_dir()+ self.refresh_warning = ""+ if (cache / ".git").exists():+ try:+ subprocess.run(+ ["git", "-C", str(cache), "pull", "--ff-only"],+ check=True,+ capture_output=True,+ text=True,+ )+ except subprocess.CalledProcessError:+ if not self.list_skills():+ raise+ self.refresh_warning = (+ f"Could not refresh {self.name}; using the existing skill "+ "cache, which may be stale."+ )+ logging.getLogger(__name__).warning(self.refresh_warning)+ else:+ cache.parent.mkdir(parents=True, exist_ok=True)+ subprocess.run(["git", "clone", repo_url, str(cache)], check=True)+def resolve(self, query: str) -> List[ResolvedSkill]:"""Filter list_skills() by name (substring match).diff --git a/src/openjarvis/skills/sources/github.py b/src/openjarvis/skills/sources/github.pyindex 62c81fea..2776de43 100644--- a/src/openjarvis/skills/sources/github.py+++ b/src/openjarvis/skills/sources/github.py@@ -31,17 +31,7 @@ class GitHubResolver(SourceResolver):return self._cache_rootdef sync(self) -> None:- if self._cache_root.exists() and (self._cache_root / ".git").exists():- subprocess.run(- ["git", "-C", str(self._cache_root), "pull", "--ff-only"],- check=True,- )- else:- self._cache_root.parent.mkdir(parents=True, exist_ok=True)- subprocess.run(- ["git", "clone", self._repo_url, str(self._cache_root)],- check=True,- )+ self._sync_git_cache(self._repo_url)def list_skills(self) -> List[ResolvedSkill]:if not self._cache_root.exists():diff --git a/src/openjarvis/skills/sources/hermes.py b/src/openjarvis/skills/sources/hermes.pyindex e238b417..d9775efe 100644--- a/src/openjarvis/skills/sources/hermes.py+++ b/src/openjarvis/skills/sources/hermes.py@@ -36,18 +36,7 @@ class HermesResolver(SourceResolver):return self._cache_rootdef sync(self) -> None:- """Clone or pull the Hermes repo into the cache directory."""- if self._cache_root.exists() and (self._cache_root / ".git").exists():- subprocess.run(- ["git", "-C", str(self._cache_root), "pull", "--ff-only"],- check=True,- )- else:- self._cache_root.parent.mkdir(parents=True, exist_ok=True)- subprocess.run(- ["git", "clone", HERMES_REPO_URL, str(self._cache_root)],- check=True,- )+ self._sync_git_cache(HERMES_REPO_URL)def list_skills(self) -> List[ResolvedSkill]:"""Walk skills/<category>/<skill>/SKILL.md."""diff --git a/src/openjarvis/skills/sources/openclaw.py b/src/openjarvis/skills/sources/openclaw.pyindex 496e4de3..78489002 100644--- a/src/openjarvis/skills/sources/openclaw.py+++ b/src/openjarvis/skills/sources/openclaw.py@@ -37,17 +37,7 @@ class OpenClawResolver(SourceResolver):return self._cache_rootdef sync(self) -> None:- if self._cache_root.exists() and (self._cache_root / ".git").exists():- subprocess.run(- ["git", "-C", str(self._cache_root), "pull", "--ff-only"],- check=True,- )- else:- self._cache_root.parent.mkdir(parents=True, exist_ok=True)- subprocess.run(- ["git", "clone", OPENCLAW_REPO_URL, str(self._cache_root)],- check=True,- )+ self._sync_git_cache(OPENCLAW_REPO_URL)def list_skills(self) -> List[ResolvedSkill]:skills_root = self._cache_root / "skills"diff --git a/tests/cli/test_skill_run_security.py b/tests/cli/test_skill_run_security.pynew file mode 100644index 00000000..a836ed28--- /dev/null+++ b/tests/cli/test_skill_run_security.py@@ -0,0 +1,227 @@+"""End-to-end skill CLI execution and security regressions."""++from __future__ import annotations++import json+import sqlite3+from pathlib import Path+from unittest.mock import patch++import pytest+from click.testing import CliRunner++from openjarvis.cli import cli+from openjarvis.core.config import JarvisConfig+from openjarvis.core.events import EventBus, EventType+from openjarvis.core.types import ToolResult+++def write_skill(root: Path, name: str, steps: list[dict]) -> None:+ folder = root / name+ folder.mkdir()+ lines = [f'[skill]\nname = "{name}"\nversion = "1.0.0"\n']+ for step in steps:+ lines.append("[[skill.steps]]")+ lines.extend(f"{key} = {json.dumps(value)}" for key, value in step.items())+ (folder / "skill.toml").write_text("\n".join(lines))+++def skill_cli(tmp_path):+ from openjarvis.core.registry import ToolRegistry+ from openjarvis.tools.calculator import CalculatorTool+ from openjarvis.tools.shell_exec import ShellExecTool++ ToolRegistry.register_value("calculator", CalculatorTool)+ ToolRegistry.register_value("shell_exec", ShellExecTool)+ cfg = JarvisConfig()+ cfg.security.audit_log_path = str(tmp_path / "audit.db")+ cfg.security.capabilities.enabled = True+ cfg.security.capabilities.default_deny = True+ cfg.security.rate_limit_enabled = False+ cfg.learning.skills.overlay_dir = str(tmp_path / "overlays")+ bus = EventBus(record_history=True)+ with (+ patch("openjarvis.cli.skill_cmd._get_skill_paths", return_value=[tmp_path]),+ patch("openjarvis.cli.skill_cmd.load_config", return_value=cfg),+ patch("openjarvis.core.config.load_config", return_value=cfg),+ patch("openjarvis.cli.skill_cmd.EventBus", return_value=bus),+ ):+ yield tmp_path, cfg, bus+++def test_executes_real_registered_tool_and_nested_skill(skill_cli):+ root, _, bus = skill_cli+ write_skill(+ root,+ "child",+ [+ {+ "tool_name": "calculator",+ "arguments_template": '{"expression": "{value} + 2"}',+ "output_key": "answer",+ }+ ],+ )+ write_skill(+ root,+ "parent",+ [{"skill_name": "child", "arguments_template": '{"value": "{value}"}'}],+ )+ result = CliRunner().invoke(cli, ["skill", "run", "parent", "-a", "value=3"])+ assert result.exit_code == 0, result.output+ assert "Success" in result.output+ assert "5" in result.output+ calls = [+ event for event in bus.history if event.event_type == EventType.TOOL_CALL_START+ ]+ assert len(calls) == 1+ assert calls[0].data["agent"] == "skill:cli"++[email protected]("nested", [False, True])+def test_prose_skill_is_not_reported_as_success(skill_cli, nested):+ root, _, _ = skill_cli+ folder = root / "prose"+ folder.mkdir()+ (folder / "SKILL.md").write_text(+ "---\nname: prose\ndescription: Instructions\n---\nRead this."+ )+ name = "prose"+ if nested:+ write_skill(root, "parent", [{"skill_name": "prose"}])+ name = "parent"+ result = CliRunner().invoke(cli, ["skill", "run", name])+ assert result.exit_code != 0+ assert "no executable steps" in result.output+ assert "Success" not in result.output+++def test_respects_configured_tool_selection(skill_cli):+ root, cfg, _ = skill_cli+ cfg.tools.enabled = "think"+ write_skill(+ root,+ "calc",+ [{"tool_name": "calculator", "arguments_template": '{"expression": "2+2"}'}],+ )+ result = CliRunner().invoke(cli, ["skill", "run", "calc"])+ assert result.exit_code != 0+ assert "disabled tools: calculator" in result.output+++def test_default_deny_blocks_real_shell_before_dispatch(skill_cli):+ root, cfg, bus = skill_cli+ write_skill(+ root,+ "shell",+ [+ {+ "tool_name": "shell_exec",+ "arguments_template": '{"command": "echo blocked"}',+ }+ ],+ )+ with patch("openjarvis.tools.shell_exec.ShellExecTool.execute") as execute:+ result = CliRunner().invoke(cli, ["skill", "run", "shell"], input="y\n")+ assert result.exit_code != 0+ assert "code:execute" in result.output and "denied" in result.output+ execute.assert_not_called()+ denied = [+ event+ for event in bus.history+ if event.event_type == EventType.CAPABILITY_DENIED+ ]+ assert denied[0].data["agent_id"] == "skill:cli"+ with sqlite3.connect(cfg.security.audit_log_path) as db:+ previews = db.execute("SELECT content_preview FROM security_events").fetchall()+ assert any("agent=skill:cli" in row[0] for row in previews)++[email protected]("answer, expected_calls", [("y", 1), ("n", 0)])+def test_granted_shell_still_requires_user_confirmation(+ skill_cli, answer, expected_calls+):+ root, cfg, _ = skill_cli+ policy = root / "policy.json"+ policy.write_text(+ json.dumps(+ {+ "agents": [+ {+ "agent_id": "skill:cli",+ "grants": [{"capability": "code:execute"}],+ }+ ]+ }+ )+ )+ cfg.security.capabilities.policy_path = str(policy)+ write_skill(+ root,+ "shell",+ [+ {+ "tool_name": "shell_exec",+ "arguments_template": '{"command": "echo allowed"}',+ }+ ],+ )+ with patch(+ "openjarvis.tools.shell_exec.ShellExecTool.execute",+ return_value=ToolResult(+ tool_name="shell_exec",+ content="STEP_RAN",+ success=True,+ ),+ ) as execute:+ result = CliRunner().invoke(cli, ["skill", "run", "shell"], input=answer + "\n")+ assert execute.call_count == expected_calls+ assert "Allow execution" in result.output+ assert (result.exit_code == 0) is bool(expected_calls), result.output+ assert ("STEP_RAN" in result.output) is bool(expected_calls)+++def test_rate_limit_applies_across_skill_steps(skill_cli):+ root, cfg, bus = skill_cli+ cfg.security.rate_limit_enabled = True+ cfg.security.rate_limit_rpm = 1+ cfg.security.rate_limit_burst = 1+ write_skill(+ root,+ "twice",+ [{"tool_name": "calculator", "arguments_template": '{"expression": "2+2"}'}]+ * 2,+ )+ result = CliRunner().invoke(cli, ["skill", "run", "twice"])+ assert result.exit_code != 0+ assert "Rate limit exceeded" in result.output+ limited = [+ event for event in bus.history if event.event_type == EventType.RATE_LIMITED+ ]+ assert limited[0].data["agent_id"] == "skill:cli"+++def test_policy_startup_failure_never_dispatches(skill_cli):+ root, cfg, _ = skill_cli+ cfg.security.capabilities.policy_path = str(root / "missing-policy.json")+ write_skill(+ root,+ "shell",+ [+ {+ "tool_name": "shell_exec",+ "arguments_template": '{"command": "echo blocked"}',+ }+ ],+ )+ with patch("openjarvis.tools.shell_exec.ShellExecTool.execute") as execute:+ result = CliRunner().invoke(cli, ["skill", "run", "shell"])+ assert result.exit_code != 0+ execute.assert_not_called()++[email protected]("command", [["sync"], ["sources"], ["search", "x"]])+def test_no_sources_message_keeps_literal_toml_section(skill_cli, command):+ result = CliRunner().invoke(cli, ["skill", *command])+ assert "[skills.sources]" in result.outputdiff --git a/tests/skills/test_source_refresh_fallback.py b/tests/skills/test_source_refresh_fallback.pynew file mode 100644index 00000000..a6ded93f--- /dev/null+++ b/tests/skills/test_source_refresh_fallback.py@@ -0,0 +1,125 @@+"""Cached skill installation survives failed upstream refreshes."""++from __future__ import annotations++import subprocess+from unittest.mock import patch++import pytest+from click.testing import CliRunner++from openjarvis.cli import cli+from openjarvis.core.config import JarvisConfig, SkillSourceConfig+from openjarvis.skills.sources.github import GitHubResolver+from openjarvis.skills.sources.hermes import HermesResolver+from openjarvis.skills.sources.openclaw import OpenClawResolver++[email protected](params=["hermes", "openclaw", "github"])+def resolver(request, tmp_path):+ root = tmp_path / "cache"+ kind = request.param+ if kind == "github":+ return GitHubResolver(root, "https://example.invalid/skills.git")+ return {"hermes": HermesResolver, "openclaw": OpenClawResolver}[kind](root)+++def cached_skill(resolver):+ root = resolver.cache_dir()+ folder = root / "skills" / "research" / "cached"+ folder.mkdir(parents=True)+ (root / ".git").mkdir()+ (folder / "SKILL.md").write_text(+ "---\nname: cached\ndescription: A cached skill\n---\nRead these instructions."+ )+ return folder+++def failed_pull(command, **kwargs):+ if "pull" in command:+ raise subprocess.CalledProcessError(1, command, stderr="network unavailable")+ if "rev-parse" in command:+ return subprocess.CompletedProcess(command, 0, stdout="cached-commit\n")+ raise AssertionError(f"Unexpected command: {command}")+++def test_usable_cache_survives_refresh_failure(resolver):+ folder = cached_skill(resolver)+ with patch("subprocess.run", side_effect=failed_pull):+ resolver.sync()+ found = resolver.list_skills()+ assert len(found) == 1+ assert found[0].path == folder+ assert found[0].commit == "cached-commit"+ assert "may be stale" in resolver.refresh_warning+++def test_initial_clone_failure_is_fatal(resolver):+ with patch("subprocess.run", side_effect=subprocess.CalledProcessError(1, "git")):+ with pytest.raises(subprocess.CalledProcessError):+ resolver.sync()+ assert not resolver.refresh_warning+++def test_empty_cache_does_not_hide_refresh_failure(resolver):+ (resolver.cache_dir() / ".git").mkdir(parents=True)+ with patch("subprocess.run", side_effect=failed_pull):+ with pytest.raises(subprocess.CalledProcessError):+ resolver.sync()+ assert not resolver.refresh_warning+++def test_successful_refresh_clears_stale_warning(resolver):+ cached_skill(resolver)+ resolver.refresh_warning = "stale warning"+ with patch("subprocess.run", return_value=subprocess.CompletedProcess([], 0)):+ resolver.sync()+ assert resolver.refresh_warning == ""+++def test_install_uses_cached_skill_and_displays_warning(+ resolver, tmp_path, monkeypatch+):+ cached_skill(resolver)+ monkeypatch.setenv("OPENJARVIS_HOME", str(tmp_path / "installed"))+ with (+ patch("subprocess.run", side_effect=failed_pull),+ patch("openjarvis.cli.skill_cmd._get_resolver", return_value=resolver),+ ):+ result = CliRunner().invoke(+ cli, ["skill", "install", f"{resolver.name}:cached"]+ )+ assert result.exit_code == 0, result.output+ assert "may be stale" in result.output+ assert "Installed:" in result.output+ assert (+ tmp_path / "installed" / "skills" / resolver.name / "cached" / "SKILL.md"+ ).is_file()+++def test_cache_cannot_satisfy_missing_skill(resolver, tmp_path, monkeypatch):+ cached_skill(resolver)+ monkeypatch.setenv("OPENJARVIS_HOME", str(tmp_path / "installed"))+ with (+ patch("subprocess.run", side_effect=failed_pull),+ patch("openjarvis.cli.skill_cmd._get_resolver", return_value=resolver),+ ):+ result = CliRunner().invoke(+ cli, ["skill", "install", f"{resolver.name}:missing"]+ )+ assert result.exit_code != 0+ assert "No skill named 'missing'" in result.output+++def test_update_does_not_claim_refresh_succeeded(resolver):+ cached_skill(resolver)+ cfg = JarvisConfig()+ cfg.skills.sources = [SkillSourceConfig(source=resolver.name)]+ with (+ patch("subprocess.run", side_effect=failed_pull),+ patch("openjarvis.cli.skill_cmd._get_resolver", return_value=resolver),+ patch("openjarvis.cli.skill_cmd.load_config", return_value=cfg),+ ):+ result = CliRunner().invoke(cli, ["skill", "update"])+ assert "may be stale" in result.output+ assert "OK" not in result.output