Files
scientific-agent-skills/scientific-skills/autoskill/tests/test_backends.py
T
Renato Umeton 412d3f22ae add: autoskill — synthesize new skills from observed local screen activity
A meta-skill that observes a researcher's own screen activity via a local
screenpipe daemon, clusters repeated workflow patterns, compares each
cluster against this repo's existing 135 skills using local embeddings,
and drafts either a thin composition recipe (a SKILL.md that chains
existing skills) or a full new SKILL.md when no combination fits.

Key design properties

- On-demand, no daemon of its own; invoked by the user with a time window.
- Local-first. Detection, clustering, redaction, and embeddings all run
  on-device. Screenpipe's native app/window filters run at capture time;
  a defense-in-depth regex pass scrubs emails, JWTs, SSH private-key
  blocks, known-env-var secret assignments, Slack / HuggingFace / OpenAI
  / GitHub / AWS / Google / Stripe tokens, US SSNs, and US phone numbers
  before any cluster summary reaches the LLM.
- LLM backend user-selectable, default local via LM Studio
  (Gemma-4-31B-it recommended). Opt-in Anthropic or BYOK Foundry
  backends sit behind the same interface.
- sentence-transformers/all-MiniLM-L6-v2 indexes every SKILL.md
  frontmatter description locally. For each cluster, top-k matches go to
  the LLM, which emits reuse / compose / novel and a SKILL.md body where
  appropriate.
- Staged output lives under ~/.autoskill/proposed/<ts>/ (default,
  outside the repo tree). A promote CLI moves approved ones into
  scientific-skills/<name>/.
- Unified CLI: autoskill run | doctor | promote. doctor preflights
  screenpipe reachability + auth, the configured LLM backend, the
  config, and the skills directory.

What's shipped

- 8 pipeline scripts (fetch_window, redact, cluster, match_skills,
  synthesize, promote, backends, run) plus the autoskill.py dispatcher.
- 83 pytest tests: unit, integration, and end-to-end with
  httpx.MockTransport fakes for screenpipe and LM Studio.
- Verified live end-to-end on macOS: source-built screenpipe daemon
  (17k+ real OCR events captured) + real all-MiniLM-L6-v2 embedding the
  full 135-skill index + real Gemma-4-31B-it at 128K context returning a
  parseable JSON verdict, producing a report.md with sensible top-k
  matches.
- SKILL.md frontmatter matches the convention used by literature-review,
  hypothesis-generation, and other sibling skills.
- skill-scanner scan scientific-skills/autoskill --use-behavioral run
  per the repo's CONTRIBUTING requirement; findings profile (15 total,
  5 critical, 8 medium, 2 low) is in line with already-merged script-
  shipping peers (literature-review: 14/3/8/2, citation-management:
  17/5/10/1). Remaining findings are intentional-behavior flags
  covering env-var-based auth to the user-configured LLM and screenpipe
  endpoints; these are documented explicitly in SKILL.md.

Tracked by issue #140.
2026-04-17 16:06:17 -04:00

122 lines
4.2 KiB
Python

import httpx
import pytest
from backends import ClaudeBackend, LocalBackend, make_backend
def _mock_client(handler, base_url=""):
return httpx.Client(transport=httpx.MockTransport(handler), base_url=base_url)
def test_claude_backend_posts_to_v1_messages_with_auth_headers():
calls = []
def handler(request):
calls.append(request)
return httpx.Response(200, json={"content": [{"type": "text", "text": "hello"}]})
backend = ClaudeBackend(api_key="sk-test", model="claude-opus-4-7",
client=_mock_client(handler, base_url="https://api.anthropic.com"))
result = backend("say hello")
assert result == "hello"
assert calls[0].url.path == "/v1/messages"
assert calls[0].headers["x-api-key"] == "sk-test"
assert calls[0].headers["anthropic-version"]
body = calls[0].read()
import json as _json
payload = _json.loads(body)
assert payload["model"] == "claude-opus-4-7"
assert payload["messages"][0]["role"] == "user"
assert payload["messages"][0]["content"] == "say hello"
def test_claude_backend_honors_custom_base_url_for_foundry():
calls = []
def handler(request):
calls.append(request)
return httpx.Response(200, json={"content": [{"type": "text", "text": "ok"}]})
backend = ClaudeBackend(api_key="k", model="claude-opus-4-7",
client=_mock_client(handler, base_url="https://foundry.example.com/anthropic"))
backend("hi")
assert str(calls[0].url).startswith("https://foundry.example.com/anthropic/v1/messages")
def test_claude_backend_raises_on_http_error():
def handler(request):
return httpx.Response(401, json={"error": "bad key"})
backend = ClaudeBackend(api_key="k", model="m",
client=_mock_client(handler, base_url="https://api.anthropic.com"))
with pytest.raises(httpx.HTTPStatusError):
backend("x")
def test_local_backend_posts_to_chat_completions():
calls = []
def handler(request):
calls.append(request)
return httpx.Response(200, json={
"choices": [{"message": {"content": "hi back"}}]
})
backend = LocalBackend(endpoint="http://localhost:11434/v1", model="qwen2.5:14b",
client=_mock_client(handler, base_url="http://localhost:11434/v1"))
result = backend("prompt")
assert result == "hi back"
assert calls[0].url.path.endswith("/chat/completions")
import json as _json
payload = _json.loads(calls[0].read())
assert payload["model"] == "qwen2.5:14b"
assert payload["messages"][0]["content"] == "prompt"
def test_make_backend_returns_claude_backend_for_claude_config(monkeypatch):
monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-env")
backend = make_backend({
"backend": "claude",
"claude": {"model": "claude-opus-4-7"},
})
assert isinstance(backend, ClaudeBackend)
assert backend.api_key == "sk-env"
assert backend.model == "claude-opus-4-7"
def test_make_backend_returns_claude_backend_with_foundry_base_url(monkeypatch):
monkeypatch.setenv("FOUNDRY_API_KEY", "sk-foundry")
backend = make_backend({
"backend": "foundry",
"foundry": {
"endpoint": "https://foundry.example.com/anthropic",
"model": "claude-opus-4-7",
},
})
assert isinstance(backend, ClaudeBackend)
assert backend.api_key == "sk-foundry"
assert "foundry.example.com" in str(backend.client.base_url)
def test_make_backend_returns_local_backend_for_local_config():
backend = make_backend({
"backend": "local",
"local": {"endpoint": "http://localhost:11434/v1", "model": "qwen2.5:14b"},
})
assert isinstance(backend, LocalBackend)
assert backend.model == "qwen2.5:14b"
def test_make_backend_raises_on_unknown_backend():
with pytest.raises(ValueError, match="unknown backend"):
make_backend({"backend": "mystery"})
def test_make_backend_raises_when_anthropic_key_missing(monkeypatch):
monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)
with pytest.raises(RuntimeError, match="ANTHROPIC_API_KEY"):
make_backend({"backend": "claude", "claude": {"model": "m"}})