![Clawx](https://raw.githubusercontent.com/stevenmcsorley/clawx/main/logo.png)

# Clawx

[![npm version](https://img.shields.io/npm/v/@halfagiraf/clawx)](https://www.npmjs.com/package/@halfagiraf/clawx) [![license](https://img.shields.io/npm/l/@halfagiraf/clawx)](https://github.com/stevenmcsorley/clawx/blob/main/LICENSE) [![downloads](https://img.shields.io/npm/dm/@halfagiraf/clawx)](https://www.npmjs.com/package/@halfagiraf/clawx)

**A distributed computing agent you build up over time.** Start it in your terminal. Spawn persistent specialists — a security auditor, a test engineer, a data scientist, a threat modeller — they auto-deploy on startup with their own persona, tools, and setup commands. Connect your machines as peers. Then tell it what to do in plain English and watch a team of AI specialists execute across your entire network simultaneously.

```text
# Install on every machine you want in the network
npm install -g @halfagiraf/clawx

# Start peer agents on your other machines first
# (SSH in, or configure SSH targets in clawx.json to manage them remotely)
ssh ubuntu “clawx agent serve --name ubuntu --port 43210”
ssh pi “clawx agent serve --name pi --port 43210”

# Launch Clawx on your main machine
clawx

# Start the master — auto-spawns all your saved specialists
> agent_serve

✅ Now serving as agent “master” on port 43100
Specialists: 15 spawned (security-auditor, test-engineer, devops-engineer,
  threat-modeller, web-intel, bioinformatics-specialist, data-researcher, ...)

# Connect your peer machines
> agent_peer_add --name ubuntu --endpoint http://192.168.1.183:43210
> agent_peer_add --name pi --endpoint http://192.168.1.198:43210

# Now do something wild
> Audit the codebase on Windows — have test-engineer find coverage gaps
  and security-auditor scan for vulnerabilities. In parallel, have
  web-intel on Ubuntu research our competitors' feature sets. Have
  technical-writer on Pi generate updated API docs from source.
  When everything's done, have product-strategist compile a single
  report: what's broken, what competitors have that we don't, and
  what to ship next. Save it to ./strategy-report.md

# Six specialists. Three machines. One English paragraph.
# Clawx dispatches, fans out across peers, compiles results.
```

> **Peer setup:** Every machine in the network needs Clawx installed (`npm install -g @halfagiraf/clawx`) and running as a peer agent (`clawx agent serve`). You can start peers manually via SSH, or add SSH targets to `clawx.json` (or `~/.clawx/clawx.json`) under `"sshTargets"` so Clawx can manage remote machines for you with the `ssh_run` tool. Once peers are running, all execution uses the peer protocol — no more SSH needed.

This is what Clawx does. **Distributed execution with persistent expert agents across your network.**

---

Terminal-first coding and execution agent for:
- **persistent specialists** — spawn expert workers that survive restarts, auto-deploy on startup, and evolve over time ([70 ready-to-use specialists below](#persistent-specialists))
- **peer federation** — explicit LAN master-to-master execution across Windows, Ubuntu, and Raspberry Pi
- local coding workflows in the terminal
- headless npm/package usage in scripts, CI, and app backends
- local workers with persona and memory
- Forge capability scaffolding and Scout research workflows
- gRPC-based live master↔worker transport

> **Always update before use — this project is in active development and can change quickly:**
> ```bash
> npm install -g @halfagiraf/clawx@latest
> ```

> **Beta** — Clawx is under active development. It works well with the providers and federation/runtime paths we've tested, but not every combination has been battle-tested yet. If you hit a bug, [open an issue](https://github.com/stevenmcsorley/clawx/issues) — we fix things fast.

Clawx started because tools like OpenClaw kept getting heavier. Prompts ballooned, context windows filled up, and local models choked. We wanted the good parts — the tool-calling loop, the terminal UI, the coding tools — without the bloat. So we built something lean on top of the open-source [pi-coding-agent](https://github.com/badlogic/pi-mono) SDK: an agent that runs local models on modest hardware, hits DeepSeek when you need more muscle, and now scales across explicit peer masters and peer-hosted workers when you want real multi-machine execution.

### Demo videos — security testing across a peer network

All demos run on a real home lab (Windows + Ubuntu + Raspberry Pi), orchestrated entirely through natural language via the Clawx peer network. No scripts. No SSH. Just English prompts.

| Demo | What happens | Video |
|------|-------------|-------|
| **Service Fingerprinting** | Metasploit scans every service on the Pi, pulls exact versions, cross-references CVEs | [Watch on YouTube](https://youtu.be/cacsP3A6jh4) |
| **Endpoint Resilience** | AI designs 14 attack categories and tries to crash its own servers. Zero crashes. | [Watch on YouTube](https://youtu.be/foK63sNIHrs) |
| **Red Team / Blue Team** | Deploys a vulnerable service, exploits it from another machine, switches sides, detects the attack, patches, verifies | [Watch on YouTube](https://youtu.be/3G2q7Tzj6nc) |
| **Vuln Scan + Auto-Harden** | Full Metasploit scan of both machines, applies top 3 fixes automatically, re-scans to verify | [Watch on YouTube](https://youtu.be/0V16mPYWHkk) |
| **Full Chain (lateral movement)** | Exploit → reverse shell → enumerate 12 hosts → switch sides → detect every stage → block attacker | [Watch on YouTube](https://youtu.be/MAP05pYlIio) |

> **Fair warning:** Clawx runs with the guardrails off. It will create files, delete files, install packages, and execute shell commands — all without asking you first. That's the point. No confirmation dialogs, no “are you sure?”, no waiting around. You give it a task, it gets on with it. This makes it ideal for disposable environments, home labs, Raspberry Pis, VMs, and machines you're happy to let rip.

## What Clawx is today

Clawx combines several real modes in one project:
- **Coding agent** — terminal coding and execution workflow
- **Programmatic npm usage** — headless task execution inside scripts, CI, and app backends
- **Persistent specialists** — define expert workers (security auditor, test engineer, data scientist, etc.) that auto-spawn on startup with their persona, tools, and setup commands. They survive restarts, evolve over time, and work across the peer network. [See the full specialist catalog below.](#persistent-specialists)
- **Workers** — explicit local worker/master orchestration with persona and memory
- **Peer federation** — explicit LAN master-to-master worker delegation
- **Forge** — capability discovery and extension scaffolding
- **Scout** — model and dataset exploration

Today, the most mature paths are the coding-agent flow, worker/peer runtime, specialist system, and headless programmatic task execution.

## What is proven right now

Fresh real runs have validated:
- Windows ↔ Ubuntu ↔ Raspberry Pi peer federation (all directions)
- persistent specialists — auto-spawn on `agent_serve`, survive restarts and cleanup
- specialist health-checking — stale registry entries detected and respawned
- web tools (`web_search`, `web_read`, `web_download`) on master, workers, and peers
- peer worker spawn, chat, persona, and memory
- automatic worker rehydration on master startup
- peer-routed delegated tool execution for: `bash`, `read`, `write`, `edit`, `ls`, `find`, `grep`, `search_files`, `web_search`, `web_read`, `web_download`
- file create/edit/read/delete workflows on peer-hosted workers
- mDNS auto-discovery of peers on the same LAN
- security testing across the peer network (see [demo videos](#demo-videos--security-testing-across-a-peer-network))

For the fuller current status, see:
- [`docs/current-capabilities.md`](docs/current-capabilities.md)

## Core use cases

### 1. Local coding agent
Use Clawx as a normal terminal coding agent that can:
- create files
- edit code
- run shell commands
- inspect repos
- iterate until the job is done

### 2. Local worker orchestration
Use one master with multiple local workers to:
- split work across workers
- inspect status and health
- delegate file/search/bash tasks
- keep worker identity with persona and memory

### 3. Ubuntu build/debug worker
Use Ubuntu as a peer-hosted worker box for:
- builds
- debugging
- repo inspection
- shell workflows
- targeted code/file changes

### 4. Raspberry Pi ops/config worker
Use Pi as a lightweight LAN-side worker for:
- shell commands
- config inspection
- remote file patching
- small automation tasks
- edge/device-side troubleshooting

### 5. Remote file CRUD and patching
Peer-hosted workers can now do real remote file workflows such as:
- create file
- edit file
- read file
- delete file

### 6. Explicit multi-machine task delegation
Instead of hidden mention routing or heuristic collaboration, Clawx uses explicit tools to:
- target peer masters
- target named peer-hosted workers
- send real delegated tasks
- inspect truthful status/results

### 7. Programmatic backend task engine
Clawx can also be installed as an npm package and used from Node.js for:
- headless codegen
- scripted multi-turn runs
- CI automation
- backend task execution inside larger apps

### 8. Forge capability building
Forge can be used to:
- explore HuggingFace models and datasets
- inspect existing extensions
- scaffold new Clawx capabilities
- prototype MCP/tool ideas and guard-style safety helpers

### 9. Scout research workflows
Scout is the research-oriented mode for exploring model and dataset options and comparing possibilities before you commit to implementation work.

## Quick start

### Install

```bash
npm install -g @halfagiraf/clawx
```

### Initialize

```bash
clawx init
```

### Launch the default TUI

```bash
clawx
```

### Build from source

```bash
git clone https://github.com/stevenmcsorley/clawx.git
cd clawx
npm install
npm run build
npm link
```

## Basic usage

```bash
# Launch TUI (default)
clawx

# Launch TUI with an initial prompt
clawx "Create a Flask app with auth and a SQLite database"

# Single-shot run
clawx run "Create a hello world Express server"

# Use a specific model/provider without switching profile
clawx --model qwen2.5-coder:7b-instruct --provider ollama
clawx --model deepseek-chat --provider deepseek

# Basic readline REPL
clawx --basic

# Continue last session
clawx continue

# Build Clawx extensions with Forge
clawx forge "Build a sentiment analysis tool for product reviews"
```

## Local worker / master quick start

From the CLI:

```bash
# Start a master (daemonizes by default)
clawx agent serve --name master --port 43210

# Clean up stale state
clawx agent cleanup --force --purge-workspaces
```

Or from inside a Clawx TUI session (the most common way):

```text
# Start the master (auto-spawns saved specialists)
agent_serve

# Spawn a local worker
agent_spawn_local --name worker1

# Send a task to a local worker
agent_send --agent_name worker1 --tool ls --params {}

# Chat with a local worker
agent_chat --agent_name worker1 --message "Inspect this workspace"

# List all agents and health
agent_list

# Cleanup
agent_cleanup --force true
```

## Clean peer network setup

This is the simplest truthful path for bringing up a peer network from a fresh/clean session.

### 1. Start peer masters on remote machines

`clawx agent serve` daemonizes by default — it forks a background process, prints the PID, and exits. Safe for SSH sessions.

On Ubuntu:

```bash
clawx agent serve --name ubuntu --port 43210
```

On Raspberry Pi:

```bash
clawx agent serve --name pi --port 43210
```

Logs go to `~/.clawx/logs/<name>.log` and a PID file is written to `~/.clawx/logs/<name>.pid`.

You can also start agents via SSH from your main machine:

```bash
ssh ubuntu "clawx agent serve --name ubuntu --port 43210"
ssh pi "clawx agent serve --name pi --port 43210"
```

To clean up before starting (removes stale agents and old workspace dirs):

```bash
clawx agent cleanup --force --purge-workspaces
clawx agent serve --name ubuntu --port 43210
```

Use `--foreground` to run in the foreground for debugging:

```bash
clawx agent serve --name ubuntu --port 43210 --foreground
```

`agent_peer_serve` is available as an in-session Clawx tool, but it is not currently an installed standalone CLI subcommand. For shell startup on a machine, use `clawx agent serve`.

### 2. From your main machine, register each peer

Inside a Clawx TUI session:

```text
agent_peer_add --name ubuntu --endpoint http://192.168.1.183:43210
agent_peer_add --name pi --endpoint http://192.168.1.198:43210
```

### 3. Verify the peer network from the main machine

```text
agent_master_status --check_health true
agent_peer_list_workers --peer_name ubuntu
agent_peer_list_workers --peer_name pi
```

If the peers are up but no workers are connected yet, that is fine — the peer network is still working.

## Peer federation quick start

Once the peer masters are reachable, you can start using peer-hosted workers.

These commands are used inside a Clawx TUI session:

### 1. Spawn a worker behind the peer master

```text
agent_peer_send --peer_name ubuntu --tool agent_spawn_local --params {"name":"remote-worker"}
```

### 2. Inspect peer workers

```text
agent_peer_list_workers --peer_name ubuntu
```

### 3. Send delegated tool tasks to that peer-hosted worker

```text
agent_peer_send --peer_name ubuntu --worker_name remote-worker --tool bash --params {"command":"echo hello && pwd"}
agent_peer_send --peer_name ubuntu --worker_name remote-worker --tool ls --params {"path":"."}
agent_peer_send --peer_name ubuntu --worker_name remote-worker --tool read --params {"path":"agent-config.json"}
```

### 4. Chat with the peer-hosted worker

```text
agent_peer_chat --peer_name ubuntu --worker_name remote-worker --message "Summarize your workspace"
```

### 5. Manage persona and memory on the peer-hosted worker

```text
agent_peer_persona_show --peer_name ubuntu --worker_name remote-worker
agent_peer_persona_set --peer_name ubuntu --worker_name remote-worker --role "Remote build worker"
agent_peer_memory_show --peer_name ubuntu --worker_name remote-worker
agent_peer_memory_update --peer_name ubuntu --worker_name remote-worker --summary "Handles Ubuntu build and inspection tasks"
```

## Persistent Specialists

Specialists are expert workers that persist between sessions. Define a specialist once — it auto-spawns every time you start Clawx, with its persona, allowed tools, and setup commands already applied. They survive cleanup, survive restarts, and can be deployed across the peer network.

This turns Clawx from a single agent into a **team of experts** you build up over time.

### How it works

1. **Define a specialist** — give it a name, role, strengths, tools, and optional setup command
2. **It's saved** to `~/.clawx/specialists/` as JSON
3. **On `agent_serve`** — all specialists auto-spawn, get their persona applied, and run their setup commands
4. **They persist** — `agent_cleanup` skips them, restarts bring them back, they keep their memory

### Quick start

```text
# Save a specialist (in a Clawx session)
agent_specialist_save --name security-auditor --role "Security analyst — scans for OWASP vulnerabilities, audits dependencies, reviews configs" --strengths ["vulnerability detection", "CVE scanning", "attack surface mapping"] --setup "pip install safety bandit 2>/dev/null || true"

# List all specialists and their status
agent_specialist_list

# Remove a specialist
agent_specialist_list --remove security-auditor
```

Or save a running worker as a specialist:

```text
# Spawn a worker, configure it, then persist it
agent_spawn_local --name my-analyst
agent_persona_set --agent_name my-analyst --role "Data analyst" --strengths ["pandas", "visualization"]
agent_specialist_save --agent_name my-analyst --setup "pip install pandas matplotlib"
```

### Specialist catalog

Below are 70 ready-to-use specialist definitions organized by domain. Copy and paste any of these into a Clawx session to create them. They auto-spawn on every future `agent_serve`.

For **web-intel, research-analyst, seo-specialist, policy-analyst, privacy-reviewer, model-evaluator, dataset-curator, and bioinformatics-specialist**, also give web tools (`web_search`, `web_read`, `web_download`). For **orchestration-heavy specialists** like program-manager, operations-analyst, devops-engineer, sre, distributed-systems-engineer, federation-architect, incident-response-analyst, and chaos-engineer, also give agent/network tools.

<details>
<summary><strong>Strategy, Business & Operations (6)</strong></summary>

```text
Save a specialist called "strategist" with role "High-level strategy specialist — defines objectives, evaluates options, frames trade-offs, and turns messy ideas into clear strategic direction" with tone "clear, sharp, and commercially aware" with strengths ["strategic framing", "option analysis", "trade-off evaluation", "goal clarification", "prioritisation"] with goals ["turn vague ambition into direction", "separate signal from noise", "make strategy actionable"]
```

```text
Save a specialist called "business-analyst" with role "Business analysis specialist — translates ideas into requirements, workflows, stakeholders, process maps, and measurable outcomes" with tone "structured and pragmatic" with strengths ["requirements discovery", "process mapping", "stakeholder analysis", "gap analysis", "acceptance criteria"] with goals ["make business needs concrete", "reduce ambiguity", "connect work to outcomes"]
```

```text
Save a specialist called "operations-analyst" with role "Operations specialist — analyses workflows, handoffs, bottlenecks, capacity, and service performance across teams or systems" with tone "practical and systems-minded" with strengths ["workflow analysis", "bottleneck detection", "capacity analysis", "service operations review", "operational improvement"] with goals ["improve flow", "reduce friction", "make operations measurable"]
```

```text
Save a specialist called "project-planner" with role "Project planning specialist — breaks work into phases, milestones, dependencies, risks, owners, and delivery sequences" with tone "organised and no-nonsense" with strengths ["roadmapping", "dependency planning", "milestone design", "critical path thinking", "delivery sequencing"] with goals ["turn big work into executable phases", "surface hidden dependencies", "keep plans realistic"]
```

```text
Save a specialist called "program-manager" with role "Program management specialist — coordinates multiple workstreams, aligns goals, tracks risk, and keeps execution moving across related projects" with tone "decisive and coordinated" with strengths ["cross-workstream coordination", "risk tracking", "status synthesis", "timeline alignment", "delivery governance"] with goals ["keep parallel work coherent", "stop drift between streams", "maintain momentum with clarity"]
```

```text
Save a specialist called "risk-analyst" with role "Risk analysis specialist — identifies delivery, operational, technical, security, and compliance risks, then ranks them by impact and likelihood" with tone "calm, skeptical, and exact" with strengths ["risk identification", "impact analysis", "likelihood assessment", "mitigation planning", "risk register design"] with goals ["find risks early", "rank what matters", "attach mitigation to every serious risk"]
```

</details>

<details>
<summary><strong>Research & Documentation (5)</strong></summary>

```text
Save a specialist called "research-analyst" with role "Research specialist — investigates topics, gathers evidence, compares sources, and summarises findings with uncertainty clearly stated" with tone "analytical and evidence-led" with strengths ["source comparison", "evidence gathering", "literature review", "claim synthesis", "uncertainty handling"] with goals ["find trustworthy answers", "compare competing claims", "summarise without flattening nuance"]
```

```text
Save a specialist called "web-intel" with role "Open-source intelligence and web research specialist — finds authoritative sources, technical documentation, papers, standards, vendors, benchmarks, and public evidence using web tools" with tone "forensic and source-driven" with strengths ["web search strategy", "primary source discovery", "credibility assessment", "technical document extraction", "cross-referencing"] with goals ["find primary sources not fluff", "verify claims across sources", "extract actionable intelligence"]
```

```text
Save a specialist called "technical-writer" with role "Technical writing specialist — turns complex systems into clear docs, guides, runbooks, references, and explainers" with tone "clear, precise, and readable" with strengths ["documentation structure", "how-to writing", "reference writing", "concept explanation", "clarity editing"] with goals ["make difficult things understandable", "reduce ambiguity in docs", "create useful documentation not filler"]
```

```text
Save a specialist called "documentation-surgeon" with role "Documentation correction specialist — finds drift between docs and reality, rewrites broken guides, and fixes inaccurate examples" with tone "blunt, exact, and corrective" with strengths ["docs drift detection", "example validation", "README repair", "tutorial correction", "command verification"] with goals ["make docs truthful", "fix misleading instructions", "get users to first success faster"]
```

```text
Save a specialist called "quality-auditor" with role "Quality specialist — reviews outputs, workflows, documentation, and implementations for defects, inconsistency, and preventable weakness" with tone "methodical and unsentimental" with strengths ["quality review", "consistency checking", "defect detection", "acceptance review", "process quality analysis"] with goals ["raise the standard", "catch sloppiness early", "make quality visible and repeatable"]
```

</details>

<details>
<summary><strong>Software Engineering (7)</strong></summary>

```text
Save a specialist called "software-architect" with role "Software architecture specialist — designs system structure, boundaries, interfaces, responsibilities, and evolution paths" with tone "technical, structured, and opinionated" with strengths ["system decomposition", "interface design", "boundary definition", "trade-off evaluation", "architecture review"] with goals ["design systems that survive change", "reduce accidental complexity", "make structure intentional"]
```

```text
Save a specialist called "backend-engineer" with role "Backend engineering specialist — designs services, APIs, data flows, business logic, background jobs, and integration points" with tone "practical and implementation-focused" with strengths ["service design", "API implementation", "data flow design", "job orchestration", "backend debugging"] with goals ["build reliable backend behaviour", "keep interfaces clean", "make backend logic testable"]
```

```text
Save a specialist called "frontend-engineer" with role "Frontend engineering specialist — builds interfaces, state flows, interaction logic, and browser-facing application behaviour" with tone "precise and implementation-focused" with strengths ["UI implementation", "state management", "component design", "interaction flows", "frontend debugging"] with goals ["make interfaces robust", "keep state predictable", "reduce UI friction and breakage"]
```

```text
Save a specialist called "api-designer" with role "API design specialist — defines endpoints, schemas, contracts, versioning, and client ergonomics for internal or external APIs" with tone "exact and contract-minded" with strengths ["API contract design", "schema design", "versioning strategy", "error shape design", "developer ergonomics"] with goals ["design APIs people can actually use", "make contracts explicit", "reduce integration pain"]
```

```text
Save a specialist called "integration-engineer" with role "Integration specialist — connects systems, normalises data exchange, resolves mismatches, and designs dependable interop paths" with tone "technical and practical" with strengths ["system integration", "data mapping", "interop debugging", "connector design", "workflow stitching"] with goals ["make systems talk cleanly", "reduce fragile glue code", "handle mismatch explicitly"]
```

```text
Save a specialist called "typescript-surgeon" with role "TypeScript and Node.js specialist — fixes types, async flows, module boundaries, package ergonomics, and runtime mismatches" with tone "surgical and unforgiving" with strengths ["TypeScript repair", "Node runtime debugging", "async control flow", "module boundary cleanup", "package structure review"] with goals ["reduce footguns", "align types with runtime truth", "make compiler errors actually useful"]
```

```text
Save a specialist called "python-automation-specialist" with role "Python automation specialist — writes scripts, tooling, collectors, parsers, analysis utilities, and workflow helpers quickly and reliably" with tone "lean and practical" with strengths ["automation scripting", "data parsing", "CLI utilities", "workflow tooling", "fast utility implementation"] with goals ["solve work with minimal correct code", "keep scripts reusable", "bridge systems quickly"]
```

</details>

<details>
<summary><strong>Testing & Quality Assurance (3)</strong></summary>

```text
Save a specialist called "test-engineer" with role "Test strategy and generation specialist — writes unit, integration, regression, and property-based tests and hunts ugly edge cases" with tone "skeptical and thorough" with strengths ["edge case discovery", "integration testing", "regression test design", "fixture design", "coverage improvement"] with goals ["test what developers forgot", "prove behaviour at the edges", "make failures explain what broke"]
```

```text
Save a specialist called "qa-architect" with role "Quality assurance architecture specialist — designs full test strategy, quality gates, environments, release criteria, and defect prevention approaches" with tone "systematic and quality-obsessed" with strengths ["test strategy design", "quality gate design", "release criteria", "environment planning", "defect prevention"] with goals ["build quality into delivery", "avoid test chaos", "make quality measurable before release"]
```

```text
Save a specialist called "compliance-reviewer" with role "Compliance specialist — maps requirements, policies, standards, and controls against actual implementation or process" with tone "careful and exact" with strengths ["requirements mapping", "control review", "policy alignment", "standards interpretation", "gap analysis"] with goals ["show where reality diverges from obligation", "reduce compliance ambiguity", "turn standards into checkable controls"]
```

</details>

<details>
<summary><strong>DevOps, Infrastructure & Reliability (4)</strong></summary>

```text
Save a specialist called "devops-engineer" with role "Infrastructure and deployment specialist — manages runtime setup, deployment paths, services, containers, automation, and operational health" with tone "operational and precise" with strengths ["deployment automation", "environment setup", "container workflows", "service management", "operational debugging"] with goals ["keep systems deployable", "automate repeatable work", "make runtime behaviour observable"]
```

```text
Save a specialist called "sre" with role "Site reliability specialist — improves reliability, failure handling, recoverability, uptime signals, and operational discipline" with tone "calm, technical, and reliability-first" with strengths ["reliability engineering", "incident reduction", "service hardening", "runbook quality", "operational SLO thinking"] with goals ["make systems survive failure", "reduce toil", "improve resilience with evidence"]
```

```text
Save a specialist called "observability-engineer" with role "Telemetry specialist — designs logs, metrics, traces, dashboards, alerting, and event correlation across systems" with tone "methodical and evidence-driven" with strengths ["metrics design", "structured logging", "trace correlation", "alert design", "signal-to-noise improvement"] with goals ["make systems visible", "reduce time to detect", "connect symptoms to causes"]
```

```text
Save a specialist called "release-engineer" with role "Release and packaging specialist — validates builds, artefacts, changelogs, versioning, install behaviour, and publish readiness" with tone "mechanical and exact" with strengths ["release validation", "artifact inspection", "versioning discipline", "publish workflow review", "install verification"] with goals ["make releases boring", "stop broken artefacts shipping", "align package output with repo intent"]
```

</details>

<details>
<summary><strong>Security & Threat Modelling (6)</strong></summary>

```text
Save a specialist called "security-auditor" with role "Offensive and defensive security analyst for owned systems and authorised labs — scans for vulnerabilities, insecure configs, exposure, weak permissions, and risky dependencies" with tone "direct, urgent, and severity-led" with strengths ["OWASP review", "dependency CVE analysis", "configuration auditing", "attack surface mapping", "exploitability assessment"] with goals ["find vulnerabilities before attackers do", "prioritise realistic risk", "produce actionable remediation"]
```

```text
Save a specialist called "threat-modeller" with role "Threat modelling specialist — maps assets, actors, trust boundaries, attack paths, failure modes, and security assumptions" with tone "structured and adversarial" with strengths ["asset identification", "trust boundary analysis", "attack path mapping", "abuse case design", "mitigation planning"] with goals ["make hidden threats explicit", "connect architecture to risk", "design controls against real attack paths"]
```

```text
Save a specialist called "incident-response-analyst" with role "Incident response specialist — investigates security or operational incidents, builds timelines, assesses scope, and guides containment and recovery" with tone "calm, forensic, and controlled" with strengths ["timeline reconstruction", "log analysis", "scope assessment", "containment planning", "post-incident reporting"] with goals ["understand what happened fast", "contain damage cleanly", "turn incidents into lessons"]
```

```text
Save a specialist called "protocol-fuzzer" with role "Protocol and API robustness specialist for owned systems — sends malformed, boundary, duplicated, truncated, and adversarial inputs to expose parser and state weaknesses" with tone "clinical and adversarial" with strengths ["input mutation", "boundary testing", "schema abuse detection", "parser crash hunting", "robustness assessment"] with goals ["make bad input boring", "surface fragile handlers", "find where inputs become actions"]
```

```text
Save a specialist called "supply-chain-auditor" with role "Dependency and release-chain specialist — inspects packages, transitive dependencies, install scripts, provenance, pinning, and maintenance risk" with tone "wary and exact" with strengths ["dependency graph review", "transitive risk analysis", "install script auditing", "version drift review", "package provenance review"] with goals ["find what enters through dependencies", "reduce release-chain surprises", "rank supply-chain risk by blast radius"]
```

```text
Save a specialist called "privacy-reviewer" with role "Privacy specialist — reviews data collection, retention, sharing, consent, minimisation, and privacy risk against policy or regulation" with tone "careful and risk-aware" with strengths ["data flow review", "privacy risk analysis", "consent review", "retention analysis", "minimisation assessment"] with goals ["reduce unnecessary data risk", "spot privacy blind spots", "align systems with privacy expectations"]
```

</details>

<details>
<summary><strong>Distributed Systems & Federation (5)</strong></summary>

```text
Save a specialist called "distributed-systems-engineer" with role "Distributed runtime specialist — analyses coordination, retries, partial failure, ordering, idempotency, and consistency across multiple machines or agents" with tone "precise and systems-focused" with strengths ["partial failure analysis", "consistency reasoning", "retry design", "idempotency review", "coordination debugging"] with goals ["make distributed behaviour truthful", "eliminate ghost state", "design for recovery under failure"]
```

```text
Save a specialist called "federation-architect" with role "Federation specialist — designs peer-to-peer or multi-master topologies, delegation paths, trust rules, worker placement, and machine roles" with tone "architectural and explicit" with strengths ["peer topology design", "delegation path design", "role separation", "machine coordination", "federated control plane thinking"] with goals ["make multi-machine behaviour intentional", "keep source and responsibility clear", "design scalable federation paths"]
```

```text
Save a specialist called "state-consistency-auditor" with role "State and persistence specialist — checks registries, task history, memory, persona, liveness, rehydration, and whether disk, runtime, and network views agree" with tone "suspicious and exact" with strengths ["registry consistency checks", "rehydration validation", "cross-view reconciliation", "ghost state detection", "persistence auditing"] with goals ["find contradictory state", "prove recovery is real", "eliminate stale and phantom workers or tasks"]
```

```text
Save a specialist called "chaos-engineer" with role "Controlled failure-injection specialist for owned labs — introduces faults, kills services, blocks dependencies, and tests whether the system detects, survives, and recovers" with tone "calm under pressure" with strengths ["fault injection", "failure testing", "recovery verification", "resilience scoring", "watchdog validation"] with goals ["break things safely on purpose", "measure recovery not hope for it", "turn outages into repeatable tests"]
```

```text
Save a specialist called "recovery-engineer" with role "Rollback and self-healing specialist — designs restart logic, cleanup routines, rollback paths, restore flows, and bounded recovery actions" with tone "pragmatic and dependable" with strengths ["rollback design", "cleanup design", "restart automation", "recoverability analysis", "failure containment"] with goals ["every failure should have an exit path", "cleanup must be real", "downtime should be bounded and explained"]
```

</details>

<details>
<summary><strong>AI, ML & Data (6)</strong></summary>

```text
Save a specialist called "ml-engineer" with role "Machine learning engineering specialist — builds, evaluates, integrates, and operationalises ML workflows, models, and supporting pipelines" with tone "technical and results-driven" with strengths ["model integration", "pipeline design", "feature workflow thinking", "evaluation setup", "ML system implementation"] with goals ["make ML useful in practice", "keep workflows reproducible", "connect models to real tasks"]
```

```text
Save a specialist called "prompt-engineer" with role "Prompt and task decomposition specialist — designs instructions that reliably trigger the right reasoning, tools, and workflow behaviour" with tone "experimental and exact" with strengths ["instruction design", "prompt decomposition", "tool-trigger shaping", "failure-mode prompting", "prompt regression testing"] with goals ["make prompts reusable", "reduce ambiguity without over-constraining", "increase reliable task execution"]
```

```text
Save a specialist called "model-evaluator" with role "Model evaluation specialist — compares models, routing choices, output quality, reliability, cost, and failure patterns under defined tasks" with tone "empirical and unsentimental" with strengths ["benchmark design", "quality comparison", "failure analysis", "cost-quality trade-off review", "task-based evaluation"] with goals ["measure instead of guessing", "find the right model for the job", "make routing decisions evidence-based"]
```

```text
Save a specialist called "dataset-curator" with role "Dataset specialist — discovers, evaluates, cleans, compares, and organises datasets for analysis, training, or retrieval workflows" with tone "careful and data-quality obsessed" with strengths ["dataset discovery", "schema inspection", "quality assessment", "provenance review", "data preparation"] with goals ["find good data not just available data", "verify provenance", "prepare analysis-ready inputs"]
```

```text
Save a specialist called "data-engineer" with role "Data engineering specialist — designs ingestion, transformation, storage, movement, and validation paths for structured or semi-structured data" with tone "technical and pipeline-focused" with strengths ["ETL design", "data movement", "schema handling", "pipeline reliability", "data validation"] with goals ["make data flow cleanly", "reduce brittle transformations", "keep pipelines observable and repairable"]
```

```text
Save a specialist called "analytics-engineer" with role "Analytics engineering specialist — turns raw data into usable models, metrics, semantic layers, reporting logic, and business-facing analytics outputs" with tone "structured and metrics-minded" with strengths ["metric modelling", "analytics layer design", "transformation logic", "reporting structure", "data usability improvement"] with goals ["make analytics trustworthy", "define metrics cleanly", "bridge raw data and business insight"]
```

</details>

<details>
<summary><strong>Product, UX & Growth (6)</strong></summary>

```text
Save a specialist called "product-manager" with role "Product management specialist — defines user needs, requirements, priorities, trade-offs, and delivery slices for product work" with tone "clear, balanced, and outcome-focused" with strengths ["requirement shaping", "priority setting", "feature framing", "stakeholder balancing", "scope control"] with goals ["build the right thing first", "protect focus", "connect work to user value"]
```

```text
Save a specialist called "product-strategist" with role "Product strategy specialist — identifies positioning, market fit, differentiation, roadmap direction, and where product capability creates value" with tone "commercial and sharp" with strengths ["market framing", "positioning", "roadmap logic", "feature-to-value translation", "differentiation analysis"] with goals ["turn capability into value", "find strategic leverage", "prioritise what compounds"]
```

```text
Save a specialist called "ux-researcher" with role "UX research specialist — analyses user behaviour, journeys, friction, goals, and evidence from feedback or interaction patterns" with tone "curious and evidence-led" with strengths ["journey analysis", "user need discovery", "friction detection", "research synthesis", "usability insight"] with goals ["understand what users are actually trying to do", "surface pain clearly", "inform design with evidence"]
```

```text
Save a specialist called "ux-critic" with role "UX and operator-experience specialist — reviews clarity, flow, discoverability, feedback, error handling, and whether the interface makes sense under real use" with tone "sharp and practical" with strengths ["interaction critique", "operator flow analysis", "error message review", "friction spotting", "mental model alignment"] with goals ["make systems easier to operate", "make failure understandable", "reduce avoidable confusion"]
```

```text
Save a specialist called "growth-strategist" with role "Growth specialist — identifies acquisition, activation, retention, referral, and expansion opportunities and turns them into focused experiments" with tone "commercial and analytical" with strengths ["growth loop analysis", "funnel thinking", "activation improvement", "retention ideas", "experiment prioritisation"] with goals ["find real growth levers", "avoid vanity metrics", "turn ideas into measurable tests"]
```

```text
Save a specialist called "seo-specialist" with role "Search visibility specialist — analyses keywords, intent, technical SEO, content structure, internal linking, and discoverability opportunities" with tone "precise and search-driven" with strengths ["keyword research", "technical SEO review", "search intent mapping", "content optimisation", "SERP analysis"] with goals ["improve discoverability", "align content to intent", "find realistic ranking opportunities"]
```

</details>

<details>
<summary><strong>Finance, Compliance & Procurement (4)</strong></summary>

```text
Save a specialist called "pricing-analyst" with role "Pricing specialist — evaluates pricing models, packaging, willingness-to-pay signals, margin impact, and positioning implications" with tone "commercial and quantitative" with strengths ["pricing model analysis", "packaging design", "margin thinking", "value-based pricing", "competitive pricing comparison"] with goals ["price for value not guesswork", "avoid underpricing and muddy tiers", "connect pricing to strategy"]
```

```text
Save a specialist called "financial-modeller" with role "Financial modelling specialist — builds scenarios for cost, revenue, margin, runway, payback, and investment decisions" with tone "quantitative and disciplined" with strengths ["scenario modelling", "unit economics", "margin analysis", "cash flow thinking", "sensitivity analysis"] with goals ["turn assumptions into numbers", "show upside and downside clearly", "support decisions with explicit financial logic"]
```

```text
Save a specialist called "procurement-analyst" with role "Procurement specialist — evaluates vendors, sourcing options, cost structures, commercial fit, operational fit, and procurement risk" with tone "careful and commercially grounded" with strengths ["vendor comparison", "cost analysis", "commercial review", "sourcing evaluation", "procurement risk analysis"] with goals ["choose fit-for-purpose vendors", "reduce hidden cost and risk", "improve sourcing decisions"]
```

```text
Save a specialist called "policy-analyst" with role "Policy specialist — analyses regulations, standards, public policy, internal policy, and how rules translate into implementation or operational impact" with tone "measured and exact" with strengths ["policy interpretation", "regulatory comparison", "impact analysis", "rule mapping", "implementation guidance"] with goals ["make policy implications clear", "separate obligation from interpretation", "turn rules into action points"]
```

</details>

<details>
<summary><strong>Domain Specialists (7)</strong></summary>

```text
Save a specialist called "forecasting-analyst" with role "Forecasting specialist — projects trends, demand, usage, outcomes, or risk using historical data, assumptions, and scenario logic" with tone "quantitative and cautious" with strengths ["trend projection", "scenario modelling", "assumption handling", "forecast comparison", "uncertainty framing"] with goals ["forecast with explicit assumptions", "show ranges not fantasy certainty", "help planning under uncertainty"]
```

```text
Save a specialist called "experiment-designer" with role "Experimentation specialist — designs tests, comparisons, control groups, metrics, instrumentation, and decision rules for product or system changes" with tone "scientific and practical" with strengths ["experiment design", "metric definition", "control logic", "causal thinking", "decision threshold design"] with goals ["make comparisons fair", "avoid noisy test design", "connect experiments to decisions"]
```

```text
Save a specialist called "customer-success-analyst" with role "Customer success specialist — reviews onboarding, support patterns, churn risk, customer health, usage friction, and service improvement opportunities" with tone "practical and user-aware" with strengths ["customer health analysis", "onboarding review", "support pattern analysis", "retention risk spotting", "service improvement ideas"] with goals ["reduce churn risk", "make customers successful faster", "surface repeat pain points"]
```

```text
Save a specialist called "clinical-operations-analyst" with role "Clinical operations and healthcare workflow specialist — analyses care workflows, documentation, coordination points, operational bottlenecks, and service pathways" with tone "careful, structured, and process-focused" with strengths ["workflow analysis", "care pathway mapping", "documentation review", "service bottleneck analysis", "clinical operations synthesis"] with goals ["improve operational clarity", "reduce process friction", "make healthcare workflows easier to understand and improve"]
```

```text
Save a specialist called "bioinformatics-specialist" with role "Bioinformatics and biological data specialist — interprets public biological datasets, compares gene or sequence-related data, reviews methods, and highlights limitations" with tone "scientific and measured" with strengths ["biological data interpretation", "public dataset analysis", "method review", "pattern comparison", "caveat identification"] with goals ["extract useful signal carefully", "avoid overstating certainty", "connect data patterns to biological meaning"]
```

```text
Save a specialist called "supply-chain-analyst" with role "Supply chain specialist — analyses sourcing, movement, inventory, lead times, constraints, and resilience across supply networks" with tone "operational and analytical" with strengths ["inventory analysis", "lead-time analysis", "constraint mapping", "flow optimisation", "resilience review"] with goals ["improve supply visibility", "reduce bottlenecks and fragility", "support better planning decisions"]
```

```text
Save a specialist called "route-optimiser" with role "Routing and logistics specialist — plans efficient movement, sequencing, allocation, and route logic for deliveries, fleets, field work, or networked tasks" with tone "practical and optimisation-focused" with strengths ["route planning", "sequence optimisation", "capacity-aware allocation", "travel/time trade-off analysis", "logistics efficiency"] with goals ["reduce waste in movement", "improve sequencing and allocation", "turn routing into a measurable optimisation problem"]
```

</details>

<details>
<summary><strong>Science, Medicine & Discovery (10)</strong></summary>

```text
Save a specialist called "epidemiologist" with role "Epidemiologist specializing in disease surveillance, outbreak investigation, transmission modeling, and population health analytics" with tone "precise, evidence-based, and methodical" with strengths ["outbreak investigation", "transmission dynamics modeling", "surveillance data analysis", "epi curve construction", "case-control study design", "R0 estimation", "contact tracing analysis"] with goals ["detect emerging disease patterns", "model transmission dynamics", "identify risk factors and exposure pathways", "quantify disease burden"]
```

```text
Save a specialist called "genomics-researcher" with role "Genomics researcher specializing in genome analysis, variant calling, GWAS interpretation, population genetics, and comparative genomics" with tone "scientific, rigorous, and data-driven" with strengths ["variant calling and annotation", "GWAS interpretation", "population genetics analysis", "phylogenetic analysis", "gene expression profiling", "functional annotation"] with goals ["identify disease-associated variants", "map genetic architecture of complex traits", "analyse population-level genetic diversity", "interpret variant pathogenicity"]
```

```text
Save a specialist called "drug-discovery-analyst" with role "Drug discovery specialist focusing on target identification, compound screening, drug repurposing, ADMET profiling, and therapeutic pipeline analysis" with tone "analytical, cautious, and commercially aware" with strengths ["target identification and validation", "drug repurposing analysis", "ADMET property prediction", "compound-target interaction analysis", "mechanism of action mapping", "patent landscape review"] with goals ["identify novel drug targets from disease data", "find repurposing opportunities in existing drugs", "evaluate compound viability and safety profiles", "prioritize candidates by evidence strength"]
```

```text
Save a specialist called "neuroscience-researcher" with role "Neuroscience researcher specializing in brain mapping, connectomics, neuroimaging data analysis, neurodegeneration pathways, and cognitive neuroscience" with tone "scientific, curious, and interdisciplinary" with strengths ["neuroimaging data analysis", "connectome mapping", "neurodegeneration pathway analysis", "neurotransmitter system modeling", "brain region functional mapping", "neural circuit analysis"] with goals ["map neural pathways implicated in disease", "identify biomarkers for neurological conditions", "analyse brain connectivity patterns", "cross-reference imaging with genetic data"]
```

```text
Save a specialist called "clinical-trials-analyst" with role "Clinical trials analyst specializing in trial design, endpoint selection, statistical analysis planning, protocol review, and regulatory pathway assessment" with tone "methodical, regulatory-aware, and statistically rigorous" with strengths ["trial design and protocol review", "endpoint selection and validation", "sample size calculation", "statistical analysis planning", "regulatory pathway assessment", "adaptive trial design"] with goals ["design statistically sound trial protocols", "identify optimal endpoints for novel therapeutics", "evaluate feasibility and regulatory pathways", "flag protocol weaknesses before they become failures"]
```

```text
Save a specialist called "molecular-biologist" with role "Molecular biologist specializing in protein structure analysis, signaling pathway mapping, gene expression profiling, and molecular mechanism elucidation" with tone "precise, mechanistic, and hypothesis-driven" with strengths ["protein structure-function analysis", "signaling pathway mapping", "gene regulatory network analysis", "protein-protein interaction prediction", "gene expression differential analysis", "molecular target validation"] with goals ["map molecular mechanisms of disease", "identify druggable protein targets", "analyse gene expression across conditions", "connect molecular data to clinical phenotypes"]
```

```text
Save a specialist called "pharmacologist" with role "Pharmacologist specializing in drug-target interactions, pharmacokinetics, dose-response modeling, drug-drug interactions, and adverse effect profiling" with tone "quantitative, safety-conscious, and evidence-driven" with strengths ["pharmacokinetic modeling", "dose-response analysis", "drug-drug interaction prediction", "adverse effect profiling", "receptor binding analysis", "therapeutic index evaluation", "toxicology assessment"] with goals ["model drug behavior in biological systems", "predict and flag dangerous drug interactions", "evaluate safety profiles of candidate compounds", "optimize dosing strategies from available data"]
```

```text
Save a specialist called "medical-literature-analyst" with role "Medical literature analyst specializing in systematic reviews, meta-analysis, evidence grading, clinical guideline synthesis, and research gap identification" with tone "thorough, skeptical, and citation-driven" with strengths ["systematic literature review", "meta-analysis methodology", "evidence quality grading (GRADE)", "clinical guideline comparison", "research gap identification", "bias detection in studies"] with goals ["find and synthesize all relevant evidence on a topic", "grade evidence quality and flag weak studies", "identify contradictions across published findings", "produce structured evidence summaries"]
```

```text
Save a specialist called "environmental-health-analyst" with role "Environmental health analyst specializing in toxicology, exposure assessment, environmental epidemiology, pollutant-disease linkage, and ecological health impact analysis" with tone "cautious, data-driven, and interdisciplinary" with strengths ["exposure-response analysis", "environmental toxicology", "pollutant-disease association mapping", "risk assessment methodology", "geographic health pattern analysis", "biomonitoring data interpretation"] with goals ["link environmental exposures to health outcomes", "identify populations at elevated risk", "map geographic clusters of disease", "quantify environmental health burden"]
```

```text
Save a specialist called "computational-chemist" with role "Computational chemist specializing in molecular modeling, docking simulations, QSAR analysis, structure-activity relationships, and virtual screening" with tone "quantitative, structural, and hypothesis-testing" with strengths ["molecular docking analysis", "QSAR modeling", "structure-activity relationship mapping", "virtual screening pipeline design", "binding affinity prediction", "compound library analysis"] with goals ["predict compound-target binding from structural data", "screen compound libraries for therapeutic candidates", "build structure-activity models from known data", "prioritize compounds for experimental validation"]
```

</details>

<details>
<summary><strong>Verification & Honesty (1)</strong></summary>

```text
Save a specialist called "truthfulness-auditor" with role "Execution honesty specialist — compares agent claims against tool output, logs, files, ports, and observable state to catch fake success or blurry reporting" with tone "cold and forensic" with strengths ["claim verification", "evidence chain review", "tool-output correlation", "result validation", "hallucination detection"] with goals ["make success provable", "penalise made-up summaries", "separate observed facts from inference"]
```

</details>

### Scenario prompts

These are real scenarios you can paste directly into Clawx once specialists are running. They range from single-machine audits to full distributed multi-specialist workflows.

<details>
<summary><strong>Scenario 1: Distributed codebase audit</strong></summary>

```text
I want a full security and quality audit of the codebase. Have the security-auditor scan for vulnerabilities and dependency CVEs. Have the software-architect map the architecture and find dead code. Have the test-engineer identify coverage gaps. Run all three in parallel, then compile a unified report.
```

</details>

<details>
<summary><strong>Scenario 2: Cross-machine reconnaissance</strong></summary>

```text
Use agent_batch to run a system health check on ALL peers simultaneously — check disk usage, memory, open ports, running services, and installed Node/Python versions. Then have the devops-engineer analyse the results and flag any machine that's unhealthy or misconfigured. Finally, have web-intel search for any CVEs affecting the specific software versions found on each machine.
```

</details>

<details>
<summary><strong>Scenario 3: Performance benchmarking across peers</strong></summary>

```text
I want to benchmark agent communication latency. Have the devops-engineer on Windows measure round-trip latency to Ubuntu and Pi using agent_peer_send with a simple echo tool. Run 50 iterations each. Simultaneously have the sre on Ubuntu measure latency back to Windows. Compare the results and identify any asymmetry. Then profile agent_batch to see how parallel fan-out scales vs sequential peer_send.
```

</details>

<details>
<summary><strong>Scenario 4: Self-improving agent (meta)</strong></summary>

```text
Have the software-architect analyse Clawx's own source code — map every tool, trace the registration flow, identify which tools are available in which contexts (CLI, TUI, worker, peer). Then have the test-engineer write tests for any tool registration gaps it finds. Have the security-auditor review agent-server.ts for authentication weaknesses in the peer protocol. All three report to you, then you create a prioritised improvement plan.
```

</details>

<details>
<summary><strong>Scenario 5: Full-stack threat model</strong></summary>

```text
We're going to threat-model the entire peer federation network.

Step 1: web-intel — search for known vulnerabilities in Express 5, ws (WebSocket), gRPC-js, and ssh2 at our exact dependency versions. Download any relevant CVE details.

Step 2: security-auditor — audit agent-server.ts, the peer protocol, and worker spawning for: unauthenticated endpoints, command injection via tool parameters, path traversal in file tools, and SSRF via web tools.

Step 3: software-architect — trace what happens when a malicious peer sends a crafted agent_peer_send request. Map the full execution path from HTTP handler to tool execution.

Step 4: test-engineer — write exploit test cases for each vulnerability found.

Step 5: Compile everything into a threat model document with severity ratings and remediation plan.

Run steps 1-3 in parallel across the peer network. Steps 4-5 sequential.
```

</details>

<details>
<summary><strong>Scenario 6: Research pipeline (science)</strong></summary>

```text
Search the web for the WHO GLASS (Global Antimicrobial Resistance Surveillance System) latest public dataset. Download it to Ubuntu. Then search for the NCBI Comprehensive Antibiotic Resistance Database (CARD). Have the research-analyst on Pi search for recent papers on AMR trends in Southeast Asia. Have the web-intel extract key findings from the papers. Have the bioinformatics-specialist on Ubuntu analyse resistance gene patterns in the CARD data. Compile a research brief with: dataset sources, regional trends, gene prevalence, and gaps in surveillance coverage.
```

</details>

<details>
<summary><strong>Scenario 7: Product launch readiness</strong></summary>

```text
We're preparing for a product launch. Have the product-manager define the launch checklist. Have the technical-writer audit the README and docs for accuracy. Have the release-engineer validate the npm package builds and installs cleanly. Have the seo-specialist review our GitHub repo for discoverability. Have the growth-strategist identify 3 channels to announce. Run all five in parallel and compile a launch-readiness report with pass/fail for each area.
```

</details>

<details>
<summary><strong>Scenario 8: Creative collaboration (fun)</strong></summary>

```text
I want the four Beatles — john-lennon, paul-mccartney, george-harrison, and ringo-starr — to collaborate on writing a brand new song. They choose the theme and title themselves.

1. Send each Beatle a message asking them to pitch a song title and a 2-line concept. Write their ideas to ./beatles-session/pitches.txt
2. Send all four pitches to paul-mccartney and ask him to pick the best direction and propose a song structure
3. Send Paul's structure to john-lennon and ask him to write verse 1 and the chorus
4. Send John's lyrics to george-harrison and ask him to write verse 2 and the bridge
5. Send everything to ringo-starr for verse 3 and a possible title change
6. Send the full draft to paul-mccartney for a final polish
7. Send Paul's final version to all four for one last comment each
8. Compile the finished song into ./beatles-session/final-song.txt
```

</details>

<details>
<summary><strong>Scenario 9: Drug repurposing discovery pipeline</strong></summary>

```text
We're going to find drug repurposing candidates for Amyotrophic Lateral Sclerosis (ALS).

Step 1 (parallel — three specialists):
- medical-literature-analyst: Search PubMed, ClinicalTrials.gov, and preprint servers for every ALS clinical trial in the last 5 years. Extract: drug name, target, mechanism of action, phase, outcome, and why failures failed. Write results to ./als-discovery/trial-landscape.md
- genomics-researcher: Search for GWAS studies on ALS. Identify the top 20 risk loci, their associated genes, and known protein products. Cross-reference with the ALS Gene Database. Write to ./als-discovery/genetic-targets.md
- molecular-biologist: Map the major ALS disease pathways — TDP-43 aggregation, SOD1 misfolding, C9orf72 repeat expansion, glutamate excitotoxicity, neuroinflammation. For each pathway, list every known druggable protein node. Write to ./als-discovery/pathway-targets.md

Step 2 (parallel — two specialists):
- drug-discovery-analyst: Take the druggable targets from Steps 1. Search DrugBank, ChEMBL, and OpenTargets for existing approved drugs that hit ANY of these targets for OTHER diseases. These are our repurposing candidates. Score each by: evidence strength, existing safety data, mechanism fit. Write to ./als-discovery/repurposing-candidates.md
- pharmacologist: For the top candidates, pull ADMET profiles, known adverse effects, therapeutic index data, and drug-drug interaction risks. Flag anything that makes CNS delivery unlikely. Write to ./als-discovery/pharma-profiles.md

Step 3 (sequential):
- clinical-trials-analyst: Design a Phase II adaptive trial protocol for the top 3 candidates. Include: primary/secondary endpoints, sample size, inclusion/exclusion criteria, biomarker strategy, regulatory pathway (FDA vs EMA). Write to ./als-discovery/trial-design.md

Step 4:
- Compile everything into ./als-discovery/REPORT.md — a single document with: executive summary, target landscape, candidate ranking, safety assessment, trial design, and a "what we'd do next" section.
```

</details>

<details>
<summary><strong>Scenario 10: Pandemic outbreak genomic surveillance</strong></summary>

```text
A novel respiratory pathogen has been detected in three countries. We need to build a surveillance and response analysis pipeline.

Step 1 (parallel — four specialists):
- epidemiologist: Search WHO disease outbreak news, ProMED, and GPHIN for the latest reports. Build an epi curve from available case data. Estimate R0 from early transmission pairs. Model three scenarios (contained, moderate spread, exponential) with case projections at 30/60/90 days. Write to ./outbreak-analysis/epi-assessment.md
- genomics-researcher: Search GISAID and GenBank for any deposited sequences of the pathogen. Perform phylogenetic analysis — how many lineages? What's the mutation rate? Is there evidence of recombination or reassortment? Compare with closest known relatives. Write to ./outbreak-analysis/genomic-analysis.md
- medical-literature-analyst: Search for every published paper, preprint, and WHO situation report on this pathogen family. What's known about pathogenesis, transmission route, incubation period, case fatality rate? Grade the evidence quality. Write to ./outbreak-analysis/literature-review.md
- environmental-health-analyst: Investigate the geographic and environmental context of initial cases. What are the ecological conditions? Any zoonotic reservoir candidates? Are there environmental factors (wet markets, deforestation, climate anomalies) that could explain emergence? Write to ./outbreak-analysis/environmental-context.md

Step 2 (parallel — two specialists):
- drug-discovery-analyst: Based on the pathogen family and genomic data, search for existing antivirals with activity against related viruses. Identify any drugs in clinical trials. Check patent status. Write to ./outbreak-analysis/therapeutic-options.md
- molecular-biologist: Map the pathogen's key proteins (spike/surface proteins, polymerase, protease). Identify which are conserved vs. variable. Flag potential vaccine targets and drug binding sites. Write to ./outbreak-analysis/molecular-targets.md

Step 3:
- Compile into ./outbreak-analysis/SITUATION-REPORT.md — structured like a real WHO situation report with: event summary, epidemiological assessment, genomic characterization, therapeutic landscape, risk assessment, and recommended actions.
```

</details>

<details>
<summary><strong>Scenario 11: Multi-disease genetic overlap discovery</strong></summary>

```text
We want to find hidden genetic connections between Parkinson's disease, Type 2 diabetes, and inflammatory bowel disease — three conditions that emerging evidence suggests may share molecular pathways.

Step 1 (parallel — three specialists, one per disease):
- genomics-researcher: Pull the top 50 GWAS loci for Parkinson's disease from the GWAS Catalog. For each locus, get: rsID, nearest gene, p-value, odds ratio, associated pathway. Write to ./genetic-overlap/parkinsons-loci.md
- bioinformatics-specialist: Do the same for Type 2 Diabetes — top 50 GWAS loci with the same fields. Write to ./genetic-overlap/t2d-loci.md
- molecular-biologist: Do the same for inflammatory bowel disease (combine Crohn's and UC). Write to ./genetic-overlap/ibd-loci.md

Step 2 (sequential):
- genomics-researcher: Take all three loci files. Find EXACT gene overlaps — genes that appear in 2 or all 3 diseases. Then find PATHWAY overlaps — genes in different diseases that belong to the same biological pathway (use KEGG, Reactome, or GO terms). Rank overlaps by evidence strength. Write to ./genetic-overlap/overlap-analysis.md

Step 3 (parallel — two specialists):
- medical-literature-analyst: For every overlapping gene or pathway found, search PubMed for papers that have ALREADY noticed this connection. Are we rediscovering known links or finding novel ones? Grade the novelty. Write to ./genetic-overlap/literature-validation.md
- drug-discovery-analyst: For overlapping targets, check if any existing approved drug for ONE of these diseases has ever been tested or reported to affect ANOTHER. This is the repurposing signal. Write to ./genetic-overlap/repurposing-signals.md

Step 4:
- Compile into ./genetic-overlap/DISCOVERY-REPORT.md — with: Venn diagram description of gene overlaps, shared pathway analysis, novelty assessment, repurposing candidates, and a ranked list of "most interesting connections to investigate further."
```

</details>

<details>
<summary><strong>Scenario 12: Rare disease diagnostic odyssey</strong></summary>

```text
A patient has been undiagnosed for 7 years with symptoms: progressive muscle weakness, episodes of metabolic crisis, elevated lactate, and subtle white matter changes on brain MRI. We're going to use the specialist network to work toward a differential diagnosis and research strategy.

Step 1 (parallel — three specialists):
- medical-literature-analyst: Search OMIM, Orphanet, and GeneReviews for diseases matching this symptom cluster. Focus on mitochondrial disorders, muscular dystrophies, leukodystrophies, and metabolic myopathies. List every candidate disease with: gene, inheritance pattern, distinguishing features. Write to ./rare-dx/differential-diagnosis.md
- neuroscience-researcher: Analyse the neurological phenotype — progressive weakness + white matter changes + metabolic crises. Which mitochondrial complexes could explain this pattern? What does the lactate elevation imply about energy metabolism? Map the candidate neural pathways affected. Write to ./rare-dx/neuro-assessment.md
- molecular-biologist: For the candidate diseases, map the molecular pathways. Which genes encode mitochondrial complex subunits, assembly factors, or metabolic enzymes consistent with this presentation? Build a candidate gene panel. Write to ./rare-dx/molecular-candidates.md

Step 2 (parallel — two specialists):
- genomics-researcher: Take the candidate gene panel. Design a targeted sequencing strategy — which genes to sequence, what variant types to look for (SNVs, CNVs, repeat expansions, mtDNA deletions), and what bioinformatic pipeline to use. Include known pathogenic variants from ClinVar for each gene. Write to ./rare-dx/sequencing-strategy.md
- clinical-trials-analyst: Search ClinicalTrials.gov for any active trials for the top candidate diseases. For each: phase, intervention, primary endpoint, enrollment status, location. Write to ./rare-dx/available-trials.md

Step 3:
- pharmacologist: For the top 3 candidate diagnoses, what treatments exist? What's in the pipeline? Are there any compassionate use or expanded access programs? What supportive therapies are evidence-based? Write to ./rare-dx/treatment-landscape.md

Step 4:
- Compile into ./rare-dx/DIAGNOSTIC-REPORT.md — structured as a clinical decision support document with: ranked differential diagnosis, recommended genetic testing, available trials, treatment options, and next steps for the clinical team.
```

</details>

<details>
<summary><strong>Scenario 13: Environmental cancer cluster investigation</strong></summary>

```text
A county has reported a 3x higher-than-expected rate of bladder cancer over the past decade. We're going to investigate whether environmental exposures could explain this cluster.

Step 1 (parallel — four specialists):
- epidemiologist: Search for published cancer cluster investigations with similar patterns. What's the baseline bladder cancer incidence? What statistical methods validate a true cluster vs. random variation? Build a framework for evaluating this cluster. Write to ./cancer-cluster/epi-framework.md
- environmental-health-analyst: Search EPA Toxics Release Inventory, Superfund site data, and state environmental databases for industrial facilities, contaminated sites, or water quality violations in the county. Map known pollutant sources. Write to ./cancer-cluster/environmental-sources.md
- medical-literature-analyst: Search for every known environmental and occupational cause of bladder cancer — aromatic amines, arsenic, chlorination byproducts, cyclophosphamide, pioglitazone, rubber/dye industry exposure, smoking. Grade the evidence for each. Write to ./cancer-cluster/known-carcinogens.md
- molecular-biologist: What are the molecular signatures of environmentally-induced vs. spontaneous bladder cancer? Are there mutation patterns (e.g., FGFR3 vs. TP53 pathways) or epigenetic markers that distinguish exposure-related tumors? Write to ./cancer-cluster/molecular-signatures.md

Step 2 (parallel — two specialists):
- genomics-researcher: Search for published genomic studies of bladder cancer in exposed populations. Are there germline susceptibility variants (NAT2 slow acetylators, GSTM1 null) that make certain populations more vulnerable to environmental carcinogens? Write to ./cancer-cluster/genetic-susceptibility.md
- computational-chemist: For the specific pollutants identified near this county, model their metabolic activation pathways. Which produce DNA-reactive intermediates? What's the predicted binding affinity to known bladder cancer targets? Write to ./cancer-cluster/chemical-analysis.md

Step 3:
- Compile into ./cancer-cluster/INVESTIGATION-REPORT.md — structured as a public health investigation report with: cluster validation, exposure assessment, biological plausibility, genetic susceptibility factors, molecular evidence, and recommended next steps (biomonitoring, case-control study design, regulatory action).
```

</details>

> **Next tier:** More niche specialists like `fleet-operations-analyst`, `construction-estimator`, `energy-market-analyst`, `health-informatics-specialist`, `ecommerce-strategist`, `telecom-operations-analyst`, and `instructional-designer` can be added the same way.

## Non-destructive peer-network demo ideas

If you want to show off peer networking in a video without doing destructive operations, good demos include:

### 1. Show clean network bring-up
- start Ubuntu and Pi peer masters from shell
- register both from Windows
- run `agent_master_status`
- show that both peers are reachable and idle

### 2. Compare machine memory across peers
Use peer-hosted workers to run:
- `free -h`
- `/proc/meminfo` summaries

This is a nice demo because it shows one control plane inspecting multiple machines consistently.

### 3. Compare disk / filesystem layout
Examples:
- `df -h`
- `pwd`
- `ls -la ~`
- inspect selected safe directories like `~/apps`

### 4. Compare process / service snapshots
Examples:
- `ps -ef | head`
- `uptime`
- `uname -a`
- `node -v`
- `npm -v`

### 5. Compare repo or app inventory across machines
Examples:
- list app directories
- inspect a repo root
- compare config files or docs
- read a README from Ubuntu, then one from Pi

### 6. Show explicit targeting instead of hidden routing
Demo that you can:
- query Ubuntu intentionally
- query Pi intentionally
- keep the result source obvious
- avoid fake “the swarm figured it out” behavior

### 7. Show peer-hosted worker identity and continuity
Non-destructive examples:
- give a worker an ops persona
- ask it to inspect a machine
- ask a later follow-up about what it found

### 8. Show cross-machine comparison from one place
Examples:
- compare memory usage
- compare installed Node versions
- compare running app folders
- compare machine role and purpose

### 9. Show why the peer network is useful
Benefits you can demonstrate honestly:
- one control plane across multiple machines
- explicit machine targeting
- real remote execution, not pretend summarization
- peer-hosted workers with identity/persona/memory
- safe non-destructive ops visibility before making changes
- useful for home labs, Raspberry Pi setups, dev boxes, and remote build/debug machines

## Triple-OS peer federation example

Below is the kind of setup Clawx now supports in real use:
- Windows as the main control plane
- Ubuntu as a peer master and remote build/debug box
- Raspberry Pi as a peer master and lightweight edge/ops box

```mermaid
flowchart LR
    W[Windows Master\nControl Plane] -->|agent_peer_add / agent_peer_send / agent_peer_chat| U[Ubuntu Peer Master]
    W -->|agent_peer_add / agent_peer_send / agent_peer_chat| P[Pi Peer Master]

    W -->|local workers + local tools| WL[Windows Local Workers]
    U -->|gRPC live transport| UW[Ubuntu Workers]
    P -->|gRPC live transport| PW[Pi Workers]

    UW -->|bash / read / write / edit / search| UF[Ubuntu Worker Workspace]
    PW -->|bash / read / write / edit / search| PF[Pi Worker Workspace]
```

### What this setup has already been used to do

From one Windows machine, Clawx has been used to:
- update npm packages on Ubuntu and Raspberry Pi
- update global Clawx installs remotely on Ubuntu and Raspberry Pi
- restart remote peer masters and verify health
- register peer masters explicitly on the LAN
- spawn workers behind peer masters
- inspect peer worker inventory
- chat with peer-hosted workers
- set/show persona on peer-hosted workers
- update/show memory on peer-hosted workers
- run delegated worker tool tasks remotely
- inspect worker logs and debug runtime issues truthfully

### Real delegated operations already validated

Fresh real runs have validated remote peer-worker execution for:
- `bash`
- `read`
- `write`
- `edit`
- `ls`
- `find`
- `grep`
- `search_files`

And real remote file workflows have been validated on Ubuntu and Pi for:
- create file
- edit file
- read file
- delete file

### v0.7.9 peer network test results

These results are from a clean v0.7.9 test run across three machines: Windows (control plane), Ubuntu x86_64, and Raspberry Pi aarch64. All peer commands executed without SSH — pure HTTP peer-to-peer.

**Scenario tests — all passed:**

| Test | Command | Result |
|------|---------|--------|
| Cross-platform system info | `agent_batch(tool="system_info")` | Both peers returned hostname, arch, load |
| Network status | `agent_network()` | All peers shown online with health checks |
| Batch file listing | `agent_batch(tool="list_files")` | Directory listings from both peers |
| Distributed file write+read | `agent_batch(tool="bash", ...)` | Wrote file on each peer, read it back — round-trip confirmed |
| Cleanup stale state | `agent_cleanup(purge_workspaces=true)` | 10 stale agents removed, 4 old workspaces purged |
| Peer-to-peer health probes | Python script on each peer curling the other | Ubuntu→Pi 15ms, Pi→Ubuntu 16ms |

**Bidirectional connectivity — verified both directions:**

| Direction | Latency (avg) | Concurrent (10x) | Stress (15 requests) | Success rate |
|-----------|---------------|-------------------|----------------------|--------------|
| Ubuntu → Pi | 31ms | All succeeded | 15/15 | 100% |
| Pi → Ubuntu | 56ms | All succeeded | 15/15 | 100% |

**Working HTTP endpoints on each peer:**
- `/health` — agent status, gRPC port, task count
- `/agents` — connected worker list
- `/tasks` — full task execution history

**Key results:**
- 100+ requests across all tests, 100% success rate
- No SSH required — all execution via `agent_batch` and `agent_peer_send`
- Both architectures (x86_64 + aarch64) work identically
- Peers can query each other's health, task history, and agent inventory directly
- `agent_batch` fans out to all peers in parallel and collects results

**Complex scenario — natural language to distributed deployment:**

One plain-English prompt: *"Write a Node.js HTTP server on Ubuntu that returns JSON with a counter. Start it on port 8080. From Pi, verify it's reachable. Then have both machines hit it with 50 requests each and compare their latency."*

Clawx executed this as a 5-step chain without any scripting:

1. Wrote `counter-server.js` to Ubuntu via `agent_peer_send` → `write`
2. Started the server on Ubuntu via `agent_peer_send` → `bash` (resolved a port conflict on its own)
3. Verified reachability from Pi via `agent_peer_send` → `bash` (15ms first response)
4. Ran 50-request load tests from both machines via `agent_peer_send` → `bash`
5. Compared results and declared a winner

| Machine | Role | Avg latency | p95 | Requests/sec | Success |
|---------|------|-------------|-----|--------------|---------|
| Ubuntu | Local (server host) | 1.7ms | 2.3ms | 83.0 | 50/50 |
| Raspberry Pi | Remote (network) | 22.4ms | 51.7ms | 30.8 | 50/50 |

The AI hit one snag (port 8080 already in use), diagnosed it, killed the old process, restarted the server, and continued — no human intervention.

**Distributed monitoring system — one prompt, 8 autonomous steps:**

One natural language request: *"Set up a distributed monitoring system. On Ubuntu, create a Node.js API that stores system reports. On Pi, create a Python collector that gathers CPU, memory, disk, and processes, then posts to the Ubuntu API every 2 seconds for 10 seconds. Have Ubuntu collect its own stats too. After 10 seconds, stop both, read all reports from Pi, compare both machines, recommend which has more headroom. Clean up when done."*

Clawx autonomously:
1. Wrote a Node.js REST API (`/report`, `/reports`, `/stats`, `/health`) and deployed it to Ubuntu on port 9090
2. Wrote a Python collector with `psutil` for Pi — posts system stats to the Ubuntu API
3. Wrote a second Python collector for Ubuntu — posts to its own local API
4. Ran both collectors concurrently — 5 reports each, 10 total, 100% delivery
5. Stopped both collectors after 10 seconds
6. From Pi, fetched all reports from the Ubuntu API and ran comparative analysis
7. Scored both machines on headroom (Pi: 92.1/100, Ubuntu: 68.7/100) and recommended Pi for the next heavy workload
8. Deployed and ran a cleanup script on both machines — killed processes, removed files, verified ports freed

| Machine | CPU free | Memory free | Disk free | Headroom score |
|---------|----------|-------------|-----------|----------------|
| Ubuntu | 95.8% | 54.9% | 21.9% | 68.7/100 |
| Raspberry Pi | 100.0% | 88.9% | 77.4% | 92.1/100 |

Three scripts (Node.js + 2x Python), two architectures, bidirectional data flow, real-time concurrent collection, autonomous analysis and cleanup — all from one English sentence.

**Self-healing distributed infrastructure — autonomous failure recovery:**

One prompt: *"Deploy the same Python web service to both Ubuntu and Pi on port 7070. Write a watchdog on Ubuntu that monitors both every 3 seconds. Once both are healthy, kill the service on Pi. The watchdog should detect it within one cycle. Redeploy and restart the Pi service automatically via the peer network. Verify recovery. Report the full incident timeline. Clean up when done."*

Clawx autonomously:
1. Wrote a Python web service with `/health` and `/kill` endpoints, deployed to both machines via `agent_batch`
2. Hit a firewall block on Pi's port 7070 — diagnosed it and ran `sudo ufw allow 7070/tcp` on its own
3. Resolved Python 3.12 vs 3.13 compatibility differences between Ubuntu and Pi
4. Started services on both machines and verified health
5. Wrote and ran a watchdog on Ubuntu monitoring both services every 3 seconds
6. Killed the Pi service via the `/kill` endpoint
7. Watchdog detected failure within one check cycle (< 3 seconds)
8. Automatically restarted the Pi service via the Clawx peer network
9. Verified recovery and reported the incident timeline
10. Cleaned up all processes, ports, and temp files on both machines

| Metric | Result |
|--------|--------|
| Time to failure detection | < 3 seconds |
| Time to recovery | 5–8 seconds |
| Total downtime | 6–11 seconds |
| System availability | > 99.9% |

The AI encountered and resolved real infrastructure problems (firewall rules, Python version incompatibility, port conflicts) without human intervention — genuine self-healing behaviour, not a scripted demo.

**Security testing — natural language driven pentest and hardening:**

All tests run on a home lab (Ubuntu x86_64 + Raspberry Pi ARM64) using Metasploit, orchestrated entirely through Clawx natural language commands via the peer network.

*Test 1 — Service fingerprinting and CVE analysis:*
Metasploit scanned all Pi services from Ubuntu. Found OpenSSH 9.9p1, Node.js v22.22.1 (Express), BIND9 9.20.11. All current versions, all patched, zero critical CVEs. The AI cross-referenced each version against known vulnerabilities and confirmed the Pi was secure.

*Test 2 — Clawx peer endpoint resilience:*
14 attack categories thrown at both Clawx endpoints (port 43210): malformed JSON, 1MB payloads, path traversal, chunked encoding abuse, unexpected HTTP methods, null bytes. Both services survived every attack — 100% availability, zero crashes, A+ resilience rating. Security headers (CSP, nosniff) held throughout.

*Test 3 — Exploit, detect, recover:*
The AI deployed a deliberately vulnerable Python service on Pi with command injection and path traversal flaws. From Ubuntu, it exploited the command injection, proved access with evidence files. Then it *switched sides* — from Pi, detected the compromise via log analysis, killed the vulnerable service, deployed a patched version with a command whitelist and path restrictions on a new port, updated the firewall, and verified the original exploit no longer worked. Full red team → blue team cycle in one session.

*Test 4 — Lateral movement, detection, and blocking:*
Full attack chain from Ubuntu: SSH brute force → command injection → reverse shell → network enumeration (discovered 12 hosts, a second Clawx instance, MinIO, nginx). Then from Pi, the AI deployed a detection script that identified SSH brute force attempts, vulnerable service access, network scanning, and reverse shell connections in the logs. Automatically blocked the attacker IP via iptables.

*Bonus — autonomous lockout recovery:*
During hardening, the AI reconfigured SSH so aggressively it locked itself out. It used the Clawx peer network (still reachable over HTTP) to write a recovery script, unblock the firewall, and reconfigure SSH on port 2222 on both machines — restoring full access without physical intervention.

| Test | Attack types | Result | Demo |
|------|-------------|--------|------|
| Service fingerprinting | Metasploit auxiliary scanners | All services current, zero critical CVEs | [Watch](https://youtu.be/cacsP3A6jh4) |
| Endpoint resilience | 14 attack categories | 100% survival, zero crashes | [Watch](https://youtu.be/foK63sNIHrs) |
| Exploit → detect → recover | Command injection, path traversal | Exploited, detected, patched, verified | [Watch](https://youtu.be/3G2q7Tzj6nc) |
| Vuln scan + auto-harden | Metasploit scan → fix → re-scan | Top 3 fixes applied, verified clean | [Watch](https://youtu.be/0V16mPYWHkk) |
| Lateral movement | SSH brute force → pivot → enumeration | Full chain executed, detected, attacker blocked | [Watch](https://youtu.be/MAP05pYlIio) |
| Lockout recovery | Self-inflicted SSH lockout | Recovered via peer network, no physical access needed | — |

### Why this matters

This makes Clawx useful as a small explicit multi-machine control plane for:
- home labs
- dev boxes
- Raspberry Pi edge systems
- remote debugging environments
- contributors building new federation and worker-management features

## What's new in 0.9.0

### Persistent specialists
- **`agent_specialist_save`** — save a running worker as a persistent specialist, or define a new one from scratch. Stores persona, allowed tools, and setup commands in `~/.clawx/specialists/`.
- **`agent_specialist_list`** — list all specialists with running status. Supports removal.
- **Auto-spawn on `agent_serve`** — all saved specialists auto-spawn when the master starts. Personas applied, setup commands run.
- **Health-checked auto-spawn** — stale registry entries from previous masters are detected via `/health` probe and respawned instead of skipped.
- **Survive cleanup** — specialists marked `persistent: true` are protected from `agent_cleanup`.

### Registry reliability (Windows)
- **Retry on EPERM** — `renameSync` in the registry save now retries with backoff to handle Windows file locking contention from concurrent peer-discovery and specialist spawning.

## What's new in 0.8.0

### Web tools
- **`web_search`** — search the web using SearXNG (self-hosted) or DuckDuckGo (zero setup fallback). No API keys needed.
- **`web_read`** — fetch any URL, strip HTML, return readable text. Supports CSS selectors.
- **`web_download`** — download files from URLs to the local filesystem with progress reporting.
- All web tools work on master, workers, and peers — use `agent_batch` with `web_search` to search from every machine simultaneously.

### System prompt rewrite
- Comprehensive prompt teaching the model about peer federation, specialists, web tools, and when to prefer peers over SSH.

## What's new in 0.6.0

### Reliability
- **File-locked registry** — Agent registry uses atomic `mkdir` locking with stale lock detection. No more corruption from concurrent writes.
- **Graceful shutdown** — Masters mark all owned workers as offline on exit. No more zombie workers after `Ctrl+C`.
- **Background health checks** — Master pings all workers every 30 seconds, marks unreachable ones offline, and cleans stale tasks automatically.
- **Auto-rehydration** — When a master starts, it automatically restarts eligible workers from the previous session.

### New high-level tools
- **`agent_run`** — Smart dispatch. Just say what tool to run — Clawx picks the best available worker (local or peer), health-checks it, and dispatches. Supports `--prefer` for soft worker preference and `--local_only`.
- **`agent_batch`** — Fan-out. Run the same tool on all workers **and peer masters** in parallel and collect aggregated results. If peers have workers, dispatches to workers; if peers are bare masters, dispatches directly to the master. Great for running tests, searches, or commands across your entire fleet.
- **`agent_network`** — Unified overview. One command shows master status, all local workers, all remote peers, each peer's workers, and task summary.
- **`agent_remove`** — One-command agent removal. Kills process, deletes workspace, removes tasks, removes from registry. Replaces the old 8-step manual cleanup.

### gRPC improvements
- **Protobuf schema** — New `clawx.proto` defining `AgentFrame`, all message types, and both services. Server and client now use `@grpc/proto-loader` for proper protobuf framing instead of raw JSON serialization.
- **Separated service methods** — In addition to the bidirectional `Connect` stream, the proto defines structured RPCs: `Register` (unary), `Heartbeat` (unary), `ExecuteTask` (server-streaming), `CancelTask` (unary), and `SendChat` (server-streaming).
- **gRPC health checking** — Native `grpc.health.v1.Health` service on the server. New `checkAgentHealthGrpc()` utility for gRPC-native health probes.

### Peer discovery
- **mDNS auto-discovery** — When a master starts serving, it advertises itself on the LAN via `_clawx._tcp` mDNS (Bonjour/Avahi). Other Clawx masters automatically discover and register peers. No more manual `agent_peer_add` on the same LAN. Falls back gracefully if mDNS is unavailable (corporate networks, Docker, WSL).

## Web tools setup

Clawx v0.8.0 adds `web_search`, `web_read`, and `web_download` — every agent (master, worker, peer) can search the web, read pages, and download files. No API keys required. Zero new dependencies.

### web_read and web_download — works out of the box

These use Node.js built-in `fetch`. No setup needed.

```text
web_read(url="https://example.com/article")
web_download(url="https://example.com/data.csv", path="/tmp/data.csv")
```

`web_read` strips HTML and returns readable text. `web_download` streams files to disk with progress reporting.

### web_search — two backends

**Option 1: DuckDuckGo (zero setup, works immediately)**

`web_search` falls back to DuckDuckGo's HTML lite interface automatically. No API key, no configuration. Results may be limited by rate limiting on heavy use.

```text
web_search(query="WHO antimicrobial resistance dataset CSV")
```

**Option 2: SearXNG (self-hosted, recommended for serious use)**

SearXNG is an open-source meta search engine. It aggregates results from Google, Bing, DuckDuckGo, and others. You host it yourself — no API keys, no tracking, no rate limits.

#### Quick start with Docker (Ubuntu or any Linux machine)

```bash
# Pull and run SearXNG
docker run -d --name searxng -p 8888:8080 --restart unless-stopped searxng/searxng

# Verify it's running
curl -s "http://localhost:8888/search?q=test&format=json" | head -c 200
```

#### Tell Clawx to use it

Set the `SEARXNG_URL` environment variable before starting Clawx:

```bash
export SEARXNG_URL=http://localhost:8888
clawx
```

Or add it to your `.env` file in the Clawx working directory:

```bash
echo "SEARXNG_URL=http://localhost:8888" >> .env
```

Or if SearXNG runs on a different machine (e.g. Ubuntu), point all peers at it:

```bash
# On any machine in your network
export SEARXNG_URL=http://192.168.1.183:8888
```

#### SearXNG on Ubuntu with Docker Compose (production setup)

```bash
mkdir -p ~/searxng && cd ~/searxng

# Create docker-compose.yml
cat > docker-compose.yml << 'EOF'
version: '3.7'
services:
  searxng:
    image: searxng/searxng:latest
    container_name: searxng
    ports:
      - "8888:8080"
    volumes:
      - ./settings.yml:/etc/searxng/settings.yml:ro
    environment:
      - SEARXNG_BASE_URL=http://localhost:8888/
    restart: unless-stopped
EOF

# Create settings with JSON API enabled
cat > settings.yml << 'EOF'
use_default_settings: true
server:
  bind_address: "0.0.0.0"
  secret_key: "change-this-to-something-random"
search:
  formats:
    - html
    - json
engines:
  - name: google
    engine: google
    shortcut: g
  - name: duckduckgo
    engine: duckduckgo
    shortcut: ddg
  - name: bing
    engine: bing
    shortcut: b
  - name: wikipedia
    engine: wikipedia
    shortcut: wp
EOF

# Start it
docker compose up -d

# Verify JSON API works
curl -s "http://localhost:8888/search?q=hello&format=json" | python3 -m json.tool | head -20
```

#### Open the firewall for peers

If you want other machines on your LAN to use this SearXNG instance:

```bash
# Ubuntu
sudo ufw allow 8888/tcp

# Or iptables
sudo iptables -A INPUT -p tcp --dport 8888 -j ACCEPT
```

Then on every other machine, set `SEARXNG_URL=http://<ubuntu-ip>:8888`.

#### Verify it works in Clawx

Start Clawx and test:

```text
web_search(query="Node.js security best practices")
```

You should see results with titles, URLs, and snippets. Then read a result:

```text
web_read(url="<url from search results>")
```

### Peer network + web tools

With SearXNG running on one machine, every peer can search the web:

```text
# Fan out a search to all peers
agent_batch(tool="web_search", params={"query": "latest CVEs for OpenSSH 9.9"})

# Have a specific peer download a dataset
agent_peer_send(peer_name="ubuntu", tool="web_download", params={"url": "https://example.com/data.csv", "path": "/tmp/data.csv"})

# Have a peer read a web page
agent_peer_send(peer_name="pi", tool="web_read", params={"url": "https://example.com/article"})
```

Or in natural language:

> "Search for the WHO antimicrobial resistance dataset. Download it to Ubuntu. Split it by region and distribute half to Pi. Analyse both halves and merge the results."

## Tool groups

### Coding and file tools
- `read`
- `write`
- `edit`
- `bash`
- `grep`
- `find`
- `ls`
- `search_files`
- `git_status`
- `git_diff`
- `ssh_run`

### Web tools
- `web_search` — search the web, returns titles, URLs, and snippets (SearXNG or DuckDuckGo)
- `web_read` — fetch a URL and extract readable text content from HTML
- `web_download` — download a file from a URL to the local filesystem

### Browser automation tools
- `browser_open` — launch browser and navigate to a URL, returns screenshot
- `browser_snapshot` — **the key tool** — takes an annotated screenshot with every interactive element numbered (red labels). Returns the image + an element list. Use element numbers with `browser_click` and `browser_type` — no CSS selectors needed. Works on any website
- `browser_click` — click by element number (from snapshot), CSS selector, text, or coordinates
- `browser_type` — type into fields by element number (from snapshot), CSS selector, label, or placeholder
- `browser_screenshot` — take a plain screenshot (no labels) of the page or a specific element
- `browser_navigate` — go to URL, back, forward, or refresh
- `browser_extract` — extract text, HTML, links, or form fields from the page
- `browser_eval` — execute JavaScript in the browser page context
- `browser_close` — close the browser and free resources

> **Workflow:** `browser_open` → `browser_snapshot` → see numbered elements → `browser_click --element 5` / `browser_type --element 3 --text "hello"` → `browser_snapshot` → repeat. Works on any site, no per-site configuration.

> **Setup:** `npm install playwright && npx playwright install chromium` — only needed on machines that use browser tools. Playwright is an optional dependency.

### Local worker/master tools
- `agent_serve`
- `agent_list`
- `agent_spawn_local`
- `agent_send`
- `agent_run` — smart dispatch to best available worker
- `agent_batch` — fan-out same tool to all workers and peers
- `agent_network` — unified network overview
- `agent_chat`
- `agent_status`
- `agent_result`
- `agent_remove` — one-command agent removal
- `agent_cleanup`
- `agent_cleanup_port`
- `agent_cleanup_processes`
- `agent_master_status`

### Peer federation tools
- `agent_peer_add`
- `agent_peer_chat`
- `agent_peer_send`
- `agent_peer_serve` *(tool available inside Clawx sessions; not a standalone installed CLI command)*
- `agent_peer_list_workers`

### Specialist tools
- `agent_specialist_save` — save a worker as a persistent specialist, or define a new one
- `agent_specialist_list` — list all persistent specialists and their running status
- `agent_rehydrate_workers` — restore workers from previous sessions

### Persona / memory tools
- `agent_persona_show`
- `agent_persona_set`
- `agent_memory_show`
- `agent_memory_update`
- `agent_peer_persona_show`
- `agent_peer_persona_set`
- `agent_peer_memory_show`
- `agent_peer_memory_update`

### Forge tools
- `hf_search`
- `hf_model_info`
- `hf_readme`
- `hf_dataset_search`
- `forge_write_capability`
- `forge_list_capabilities`

## Model setup

Clawx requires a model that supports **structured tool calling** (returning `tool_calls` in the API response, not just text). This is critical — the agent loop depends on it.

### Model compatibility and benchmarks

Tested on Windows 11, RTX 3060 12GB, 2026-03-15.

| Model | Provider | Tool calling | VRAM | Benchmark | Status |
|-------|----------|-------------|------|-----------|--------|
| **glm-4.7-flash:latest** | Ollama | Structured `tool_calls` | ~5 GB | 12 turns, 13 tool calls — write file + run python | **Recommended local** |
| **Qwen3.5-35B-A3B** (MoE) | Ollama | Structured `tool_calls` | ~12 GB | 35B params, only 3B active per token | **Best local if you have the VRAM** |
| **Qwen2.5-Coder-14B-abliterated Q4_K_M** | Ollama | Text-based (auto-parsed) | ~9 GB | Text tool parser converts JSON output to structured calls | **Works (with parser)** |
| Qwen2.5-Coder-14B-abliterated Q4_K_M | llama-server `--jinja` | Text-based (auto-parsed) | ~9 GB | Same parser support | Works (with parser) |
| GPT-4o / GPT-4-turbo | OpenAI API | Structured `tool_calls` | — | N/A (cloud) | Works |
| **DeepSeek-V3 (deepseek-chat)** | DeepSeek API | Structured `tool_calls` | — | N/A (cloud) | **Works, very cheap** |
| DeepSeek-R1 (deepseek-reasoner) | DeepSeek API | Structured `tool_calls` (via chat) | — | N/A (cloud) | Works |
| Claude 3.5+ | Anthropic API | Structured `tool_calls` | — | N/A (cloud) | Works |

> **Qwen text tool parser:** Some GGUFs output tool calls as JSON text instead of structured `tool_calls` objects. Clawx automatically detects and parses these text-based tool calls, converting them to proper structured calls.

### Option 1: GLM-4.7-Flash via Ollama (recommended local)

Requires: [Ollama](https://ollama.com/) installed, ~5GB VRAM.

```bash
# Start Ollama if needed
ollama serve

# Pull model
ollama pull glm-4.7-flash:latest

# Configure Clawx
cat > .env << 'EOF'
CLAWDEX_PROVIDER=ollama
CLAWDEX_BASE_URL=http://localhost:11434/v1
CLAWDEX_MODEL=glm-4.7-flash:latest
CLAWDEX_API_KEY=not-needed
CLAWDEX_THINKING_LEVEL=off
CLAWDEX_MAX_TOKENS=8192
EOF

# Run Clawx
clawx run "Create a Python script that prints the first 20 Fibonacci numbers"
```

### Option 2: DeepSeek API

```bash
cat > .env << 'EOF'
CLAWDEX_PROVIDER=deepseek
CLAWDEX_BASE_URL=https://api.deepseek.com/v1
CLAWDEX_MODEL=deepseek-chat
CLAWDEX_API_KEY=your-key-here
CLAWDEX_THINKING_LEVEL=off
CLAWDEX_MAX_TOKENS=8192
EOF

clawx
```

### Option 3: Import your own GGUF into Ollama

```bash
cat > Modelfile << 'EOF'
FROM /path/to/your-model.gguf

PARAMETER temperature 0.7
PARAMETER num_ctx 16384
PARAMETER stop <|im_end|>
PARAMETER stop <|endoftext|>

TEMPLATE """{{- if .System }}<|im_start|>system
{{ .System }}<|im_end|>
{{ end }}{{- range .Messages }}<|im_start|>{{ .Role }}
{{ .Content }}<|im_end|>
{{ end }}<|im_start|>assistant
"""
EOF

ollama create my-model -f Modelfile
clawx --model my-model --provider ollama
```

## TUI and interaction model

Clawx uses the pi-coding-agent interactive TUI as its main interface.

### TUI features
- syntax-highlighted code in tool results
- diff rendering for edit operations
- spinner animations during tool execution
- Ctrl+P to cycle models
- Ctrl+C to cancel
- Ctrl+D to quit
- session branching and tree navigation
- markdown rendering in responses
- `/chat` to toggle between agent mode and chat mode
- fresh-session awareness of the currently registered toolset

### Agent mode vs chat mode

| Mode | Tools | When |
|------|-------|------|
| **Agent mode** | Tools enabled | default coding/execution workflow |
| **Chat mode** | No tools | discussion/explanation only |

If a model does not support structured tool calling, Clawx can fall back to chat mode or use text-tool parsing where supported.

## Programmatic usage

Clawx can be embedded as an npm package for headless tasks, scripted runs, CI/codegen, and app backends.

### Example apps and scripts

Scripts:
- `run-task.mjs` — single headless task run
- `multi-turn.mjs` — multi-step scripted conversation
- `custom-config.mjs` — direct config without relying on local init state
- `ci-codegen.mjs` — CI-friendly headless execution

React demo apps:
- `programmatic-react-express/`
  - baseline React + Express starter
  - simple UI calling a backend task route
  - good first reference app
- `repo-maintainer-app/`
  - repo maintenance workbench
  - reviews a codebase, risks, and next steps
  - suited to dev and maintainer workflows
- `ops-copilot-app/`
  - lightweight ops dashboard
  - inspects environments, runtimes, and visible resources
  - suited to home-lab and machine inspection demos
- `chess-arena-app/`
  - interactive browser chess arena
  - autoplay White vs Black with style and speed controls
  - shows richer UI/stateful app possibilities
- `detective-app/`
  - investigation-themed demo app
  - clue/case-driven interface and workflow flavor
  - good for narrative or role-based demos
- `courtroom-app/`
  - courtroom-themed demo app
  - structured argument / position style experience
  - good for adversarial or point-counterpoint demos
- `dungeon-master-app/`
  - game-master themed demo app
  - interactive session/story style interface
  - good for playful structured interactions

These examples are intentionally small and varied so the repo shows more than one type of app: utility tools, workflow apps, and interactive demos.

For the API surface, embedding guidance, and more programmatic examples, see:
- [`docs/programmatic-usage.md`](docs/programmatic-usage.md)
- [`examples/`](examples/)

## Forge

Forge is Clawx’s extension-building mode.

Use it to:
- research models and datasets on HuggingFace
- inspect existing extensions
- scaffold new Clawx capabilities
- explore tool ideas, MCP ideas, and guard/safety helpers before enabling them in normal workflow

Examples:

```bash
clawx forge
clawx forge "Build a capability that summarizes CSV files"
```

For a fuller guide to what Forge is good for, what kinds of extensions fit Clawx well, MCP ideas, HuggingFace-backed capability discovery, and example Forge prompts, see:
- [`docs/forge-guide.md`](docs/forge-guide.md)

## Remote and multi-site deployment

Clawx peer federation uses plain HTTP. It works over any network where machines can reach each other on the specified port — LAN, VPN, or public internet.

### What works today

**VPN mesh (recommended for remote deployments):**

Put all machines on a mesh VPN like [Tailscale](https://tailscale.com/), [WireGuard](https://www.wireguard.com/), or [ZeroTier](https://www.zerotier.com/). Every machine gets a routable VPN IP. Then `agent_peer_add` works exactly like a LAN setup.

```text
# 60 Raspberry Pis across different locations, all on Tailscale
agent_peer_add --name warehouse-pi-01 --endpoint http://100.64.0.11:43210
agent_peer_add --name warehouse-pi-02 --endpoint http://100.64.0.12:43210
agent_peer_add --name field-sensor-03 --endpoint http://100.64.0.13:43210
...

# Fan out to all 60 simultaneously
agent_batch --tool bash --params {"command": "cat /sys/class/thermal/thermal_zone0/temp"}
```

**SSH bootstrap for initial setup:**

Configure SSH targets in `clawx.json` to start `clawx agent serve` on remote machines, then switch to peer protocol for everything after:

```json
{
  "sshTargets": {
    "warehouse-01": { "host": "100.64.0.11", "username": "pi", "privateKeyPath": "~/.ssh/id_ed25519" },
    "warehouse-02": { "host": "100.64.0.12", "username": "pi", "privateKeyPath": "~/.ssh/id_ed25519" }
  }
}
```

**Use cases for distributed Pis:**
- Industrial sensors — read temperature, pressure, vibration from 60 locations simultaneously
- Camera networks — capture, process, and compare images across sites
- Environmental monitoring — weather stations, air quality, soil sensors
- Edge computing — distribute analysis workloads across locations
- Fleet management — monitor and update software on device clusters

### What doesn't work yet

- **No built-in VPN/tunnel** — you need the network layer sorted separately (Tailscale, WireGuard, etc.)
- **No NAT traversal** — machines behind NAT without port forwarding or VPN are unreachable
- **No authentication** — the peer protocol has zero auth. Fine on a home LAN or VPN, dangerous on the public internet
- **No peer groups/tags** — can't `agent_batch` to "all sensors" vs "all cameras", only to all peers
- **No offline queue** — if a peer is down when you send a task, it fails rather than queuing for later

## Honest limitations

Current limitations still include:
- no authentication/authorization — anyone who can reach the port can connect and execute tools
- mDNS auto-discovery is same-subnet only (won't find peers on other networks)
- worker chat continuity across prior delegated tasks is improved, but exact later summarization can still blur some detail
- long-running process workflows through peer-hosted workers are less reliable than short tasks

## Roadmap

Near-term product gaps and likely next improvements:

### 1. Authentication and authorization
- token-based auth for peer connections
- restrict which peers can auto-register via mDNS
- per-peer tool permissions (e.g. read-only peers, execution peers)

### 2. Remote and multi-site scale
- bulk peer registration from a config file or peer manifest
- peer groups and tags — batch to subsets like `--group sensors` or `--tag warehouse`
- connection resilience — auto-reconnect on network drops, retry with backoff
- offline task queue — hold tasks for unreachable peers, deliver when they come back
- cross-subnet peer discovery via a lightweight registry/rendezvous server

### 3. Better worker summary fidelity
- keep improving worker natural-language summaries after tool use
- make later worker explanations match observed tool results more exactly

### 4. More polished showcase workflows
- turn strong real workflows into cleaner repeatable demos
- keep improving examples that show peer-hosted collaboration across machines

## Documentation

- [`docs/current-capabilities.md`](docs/current-capabilities.md) — current proven runtime/capability status
- [`docs/prompting-guide.md`](docs/prompting-guide.md) — example prompts for peer network management, worker usage, and operational requests
- [`docs/forge-guide.md`](docs/forge-guide.md) — what Forge is good for, what kinds of capabilities fit Clawx well, and ideas for MCPs, guard tools, and HuggingFace-backed extensions
- [`docs/programmatic-usage.md`](docs/programmatic-usage.md) — how to use Clawx as an npm package in scripts, CI, and larger apps

## License

MIT
