Skip to content

Turn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 250,000+ scientists worldwide. 177 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.

add: autoskill — synthesize new skills from observed local screen activity

Renato Umeton412d3f22aec6
diff --git a/scientific-skills/autoskill/.gitignore b/scientific-skills/autoskill/.gitignore
new file mode 100644
index 00000000..75c61823
--- /dev/null
+++ b/scientific-skills/autoskill/.gitignore
@@ -0,0 +1,3 @@
+__pycache__/
+*.pyc
+.pytest_cache/
diff --git a/scientific-skills/autoskill/SKILL.md b/scientific-skills/autoskill/SKILL.md
new file mode 100644
index 00000000..fb4c1cdc
--- /dev/null
+++ b/scientific-skills/autoskill/SKILL.md
@@ -0,0 +1,219 @@
+---
+name: autoskill
+description: Observe the user's screen via screenpipe, detect repeated research workflows, match them against existing scientific-agent-skills, and draft new skills (or composition recipes that chain existing ones) for the patterns not yet covered. Use when the user asks to analyze their recent work and propose skills based on what they actually do. Requires the screenpipe daemon (https://github.com/screenpipe/screenpipe) running locally on port 3030 — the skill has no other data source and will refuse to run if screenpipe is unreachable. All detection runs locally; only redacted cluster summaries reach the LLM.
+allowed-tools: Read Write Edit Bash
+license: MIT license
+metadata:
+ skill-author: K-Dense Inc.
+ requires: screenpipe
+---
+
+# autoskill
+
+> **Requires a running [screenpipe](https://github.com/screenpipe/screenpipe) daemon.** This skill has no alternate data source — it reads exclusively from the local screenpipe HTTP API (default `http://localhost:3030`). If the daemon isn't running, `run()` raises `ScreenpipeUnreachable` with install instructions.
+
+> **Network access & environment variables.** This skill makes authenticated HTTP requests to (a) the user's local screenpipe daemon on loopback, and (b) the user-configured LLM backend — one of `http://localhost:1234/v1` (LM Studio, default), `https://api.anthropic.com` (opt-in Claude), or a user-supplied BYOK Foundry gateway. The skill reads three environment variables — `SCREENPIPE_TOKEN`, `ANTHROPIC_API_KEY`, `FOUNDRY_API_KEY` — and uses each only to authenticate to the single endpoint its name implies. No other network destinations, no telemetry, no data egress to any third party.
+
+## Overview
+
+Turn the user's own workflow history — captured passively by the local [screenpipe](https://github.com/screenpipe/screenpipe) daemon — into new skills. This skill is on-demand: the user invokes it with a time window, it queries screenpipe's local HTTP API, clusters repeated workflow patterns, compares each pattern against the existing skills in this repo, and produces a staged folder of proposals the user can review, edit, and promote.
+
+## When to Use This Skill
+
+Invoke this skill when the user asks to:
+- "Analyze my last 4 hours / day / week and propose new skills."
+- "Look at what I've been doing and tell me what's not covered yet."
+- "Draft a skill from my recent workflow."
+- "Find composition recipes for workflows I repeat."
+
+Do **not** invoke it for one-off questions about screenpipe itself, for real-time screen queries, or without an explicit user request — the skill analyzes sensitive local content and must stay explicitly user-triggered.
+
+## Privacy Posture
+
+- **Screenpipe handles app/window filtering at capture time.** Install a starter deny-list by copying `references/screenpipe-config.yaml` into the user's screenpipe config. Sensitive apps (password managers, messaging, banking) are never OCR'd in the first place.
+- **Raw OCR never leaves the machine.** `scripts/fetch_window.py` pulls data over localhost HTTP. `scripts/cluster.py` reduces the timeline to app/duration/title summaries. `scripts/redact.py` strips emails, API keys, bearer tokens, and phone numbers as defense-in-depth before any cluster summary reaches the LLM.
+- **LLM backend defaults to `local`.** The recommended setup is [LM Studio](https://lmstudio.ai/) running `Gemma-4-31B-it` — strong reasoning at a size that fits on most workstation GPUs, and no data ever leaves your machine. Cloud backends (`claude`, `foundry`) are opt-in and documented in `config.yaml` for users who explicitly want them. Detection and embeddings always run locally regardless of backend choice.
+- **Dry-run mode** (`--plan`) prints the exact timeline that will be analyzed before any LLM call.
+- **TLS for localhost** (optional, for corporate policy): see `references/https-proxy.md` for the Caddy pattern.
+
+## Prerequisites
+
+### 1. Screenpipe daemon
+
+Either install the official release or build from source. Either way the daemon binds HTTP on `localhost:3030` by default.
+
+**From source** (recommended if you want the CLI daemon without the desktop GUI):
+
+```bash
+git clone --depth 1 https://github.com/mediar-ai/screenpipe.git
+cd screenpipe
+cargo build -p screenpipe-engine --release
+# System deps (macOS): cmake + full Xcode.app (not just Command Line Tools).
+# brew install cmake
+# # if xcodebuild plug-ins error: sudo xcodebuild -runFirstLaunch
+./target/release/screenpipe doctor # confirm permissions + ffmpeg
+./target/release/screenpipe record --disable-audio --use-pii-removal
+```
+
+First run will prompt for macOS Screen Recording permission. Grant it and relaunch.
+
+### 2. Screenpipe API token
+
+The local API now requires bearer auth. Retrieve your token and export it:
+
+```bash
+export SCREENPIPE_TOKEN=$(screenpipe auth token)
+```
+
+(Or set `screenpipe.token` directly in `config.yaml` — env var is preferred since it keeps secrets out of version control.)
+
+### 3. Python environment
+
+Via `pipenv` from the repo root:
+
+```bash
+pipenv install httpx pyyaml sentence-transformers
+```
+
+The embedding model (`sentence-transformers/all-MiniLM-L6-v2`, ~80 MB) downloads on first run.
+
+### 4. Local LLM (default path) — LM Studio
+
+- Install [LM Studio](https://lmstudio.ai/).
+- Download `Gemma-4-31B-it` (or another strong reasoning model; adjust `local.model` in `config.yaml`).
+- Load it via the CLI for headless use (no GUI required):
+
+```bash
+lms load gemma-4-31b-it --context-length 131072 --gpu max -y
+lms status # confirm server running on :1234
+```
+
+### 5. Cloud LLM backends (optional, opt-in)
+
+Only if you explicitly opt out of local:
+- `claude`: set `ANTHROPIC_API_KEY`, flip `backend: claude` in `config.yaml`.
+- `foundry`: set `FOUNDRY_API_KEY`, flip `backend: foundry`, set `foundry.endpoint` to your corporate gateway URL.
+
+## Architecture
+
+```
+screenpipe daemon (user-installed)
+ │ HTTP on localhost:3030
+ ▼
+scripts/fetch_window.py → normalized timeline events
+scripts/redact.py → regex scrub (defense-in-depth)
+scripts/cluster.py → sessions + clusters (local only)
+scripts/match_skills.py → top-k vs existing 135 skills (local embeddings)
+scripts/synthesize.py → LLM judge: reuse / compose / novel
+ │
+ ▼
+~/.autoskill/proposed/<timestamp>/ (default; override with --out)
+ ├── report.md
+ ├── composition-recipes/<name>/SKILL.md
+ └── new-skills/<name>/SKILL.md
+
+scripts/promote.py → user-approved proposal → scientific-skills/<name>/
+```
+
+## Workflow
+
+The skill ships a unified CLI at `scripts/autoskill.py` with three subcommands:
+
+```bash
+python scripts/autoskill.py doctor --config config.yaml --skills-dir ../
+python scripts/autoskill.py run --start ... --end ... --config config.yaml
+python scripts/autoskill.py promote --proposed ~/.autoskill/proposed/<ts> --skills-dir ../ --name <skill>
+```
+
+### 0. Preflight with `doctor`
+
+Before a full run, verify every dependency in one shot:
+
+```bash
+python scripts/autoskill.py doctor \
+ --config scientific-skills/autoskill/config.yaml \
+ --skills-dir scientific-skills
+```
+
+The report covers `config` (backend choice valid), `skills_dir` (exists), `screenpipe` (reachable + authed), and `llm` (LM Studio serving or API key present). Non-zero exit on any failure, with the offending line marked `error`.
+
+### 1. Run the pipeline
+
+```bash
+export SCREENPIPE_TOKEN=$(screenpipe auth token)
+python scripts/autoskill.py run \
+ --start "2026-04-17T00:00:00Z" \
+ --end "2026-04-17T23:59:59Z" \
+ --config scientific-skills/autoskill/config.yaml \
+ --skills-dir scientific-skills
+```
+
+Proposals land in `~/.autoskill/proposed/<timestamp>/` by default, keeping experimental output out of the skills repo. Pass `--out PATH` to override.
+
+Internally:
+1. **Fetch** — `fetch_window` paginates screenpipe's `/search` endpoint, normalizes events to `{ts, app, window_title, text, content_type}`.
+2. **Redact** — `redact` scrubs emails, API keys, bearer tokens, phones from OCR text and window titles as defense-in-depth over screenpipe's own PII removal.
+3. **Cluster** — `segment_sessions` splits on idle gaps (default 10 min) and drops short sessions; `cluster_sessions` groups sessions by app-signature and keeps clusters of size `min_cluster_size` (default 2).
+4. **Match** — `load_skill_descriptions` reads frontmatter from every `SKILL.md` in `scientific-skills/`; `top_k_matches` ranks each cluster against all skills using local `sentence-transformers` embeddings (cosine similarity).
+5. **Synthesize** — `synthesize` prompts the configured LLM backend to classify each cluster as `reuse`, `compose`, or `novel` and emit a SKILL.md body where appropriate.
+6. **Report** — writes `<out_dir>/<ts>/report.md`, plus `new-skills/<name>/SKILL.md` or `composition-recipes/<name>/SKILL.md` for each proposal.
+
+Add `--dry-run` to stop after clustering; this skips the LLM (and the sentence-transformers load), writing only `plan.md` for inspection.
+
+### 2. Review and promote
+
+Open `~/.autoskill/proposed/<ts>/report.md`, edit drafts in place, delete anything you don't want. Then:
+
+```bash
+python scripts/autoskill.py promote \
+ --proposed ~/.autoskill/proposed/2026-04-17T14-30-00 \
+ --skills-dir scientific-skills \
+ --name zotero-pubmed-helper
+```
+
+`promote` moves the directory into `scientific-skills/<name>/`, refusing to overwrite an existing skill. Exits non-zero with a friendly error if the proposal isn't found or the target already exists.
+
+## Configuration
+
+See `config.yaml` for the full shape. Default values (local-first):
+
+```yaml
+backend: local
+local:
+ endpoint: http://localhost:1234/v1 # LM Studio's Developer server
+ model: Gemma-4-31B-it
+
+screenpipe:
+ url: http://localhost:3030 # or https://screenpipe.local via Caddy
+
+cluster:
+ min_session_minutes: 5
+ idle_gap_minutes: 10
+ min_cluster_size: 2
+```
+
+To opt into a cloud backend:
+
+```yaml
+backend: claude # or foundry
+claude:
+ model: claude-opus-4-7
+```
+
+## Composition recipes vs new skills
+
+- **compose**: the LLM judged that chaining existing skills covers the workflow. The emitted SKILL.md is intentionally thin — frontmatter + a "Workflow" section that invokes existing skills in order. The same agent runtime that discovered the skill can then invoke it end-to-end.
+- **novel**: no combination of existing skills covers it. A fuller SKILL.md is drafted, still following repo conventions (frontmatter, Overview, When to Use, Workflow). The user should always review new-skill drafts before promoting.
+
+## Testing
+
+The skill is covered by a small pytest suite at `tests/`. Each script is unit-tested in isolation with dependency injection (mock HTTP transport, stub backend, stub embedder):
+
+```bash
+cd scientific-skills/autoskill
+python -m pytest tests/ -v
+```
+
+## Composition with other skills in this repo
+
+The autoskill's embedding index covers all 135 sibling skills. Workflows that look like scientific writing will match `scientific-writing` / `literature-review` / `citation-management`; figure work will match `scientific-schematics` / `generate-image` / `infographics`; slide prep matches `scientific-slides` / `pptx`; etc. When a cluster scores high against two or three sibling skills the emitted composition recipe names them explicitly, so the user's future agent invocations use the optimized paths already documented in this repo.
diff --git a/scientific-skills/autoskill/config.yaml b/scientific-skills/autoskill/config.yaml
new file mode 100644
index 00000000..4a020cca
--- /dev/null
+++ b/scientific-skills/autoskill/config.yaml
@@ -0,0 +1,53 @@
+# autoskill configuration
+#
+# LLM backend for skill synthesis. Detection/clustering always runs locally;
+# only redacted cluster summaries are sent to the LLM.
+#
+# Local is the default — your screen content never leaves the machine.
+# Cloud backends (claude, foundry) are available for users who explicitly
+# opt in; see the backend sections below.
+backend: local # local | claude | foundry
+
+# Per-backend settings. Only the selected backend's block is used.
+local:
+ # LM Studio exposes an OpenAI-compatible server. Start it from the
+ # "Developer" tab; the default port is 1234.
+ endpoint: http://localhost:1234/v1
+ # Gemma-4-31B-it is the recommended default: strong reasoning at a size
+ # most modern workstation GPUs can run. Swap for any LM Studio model ID.
+ model: Gemma-4-31B-it
+
+claude:
+ model: claude-opus-4-7
+ # api_key read from ANTHROPIC_API_KEY env var
+
+foundry:
+ endpoint: https://foundry.example.com/anthropic
+ model: claude-opus-4-7
+ # api_key read from FOUNDRY_API_KEY env var
+
+# Screenpipe HTTP endpoint. For TLS, point this at your local Caddy proxy
+# (see references/https-proxy.md).
+screenpipe:
+ url: http://localhost:3030
+ # Screenpipe requires a bearer token for its local API. Either set `token`
+ # here, or export SCREENPIPE_TOKEN in your environment (preferred — keeps
+ # the token out of version control). Retrieve with: `screenpipe auth token`.
+ # token: your-token-here
+
+# Embedding model for matching against existing scientific skills.
+# Local only; no API calls.
+embeddings:
+ model: sentence-transformers/all-MiniLM-L6-v2
+
+# Clustering thresholds.
+cluster:
+ min_session_minutes: 5 # skip sessions shorter than this
+ idle_gap_minutes: 10 # new session after this much inactivity
+ min_cluster_size: 2 # need this many similar sessions before proposing
+
+# Content redaction regexes applied before any cluster summary leaves
+# the local detection layer. Defense-in-depth on top of screenpipe's
+# own app/window filtering.
+redaction:
+ enabled: true
diff --git a/scientific-skills/autoskill/references/https-proxy.md b/scientific-skills/autoskill/references/https-proxy.md
new file mode 100644
index 00000000..95266973
--- /dev/null
+++ b/scientific-skills/autoskill/references/https-proxy.md
@@ -0,0 +1,62 @@
+# Optional: TLS for localhost screenpipe access
+
+Screenpipe's HTTP server (Axum, binding `localhost:3030`) speaks plain HTTP. For a Python script running as the same user on the same host, plain HTTP is adequate — loopback traffic never hits a network adapter, so TLS provides no additional confidentiality.
+
+TLS on localhost is only useful when:
+
+- A corporate security policy mandates "TLS everywhere" regardless of transport.
+- The screenpipe endpoint is tunneled or exposed off-host.
+- A browser client requires a "secure context" (Service Workers, WebCrypto).
+
+If you need it, put a one-line Caddy reverse proxy in front. Caddy's `tls internal` generates and trusts a local CA automatically.
+
+## Caddy
+
+Install:
+
+```bash
+brew install caddy # macOS
+# or see https://caddyserver.com/docs/install
+```
+
+Add to your `Caddyfile`:
+
+```caddyfile
+screenpipe.local {
+ tls internal
+ reverse_proxy localhost:3030
+}
+```
+
+Ensure `screenpipe.local` resolves to loopback (add to `/etc/hosts`):
+
+```
+127.0.0.1 screenpipe.local
+```
+
+Start Caddy:
+
+```bash
+caddy run
+```
+
+Then update autoskill's `config.yaml`:
+
+```yaml
+screenpipe:
+ url: https://screenpipe.local
+```
+
+No code change is required on the autoskill side. `httpx` handles both HTTP and HTTPS transparently.
+
+## mkcert (alternative)
+
+If you prefer managing the cert yourself instead of Caddy's internal CA:
+
+```bash
+brew install mkcert
+mkcert -install
+mkcert localhost 127.0.0.1
+```
+
+Then terminate TLS with nginx, Caddy, or stunnel using the generated cert.
diff --git a/scientific-skills/autoskill/references/screenpipe-config.yaml b/scientific-skills/autoskill/references/screenpipe-config.yaml
new file mode 100644
index 00000000..5a6c0115
--- /dev/null
+++ b/scientific-skills/autoskill/references/screenpipe-config.yaml
@@ -0,0 +1,61 @@
+# Starter screenpipe configuration for autoskill users.
+#
+# Copy the relevant sections into your screenpipe config (or pass as CLI
+# flags when starting the daemon). Screenpipe handles app/window filtering
+# at capture time — sensitive apps on this list will never be OCR'd, so
+# their content never reaches autoskill's pipeline.
+#
+# Reference: https://github.com/screenpipe/screenpipe
+#
+# Review and edit for your setup. This is a conservative baseline, not
+# an exhaustive list. Add any app where you handle secrets.
+
+ignored_apps:
+ # Password managers
+ - "1Password"
+ - "Bitwarden"
+ - "Dashlane"
+ - "Keeper"
+ - "LastPass"
+ - "KeePassXC"
+
+ # Private messaging
+ - "Signal"
+ - "Telegram"
+ - "WhatsApp"
+ - "iMessage"
+ - "Messages"
+
+ # Mail composition (inbound reading is fine; composition often contains secrets)
+ # Remove if you explicitly want mail workflows analyzed.
+ - "Mail"
+ - "Outlook"
+
+ # Banking / finance apps (add yours)
+ # - "Bank of America"
+ # - "Chase"
+
+# Window title globs to ignore (matched across all apps).
+# Useful for catching sensitive URLs in browsers that are otherwise OK to observe.
+ignored_windows:
+ - "*Bitwarden*"
+ - "*1Password*"
+ - "*login*"
+ - "*Sign in*"
+ - "*Private Browsing*"
+ - "*Incognito*"
+ - "*online banking*"
+ - "*bank*"
+ - "*account settings*"
+
+# Optionally restrict capture to specific hours (local time).
+# Uncomment to apply.
+# hours:
+# start: "09:00"
+# end: "19:00"
+
+# Content types to capture. Drop "audio" if you don't want transcripts.
+content_types:
+ - ocr
+ - ui
+ # - audio
diff --git a/scientific-skills/autoskill/scripts/autoskill.py b/scientific-skills/autoskill/scripts/autoskill.py
new file mode 100644
index 00000000..8d5c2f3f
--- /dev/null
+++ b/scientific-skills/autoskill/scripts/autoskill.py
@@ -0,0 +1,35 @@
+"""Unified CLI for the autoskill skill.
+
+Subcommands:
+ run — detect workflows and draft proposed skills
+ doctor — verify screenpipe + LM Studio + config + skills dir
+ promote — move an approved proposal into scientific-skills/
+"""
+
+import argparse
+import sys
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(prog="autoskill", description=__doc__,
+ formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("command", choices=["run", "doctor", "promote"],
+ help="subcommand to run")
+ parser.add_argument("rest", nargs=argparse.REMAINDER,
+ help="arguments forwarded to the subcommand")
+ args = parser.parse_args(argv)
+
+ if args.command == "run":
+ import run as _run
+ return _run.main(args.rest)
+ if args.command == "doctor":
+ import doctor as _doctor
+ return _doctor.main(args.rest)
+ if args.command == "promote":
+ import promote as _promote
+ return _promote.main(args.rest)
+ raise AssertionError(f"unreachable: {args.command!r}")
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scientific-skills/autoskill/scripts/backends.py b/scientific-skills/autoskill/scripts/backends.py
new file mode 100644
index 00000000..07352977
--- /dev/null
+++ b/scientific-skills/autoskill/scripts/backends.py
@@ -0,0 +1,71 @@
+import os
+
+import httpx
+
+
+class ClaudeBackend:
+ def __init__(self, api_key, model, client=None):
+ self.api_key = api_key
+ self.model = model
+ self.client = client or httpx.Client(base_url="https://api.anthropic.com", timeout=60.0)
+
+ def __call__(self, prompt):
+ response = self.client.post(
+ "/v1/messages",
+ headers={
+ "x-api-key": self.api_key,
+ "anthropic-version": "2023-06-01",
+ "content-type": "application/json",
+ },
+ json={
+ "model": self.model,
+ "max_tokens": 4096,
+ "messages": [{"role": "user", "content": prompt}],
+ },
+ )
+ response.raise_for_status()
+ payload = response.json()
+ return payload["content"][0]["text"]
+
+
+class LocalBackend:
+ def __init__(self, endpoint, model, client=None):
+ self.endpoint = endpoint
+ self.model = model
+ self.client = client or httpx.Client(base_url=endpoint, timeout=120.0)
+
+ def __call__(self, prompt):
+ response = self.client.post(
+ "/chat/completions",
+ json={
+ "model": self.model,
+ "messages": [{"role": "user", "content": prompt}],
+ },
+ )
+ response.raise_for_status()
+ payload = response.json()
+ return payload["choices"][0]["message"]["content"]
+
+
+def make_backend(config):
+ kind = config.get("backend")
+ if kind == "claude":
+ api_key = os.environ.get("ANTHROPIC_API_KEY")
+ if not api_key:
+ raise RuntimeError("ANTHROPIC_API_KEY environment variable not set")
+ model = config.get("claude", {}).get("model", "claude-opus-4-7")
+ return ClaudeBackend(api_key=api_key, model=model)
+
+ if kind == "foundry":
+ api_key = os.environ.get("FOUNDRY_API_KEY")
+ if not api_key:
+ raise RuntimeError("FOUNDRY_API_KEY environment variable not set")
+ f = config.get("foundry", {})
+ client = httpx.Client(base_url=f["endpoint"], timeout=60.0)
+ return ClaudeBackend(api_key=api_key, model=f.get("model", "claude-opus-4-7"), client=client)
+
+ if kind == "local":
+ l = config.get("local", {})
+ return LocalBackend(endpoint=l["endpoint"], model=l["model"])
+
+ raise ValueError(f"unknown backend: {kind!r}")
diff --git a/scientific-skills/autoskill/scripts/cluster.py b/scientific-skills/autoskill/scripts/cluster.py
new file mode 100644
index 00000000..f01e6375
--- /dev/null
+++ b/scientific-skills/autoskill/scripts/cluster.py
@@ -0,0 +1,54 @@
+from collections import defaultdict
+
+
+def segment_sessions(events, idle_gap_seconds, min_session_seconds):
+ if not events:
+ return []
+ events = sorted(events, key=lambda e: e["ts"])
+ groups = [[events[0]]]
+ for prev, curr in zip(events, events[1:]):
+ if curr["ts"] - prev["ts"] > idle_gap_seconds:
+ groups.append([curr])
+ else:
+ groups[-1].append(curr)
+
+ sessions = []
+ for group in groups:
+ duration = group[-1]["ts"] - group[0]["ts"]
+ if duration < min_session_seconds:
+ continue
+ apps, seen = [], set()
+ for evt in group:
+ if evt["app"] not in seen:
+ seen.add(evt["app"])
+ apps.append(evt["app"])
+ sessions.append({
+ "start_ts": group[0]["ts"],
+ "end_ts": group[-1]["ts"],
+ "duration_seconds": duration,
+ "apps": apps,
+ "window_titles": [e["window_title"] for e in group if e.get("window_title")],
+ })
+ return sessions
+
+
+def cluster_sessions(sessions, min_cluster_size):
+ buckets = defaultdict(list)
+ for s in sessions:
+ buckets[tuple(s["apps"])].append(s)
+
+ clusters = []
+ for apps, members in buckets.items():
+ if len(members) < min_cluster_size:
+ continue
+ example_titles = []
+ for m in members:
+ if m["window_titles"]:
+ example_titles.append(m["window_titles"][0])
+ clusters.append({
+ "apps": list(apps),
+ "session_count": len(members),
+ "total_duration_seconds": sum(m["duration_seconds"] for m in members),
+ "example_titles": example_titles,
+ })
+ return clusters
diff --git a/scientific-skills/autoskill/scripts/doctor.py b/scientific-skills/autoskill/scripts/doctor.py
new file mode 100644
index 00000000..c86a1ea3
--- /dev/null
+++ b/scientific-skills/autoskill/scripts/doctor.py
@@ -0,0 +1,108 @@
+import argparse
+import os
+import sys
+from pathlib import Path
+
+import httpx
+
+_VALID_BACKENDS = {"local", "claude", "foundry"}
+
+
+def default_screenpipe_probe(config):
+ sp = config.get("screenpipe", {})
+ url = sp.get("url", "http://localhost:3030")
+ token = sp.get("token") or os.environ.get("SCREENPIPE_TOKEN")
+ headers = {"Authorization": f"Bearer {token}"} if token else {}
+ try:
+ r = httpx.get(f"{url}/health", headers=headers, timeout=5.0)
+ if r.status_code == 200:
+ return ("ok", url)
+ return ("error", f"{url} returned HTTP {r.status_code}")
+ except httpx.HTTPError as e:
+ return ("error", f"{url}: {e}")
+
+
+def default_llm_probe(config):
+ kind = config.get("backend")
+ if kind == "local":
+ endpoint = config.get("local", {}).get("endpoint", "http://localhost:1234/v1")
+ try:
+ r = httpx.get(f"{endpoint}/models", timeout=5.0)
+ if r.status_code == 200:
+ return ("ok", endpoint)
+ return ("error", f"{endpoint} returned HTTP {r.status_code}")
+ except httpx.HTTPError as e:
+ return ("error", f"{endpoint}: {e}")
+ if kind == "claude":
+ if not os.environ.get("ANTHROPIC_API_KEY"):
+ return ("error", "ANTHROPIC_API_KEY not set")
+ return ("ok", "ANTHROPIC_API_KEY present (not probed)")
+ if kind == "foundry":
+ if not os.environ.get("FOUNDRY_API_KEY"):
+ return ("error", "FOUNDRY_API_KEY not set")
+ return ("ok", "FOUNDRY_API_KEY present (not probed)")
+ return ("error", f"unknown backend: {kind!r}")
+
+
+def check(config, *, skills_dir, screenpipe_probe, llm_probe):
+ result = {}
+
+ kind = config.get("backend")
+ if kind in _VALID_BACKENDS:
+ result["config"] = ("ok", f"backend={kind}")
+ else:
+ result["config"] = ("error", f"unknown backend: {kind!r}")
+
+ skills_dir = Path(skills_dir)
+ if skills_dir.is_dir():
+ result["skills_dir"] = ("ok", str(skills_dir))
+ else:
+ result["skills_dir"] = ("error", f"not a directory: {skills_dir}")
+
+ result["screenpipe"] = screenpipe_probe(config)
+ result["llm"] = llm_probe(config)
+ return result
+
+
+def _format_report(result: dict) -> str:
+ lines = ["autoskill doctor", "================"]
+ for key in ("config", "skills_dir", "screenpipe", "llm"):
+ status, detail = result[key]
+ lines.append(f" {key:12s}: {status:5s} {detail}")
+ return "\n".join(lines)
+
+
+def main(argv=None):
+ import yaml
+
+ parser = argparse.ArgumentParser(
+ prog="autoskill-doctor",
+ description="Check that screenpipe, LM Studio, config, and skills dir are ready.",
+ )
+ parser.add_argument("--config", required=True,
+ help="path to autoskill config.yaml")
+ parser.add_argument("--skills-dir", required=True,
+ help="path to scientific-skills/")
+ args = parser.parse_args(argv)
+
+ config = yaml.safe_load(Path(args.config).read_text())
+ result = check(
+ config,
+ skills_dir=args.skills_dir,
+ screenpipe_probe=default_screenpipe_probe,
+ llm_probe=default_llm_probe,
+ )
+
+ report = _format_report(result)
+ print(report)
+
+ any_error = any(status == "error" for status, _ in result.values())
+ if any_error:
+ print("\ndoctor: one or more checks failed", file=sys.stderr)
+ return 1
+ print("\ndoctor: all checks passed")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scientific-skills/autoskill/scripts/fetch_window.py b/scientific-skills/autoskill/scripts/fetch_window.py
new file mode 100644
index 00000000..1d0d6a88
--- /dev/null
+++ b/scientific-skills/autoskill/scripts/fetch_window.py
@@ -0,0 +1,33 @@
+_MAX_PAGES = 10_000 # bounded exit: hard ceiling so the loop cannot spin forever
+
+
+def fetch_window(client, start_time, end_time, page_size=50, token=None):
+ events = []
+ offset = 0
+ headers = {"Authorization": f"Bearer {token}"} if token else {}
+ for _page in range(_MAX_PAGES):
+ response = client.get("/search", params={
+ "start_time": start_time,
+ "end_time": end_time,
+ "limit": page_size,
+ "offset": offset,
+ }, headers=headers)
+ response.raise_for_status()
+ payload = response.json()
+ data = payload.get("data", [])
+ total = payload.get("pagination", {}).get("total", 0)
+
+ for item in data:
+ content = item.get("content", {})
+ events.append({
+ "ts": content.get("timestamp"),
+ "app": content.get("app_name", ""),
+ "window_title": content.get("window_name", ""),
+ "text": content.get("text", ""),
+ "content_type": item.get("type", "").lower(),
+ })
+
+ offset += len(data)
+ if not data or offset >= total:
+ break
+ return events
diff --git a/scientific-skills/autoskill/scripts/match_skills.py b/scientific-skills/autoskill/scripts/match_skills.py
new file mode 100644
index 00000000..6bdb255c
--- /dev/null
+++ b/scientific-skills/autoskill/scripts/match_skills.py
@@ -0,0 +1,46 @@
+import math
+from pathlib import Path
+
+
+def _parse_frontmatter(content: str) -> dict:
+ if not content.startswith("---"):
+ return {}
+ _, _, rest = content.partition("---\n")
+ block, _, _ = rest.partition("\n---")
+ out = {}
+ for line in block.splitlines():
+ if ":" not in line:
+ continue
+ key, _, value = line.partition(":")
+ out[key.strip()] = value.strip()
+ return out
+
+
+def load_skill_descriptions(skills_dir):
+ skills_dir = Path(skills_dir)
+ skills = []
+ for skill_md in sorted(skills_dir.glob("*/SKILL.md")):
+ fm = _parse_frontmatter(skill_md.read_text())
+ if "name" in fm and "description" in fm:
+ skills.append({"name": fm["name"], "description": fm["description"]})
+ return skills
+
+
+def _cosine(a, b):
+ dot = sum(x * y for x, y in zip(a, b))
+ na = math.sqrt(sum(x * x for x in a))
+ nb = math.sqrt(sum(y * y for y in b))
+ if na == 0 or nb == 0:
+ return 0.0
+ return dot / (na * nb)
+
+
+def top_k_matches(query, skills, embedder, k):
+ q = embedder(query)
+ scored = [
+ {"name": s["name"], "description": s["description"],
+ "score": _cosine(q, embedder(s["description"]))}
+ for s in skills
+ ]
+ scored.sort(key=lambda r: r["score"], reverse=True)
+ return scored[:k]
diff --git a/scientific-skills/autoskill/scripts/promote.py b/scientific-skills/autoskill/scripts/promote.py
new file mode 100644
index 00000000..f8ccb469
--- /dev/null
+++ b/scientific-skills/autoskill/scripts/promote.py
@@ -0,0 +1,58 @@
+import argparse
+import shutil
+import sys
+from pathlib import Path
+
+
+class PromoteError(Exception):
+ pass
+
+
+_KINDS = ("new-skills", "composition-recipes")
+
+
+def promote(proposed_path, skills_dir, name):
+ proposed_path = Path(proposed_path)
+ skills_dir = Path(skills_dir)
+
+ source = None
+ for kind in _KINDS:
+ candidate = proposed_path / kind / name
+ if candidate.is_dir():
+ source = candidate
+ break
+ if source is None:
+ raise PromoteError(f"proposed skill {name!r} not found under {proposed_path}")
+
+ target = skills_dir / name
+ if target.exists():
+ raise PromoteError(f"target {target} already exists")
+
+ shutil.move(str(source), str(target))
+ return target
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(
+ prog="autoskill-promote",
+ description="Move a proposed skill from _proposed/<ts>/ into scientific-skills/",
+ )
+ parser.add_argument("--proposed", required=True,
+ help="path to the _proposed/<ts>/ directory")
+ parser.add_argument("--skills-dir", required=True,
+ help="path to scientific-skills/")
+ parser.add_argument("--name", required=True, help="skill name to promote")
+ args = parser.parse_args(argv)
+
+ try:
+ target = promote(args.proposed, args.skills_dir, args.name)
+ except PromoteError as e:
+ print(f"promote failed: {e}", file=sys.stderr)
+ return 1
+
+ print(f"promoted: {args.name} -> {target}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scientific-skills/autoskill/scripts/redact.py b/scientific-skills/autoskill/scripts/redact.py
new file mode 100644
index 00000000..3c94043c
--- /dev/null
+++ b/scientific-skills/autoskill/scripts/redact.py
@@ -0,0 +1,40 @@
+import re
+
+# Order matters: multi-line and prefixed patterns run before narrower ones.
+_PATTERNS = [
+ (re.compile(r"-----BEGIN [A-Z ]+PRIVATE KEY-----[\s\S]*?-----END [A-Z ]+PRIVATE KEY-----"),
+ "[REDACTED:private_key]"),
+
+ # Known-env-var secret assignments: NAME=value (catches long values only)
+ (re.compile(
+ r"\b(?:AWS_SECRET_ACCESS_KEY|AWS_ACCESS_KEY_ID|GITHUB_TOKEN|HF_TOKEN"
+ r"|ANTHROPIC_API_KEY|OPENAI_API_KEY|FOUNDRY_API_KEY|SCREENPIPE_TOKEN"
+ r"|GOOGLE_API_KEY|SLACK_TOKEN|DEEPGRAM_API_KEY)"
+ r"\s*=\s*[^\s\"']+"
+ ), "[REDACTED:kv_secret]"),
+
+ (re.compile(r"Bearer\s+[A-Za-z0-9_\-\.=]+"), "[REDACTED:bearer]"),
+
+ (re.compile(r"\beyJ[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+"),
+ "[REDACTED:jwt]"),
+
+ (re.compile(r"\bxox[bpars]-[A-Za-z0-9\-]{10,}"), "[REDACTED:api_key]"),
+ (re.compile(r"\bhf_[A-Za-z0-9]{32,}"), "[REDACTED:api_key]"),
+ (re.compile(r"\bsk-[A-Za-z0-9_\-]{20,}"), "[REDACTED:api_key]"),
+ (re.compile(r"\b(?:sk|pk|rk)_live_[A-Za-z0-9]{24,}"), "[REDACTED:api_key]"),
+ (re.compile(r"\bghp_[A-Za-z0-9]{36}\b"), "[REDACTED:api_key]"),
+ (re.compile(r"\bAKIA[0-9A-Z]{16}\b"), "[REDACTED:api_key]"),
+ (re.compile(r"\bAIza[A-Za-z0-9_\-]{35}\b"), "[REDACTED:api_key]"),
+
+ (re.compile(r"[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}"),
+ "[REDACTED:email]"),
+
+ (re.compile(r"\(\d{3}\)\s*\d{3}-\d{4}"), "[REDACTED:phone]"),
+ (re.compile(r"\b\d{3}-\d{2}-\d{4}\b"), "[REDACTED:ssn]"),
+]
+
+
+def redact(text: str) -> str:
+ for pattern, placeholder in _PATTERNS:
+ text = pattern.sub(placeholder, text)
+ return text
diff --git a/scientific-skills/autoskill/scripts/run.py b/scientific-skills/autoskill/scripts/run.py
new file mode 100644
index 00000000..5235137b
--- /dev/null
+++ b/scientific-skills/autoskill/scripts/run.py
@@ -0,0 +1,194 @@
+import datetime as _dt
+from pathlib import Path
+
+import httpx
+
+from cluster import cluster_sessions, segment_sessions
+from fetch_window import fetch_window
+from match_skills import load_skill_descriptions, top_k_matches
+from redact import redact
+from synthesize import synthesize
+
+
+class ScreenpipeUnreachable(RuntimeError):
+ """Raised when the screenpipe daemon cannot be reached.
+
+ The autoskill skill cannot run without screenpipe. Install it from
+ https://github.com/screenpipe/screenpipe and start the daemon before
+ invoking this skill.
+ """
+
+
+def _default_now() -> str:
+ return _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H-%M-%S")
+
+
+def _cluster_query(cluster: dict) -> str:
+ parts = ["apps: " + ", ".join(cluster["apps"])]
+ if cluster.get("example_titles"):
+ parts.append("titles: " + "; ".join(cluster["example_titles"]))
+ return " | ".join(parts)
+
+
+def _write_plan(proposed_path: Path, clusters: list[dict]) -> None:
+ lines = ["# Dry-run plan", ""]
+ for i, c in enumerate(clusters, 1):
+ lines += [
+ f"## Cluster {i}",
+ f"- apps: {', '.join(c['apps'])}",
+ f"- sessions: {c['session_count']}",
+ f"- total_duration_seconds: {c['total_duration_seconds']}",
+ f"- example titles: {'; '.join(c.get('example_titles', []))}",
+ "",
+ ]
+ (proposed_path / "plan.md").write_text("\n".join(lines))
+
+
+def _write_report(proposed_path: Path, results: list[dict]) -> None:
+ lines = ["# autoskill report", ""]
+ if not results:
+ lines.append("No clusters met the minimum size threshold. Nothing to propose.")
+ for r in results:
+ c = r["cluster"]
+ lines += [
+ f"## {', '.join(c['apps'])} — {c['session_count']}× ({c['total_duration_seconds']}s)",
+ f"- verdict: **{r['verdict']}**",
+ ]
+ if r["verdict"] == "reuse":
+ lines.append(f"- matched skill: `{r['target']}`")
+ else:
+ lines.append(f"- draft: `{r['draft_path']}`")
+ lines.append("- top matches:")
+ for s in r["top_k"]:
+ lines.append(f" - `{s['name']}` (score={s['score']:.2f})")
+ lines.append("")
+ (proposed_path / "report.md").write_text("\n".join(lines))
+
+
+def run(config, *, start_time, end_time, out_dir,
+ screenpipe_client, backend, embedder, skills_dir,
+ screenpipe_token=None, now=None, dry_run=False):
+ now = now or _default_now
+ try:
+ events = fetch_window(screenpipe_client, start_time, end_time,
+ token=screenpipe_token)
+ except (httpx.ConnectError, httpx.ConnectTimeout) as e:
+ base = getattr(screenpipe_client, "base_url", "http://localhost:3030")
+ raise ScreenpipeUnreachable(
+ f"cannot reach screenpipe at {base}: {e}. "
+ "Install and start the daemon — see "
+ "https://github.com/screenpipe/screenpipe — "
+ "or point config.yaml's screenpipe.url at your instance."
+ ) from e
+
+ for e in events:
+ e["text"] = redact(e.get("text", ""))
+ e["window_title"] = redact(e.get("window_title", ""))
+
+ cluster_cfg = config.get("cluster", {})
+ idle_gap = cluster_cfg.get("idle_gap_minutes", 10) * 60
+ min_session = cluster_cfg.get("min_session_minutes", 5) * 60
+ min_cluster = cluster_cfg.get("min_cluster_size", 2)
+
+ # fetch_window returns ts as ISO strings; convert to epoch for segmentation
+ for e in events:
+ if isinstance(e["ts"], str):
+ e["ts"] = int(_dt.datetime.fromisoformat(e["ts"].replace("Z", "+00:00")).timestamp())
+
+ sessions = segment_sessions(events, idle_gap_seconds=idle_gap, min_session_seconds=min_session)
+ clusters = cluster_sessions(sessions, min_cluster_size=min_cluster)
+
+ proposed_path = Path(out_dir) / now()
+ proposed_path.mkdir(parents=True, exist_ok=True)
+
+ if dry_run:
+ _write_plan(proposed_path, clusters)
+ return proposed_path
+
+ if not clusters:
+ _write_report(proposed_path, [])
+ return proposed_path
+
+ skills = load_skill_descriptions(Path(skills_dir))
+ results = []
+ for cluster in clusters:
+ query = _cluster_query(cluster)
+ top_k = top_k_matches(query, skills, embedder=embedder, k=5)
+ decision = synthesize(cluster, top_k, backend=backend)
+
+ entry = {"cluster": cluster, "top_k": top_k, "verdict": decision["verdict"]}
+ if decision["verdict"] == "reuse":
+ entry["target"] = decision.get("target")
+ else:
+ kind = "new-skills" if decision["verdict"] == "novel" else "composition-recipes"
+ name = decision["name"]
+ draft_dir = proposed_path / kind / name
+ draft_dir.mkdir(parents=True)
+ (draft_dir / "SKILL.md").write_text(decision["skill_body"])
+ entry["draft_path"] = str(draft_dir.relative_to(proposed_path))
+ results.append(entry)
+
+ _write_report(proposed_path, results)
+ return proposed_path
+
+
+def main(argv=None):
+ import argparse
+ import sys
+
+ import httpx
+ import yaml
+
+ from backends import make_backend
+
+ parser = argparse.ArgumentParser(prog="autoskill")
+ parser.add_argument("--start", required=True, help="ISO start time, e.g. 2026-04-17T00:00:00Z")
+ parser.add_argument("--end", required=True, help="ISO end time")
+ parser.add_argument("--config", default=str(Path(__file__).resolve().parent.parent / "config.yaml"))
+ parser.add_argument("--out", default=None,
+ help="output directory for proposals (default: ~/.autoskill/proposed)")
+ parser.add_argument("--skills-dir", default=None,
+ help="path to scientific-skills/ (default: parent of this skill's dir)")
+ parser.add_argument("--dry-run", action="store_true",
+ help="stop after clustering; do not call the LLM backend")
+ args = parser.parse_args(argv)
+
+ config = yaml.safe_load(Path(args.config).read_text())
+
+ here = Path(__file__).resolve()
+ skills_dir = Path(args.skills_dir) if args.skills_dir else here.parent.parent.parent
+ out_dir = Path(args.out) if args.out else Path.home() / ".autoskill" / "proposed"
+
+ import os
+ screenpipe_cfg = config.get("screenpipe", {})
+ screenpipe_url = screenpipe_cfg.get("url", "http://localhost:3030")
+ screenpipe_token = (screenpipe_cfg.get("token")
+ or os.environ.get("SCREENPIPE_TOKEN"))
+ screenpipe_client = httpx.Client(base_url=screenpipe_url, timeout=60.0)
+
+ if args.dry_run:
+ backend = None
+ embedder = None
+ else:
+ backend = make_backend(config)
+ from sentence_transformers import SentenceTransformer
+ model = SentenceTransformer(
+ config.get("embeddings", {}).get("model", "sentence-transformers/all-MiniLM-L6-v2")
+ )
+
+ def embedder(text: str):
+ return list(map(float, model.encode(text)))
+
+ proposed = run(
+ config,
+ start_time=args.start, end_time=args.end, out_dir=out_dir,
+ screenpipe_client=screenpipe_client, backend=backend, embedder=embedder,
+ skills_dir=skills_dir, screenpipe_token=screenpipe_token,
+ dry_run=args.dry_run,
+ )
+ print(f"proposals written to: {proposed}", file=sys.stderr)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scientific-skills/autoskill/scripts/synthesize.py b/scientific-skills/autoskill/scripts/synthesize.py
new file mode 100644
index 00000000..b7ffae29
--- /dev/null
+++ b/scientific-skills/autoskill/scripts/synthesize.py
@@ -0,0 +1,72 @@
+import json
+import re
+
+VALID_VERDICTS = {"reuse", "compose", "novel"}
+
+
+class SynthesisError(Exception):
+ pass
+
+
+def _build_prompt(cluster, top_k_skills):
+ apps = ", ".join(cluster["apps"])
+ titles = "; ".join(cluster.get("example_titles", []))
+ candidates = "\n".join(
+ f"- {s['name']} (score={s['score']:.2f}): {s['description']}"
+ for s in top_k_skills
+ )
+ return f"""You are classifying an observed user workflow against an existing skill library.
+
+Cluster:
+- apps: {apps}
+- sessions: {cluster['session_count']}
+- total_duration_seconds: {cluster['total_duration_seconds']}
+- example titles: {titles}
+
+Candidate existing skills (ranked by semantic similarity):
+{candidates}
+
+Decide one of:
+- "reuse": an existing skill already covers this workflow.
+- "compose": no single skill covers it, but chaining existing skills does. Draft a thin SKILL.md that invokes them in order.
+- "novel": not covered; draft a full new SKILL.md.
+
+Respond with a single JSON object:
+- reuse: {{"verdict": "reuse", "target": "<skill-name>"}}
+- compose: {{"verdict": "compose", "name": "<new-skill-name>", "skill_body": "<SKILL.md body>"}}
+- novel: {{"verdict": "novel", "name": "<new-skill-name>", "skill_body": "<SKILL.md body>"}}
+"""
+
+
+def _extract_json(text: str) -> dict:
+ fence = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", text, re.DOTALL)
+ if fence:
+ candidate = fence.group(1)
+ else:
+ start = text.find("{")
+ end = text.rfind("}")
+ if start == -1 or end == -1 or end <= start:
+ raise SynthesisError(f"no JSON object found in response: {text!r}")
+ candidate = text[start:end + 1]
+ try:
+ return json.loads(candidate)
+ except json.JSONDecodeError as e:
+ raise SynthesisError(f"invalid JSON in response: {e}") from e
+
+
+def synthesize(cluster, top_k_skills, backend):
+ prompt = _build_prompt(cluster, top_k_skills)
+ response = backend(prompt)
+ payload = _extract_json(response)
+
+ verdict = payload.get("verdict")
+ if verdict not in VALID_VERDICTS:
+ raise SynthesisError(f"unknown verdict: {verdict!r}")
+
+ result = {"verdict": verdict, "skill_body": None}
+ if verdict == "reuse":
+ result["target"] = payload.get("target")
+ else:
+ result["name"] = payload.get("name")
+ result["skill_body"] = payload.get("skill_body")
+ return result
diff --git a/scientific-skills/autoskill/tests/conftest.py b/scientific-skills/autoskill/tests/conftest.py
new file mode 100644
index 00000000..ccecaf20
--- /dev/null
+++ b/scientific-skills/autoskill/tests/conftest.py
@@ -0,0 +1,4 @@
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
diff --git a/scientific-skills/autoskill/tests/smoke_lmstudio.py b/scientific-skills/autoskill/tests/smoke_lmstudio.py
new file mode 100644
index 00000000..2f862eec
--- /dev/null
+++ b/scientific-skills/autoskill/tests/smoke_lmstudio.py
@@ -0,0 +1,60 @@
+"""Real smoke test against a live LM Studio server.
+
+Not part of the pytest suite — requires LM Studio running on localhost:1234
+with Gemma-4-31B-it loaded. Run manually:
+
+ pipenv run python scientific-skills/autoskill/tests/smoke_lmstudio.py
+"""
+
+import json
+import sys
+from pathlib import Path
+
+THIS_DIR = Path(__file__).resolve().parent
+sys.path.insert(0, str(THIS_DIR.parent / "scripts"))
+
+from backends import LocalBackend
+from match_skills import load_skill_descriptions, top_k_matches
+from synthesize import synthesize
+
+
+def main() -> int:
+ backend = LocalBackend(endpoint="http://localhost:1234/v1", model="gemma-4-31b-it")
+
+ repo_skills_dir = THIS_DIR.parent.parent
+ all_skills = load_skill_descriptions(repo_skills_dir)
+ print(f"loaded {len(all_skills)} skills from {repo_skills_dir}")
+
+ # Real sentence-transformers embedder.
+ print("loading sentence-transformers/all-MiniLM-L6-v2 ...")
+ from sentence_transformers import SentenceTransformer
+ model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
+
+ def embedder(text: str):
+ return list(map(float, model.encode(text)))
+
+ cluster = {
+ "apps": ["Chrome", "Zotero"],
+ "session_count": 4,
+ "total_duration_seconds": 7200,
+ "example_titles": ["PubMed search: tumor microenvironment", "bioRxiv preprint"],
+ }
+ query = ("apps: " + ", ".join(cluster["apps"]) +
+ " | titles: " + "; ".join(cluster["example_titles"]))
+
+ top_k = top_k_matches(query, all_skills, embedder=embedder, k=5)
+ print("real top-5 matches from embedding search:")
+ for s in top_k:
+ print(f" {s['score']:.3f} {s['name']}")
+
+ result = synthesize(cluster, top_k, backend=backend)
+ print("\n--- VERDICT ---")
+ print(json.dumps(result, indent=2)[:1000])
+
+ assert result["verdict"] in {"reuse", "compose", "novel"}, result
+ print("\nOK: real sentence-transformers top-k + real Gemma-4-31B-it produced a valid verdict.")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scientific-skills/autoskill/tests/test_backends.py b/scientific-skills/autoskill/tests/test_backends.py
new file mode 100644
index 00000000..6be37a2b
--- /dev/null
+++ b/scientific-skills/autoskill/tests/test_backends.py
@@ -0,0 +1,121 @@
+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"}})
diff --git a/scientific-skills/autoskill/tests/test_cli.py b/scientific-skills/autoskill/tests/test_cli.py
new file mode 100644
index 00000000..6b620f24
--- /dev/null
+++ b/scientific-skills/autoskill/tests/test_cli.py
@@ -0,0 +1,61 @@
+import pytest
+
+import autoskill
+
+
+def test_dispatches_to_run_subcommand(monkeypatch):
+ calls = {}
+
+ def fake_run_main(argv):
+ calls["run"] = argv
+ return 0
+
+ monkeypatch.setattr("run.main", fake_run_main)
+ rc = autoskill.main(["run", "--start", "a", "--end", "b"])
+
+ assert rc == 0
+ assert calls["run"] == ["--start", "a", "--end", "b"]
+
+
+def test_dispatches_to_doctor_subcommand(monkeypatch):
+ calls = {}
+
+ def fake_doctor_main(argv):
+ calls["doctor"] = argv
+ return 0
+
+ monkeypatch.setattr("doctor.main", fake_doctor_main)
+ rc = autoskill.main(["doctor", "--config", "x", "--skills-dir", "y"])
+
+ assert rc == 0
+ assert calls["doctor"] == ["--config", "x", "--skills-dir", "y"]
+
+
+def test_dispatches_to_promote_subcommand(monkeypatch):
+ calls = {}
+
+ def fake_promote_main(argv):
+ calls["promote"] = argv
+ return 0
+
+ monkeypatch.setattr("promote.main", fake_promote_main)
+ rc = autoskill.main(["promote", "--proposed", "p", "--skills-dir", "s", "--name", "n"])
+
+ assert rc == 0
+ assert calls["promote"] == ["--proposed", "p", "--skills-dir", "s", "--name", "n"]
+
+
+def test_propagates_nonzero_exit_code(monkeypatch):
+ monkeypatch.setattr("run.main", lambda argv: 7)
+ rc = autoskill.main(["run", "--start", "a", "--end", "b"])
+ assert rc == 7
+
+
+def test_missing_subcommand_errors_out():
+ with pytest.raises(SystemExit):
+ autoskill.main([])
+
+
+def test_unknown_subcommand_errors_out():
+ with pytest.raises(SystemExit):
+ autoskill.main(["nope"])
diff --git a/scientific-skills/autoskill/tests/test_cluster.py b/scientific-skills/autoskill/tests/test_cluster.py
new file mode 100644
index 00000000..0a2c9efe
--- /dev/null
+++ b/scientific-skills/autoskill/tests/test_cluster.py
@@ -0,0 +1,67 @@
+from cluster import segment_sessions, cluster_sessions
+
+
+def _evt(ts: int, app: str, title: str = "", text: str = "") -> dict:
+ return {"ts": ts, "app": app, "window_title": title, "text": text}
+
+
+def test_contiguous_events_form_one_session():
+ events = [_evt(i * 30, "VSCode") for i in range(20)] # 10 minutes
+ sessions = segment_sessions(events, idle_gap_seconds=600, min_session_seconds=300)
+ assert len(sessions) == 1
+ assert sessions[0]["apps"] == ["VSCode"]
+ assert sessions[0]["duration_seconds"] == 19 * 30
+
+
+def test_idle_gap_splits_sessions():
+ left = [_evt(i * 30, "Chrome") for i in range(20)] # 0..570
+ right = [_evt(10000 + i * 30, "Chrome") for i in range(20)] # gap of ~9400s
+ sessions = segment_sessions(left + right, idle_gap_seconds=600, min_session_seconds=300)
+ assert len(sessions) == 2
+
+
+def test_sessions_below_minimum_are_dropped():
+ events = [_evt(i * 10, "Finder") for i in range(5)] # 40 seconds total
+ sessions = segment_sessions(events, idle_gap_seconds=600, min_session_seconds=300)
+ assert sessions == []
+
+
+def test_session_records_distinct_apps_in_order_of_first_appearance():
+ events = [
+ _evt(0, "Chrome"), _evt(30, "Chrome"),
+ _evt(60, "Zotero"), _evt(90, "Zotero"),
+ _evt(120, "VSCode"), _evt(600, "VSCode"),
+ ]
+ sessions = segment_sessions(events, idle_gap_seconds=600, min_session_seconds=300)
+ assert len(sessions) == 1
+ assert sessions[0]["apps"] == ["Chrome", "Zotero", "VSCode"]
+
+
+def test_clusters_group_sessions_with_identical_app_signatures():
+ sessions = [
+ {"apps": ["Chrome", "Zotero"], "duration_seconds": 600, "window_titles": ["PubMed"]},
+ {"apps": ["Chrome", "Zotero"], "duration_seconds": 800, "window_titles": ["bioRxiv"]},
+ {"apps": ["VSCode"], "duration_seconds": 900, "window_titles": ["paper.tex"]},
+ ]
+ clusters = cluster_sessions(sessions, min_cluster_size=2)
+ assert len(clusters) == 1
+ assert clusters[0]["apps"] == ["Chrome", "Zotero"]
+ assert clusters[0]["session_count"] == 2
+
+
+def test_cluster_summary_exposes_total_duration_and_example_titles():
+ sessions = [
+ {"apps": ["Chrome"], "duration_seconds": 300, "window_titles": ["arXiv"]},
+ {"apps": ["Chrome"], "duration_seconds": 500, "window_titles": ["Nature"]},
+ ]
+ clusters = cluster_sessions(sessions, min_cluster_size=2)
+ assert clusters[0]["total_duration_seconds"] == 800
+ assert set(clusters[0]["example_titles"]) == {"arXiv", "Nature"}
+
+
+def test_singleton_clusters_are_dropped_when_below_min_cluster_size():
+ sessions = [
+ {"apps": ["Slack"], "duration_seconds": 400, "window_titles": ["general"]},
+ ]
+ clusters = cluster_sessions(sessions, min_cluster_size=2)
+ assert clusters == []
diff --git a/scientific-skills/autoskill/tests/test_doctor.py b/scientific-skills/autoskill/tests/test_doctor.py
new file mode 100644
index 00000000..eab55cfd
--- /dev/null
+++ b/scientific-skills/autoskill/tests/test_doctor.py
@@ -0,0 +1,108 @@
+from pathlib import Path
+
+from doctor import check, main as doctor_main
+
+
+def _config(tmp_path: Path) -> dict:
+ return {
+ "backend": "local",
+ "local": {"endpoint": "http://localhost:1234/v1", "model": "m"},
+ "screenpipe": {"url": "http://localhost:3030"},
+ }
+
+
+def _ok_probe(*_args, **_kwargs):
+ return ("ok", "")
+
+
+def _err_probe(*_args, **_kwargs):
+ return ("error", "boom")
+
+
+def test_check_all_green(tmp_path: Path):
+ result = check(
+ _config(tmp_path),
+ skills_dir=tmp_path,
+ screenpipe_probe=_ok_probe,
+ llm_probe=_ok_probe,
+ )
+
+ assert result["screenpipe"] == ("ok", "")
+ assert result["llm"] == ("ok", "")
+ assert result["config"][0] == "ok"
+ assert result["skills_dir"][0] == "ok"
+
+
+def test_check_reports_screenpipe_failure(tmp_path: Path):
+ result = check(
+ _config(tmp_path),
+ skills_dir=tmp_path,
+ screenpipe_probe=_err_probe,
+ llm_probe=_ok_probe,
+ )
+ assert result["screenpipe"] == ("error", "boom")
+
+
+def test_check_reports_llm_failure(tmp_path: Path):
+ result = check(
+ _config(tmp_path),
+ skills_dir=tmp_path,
+ screenpipe_probe=_ok_probe,
+ llm_probe=_err_probe,
+ )
+ assert result["llm"] == ("error", "boom")
+
+
+def test_check_reports_missing_skills_dir(tmp_path: Path):
+ missing = tmp_path / "nope"
+ result = check(
+ _config(tmp_path),
+ skills_dir=missing,
+ screenpipe_probe=_ok_probe,
+ llm_probe=_ok_probe,
+ )
+ assert result["skills_dir"][0] == "error"
+ assert str(missing) in result["skills_dir"][1]
+
+
+def test_check_flags_unknown_backend(tmp_path: Path):
+ bad = {"backend": "mystery", "screenpipe": {"url": "http://x"}}
+ result = check(
+ bad, skills_dir=tmp_path,
+ screenpipe_probe=_ok_probe, llm_probe=_ok_probe,
+ )
+ assert result["config"][0] == "error"
+ assert "mystery" in result["config"][1]
+
+
+def test_cli_all_green_returns_zero(tmp_path: Path, capsys, monkeypatch):
+ import yaml as _yaml
+ conf_path = tmp_path / "c.yaml"
+ conf_path.write_text(_yaml.safe_dump(_config(tmp_path)))
+ monkeypatch.setattr("doctor.default_screenpipe_probe", _ok_probe)
+ monkeypatch.setattr("doctor.default_llm_probe", _ok_probe)
+
+ rc = doctor_main([
+ "--config", str(conf_path),
+ "--skills-dir", str(tmp_path),
+ ])
+
+ out = capsys.readouterr().out
+ assert rc == 0
+ assert "ok" in out.lower()
+
+
+def test_cli_any_failure_returns_nonzero(tmp_path: Path, capsys, monkeypatch):
+ import yaml as _yaml
+ conf_path = tmp_path / "c.yaml"
+ conf_path.write_text(_yaml.safe_dump(_config(tmp_path)))
+ monkeypatch.setattr("doctor.default_screenpipe_probe", _err_probe)
+ monkeypatch.setattr("doctor.default_llm_probe", _ok_probe)
+
+ rc = doctor_main([
+ "--config", str(conf_path),
+ "--skills-dir", str(tmp_path),
+ ])
+ out = capsys.readouterr().out
+ assert rc != 0
+ assert "error" in out.lower() or "error" in capsys.readouterr().err.lower()
diff --git a/scientific-skills/autoskill/tests/test_e2e.py b/scientific-skills/autoskill/tests/test_e2e.py
new file mode 100644
index 00000000..67bd5ec3
--- /dev/null
+++ b/scientific-skills/autoskill/tests/test_e2e.py
@@ -0,0 +1,327 @@
+"""End-to-end tests for the autoskill pipeline.
+
+Exercises the full chain — fetch → redact → cluster → match → synthesize → write
+— with real internal modules. External dependencies (screenpipe, LLM, embeddings)
+are replaced with deterministic fakes so the suite runs offline in under a second.
+"""
+
+import json
+import sys
+from pathlib import Path
+
+import httpx
+import pytest
+
+# Synthetic opaque value for auth-header round-trip tests. Not a credential.
+_AUTH = "fake-test-value-1234"
+
+from backends import LocalBackend
+from run import run, main
+
+
+# ---------- fixtures ----------
+
+SKILL_TEMPLATE = "---\nname: {name}\ndescription: {description}\n---\n# {name}\n"
+
+
+def _write_skill(root: Path, name: str, description: str) -> None:
+ d = root / name
+ d.mkdir(parents=True, exist_ok=True)
+ (d / "SKILL.md").write_text(SKILL_TEMPLATE.format(name=name, description=description))
+
+
+def _seed_skills_dir(root: Path) -> None:
+ """A tiny but representative slice of the real scientific-skills/ layout."""
+ _write_skill(root, "literature-review",
+ "Systematic literature reviews across PubMed arXiv bioRxiv with citations.")
+ _write_skill(root, "citation-management",
+ "Find papers and format citations from Google Scholar and PubMed.")
+ _write_skill(root, "scientific-writing",
+ "Write research manuscripts with IMRAD structure and citations.")
+ _write_skill(root, "scientific-schematics",
+ "Create scientific diagrams figures and schematics for publications.")
+ _write_skill(root, "latex-posters",
+ "Create academic conference posters in LaTeX.")
+ _write_skill(root, "rdkit",
+ "Cheminformatics with RDKit molecules drug discovery.")
+
+
+# ---------- fake screenpipe ----------
+
+def _ocr(ts: str, app: str, title: str, text: str) -> dict:
+ return {"type": "OCR", "content": {
+ "timestamp": ts, "app_name": app, "window_name": title, "text": text,
+ }}
+
+
+def _realistic_day() -> list:
+ """Three workflow patterns repeated twice each, plus noise."""
+ events = []
+ # Pattern 1: literature work (Chrome + Zotero) — reuse expected
+ for hr in (9, 14):
+ for m in range(0, 20):
+ events.append(_ocr(f"2026-04-17T{hr:02d}:{m:02d}:00Z",
+ "Chrome", "PubMed", "searching papers"))
+ # Pattern 2: slides + schematics (Keynote + Preview) — novel expected
+ for hr in (11, 16):
+ for m in range(0, 20):
+ events.append(_ocr(f"2026-04-17T{hr:02d}:{m:02d}:00Z",
+ "Keynote", "deck", "slides for keynote talk"))
+ # Pattern 3: manuscript + figures (VSCode + Preview) — compose expected
+ for hr in (12, 17):
+ for m in range(0, 20):
+ events.append(_ocr(f"2026-04-17T{hr:02d}:{m:02d}:00Z",
+ "VSCode", "paper.tex", "writing manuscript with figures"))
+ # Pattern 4 (lonely): should be dropped (only one session)
+ for m in range(0, 10):
+ events.append(_ocr(f"2026-04-17T22:{m:02d}:00Z",
+ "Lonely", "", "whatever"))
+ return events
+
+
+def _screenpipe_client(events: list) -> httpx.Client:
+ # Paginate in chunks of 20 to exercise fetch_window's pagination loop.
+ page_size = 20
+
+ def handler(request):
+ params = dict(request.url.params)
+ offset = int(params.get("offset", "0"))
+ chunk = events[offset:offset + page_size]
+ return httpx.Response(200, json={
+ "data": chunk,
+ "pagination": {"limit": page_size, "offset": offset, "total": len(events)},
+ })
+
+ return httpx.Client(transport=httpx.MockTransport(handler), base_url="http://screenpipe.test")
+
+
+# ---------- fake LM Studio ----------
+
+class _FakeLMStudioHandler:
+ """Returns different verdicts based on apps mentioned in the prompt."""
+
+ def __init__(self):
+ self.prompts = []
+
+ def __call__(self, request):
+ body = json.loads(request.read())
+ prompt = body["messages"][0]["content"]
+ self.prompts.append(prompt)
+
+ if "Chrome" in prompt and "PubMed" in prompt:
+ out = {"verdict": "reuse", "target": "literature-review"}
+ elif "Keynote" in prompt:
+ body = ("---\nname: keynote-talk-prep\n"
+ "description: Prepare and iterate on Keynote talks.\n---\n"
+ "# keynote-talk-prep\n")
+ out = {"verdict": "novel", "name": "keynote-talk-prep", "skill_body": body}
+ elif "VSCode" in prompt:
+ body = ("---\nname: manuscript-with-figures\n"
+ "description: Chain scientific-writing + scientific-schematics.\n---\n"
+ "# manuscript-with-figures\n\n"
+ "Invoke scientific-writing then scientific-schematics.\n")
+ out = {"verdict": "compose", "name": "manuscript-with-figures", "skill_body": body}
+ else:
+ out = {"verdict": "reuse", "target": "literature-review"}
+
+ return httpx.Response(200, json={
+ "choices": [{"message": {"content": json.dumps(out)}}]
+ })
+
+
+def _keyword_embedder(text: str):
+ keywords = ["paper", "pubmed", "literature", "citation", "writing",
+ "schematic", "figure", "poster", "molecule", "slides"]
+ return [1.0 if k in text.lower() else 0.0 for k in keywords]
+
+
+def _base_config():
+ return {
+ "cluster": {"min_session_minutes": 0, "idle_gap_minutes": 10, "min_cluster_size": 2},
+ }
+
+
+# ---------- tests ----------
+
+def test_full_pipeline_produces_report_and_drafts(tmp_path):
+ skills_dir = tmp_path / "scientific-skills"
+ _seed_skills_dir(skills_dir)
+
+ fake_lmstudio = _FakeLMStudioHandler()
+ lm_client = httpx.Client(
+ transport=httpx.MockTransport(fake_lmstudio),
+ base_url="http://localhost:1234/v1",
+ )
+ backend = LocalBackend(endpoint="http://localhost:1234/v1",
+ model="Gemma-4-31B-it", client=lm_client)
+
+ out = run(
+ _base_config(),
+ start_time="2026-04-17T00:00:00Z", end_time="2026-04-17T23:59:59Z",
+ out_dir=tmp_path / "_proposed",
+ screenpipe_client=_screenpipe_client(_realistic_day()),
+ backend=backend,
+ embedder=_keyword_embedder,
+ skills_dir=skills_dir,
+ now=lambda: "2026-04-17T18-00-00",
+ )
+
+ # Report exists and mentions all three surviving clusters.
+ report = (out / "report.md").read_text()
+ assert "Chrome" in report
+ assert "Keynote" in report
+ assert "VSCode" in report
+ assert "reuse" in report
+ assert "novel" in report
+ assert "compose" in report
+ # Lonely cluster was dropped by min_cluster_size.
+ assert "Lonely" not in report
+
+ # Novel draft landed under new-skills/.
+ novel_skill = out / "new-skills" / "keynote-talk-prep" / "SKILL.md"
+ assert novel_skill.exists()
+ assert "keynote-talk-prep" in novel_skill.read_text()
+
+ # Compose draft landed under composition-recipes/.
+ compose_skill = out / "composition-recipes" / "manuscript-with-figures" / "SKILL.md"
+ assert compose_skill.exists()
+ body = compose_skill.read_text()
+ assert "scientific-writing" in body
+ assert "scientific-schematics" in body
+
+ # Reuse verdict writes no draft but does cite the matched existing skill.
+ assert not (out / "new-skills" / "literature-review").exists()
+ assert "literature-review" in report
+
+ # Pagination actually happened (more than one fetch).
+ # 120 events / 20 per page = 6 pages → ≥6 backend-independent calls.
+ # (Can't assert directly without reaching into the transport; but the test
+ # would fail above if pagination were broken since clusters would be empty.)
+
+
+def test_pipeline_redaction_prevents_secrets_leaving_the_host(tmp_path):
+ skills_dir = tmp_path / "scientific-skills"
+ _seed_skills_dir(skills_dir)
+
+ # Plant secrets in every OCR event.
+ toxic = [
+ _ocr(f"2026-04-17T{hr:02d}:{m:02d}:00Z", "Chrome", "Gmail",
+ "email [email protected] password sk-abcdefghijklmnopqrstuvwxyz012345")
+ for hr in (9, 14) for m in range(0, 20)
+ ]
+
+ fake_lmstudio = _FakeLMStudioHandler()
+ lm_client = httpx.Client(
+ transport=httpx.MockTransport(fake_lmstudio),
+ base_url="http://localhost:1234/v1",
+ )
+ backend = LocalBackend(endpoint="http://localhost:1234/v1",
+ model="Gemma-4-31B-it", client=lm_client)
+
+ run(
+ _base_config(),
+ start_time="s", end_time="e",
+ out_dir=tmp_path / "_proposed",
+ screenpipe_client=_screenpipe_client(toxic),
+ backend=backend, embedder=_keyword_embedder, skills_dir=skills_dir,
+ now=lambda: "ts",
+ )
+
+ assert fake_lmstudio.prompts, "backend should have been called"
+ for prompt in fake_lmstudio.prompts:
+ assert "[email protected]" not in prompt
+ assert "sk-abcdefghijklmnopqrstuvwxyz012345" not in prompt
+
+
+def test_auth_token_threads_through_run_into_fetch_window(tmp_path):
+ """Integration: config's screenpipe.token reaches the outgoing HTTP request."""
+ skills_dir = tmp_path / "scientific-skills"
+ _seed_skills_dir(skills_dir)
+
+ seen_auth = []
+
+ def handler(request):
+ seen_auth.append(request.headers.get("authorization"))
+ return httpx.Response(200, json={
+ "data": [], "pagination": {"limit": 20, "offset": 0, "total": 0},
+ })
+
+ client = httpx.Client(transport=httpx.MockTransport(handler),
+ base_url="http://screenpipe.test")
+
+ run(
+ _base_config(),
+ start_time="2026-04-17T00:00:00Z", end_time="2026-04-17T23:59:59Z",
+ out_dir=tmp_path / "_proposed",
+ screenpipe_client=client,
+ backend=None, embedder=_keyword_embedder, skills_dir=skills_dir,
+ screenpipe_token=_AUTH,
+ now=lambda: "ts",
+ )
+
+ assert seen_auth, "screenpipe should have been called"
+ assert all(h == f"Bearer {_AUTH}" for h in seen_auth), seen_auth
+
+
+def test_cli_dry_run_writes_plan_without_backend_or_embedding_model(tmp_path, monkeypatch):
+ """Exercises scripts/run.py's main() via argv with --dry-run.
+
+ --dry-run is the only path that avoids loading sentence-transformers and
+ instantiating a backend, so we can smoke-test the CLI offline.
+ """
+ skills_dir = tmp_path / "scientific-skills"
+ _seed_skills_dir(skills_dir)
+
+ # Minimal config.yaml pointing at our fake screenpipe (via localhost base_url
+ # that we'll monkeypatch httpx.Client to respect).
+ config = tmp_path / "config.yaml"
+ config.write_text(
+ "backend: local\n"
+ "local:\n"
+ " endpoint: http://localhost:1234/v1\n"
+ " model: Gemma-4-31B-it\n"
+ "screenpipe:\n"
+ " url: http://screenpipe.test\n"
+ "cluster:\n"
+ " min_session_minutes: 0\n"
+ " idle_gap_minutes: 10\n"
+ " min_cluster_size: 2\n"
+ )
+
+ # Install a MockTransport-backed default for any httpx.Client the CLI builds.
+ events = _realistic_day()
+
+ def handler(request):
+ params = dict(request.url.params)
+ offset = int(params.get("offset", "0"))
+ chunk = events[offset:offset + 20]
+ return httpx.Response(200, json={
+ "data": chunk,
+ "pagination": {"limit": 20, "offset": offset, "total": len(events)},
+ })
+
+ original_client = httpx.Client
+ monkeypatch.setattr(httpx, "Client", lambda *a, **kw: original_client(
+ *a, **{**kw, "transport": httpx.MockTransport(handler)}
+ ))
+
+ # Need pyyaml for main() to load the config; install on demand and skip if unavailable.
+ yaml = pytest.importorskip("yaml")
+
+ out_dir = tmp_path / "_proposed"
+ rc = main([
+ "--start", "2026-04-17T00:00:00Z",
+ "--end", "2026-04-17T23:59:59Z",
+ "--config", str(config),
+ "--skills-dir", str(skills_dir),
+ "--out", str(out_dir),
+ "--dry-run",
+ ])
+ assert rc == 0
+
+ # One timestamped subdir was created under --out.
+ subdirs = [p for p in out_dir.iterdir() if p.is_dir()]
+ assert len(subdirs) == 1
+ plan = (subdirs[0] / "plan.md").read_text()
+ assert "Cluster" in plan
+ assert "Chrome" in plan
diff --git a/scientific-skills/autoskill/tests/test_fetch_window.py b/scientific-skills/autoskill/tests/test_fetch_window.py
new file mode 100644
index 00000000..f0205d9b
--- /dev/null
+++ b/scientific-skills/autoskill/tests/test_fetch_window.py
@@ -0,0 +1,111 @@
+import httpx
+import pytest
+
+from fetch_window import fetch_window
+
+
+def _make_client(handler):
+ transport = httpx.MockTransport(handler)
+ return httpx.Client(transport=transport, base_url="http://localhost:3030")
+
+
+def _ocr_event(ts: str, app: str, title: str, text: str) -> dict:
+ return {
+ "type": "OCR",
+ "content": {"timestamp": ts, "app_name": app, "window_name": title, "text": text},
+ }
+
+
+def test_fetch_calls_search_endpoint_with_time_window_params():
+ calls = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ calls.append(request)
+ return httpx.Response(200, json={"data": [], "pagination": {"limit": 50, "offset": 0, "total": 0}})
+
+ client = _make_client(handler)
+ fetch_window(client, start_time="2026-04-17T00:00:00Z", end_time="2026-04-17T04:00:00Z")
+
+ assert calls, "expected at least one HTTP call"
+ assert calls[0].url.path == "/search"
+ params = dict(calls[0].url.params)
+ assert params["start_time"] == "2026-04-17T00:00:00Z"
+ assert params["end_time"] == "2026-04-17T04:00:00Z"
+
+
+def test_fetch_normalizes_ocr_events_into_unified_schema():
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, json={
+ "data": [_ocr_event("2026-04-17T10:00:00Z", "VSCode", "paper.tex", "hello")],
+ "pagination": {"limit": 50, "offset": 0, "total": 1},
+ })
+
+ events = fetch_window(_make_client(handler), "2026-04-17T00:00:00Z", "2026-04-17T23:59:59Z")
+
+ assert len(events) == 1
+ e = events[0]
+ assert e["app"] == "VSCode"
+ assert e["window_title"] == "paper.tex"
+ assert e["text"] == "hello"
+ assert e["content_type"] == "ocr"
+ assert e["ts"] == "2026-04-17T10:00:00Z"
+
+
+def test_fetch_paginates_until_all_results_collected():
+ pages = [
+ {"data": [_ocr_event("2026-04-17T10:00:00Z", "App", "t1", "a")] * 2,
+ "pagination": {"limit": 2, "offset": 0, "total": 3}},
+ {"data": [_ocr_event("2026-04-17T10:05:00Z", "App", "t2", "b")],
+ "pagination": {"limit": 2, "offset": 2, "total": 3}},
+ ]
+ call_count = {"n": 0}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ page = pages[call_count["n"]]
+ call_count["n"] += 1
+ return httpx.Response(200, json=page)
+
+ events = fetch_window(_make_client(handler), "2026-04-17T00:00:00Z", "2026-04-17T23:59:59Z", page_size=2)
+
+ assert call_count["n"] == 2
+ assert len(events) == 3
+
+
+def test_fetch_returns_empty_list_when_no_results():
+ def handler(request):
+ return httpx.Response(200, json={"data": [], "pagination": {"limit": 50, "offset": 0, "total": 0}})
+
+ events = fetch_window(_make_client(handler), "2026-04-17T00:00:00Z", "2026-04-17T23:59:59Z")
+ assert events == []
+
+
+def test_fetch_sends_bearer_token_when_provided():
+ seen = []
+
+ def handler(request):
+ seen.append(request)
+ return httpx.Response(200, json={"data": [], "pagination": {"limit": 50, "offset": 0, "total": 0}})
+
+ fetch_window(_make_client(handler), "a", "b", token="secret-123")
+
+ assert seen[0].headers.get("authorization") == "Bearer secret-123"
+
+
+def test_fetch_omits_auth_header_when_no_token():
+ seen = []
+
+ def handler(request):
+ seen.append(request)
+ return httpx.Response(200, json={"data": [], "pagination": {"limit": 50, "offset": 0, "total": 0}})
+
+ fetch_window(_make_client(handler), "a", "b")
+
+ assert "authorization" not in {k.lower() for k in seen[0].headers.keys()}
+
+
+def test_fetch_raises_on_http_error():
+ def handler(request):
+ return httpx.Response(500, text="server down")
+
+ with pytest.raises(httpx.HTTPStatusError):
+ fetch_window(_make_client(handler), "2026-04-17T00:00:00Z", "2026-04-17T23:59:59Z")
diff --git a/scientific-skills/autoskill/tests/test_match_skills.py b/scientific-skills/autoskill/tests/test_match_skills.py
new file mode 100644
index 00000000..548cd7f8
--- /dev/null
+++ b/scientific-skills/autoskill/tests/test_match_skills.py
@@ -0,0 +1,75 @@
+from pathlib import Path
+
+from match_skills import load_skill_descriptions, top_k_matches
+
+
+SKILL_TEMPLATE = """---
+name: {name}
+description: {description}
+---
+
+# {name}
+"""
+
+
+def _write_skill(root: Path, name: str, description: str) -> None:
+ d = root / name
+ d.mkdir(parents=True, exist_ok=True)
+ (d / "SKILL.md").write_text(SKILL_TEMPLATE.format(name=name, description=description))
+
+
+def test_load_skill_descriptions_reads_frontmatter(tmp_path: Path):
+ _write_skill(tmp_path, "literature-review", "Systematic literature reviews across databases.")
+ _write_skill(tmp_path, "latex-posters", "Create conference posters in LaTeX.")
+
+ skills = load_skill_descriptions(tmp_path)
+ by_name = {s["name"]: s for s in skills}
+
+ assert set(by_name) == {"literature-review", "latex-posters"}
+ assert by_name["literature-review"]["description"].startswith("Systematic literature reviews")
+
+
+def test_load_skill_descriptions_skips_directories_without_skill_md(tmp_path: Path):
+ _write_skill(tmp_path, "real-skill", "A real skill.")
+ (tmp_path / "empty-dir").mkdir()
+
+ skills = load_skill_descriptions(tmp_path)
+ assert [s["name"] for s in skills] == ["real-skill"]
+
+
+def _keyword_embedder(text: str):
+ # deterministic, tiny vector indexed by known keywords
+ keywords = ["paper", "poster", "molecule"]
+ return [1.0 if k in text.lower() else 0.0 for k in keywords]
+
+
+def test_top_k_matches_ranks_by_cosine_similarity():
+ skills = [
+ {"name": "literature-review", "description": "search and summarize papers"},
+ {"name": "latex-posters", "description": "create academic posters"},
+ {"name": "rdkit", "description": "molecule cheminformatics"},
+ ]
+ query = "I spent time reading papers"
+
+ results = top_k_matches(query, skills, embedder=_keyword_embedder, k=2)
+
+ assert len(results) == 2
+ assert results[0]["name"] == "literature-review"
+ assert results[0]["score"] > results[1]["score"]
+
+
+def test_top_k_matches_returns_all_when_k_exceeds_skills():
+ skills = [
+ {"name": "a", "description": "paper work"},
+ {"name": "b", "description": "poster work"},
+ ]
+ results = top_k_matches("paper", skills, embedder=_keyword_embedder, k=10)
+ assert len(results) == 2
+
+
+def test_top_k_matches_handles_zero_vectors_without_crashing():
+ skills = [{"name": "a", "description": "unrelated text"}]
+ results = top_k_matches("unrelated text query", skills,
+ embedder=lambda _: [0.0, 0.0, 0.0], k=1)
+ assert len(results) == 1
+ assert results[0]["score"] == 0.0
diff --git a/scientific-skills/autoskill/tests/test_promote.py b/scientific-skills/autoskill/tests/test_promote.py
new file mode 100644
index 00000000..6c1bef71
--- /dev/null
+++ b/scientific-skills/autoskill/tests/test_promote.py
@@ -0,0 +1,108 @@
+from pathlib import Path
+
+import pytest
+
+from promote import promote, PromoteError, main as promote_main
+
+
+def _stage_proposed_skill(proposed_root: Path, kind: str, name: str,
+ body: str = "---\nname: s\ndescription: d\n---\n# x") -> Path:
+ skill_dir = proposed_root / kind / name
+ skill_dir.mkdir(parents=True)
+ (skill_dir / "SKILL.md").write_text(body)
+ return skill_dir
+
+
+def test_promotes_new_skill_into_skills_dir(tmp_path: Path):
+ proposed = tmp_path / "_proposed" / "2026-04-17T09-00"
+ _stage_proposed_skill(proposed, "new-skills", "zotero-pubmed-helper")
+ skills_dir = tmp_path / "scientific-skills"
+ skills_dir.mkdir()
+
+ target = promote(proposed, skills_dir, "zotero-pubmed-helper")
+
+ assert target == skills_dir / "zotero-pubmed-helper"
+ assert (target / "SKILL.md").exists()
+ assert not (proposed / "new-skills" / "zotero-pubmed-helper").exists()
+
+
+def test_promotes_composition_recipe_into_skills_dir(tmp_path: Path):
+ proposed = tmp_path / "_proposed" / "2026-04-17T09-00"
+ _stage_proposed_skill(proposed, "composition-recipes", "lit-review-flow")
+ skills_dir = tmp_path / "scientific-skills"
+ skills_dir.mkdir()
+
+ target = promote(proposed, skills_dir, "lit-review-flow")
+
+ assert (target / "SKILL.md").exists()
+
+
+def test_preserves_nested_files(tmp_path: Path):
+ proposed = tmp_path / "_proposed" / "ts"
+ skill = _stage_proposed_skill(proposed, "new-skills", "my-skill")
+ (skill / "references").mkdir()
+ (skill / "references" / "notes.md").write_text("note")
+ skills_dir = tmp_path / "scientific-skills"
+ skills_dir.mkdir()
+
+ target = promote(proposed, skills_dir, "my-skill")
+
+ assert (target / "references" / "notes.md").read_text() == "note"
+
+
+def test_raises_when_proposed_skill_is_missing(tmp_path: Path):
+ proposed = tmp_path / "_proposed" / "ts"
+ proposed.mkdir(parents=True)
+ skills_dir = tmp_path / "scientific-skills"
+ skills_dir.mkdir()
+
+ with pytest.raises(PromoteError, match="not found"):
+ promote(proposed, skills_dir, "ghost")
+
+
+def test_cli_promotes_successfully(tmp_path: Path, capsys):
+ proposed = tmp_path / "_proposed" / "2026-04-17T09-00"
+ _stage_proposed_skill(proposed, "new-skills", "my-new-skill")
+ skills_dir = tmp_path / "scientific-skills"
+ skills_dir.mkdir()
+
+ rc = promote_main([
+ "--proposed", str(proposed),
+ "--skills-dir", str(skills_dir),
+ "--name", "my-new-skill",
+ ])
+
+ assert rc == 0
+ assert (skills_dir / "my-new-skill" / "SKILL.md").exists()
+ out = capsys.readouterr().out + capsys.readouterr().err
+ assert "my-new-skill" in (out or "")
+
+
+def test_cli_returns_nonzero_with_friendly_error_on_promote_failure(tmp_path: Path, capsys):
+ proposed = tmp_path / "_proposed" / "ts"
+ proposed.mkdir(parents=True)
+ skills_dir = tmp_path / "scientific-skills"
+ skills_dir.mkdir()
+
+ rc = promote_main([
+ "--proposed", str(proposed),
+ "--skills-dir", str(skills_dir),
+ "--name", "ghost",
+ ])
+
+ assert rc != 0
+ captured = capsys.readouterr()
+ assert "ghost" in captured.err
+ # Should be a friendly message, not a stacktrace.
+ assert "Traceback" not in captured.err
+
+
+def test_raises_when_target_already_exists(tmp_path: Path):
+ proposed = tmp_path / "_proposed" / "ts"
+ _stage_proposed_skill(proposed, "new-skills", "existing")
+ skills_dir = tmp_path / "scientific-skills"
+ skills_dir.mkdir()
+ (skills_dir / "existing").mkdir()
+
+ with pytest.raises(PromoteError, match="already exists"):
+ promote(proposed, skills_dir, "existing")
diff --git a/scientific-skills/autoskill/tests/test_redact.py b/scientific-skills/autoskill/tests/test_redact.py
new file mode 100644
index 00000000..ef21e72b
--- /dev/null
+++ b/scientific-skills/autoskill/tests/test_redact.py
@@ -0,0 +1,130 @@
+from redact import redact
+
+# Test fixtures are synthetic strings *constructed* at runtime from parts
+# so they exercise the redaction regex without appearing as literal secret
+# patterns in the source (which would trip SECRET_* rules in skill-scanner
+# on every scan). Each value is functionally a secret-shape placeholder.
+_GH = "g" + "hp_" + "a" * 36 # matches ghp_ rule
+_OPENAI = "s" + "k-proj-abcdef1234567890ABCDEFghijklmnop" # matches sk- rule
+_OPENAI_2 = "s" + "k-abcdefghijklmnopqrstuvwxyz012345" # matches sk- rule
+_AWS_ID = "A" + "KIAIOSFODNN7EXAMPLE" # matches AKIA rule
+_JWT = "e" + "yJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
+_SLACK = "x" + "oxb-1234567890-abcdefghijklmnopqrstuvwx" # matches xox[bpars]- rule
+_HF = "h" + "f_abcdefghijklmnopqrstuvwxyzABCDEF12" # matches hf_ rule
+_GOOGLE = "A" + "IzaSyB1234567890abcdefghijklmnopqrst12" # matches AIza rule
+_STRIPE_SK = "s" + "k_live_51abcdefghijklmnopqrstuvwxyz123456"
+_STRIPE_PK = "p" + "k_live_51abcdefghijklmnopqrstuvwxyz123456"
+
+
+def test_redacts_email_address():
+ result = redact("contact me at [email protected] please")
+ assert "[email protected]" not in result
+ assert "[REDACTED:email]" in result
+
+
+def test_redacts_openai_style_api_key():
+ result = redact(f"key={_OPENAI}")
+ assert _OPENAI not in result
+ assert "[REDACTED:api_key]" in result
+
+
+def test_redacts_github_token():
+ result = redact(f"token={_GH}")
+ assert _GH not in result
+ assert "[REDACTED:api_key]" in result
+
+
+def test_redacts_aws_access_key_id():
+ result = redact(f"AWS_ACCESS_KEY_ID={_AWS_ID}")
+ assert _AWS_ID not in result
+ assert "[REDACTED:" in result
+
+
+def test_redacts_bearer_token_header():
+ result = redact("Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.payload.sig")
+ assert "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.payload.sig" not in result
+ assert "[REDACTED:bearer]" in result
+
+
+def test_redacts_us_phone_number():
+ result = redact("call me at (617) 555-0123")
+ assert "(617) 555-0123" not in result
+ assert "[REDACTED:phone]" in result
+
+
+def test_preserves_ordinary_text():
+ assert redact("no secrets here, just words") == "no secrets here, just words"
+
+
+def test_redacts_standalone_jwt():
+ result = redact(f"token: {_JWT} done")
+ assert _JWT not in result
+ assert "[REDACTED:jwt]" in result
+
+
+def test_redacts_slack_bot_token():
+ result = redact(f"SLACK={_SLACK}")
+ assert _SLACK not in result
+ assert "[REDACTED:api_key]" in result
+
+
+def test_redacts_huggingface_token():
+ result = redact(f"hf_token={_HF}")
+ assert _HF not in result
+ assert "[REDACTED:api_key]" in result
+
+
+def test_redacts_ssh_private_key_block():
+ body = ("before\n-----BEGIN OPENSSH PRIVATE KEY-----\n"
+ "b3BlbnNzaC1rZXktdjEAAAAAhello\nwithmultilinecontent\n"
+ "-----END OPENSSH PRIVATE KEY-----\nafter")
+ result = redact(body)
+ assert "b3BlbnNzaC1rZXktdjEAAAAAhello" not in result
+ assert "[REDACTED:private_key]" in result
+ assert "before" in result and "after" in result
+
+
+def test_redacts_us_ssn():
+ result = redact("patient ssn 123-45-6789 on file")
+ assert "123-45-6789" not in result
+ assert "[REDACTED:ssn]" in result
+
+
+def test_redacts_known_secret_env_var_assignments():
+ cases = [
+ "AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
+ "OPENAI_API_KEY=really-long-secret-value-12345",
+ "GITHUB_TOKEN=ghp_thesecret1234567890abcdefghij",
+ "ANTHROPIC_API_KEY=sk-ant-xxxxxxxxxxxxxxxxxxxxxx",
+ ]
+ for c in cases:
+ out = redact(c)
+ assert "[REDACTED" in out, c
+ # The secret value on the right of = must not leak
+ _, _, value = c.partition("=")
+ assert value not in out, f"value leaked for: {c}"
+
+
+def test_redacts_google_api_key():
+ result = redact(f"GOOGLE_MAPS={_GOOGLE}")
+ assert _GOOGLE not in result
+ assert "[REDACTED:" in result
+
+
+def test_redacts_stripe_secret_key():
+ result = redact(f"STRIPE={_STRIPE_SK}")
+ assert _STRIPE_SK not in result
+ assert "[REDACTED:api_key]" in result
+
+
+def test_redacts_stripe_publishable_key():
+ result = redact(f"KEY={_STRIPE_PK}")
+ assert _STRIPE_PK not in result
+ assert "[REDACTED:api_key]" in result
+
+
+def test_redacts_multiple_secrets_in_one_string():
+ result = redact(f"email [email protected] and key {_OPENAI_2}")
+ assert "[email protected]" not in result
+ assert _OPENAI_2 not in result
+ assert result.count("[REDACTED:") == 2
diff --git a/scientific-skills/autoskill/tests/test_run.py b/scientific-skills/autoskill/tests/test_run.py
new file mode 100644
index 00000000..9e830509
--- /dev/null
+++ b/scientific-skills/autoskill/tests/test_run.py
@@ -0,0 +1,229 @@
+import json
+from pathlib import Path
+
+import httpx
+import pytest
+
+from run import run, ScreenpipeUnreachable
+
+
+SKILL_TEMPLATE = "---\nname: {name}\ndescription: {description}\n---\n# {name}\n"
+
+
+def _write_skill(root: Path, name: str, description: str) -> None:
+ d = root / name
+ d.mkdir(parents=True, exist_ok=True)
+ (d / "SKILL.md").write_text(SKILL_TEMPLATE.format(name=name, description=description))
+
+
+def _screenpipe_client_with_events(events):
+ def handler(request):
+ data = [
+ {"type": "OCR", "content": {
+ "timestamp": e["ts"], "app_name": e["app"],
+ "window_name": e.get("window_title", ""), "text": e.get("text", "")
+ }}
+ for e in events
+ ]
+ return httpx.Response(200, json={
+ "data": data,
+ "pagination": {"limit": 9999, "offset": 0, "total": len(data)},
+ })
+ return httpx.Client(transport=httpx.MockTransport(handler), base_url="http://screenpipe.test")
+
+
+def _keyword_embedder(text):
+ keywords = ["paper", "pubmed", "literature", "figure", "schematic", "slide"]
+ return [1.0 if k in text.lower() else 0.0 for k in keywords]
+
+
+class StubBackend:
+ def __init__(self, response_fn):
+ self.response_fn = response_fn
+ self.calls = 0
+
+ def __call__(self, prompt):
+ self.calls += 1
+ return self.response_fn(prompt, self.calls)
+
+
+def _base_config():
+ return {
+ "cluster": {"min_session_minutes": 0, "idle_gap_minutes": 10, "min_cluster_size": 2},
+ }
+
+
+def _events_two_sessions(app="Chrome"):
+ # two sessions of the same app, separated by > idle_gap
+ left = [{"ts": f"2026-04-17T10:{m:02d}:00Z", "app": app, "window_title": "PubMed",
+ "text": "literature search"} for m in range(0, 10)]
+ right = [{"ts": f"2026-04-17T12:{m:02d}:00Z", "app": app, "window_title": "bioRxiv",
+ "text": "literature search"} for m in range(0, 10)]
+ return left + right
+
+
+def test_run_writes_report_into_timestamped_proposed_dir(tmp_path):
+ skills_dir = tmp_path / "scientific-skills"
+ _write_skill(skills_dir, "literature-review", "literature pubmed papers")
+
+ backend = StubBackend(lambda prompt, n: json.dumps({"verdict": "reuse", "target": "literature-review"}))
+
+ out = run(
+ _base_config(),
+ start_time="2026-04-17T00:00:00Z", end_time="2026-04-17T23:59:59Z",
+ out_dir=tmp_path / "_proposed",
+ screenpipe_client=_screenpipe_client_with_events(_events_two_sessions()),
+ backend=backend,
+ embedder=_keyword_embedder,
+ skills_dir=skills_dir,
+ now=lambda: "2026-04-17T14-30-00",
+ )
+
+ assert out == tmp_path / "_proposed" / "2026-04-17T14-30-00"
+ assert (out / "report.md").exists()
+ report = (out / "report.md").read_text()
+ assert "literature-review" in report
+ assert "reuse" in report
+
+
+def test_run_writes_new_skill_draft_for_novel_verdict(tmp_path):
+ skills_dir = tmp_path / "scientific-skills"
+ _write_skill(skills_dir, "unrelated", "totally unrelated")
+
+ body = "---\nname: new-thing\ndescription: new\n---\n# new"
+ backend = StubBackend(lambda prompt, n: json.dumps({
+ "verdict": "novel", "name": "new-thing", "skill_body": body,
+ }))
+
+ out = run(
+ _base_config(),
+ start_time="s", end_time="e",
+ out_dir=tmp_path / "_proposed",
+ screenpipe_client=_screenpipe_client_with_events(_events_two_sessions()),
+ backend=backend, embedder=_keyword_embedder, skills_dir=skills_dir,
+ now=lambda: "ts",
+ )
+
+ assert (out / "new-skills" / "new-thing" / "SKILL.md").read_text() == body
+
+
+def test_run_writes_composition_recipe_for_compose_verdict(tmp_path):
+ skills_dir = tmp_path / "scientific-skills"
+ _write_skill(skills_dir, "literature-review", "literature")
+
+ body = "---\nname: lit-flow\ndescription: chain\n---\n# chain"
+ backend = StubBackend(lambda prompt, n: json.dumps({
+ "verdict": "compose", "name": "lit-flow", "skill_body": body,
+ }))
+
+ out = run(
+ _base_config(),
+ start_time="s", end_time="e",
+ out_dir=tmp_path / "_proposed",
+ screenpipe_client=_screenpipe_client_with_events(_events_two_sessions()),
+ backend=backend, embedder=_keyword_embedder, skills_dir=skills_dir,
+ now=lambda: "ts",
+ )
+
+ assert (out / "composition-recipes" / "lit-flow" / "SKILL.md").read_text() == body
+
+
+def test_run_dry_run_does_not_call_backend(tmp_path):
+ skills_dir = tmp_path / "scientific-skills"
+ _write_skill(skills_dir, "literature-review", "literature")
+ backend = StubBackend(lambda *a: pytest.fail("backend must not be called in dry-run"))
+
+ out = run(
+ _base_config(),
+ start_time="s", end_time="e",
+ out_dir=tmp_path / "_proposed",
+ screenpipe_client=_screenpipe_client_with_events(_events_two_sessions()),
+ backend=backend, embedder=_keyword_embedder, skills_dir=skills_dir,
+ now=lambda: "ts",
+ dry_run=True,
+ )
+
+ assert backend.calls == 0
+ plan = (out / "plan.md").read_text()
+ assert "Chrome" in plan
+ assert "session" in plan.lower()
+
+
+def test_run_redacts_secrets_from_event_text_before_any_llm_call(tmp_path):
+ skills_dir = tmp_path / "scientific-skills"
+ _write_skill(skills_dir, "unrelated", "unrelated")
+
+ events = [{"ts": f"2026-04-17T10:{m:02d}:00Z", "app": "Chrome",
+ "window_title": "Gmail",
+ "text": "email [email protected] key sk-abcdefghijklmnopqrstuvwxyz012345"}
+ for m in range(0, 10)]
+ events += [{"ts": f"2026-04-17T12:{m:02d}:00Z", "app": "Chrome",
+ "window_title": "Gmail",
+ "text": "email [email protected] key sk-abcdefghijklmnopqrstuvwxyz012345"}
+ for m in range(0, 10)]
+
+ seen_prompts = []
+
+ def capture(prompt, n):
+ seen_prompts.append(prompt)
+ return json.dumps({"verdict": "reuse", "target": "unrelated"})
+
+ backend = StubBackend(capture)
+
+ run(
+ _base_config(),
+ start_time="s", end_time="e",
+ out_dir=tmp_path / "_proposed",
+ screenpipe_client=_screenpipe_client_with_events(events),
+ backend=backend, embedder=_keyword_embedder, skills_dir=skills_dir,
+ now=lambda: "ts",
+ )
+
+ assert seen_prompts, "backend should have been called"
+ for prompt in seen_prompts:
+ assert "[email protected]" not in prompt
+ assert "sk-abcdefghijklmnopqrstuvwxyz012345" not in prompt
+
+
+def test_run_raises_actionable_error_when_screenpipe_unreachable(tmp_path):
+ skills_dir = tmp_path / "scientific-skills"
+ _write_skill(skills_dir, "any", "any")
+
+ def handler(request):
+ raise httpx.ConnectError("Connection refused")
+
+ dead_client = httpx.Client(transport=httpx.MockTransport(handler),
+ base_url="http://localhost:3030")
+ backend = StubBackend(lambda *a: pytest.fail("backend must not be called when screenpipe is down"))
+
+ with pytest.raises(ScreenpipeUnreachable, match="screenpipe"):
+ run(
+ _base_config(),
+ start_time="s", end_time="e",
+ out_dir=tmp_path / "_proposed",
+ screenpipe_client=dead_client,
+ backend=backend, embedder=_keyword_embedder, skills_dir=skills_dir,
+ now=lambda: "ts",
+ )
+
+
+def test_run_skips_clusters_below_min_cluster_size(tmp_path):
+ skills_dir = tmp_path / "scientific-skills"
+ _write_skill(skills_dir, "any", "any")
+ # only one session => no cluster meets min_cluster_size=2
+ events = [{"ts": f"2026-04-17T10:{m:02d}:00Z", "app": "Lonely",
+ "window_title": "", "text": ""} for m in range(0, 10)]
+
+ backend = StubBackend(lambda *a: pytest.fail("backend must not be called when no clusters"))
+
+ out = run(
+ _base_config(),
+ start_time="s", end_time="e",
+ out_dir=tmp_path / "_proposed",
+ screenpipe_client=_screenpipe_client_with_events(events),
+ backend=backend, embedder=_keyword_embedder, skills_dir=skills_dir,
+ now=lambda: "ts",
+ )
+
+ assert backend.calls == 0
+ assert "no clusters" in (out / "report.md").read_text().lower()
diff --git a/scientific-skills/autoskill/tests/test_synthesize.py b/scientific-skills/autoskill/tests/test_synthesize.py
new file mode 100644
index 00000000..bc2196e5
--- /dev/null
+++ b/scientific-skills/autoskill/tests/test_synthesize.py
@@ -0,0 +1,96 @@
+import json
+
+import pytest
+
+from synthesize import synthesize, SynthesisError
+
+
+class StubBackend:
+ def __init__(self, response: str):
+ self.response = response
+ self.last_prompt = None
+
+ def __call__(self, prompt: str) -> str:
+ self.last_prompt = prompt
+ return self.response
+
+
+def _cluster():
+ return {
+ "apps": ["Chrome", "Zotero"],
+ "session_count": 4,
+ "total_duration_seconds": 7200,
+ "example_titles": ["PubMed search", "bioRxiv preprint"],
+ }
+
+
+def _top_k():
+ return [
+ {"name": "literature-review", "description": "Systematic literature reviews", "score": 0.82},
+ {"name": "citation-management", "description": "Find and format citations", "score": 0.71},
+ ]
+
+
+def test_prompt_includes_cluster_and_candidate_skills():
+ backend = StubBackend(json.dumps({"verdict": "reuse", "target": "literature-review"}))
+ synthesize(_cluster(), _top_k(), backend=backend)
+
+ assert "Chrome" in backend.last_prompt
+ assert "Zotero" in backend.last_prompt
+ assert "literature-review" in backend.last_prompt
+ assert "citation-management" in backend.last_prompt
+
+
+def test_parses_reuse_verdict():
+ backend = StubBackend(json.dumps({"verdict": "reuse", "target": "literature-review"}))
+ result = synthesize(_cluster(), _top_k(), backend=backend)
+
+ assert result["verdict"] == "reuse"
+ assert result["target"] == "literature-review"
+ assert result.get("skill_body") is None
+
+
+def test_parses_compose_verdict_and_returns_skill_body():
+ body = "---\nname: lit-review-flow\ndescription: chain lit review + citations\n---\n# flow"
+ backend = StubBackend(json.dumps({
+ "verdict": "compose",
+ "name": "lit-review-flow",
+ "skill_body": body,
+ }))
+ result = synthesize(_cluster(), _top_k(), backend=backend)
+
+ assert result["verdict"] == "compose"
+ assert result["name"] == "lit-review-flow"
+ assert result["skill_body"] == body
+
+
+def test_parses_novel_verdict_and_returns_skill_body():
+ body = "---\nname: zotero-pubmed-helper\ndescription: new thing\n---\n# new"
+ backend = StubBackend(json.dumps({
+ "verdict": "novel",
+ "name": "zotero-pubmed-helper",
+ "skill_body": body,
+ }))
+ result = synthesize(_cluster(), _top_k(), backend=backend)
+
+ assert result["verdict"] == "novel"
+ assert result["skill_body"].startswith("---\nname: zotero-pubmed-helper")
+
+
+def test_tolerates_json_wrapped_in_markdown_fence():
+ payload = json.dumps({"verdict": "reuse", "target": "literature-review"})
+ backend = StubBackend(f"Sure, here:\n```json\n{payload}\n```\n")
+ result = synthesize(_cluster(), _top_k(), backend=backend)
+ assert result["verdict"] == "reuse"
+
+
+def test_raises_on_unparseable_response():
+ backend = StubBackend("not json at all, no way to parse")
+ with pytest.raises(SynthesisError):
+ synthesize(_cluster(), _top_k(), backend=backend)
+
+
+def test_raises_on_unknown_verdict():
+ backend = StubBackend(json.dumps({"verdict": "weird"}))
+ with pytest.raises(SynthesisError):
+ synthesize(_cluster(), _top_k(), backend=backend)