Skip to content
Back to search

claudectl

Hive compute for coding agents - expand your personal compute capacity by adding on-demand agentic compute

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/mercurialsolo--claudectl/badge.svg)](/listings/mercurialsolo--claudectl)

HTML

<a href="/listings/mercurialsolo--claudectl"><img src="/api/listings/mercurialsolo--claudectl/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

These steps run a script from the network that findsafeskills does not scan.

brew install mercurialsolo/tap/claudectl     # Homebrew (macOS / Linux)
cargo install claudectl                       # Cargo (any platform)

Both produce the same ~6 MB binary with bus/coord/relay/hive enabled — `claudectl bus`, `coord`, `relay`, and `hive` work out of the box. For the minimal ~3.5 MB sync-only build, opt out with `cargo install claudectl --no-default-features --features hive`.

Building from source (Cargo) requires **rustc 1.88+**. Older toolchains fail with an opaque transitive-dependency error before the build starts — run `rustup update stable` first. The Homebrew bottle ships prebuilt and has no toolchain requirement.

<details> <summary>Other methods</summary>

curl -fsSL https://raw.githubusercontent.com/mercurialsolo/claudectl/main/install.sh | sh
nix run github:mercurialsolo/claudectl
git clone https://github.com/mercurialsolo/claudectl.git && cd claudectl && cargo install --path .

</details>

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 15 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. {
  2. "name": "claudectl",
  3. "description": "claudectl's Claude Code plugin: hive, session monitoring, brain and spend control",
  4. "owner": {
  5. "name": "mercurialsolo",
  6. "url": "https://github.com/mercurialsolo"
  7. },
  8. "plugins": [
  9. {
  10. "name": "claudectl",
  11. "source": "./claude-plugin",
  12. "description": "Hive mind for Claude Code: start and join a hive across machines, session monitoring, local LLM brain, spend control"
  13. }
  14. ]
  15. }
README.md · README · 595 lines · 1 finding marked

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. <p align="center">
  2. <img src="assets/logo.png" alt="claudectl" width="372">
  3. </p>
  4. <p align="center"><strong>Hive mind for Claude Code - expand your consciousness with an agentic hive that learns from you once and remembers everywhere</strong></p>
  5. [![CI](https://github.com/mercurialsolo/claudectl/actions/workflows/ci.yml/badge.svg)](https://github.com/mercurialsolo/claudectl/actions/workflows/ci.yml)
  6. [![Crates.io](https://img.shields.io/crates/v/claudectl)](https://crates.io/crates/claudectl)
  7. [![Homebrew](https://img.shields.io/badge/homebrew-mercurialsolo%2Ftap-orange)](https://github.com/mercurialsolo/homebrew-tap)
  8. [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
  9. [![Downloads](https://img.shields.io/crates/d/claudectl)](https://crates.io/crates/claudectl)
  10. [![Platforms](https://img.shields.io/badge/platform-macOS%20%7C%20Linux-lightgrey)]()
  11. <sub>~6 MB binary (full features, Homebrew bottle). Sub-50ms startup. Zero config required.</sub>
  12. [Website](https://mercurialsolo.github.io/claudectl/) | [Docs](https://mercurialsolo.github.io/claudectl/quickstart/) | [Blog: Why a local brain?](blog/local-brain-architecture.md) | [Releases](https://github.com/mercurialsolo/claudectl/releases)
  13. <img src="assets/hive-demo.gif" alt="Two Macs forming a hive: discover, ask to join, owner approves, knowledge syncs" width="100%" />
  14. <img src="assets/migration-demo.gif" alt="A migration spread across the hive: three services ported from a blocking thread pool to asyncio, two arms delegated to a Mac mini and one run locally, every test green and 0.9s down to 0.05s" width="100%" />
  15. ## What it does for you
  16. Run `claudectl --brain-stats impact` to see your numbers:
  17. ```
  18. ╔════════════════════════════════════════════════╗
  19. ║ IMPACT SCORECARD ║
  20. ║ 1200 decisions tracked ║
  21. ╠════════════════════════════════════════════════╣
  22. ║ Auto-handled 71% ║
  23. ║ ████████████████████░░░░░░░░ 847/1200 ║
  24. ║ ║
  25. ║ Brain accuracy 96.2% ║
  26. ║ ███████████████████████████░ 1154/1200 ║
  27. ║ ║
  28. ║ Coverage vs static rules 2.9x ║
  29. ║ brain ████████████████████████████ 100% ║
  30. ║ rules █████████░░░░░░░░░░░░░░░░░░░ 34% ║
  31. ║ ║
  32. ║ Dangerous ops blocked 12 Time saved 42m ║
  33. ║ 2 critical | 10 high-risk | 847 auto x 3s ║
  34. ║ ║
  35. ║ Learning: correction rate 8.4% ↓ 2.1% (-6pp) ║
  36. ╚════════════════════════════════════════════════╝
  37. ```
  38. ## Install
  39. ```bash
  40. brew install mercurialsolo/tap/claudectl # Homebrew (macOS / Linux)
  41. cargo install claudectl # Cargo (any platform)
  42. ```
  43. Both produce the same ~6 MB binary with bus/coord/relay/hive enabled — `claudectl bus`, `coord`, `relay`, and `hive` work out of the box. For the minimal ~3.5 MB sync-only build, opt out with `cargo install claudectl --no-default-features --features hive`.
  44. Building from source (Cargo) requires **rustc 1.88+**. Older toolchains fail with an opaque transitive-dependency error before the build starts — run `rustup update stable` first. The Homebrew bottle ships prebuilt and has no toolchain requirement.
  45. <details>
  46. <summary>Other methods</summary>
  47. ```bash
  48. curl -fsSL https://raw.githubusercontent.com/mercurialsolo/claudectl/main/install.sh | sh
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 62 on GitHub
  49. nix run github:mercurialsolo/claudectl
  50. git clone https://github.com/mercurialsolo/claudectl.git && cd claudectl && cargo install --path .
  51. ```
  52. </details>
  53. ## Get started
  54. ```bash
  55. claudectl demo # Guided first-value tour — no live sessions needed
  56. claudectl init # Onboarding wizard (budget, brain, hooks, bus, skills)
  57. claudectl doctor # Verify install + runtime health (✓ checklist)
  58. claudectl # Live dashboard — see all sessions at a glance
  59. claudectl --brain # Enable local LLM auto-pilot
  60. ```
  61. After `brew upgrade claudectl`, run **`claudectl init --upgrade`** to re-sync hook entries, plugin files, and DB migrations to the new binary. `claudectl doctor`'s `plugin version` row will tell you when this is needed.
  62. The `init` wizard walks five phases — weekly budget, local-LLM brain detection, Claude Code hook install, agent-bus role, and curated skill suggestions. Run `claudectl doctor` to verify every piece is wired up, or `claudectl init --check` for the drift report against the onboarding marker.
  63. To use claudectl from inside Claude Code (the `hive` and `session-monitoring` skills, slash commands, the supervisor agent, the brain gate and the bus MCP server), install the plugin from this repo's marketplace:
  64. ```bash
  65. claude plugin marketplace add mercurialsolo/claudectl
  66. claude plugin install claudectl@claudectl
  67. ```
  68. Then ask Claude to "start a hive" or "invite my other machine". The plugin's brain gate hook runs on every Bash, Write, Edit and NotebookEdit call and answers for you: with no local LLM configured it falls back to built-in rules, auto-approving calls it rates low-risk (Claude Code does not prompt for those) and denying ones it rates critical. `claudectl --mode off` turns it off; set up a local LLM with `claudectl --brain` before relying on it for anything the rules do not cover.
  69. ## Why claudectl
  70. - **Hive mind** — name a hive and it becomes joinable: it advertises on the LAN, hands out invites, and queues join requests for you to approve. Members exchange what their brains learned, so a second machine starts with what the first one worked out. A read-only member receives and can never contribute. Nothing is advertised or shared until you name one.
  71. - **Local LLM auto-pilot** — a brain that learns your preferences and auto-approves/denies tool calls. No cloud API, and every decision stays on your machine.
  72. - **Self-improving** — detects friction patterns, suggests rules, and gets smarter with every correction.
  73. - **Multi-session orchestration** — run parallel tasks with dependency ordering and cross-session context routing.
  74. - **Health monitoring** — catches cognitive decay, cost spikes, error loops, and context saturation before they waste money.
  75. - **Works everywhere** — Claude Code plugin for inline use, TUI dashboard for oversight, CLI for automation.
  76. [Full feature comparison](docs/reference.md#comparison)
  77. ## Local LLM Brain
  78. The brain observes all your sessions and makes real-time decisions:
  79. - **Approve** safe tool calls automatically (reads, greps, test runs)
  80. - **Deny** dangerous operations before they execute (force pushes, destructive commands)
  81. - **Terminate** sessions that are looping, stalled, or burning money
  82. - **Route** summarized output between sessions so they share context
  83. - **Spawn** new sessions when the brain detects parallelizable work
  84. ```bash
  85. ollama pull gemma4:e4b && ollama serve # One-time setup
  86. claudectl --brain # Advisory mode (default)
  87. claudectl --brain --auto-run # Auto mode: brain executes without asking
  88. claudectl --mode auto # Or toggle mid-session (Ctrl+b in TUI)
  89. ```
  90. Works with any OpenAI-compatible endpoint: [ollama](https://ollama.com), [llama.cpp](https://github.com/ggerganov/llama.cpp), [vLLM](https://github.com/vllm-project/vllm), [LM Studio](https://lmstudio.ai).
  91. ### How the brain learns
  92. The brain learns from **everything** you do — not just brain-involved decisions, but every manual approve, reject, rule execution, and conflict resolution. All data stays on your machine.
  93. | Level | What it learns | Example |
  94. |-------|---------------|---------|
  95. | **Conditional preferences** | Context-dependent rules via decision tree splits | `approve [Bash] "git push" when cost<$5 (n=8)` |
  96. | **Outcome tracking** | Correlates decisions to detect "approved but broke" | Downweights false-positive approvals |
  97. | **Temporal patterns** | Behavioral sequences and time-of-day behavior | `After 3+ errors: user usually denies` |
  98. | **Per-project models** | Separate preferences per project | `[Read] always approve in frontend, usually deny in infra` |
  99. | **Adaptive thresholds** | Per-tool confidence requirements based on accuracy | 90%+ accurate on Read = auto-execute at 0.5 confidence |
  100. ### Explain & audit every decision
  101. To leave the brain unattended you need to trust and audit it. Every decision now carries a **"why"** — the source (rule, few-shot, or LLM), the confidence, and the past examples that informed it — surfaced inline in `--brain-query` output and the Brain Review panel.
  102. ```bash
  103. claudectl --brain-review # Triage decisions; press [c] to correct-and-learn in one keystroke
  104. claudectl --brain-export # Export the decision timeline as Markdown (paste into a PR)
  105. claudectl --brain-export json --project acme # …or JSON, filtered to one project (or --pid <n>)
  106. ```
  107. A one-key **correct-and-learn** in the review view records the right answer as canonical training material, so the next similar decision improves.
  108. ### Self-improving sessions
  109. The brain automatically detects friction patterns and suggests workflow improvements:
  110. ```bash
  111. claudectl --brain --insights on # Enable auto-generation (every 10 decisions)
  112. claudectl --brain --insights # View current insights
  113. ```
  114. Detects: friction patterns, error loops, context blowouts, missing rules, accuracy gaps, cost trends. Only new insights are surfaced — the system tracks what you've already seen. Use `/auto-insights` in the Claude Code plugin.
  115. ## Hive Mind & Relay
  116. The brain distills your decisions into shareable knowledge. Connect instances across machines to build a convergent hive mind — then move work, or a whole conversation, to whichever machine is free.
  117. ```bash
  118. # Hive knowledge is built-in — view what the brain has learned
  119. claudectl hive status
  120. claudectl hive knowledge
  121. claudectl hive distill # Condense archive into curriculum
  122. # Relay for cross-machine networking is enabled by default
  123. claudectl relay invite # Generate an invite code
  124. claudectl relay join YCU-AIG-EAH-CC7-GUK-RYW-ZB4 # Join from another machine
  125. claudectl relay discover # Scan LAN for nearby instances
  126. claudectl relay install-agent # Keep the relay running across logout
  127. # Run a relay on each machine, then see every session on either one
  128. claudectl relay serve # leave running on both machines
  129. claudectl relay fleet # every session across the cluster
  130. claudectl relay delegate mac-mini "run the full test suite" --cwd ~/code/app
  131. # Move a conversation to another machine and carry on there — or press `S`
  132. # on the session in the TUI and pick the machine from the list
  133. claudectl relay send-session mac-mini <session-id>
  134. claudectl relay sessions # what went where, and how to resume it
  135. # Remote sessions also appear in the TUI as [worker-id] project-name.
  136. # Tab on one sshes in and attaches to its tmux pane on that machine.
  137. # The coordinator's HTTP API serves the same unified view to a dashboard:
  138. claudectl relay serve --http-port 9876 --auth-token secret
  139. # GET /api/sessions across all workers. Binds 127.0.0.1 — it is plaintext with
  140. # a bearer token, so forward the port for an off-machine dashboard.
  141. ```
  142. ### Name a hive, and it becomes joinable
  143. By default a hive has no name — it is whatever your relay peers happen to be. Naming one makes it something you can advertise, find and join *as such*, and lets you decide who gets in:
  144. ```bash
  145. claudectl hive identity set --name barrys-hive --join-policy ask
  146. claudectl hive discover # named hives on the LAN, with peer/unit counts
  147. claudectl hive invite # a link, a code, or a word phrase (--qr, --words)
  148. claudectl hive join cctl://hive/hv_3a9f21?a=... # from another machine
  149. claudectl hive requests # who is waiting; approve <peer> / deny <peer>
  150. ```
  151. **The host decides, not the link.** With `--join-policy ask`, holding an invite gets you queued for approval rather than admitted. `invite` admits a paired peer that asks; `open` warns you about what it exposes and records your confirmation before it will advertise as open.
  152. **Read-only membership.** A `hive.read` capability grant admits someone who receives your hive's knowledge and can never contribute any — useful for a contractor or a colleague you want to teach without being taught by:
  153. ```bash
  154. claudectl access grant --scopes hive.read --project barrys-hive --label "alice, read-only"
  155. # alice, with both the invite and the grant:
  156. claudectl hive join <invite> --grant cctl_gr_cf827c_...
  157. ```
  158. A hive with no name advertises nothing and gates nothing, so none of this changes anything until you opt in.
  159. Knowledge categories (best practices, techniques, workflow patterns) propagate between hive members. Personal patterns (time-of-day habits, cost tolerance) stay local. You control what's shared:
  160. ```toml
  161. [hive]
  162. share_categories = ["best_practice", "technique"]
  163. exclude_tools = ["Write"]
  164. max_units = 500
  165. max_prompt_units = 20
  166. ```
  167. > **How propagation works.** Both ends of a relay connection offer each other whatever the other has not been sent yet, every 12 seconds, incrementally. One timer covers connect, reconnect, a peer approved after it asked to join, and a unit distilled while the link was down — a machine that joins late catches up on the next tick. Accepted units are re-offered onward up to a hop cap, so knowledge crosses a mesh it was not directly connected to. What it needs is a live relay connection: one machine running `relay serve`, the other dialling it.
  168. See the [full Relay & Hive Mind guide](docs/relay.md).
  169. ## Open Cluster — let someone ask about your project
  170. A relay peer is symmetric: it reads your sessions, delegates to you, interrupts you. A **capability grant** is the opposite — scoped, expiring, revocable, read-only. Someone outside your trust boundary (or their Claude) can ask *"how is auth structured?"* and get cited answers, with no way to write, execute, delegate or interrupt.
  171. ```bash
  172. # Mint a token for a third party — prints once, store it then
  173. claudectl access grant --project claudectl \
  174. --label "acme integration review" \
  175. --scopes project.query \
  176. --expires 30d
  177. claudectl access list # every grant, its state, uses, last use
  178. claudectl access audit gr_a38487 # what that grant actually asked for
  179. claudectl access revoke gr_a38487 # immediate, nothing to restart
  180. # Serve the repo you're in — one process, one project
  181. claudectl query serve # 127.0.0.1:8787 by default
  182. claudectl query stdio # same surface over MCP
  183. ```
  184. Answers are **verbatim doc spans with citations**, never generated prose. They come only from a pre-built index of what git tracks, minus a deny-list covering `.env*`, ssh keys, transcripts, `.claudectl/`, databases and more. Source bodies are never indexed — only `//!` headers, `///` docs and public signatures. There is no code path from a query to an unindexed file, and no write verb anywhere in the surface.
  185. A token for one project returns an opaque `404` for every other. Each grant carries its own rate limit and daily budget, so one noisy caller can't spend another's.
  186. Classification is optional and off unless you set `TYPESAFE_API_KEY`. When on, it routes questions — deny, decline, answer, or escalate to you — but it is never the boundary: it runs *after* scopes and budgets, and answers still come only from the index. Remove it and the surface is blunter, not less safe. It is the one thing in claudectl that sends anything off-machine: the question and one paragraph of `CLAUDE.md`, never index contents or session data.
  187. See [Capability Grants](docs/access.md) and the [Open Cluster spec](docs/open-cluster.md).
  188. ## Claude Code Plugin
  189. Integrates the brain directly into Claude Code sessions — no TUI required.
  190. | Component | What it does |
  191. |-----------|-------------|
  192. | **Brain gate hook** | Queries the brain before every Bash/Write/Edit call |
  193. | `/brain on\|off\|auto` | Toggle brain mode mid-session (or `Ctrl+b` in TUI) |
  194. | `/sessions` | Show all active sessions with status, cost, health |
  195. | `/spend` | Cost breakdown by project and time window |
  196. | `/brain-stats` | Brain learning metrics and accuracy |
  197. | `/auto-insights` | Auto-generated workflow insights |
  198. | `/inbox` | Drain pending agent-bus messages addressed to this session's role |
  199. | `/role <name>` | Set this session's agent-bus role, e.g. `/role frontend` or `/role tester` (auto-detects pid) |
  200. ## Headless Mode
  201. Run the full autonomous stack without a TUI. Attach a dashboard from another terminal.
  202. ```bash
  203. claudectl --headless --brain --auto-run # Human-readable events
  204. claudectl --headless --brain --auto-run --json # Structured JSON events
  205. ```
  206. What runs in headless mode:
  207. - Brain inference (approve/deny/route/spawn with adaptive confidence)
  208. - Coordination layer (leases, interrupts, handoffs, memory)
  209. - Context rot prevention (auto-raises compact/stop interrupts when decay detected)
  210. - Rule evaluation and health monitoring
  211. The TUI dashboard can run alongside -- both share state via the coordination SQLite store, brain decision logs, and session discovery.
  212. ```bash
  213. # Background daemon
  214. nohup claudectl --headless --brain --auto-run > ~/.claudectl/autopilot.jsonl 2>&1 &
  215. # Attach dashboard in another terminal
  216. claudectl
  217. ```
  218. ## Coordination Layer
  219. Multi-agent coordination for parallel coding sessions. Prevents duplicate work, manages ownership, and routes context between agents.
  220. Enabled by default. For the minimal sync-only build, use `cargo build --no-default-features --features hive`.
  221. ```bash
  222. # Ownership leases — prevent two agents from editing the same file
  223. claudectl coord claim --session sess_1 --path src/app.rs --mode exclusive
  224. claudectl coord release lease_123
  225. # Any resource, not only paths; wait in line instead of failing
  226. claudectl coord claim --session sess_2 --resource res:dev-db --wait --timeout 300
  227. # Leases expire after --ttl (default 300s) unless the owning session is running
  228. claudectl coord renew lease_123 --ttl 900
  229. # Fleet-wide: one machine is [relay] lease_authority; every peer claims through it
  230. claudectl coord claim --fleet --session sess_3 --resource res:staging-deploy --wait
  231. # Handoffs — structured context transfer between sessions
  232. claudectl coord handoff --from sess_1 --to sess_2 --task task_1 --summary 'Fix path normalization'
  233. # Interrupts — typed cross-agent signals with delivery modes
  234. claudectl coord raise --type pause --target sess_1 --reason 'lease conflict'
  235. claudectl coord ack intr_123
  236. # Memory — validated patterns promoted from brain decisions
  237. claudectl coord promote --project myproject
  238. claudectl coord context --session sess_1 # Preview injected context
  239. # Inspection
  240. claudectl coord leases # Active ownership leases
  241. claudectl coord interrupts # Pending interrupts
  242. claudectl coord events # Event audit log
  243. claudectl coord metrics # Coordination health metrics
  244. claudectl coord eval # Run 10 eval scenarios
  245. claudectl coord adapters # Registered agent adapters
  246. ```
  247. The coordination layer stores state in a local SQLite database (`~/.claudectl/coord/coord.db`) and injects compact context into the brain's prompt before every decision.
  248. ## Agent Bus (preview)
  249. A durable directory + mailbox that exposes the running swarm as an MCP server. Agents discover each other (`list_agents`), look up their own role (`whoami`), publish directed messages, and drain their inbox at turn boundaries. Phases 1–4 of the [design spec](docs/AGENT_BUS.md) are shipped.
  250. Enabled by default. Pulls in `rmcp` + a current-thread Tokio runtime, which is why the default binary is ~6 MB; the no-async-runtime invariant is deliberately relaxed for the `bus` feature path. For the minimal sync-only build (~3.5 MB), use `cargo build --no-default-features --features hive`.
  251. ```bash
  252. # Bind durable role addresses to working directories
  253. claudectl bus role bind planner ~/work/proj-plan
  254. claudectl bus role bind impl ~/work/proj-impl
  255. claudectl bus role list
  256. # Directed send + drain
  257. claudectl bus send impl "review the auth diff" --from planner --priority high
  258. ( cd ~/work/proj-impl && claudectl bus inbox )
  259. # A role bound to a subtree owns it: route work by the path it touches
  260. claudectl bus role bind relay ~/work/proj-impl/src/relay
  261. claudectl bus owner ~/work/proj-impl/src/relay/peer.rs # → relay
  262. claudectl bus route ~/work/proj-impl/src/relay/peer.rs "peer reconnect loops" --from planner
  263. # Resolve which role this cwd is
  264. claudectl bus whoami
  265. # Run the MCP server on stdio (this is what the Claude Code plugin invokes)
  266. claudectl bus stdio
  267. ```
  268. The Claude Code plugin registers the bus as an MCP server (`claude-plugin/.mcp.json`) and ships two slash commands: `/inbox` (drain mailbox) and `/role <name>` (e.g. `/role frontend`, `/role tester` — set this session's role). Bindings are PID-keyed when made through the TUI's `Ctrl+R` or `/role`; cwd-keyed for the legacy `claudectl bus role bind <name> <cwd>` flow. The resolver prefers a PID match over cwd-inference, which disambiguates "two sessions in one worktree". `list_agents` also reports each session's `focus`, the directory its recent edits concentrate in, so an agent can see who is working where and address work to whoever owns that part of the tree ([#596](https://github.com/mercurialsolo/claudectl/issues/596)).
  269. Mailboxes live in `~/.claudectl/bus/bus.db` (SQLite WAL). Message bodies are sanitized at the boundary — a leading `/` is neutralized so a queued message cannot smuggle a slash command into the recipient.
  270. **Full guide:** [Agent Bus](docs/agent-bus.md) — wire-up, role binding, sending and receiving messages, worked planner→implementer example, where state lives, uninstall.
  271. Flow guards (hop limit, per-role rate limit, reserved-role ACL) and the supervisor for long-horizon role persistence are shipped. Pub/sub `subscribe` + claim protocol and the TUI bus view are still in flight. See [AGENT_BUS.md](docs/AGENT_BUS.md#implementation-status) for the per-phase status table.
  272. ## Supervisor
  273. Durable, verified task lifecycles on top of the bus. Where the agent bus answers "how do I talk to the swarm?", the supervisor answers "how do I trust the swarm to run unattended overnight?" Submit a task, it lands in a SQLite ledger; the reconciler assigns it via mailbox (or, if no role is set, routes it to the live role that owns its `paths` when `auto_route` is on, else spawns a session); declared verifiers (`run` / `brain` / `agent`) gate the move to DONE; a dead session triggers Resume with a recovery prompt that carries autopsy findings forward; health-check signals (stalled, retry loop) become first-class transitions instead of dashboard warnings.
  274. ```bash
  275. # One-shot inline submission
  276. claudectl supervisor submit \
  277. --name "auth-middleware" \
  278. --cwd ~/work/services \
  279. --prompt "Add JWT middleware to all API routes" \
  280. --role backend --budget-usd 3.00
  281. # Batch submission from a TOML file
  282. claudectl supervisor run tasks.toml --dry-run # preview
  283. claudectl supervisor run tasks.toml # commit (queues; doesn't run)
  284. # Run the queue: a session per task (in its own worktree when it names a
  285. # git_ref), watched until it ends, then its verifiers. Touches no other session.
  286. claudectl supervisor work --until-idle
  287. # Inspect fleet state
  288. claudectl supervisor status
  289. claudectl supervisor status --state RUNNING
  290. claudectl supervisor status --graph # the depends_on tree, with why a task is blocked
  291. claudectl supervisor logs <task_id> # full transition log + verifier history
  292. # Lifecycle controls
  293. claudectl supervisor cancel <task_id> # idempotent move to CANCELLED
  294. claudectl supervisor drain # stop issuing new assignments
  295. claudectl supervisor undrain # resume
  296. ```
  297. A `tasks.toml` block carrying every supported field — including the three verifier kinds:
  298. ```toml
  299. [[task]]
  300. name = "auth-middleware"
  301. role = "backend"
  302. cwd = "./services"
  303. prompt = "Add JWT auth middleware to all API routes"
  304. model = "sonnet"
  305. budget_usd = 3.00
  306. max_retries = 2
  307. timeout_min = 45
  308. git_ref = "main" # run in a new worktree from this ref, on its own branch
  309. branch = "feat/auth" # optional; default claudectl/<name>-<id>
  310. permission_mode = "acceptEdits" # optional; passed to claude --permission-mode
  311. depends_on = ["user-schema"] # start only after these tasks (by name, same file) are DONE
  312. requires = ["docker", "node>=22"] # tools the relay probes, or tags a machine advertises
  313. [[task.verify]]
  314. run = "cargo test --all-targets" # exit code is the verdict, run in the worktree
  315. [[task.verify]]
  316. brain = "Review the diff for auth-coverage gaps. PASS or FAIL with reasons."
  317. # local brain, shown the task's diff — free
  318. [[task.verify]]
  319. agent = "Adversarial review: find a request that bypasses the middleware."
  320. model = "haiku" # headless claude -p in the worktree, read-only
  321. budget_usd = 0.25
  322. ```
  323. When a verifier fails, the task goes back to work in the same worktree with the failing verifier's output added to its prompt, up to `max_retries`; after that it's NEEDS_HUMAN. A session that dies is resumed with a prompt that tells it to assess the worktree before continuing. A task with `depends_on` starts once each dependency is DONE, and its prompt names each dependency's branch and closing summary; if a dependency is cancelled or needs a human, the tasks after it move to NEEDS_HUMAN with the reason (`dependency_cancelled:<name>`).
  324. <img src="assets/fleet-supervisor.gif" alt="A laptop hands two Claude Code tasks to a Mac mini: one fails its verifier on the mini, is retried there with the failure, and passes" width="100%" />
  325. The full guide, with a two-machine walkthrough: [docs/fleet-supervisor.md](docs/fleet-supervisor.md).
  326. **Where tasks run.** Each machine has a slot policy in `~/.claudectl/coord/policy.toml`, and a task starts only where it fits. Without the file, this machine runs four tasks at a time, as before.
  327. ```toml
  328. stale_after_secs = 90 # a peer heard from longer ago is skipped
  329. [local] # this machine
  330. max_tasks = 4
  331. min_free_mem_mb = 2048 # floors; an unmeasured value never counts as room
  332. max_load_per_core = 1.5
  333. min_free_disk_mb = 5120
  334. mem_per_task_mb = 1024 # assumed per task until the next measurement
  335. drain = false # same as `supervisor drain`
  336. [peers] # defaults for every relay peer
  337. max_tasks = 2
  338. [peers.baradas-mac-mini-508f9c0e]
  339. max_tasks = 6
  340. ```
  341. `relay serve` advertises its machine's free memory, load per core, free disk, running tasks, its own `max_tasks` and `[relay] tags` on every heartbeat, and `relay peers` shows what each peer last said. A task goes to the eligible machine with the most free memory, here or on a peer; `peer = "…"` pins it. A task that can't start says why in `supervisor work`'s output, once per change of reason: `this machine is running 4 of 4 tasks`, ``this machine lacks `docker`; mini is running 2 of 2 tasks``.
  342. **Running on a peer.** The supervisor sends the task over the relay, and the peer runs `claude` and then the task's `run =` verifiers, in its own worktree, sending the verdicts back. Both machines need `relay serve` running, both on a build with `supervised-task` (each `relay serve` logs the features a link agreed). The task's `cwd` is used on the peer as-is, so keep the repo at the same path on both; the work stays on the task's branch in the peer's worktree, and the handoff names it. A retry goes back to the same peer and worktree. A task with a `role`, or with a `brain =` or `agent =` verifier, runs on this machine only. A peer that declines a task (it's at its own `max_tasks`, say) doesn't use up a retry: the task is placed again.
  343. Tasks are submittable three ways: this CLI, a `task.created` bus message addressed to the `supervisor` role, or the `submit_task` MCP tool from inside a Claude Code session. All three land as the same SQLite row.
  344. Three load-bearing properties from the design spec:
  345. - **Cattle vs. pets** — a task survives the death of the session executing it; the next attempt is a fresh session that reads the recovery context (original prompt + autopsy + prior verifier failures + tree-state drift warning).
  346. - **Crash-safe by construction** — kill the headless daemon mid-tick, restart, and observed state re-converges from `~/.claudectl/coord/coord.db`. The ledger is the source of truth.
  347. - **Fail-closed verifiers** — a brain/agent verifier whose reply lacks the leading `PASS` / `FAIL:` marker is treated as FAIL. RFC §5 calls this the verifier-is-the-gradient principle: every FAIL output becomes the retry prompt the next attempt sees.
  348. Metrics (team observability): `claudectl supervisor metrics` serves a Prometheus `/metrics` endpoint on `127.0.0.1:9464` (`claudectl_tasks_by_state`, `claudectl_fleet_cost_usd_total`, `claudectl_retries_total`, `claudectl_verifier_pass_rate`) that Grafana or Datadog scrape with no claudectl-specific glue. Each scrape reads the coord DB fresh (WAL), so it runs safely alongside the reconciler. A ready dashboard and the full recipe live in [docs/team-observability.md](docs/team-observability.md).
  349. Policy as code (team guardrails): commit a `.claudectl/policy.toml` to the repo and its `[deny]` commands/tools are enforced by the brain gate at the highest precedence — a developer can't soften them by editing local config. Scaffold with `claudectl --policy init`, inspect with `claudectl --policy`. See [docs/policy-as-code.md](docs/policy-as-code.md).
  350. ## Orchestrate Sessions
  351. Run coordinated tasks with dependency ordering, retries, and cross-session data routing:
  352. ```json
  353. {
  354. "tasks": [
  355. { "name": "auth", "cwd": "./backend", "prompt": "Add JWT auth middleware" },
  356. { "name": "tests", "cwd": "./backend", "prompt": "Update API tests. Previous: {{auth.stdout}}", "depends_on": ["auth"] },
  357. { "name": "docs", "cwd": "./docs", "prompt": "Document the new auth flow", "depends_on": ["auth"] }
  358. ]
  359. }
  360. ```
  361. ```bash
  362. claudectl --run tasks.json --parallel
  363. claudectl --decompose "Add auth, write tests, update docs" # Auto-split into parallel tasks
  364. ```
  365. ## Session Health Monitoring
  366. Continuously checks each session and surfaces problems in the dashboard:
  367. - **Cognitive decay** — composite 0-100 score tracking degradation over time
  368. - **Proactive compaction** — suggests `/compact` at 50% context, before the 80/90% thresholds
  369. - **Cost spikes** — flags when burn rate exceeds the session average
  370. - **Loop detection** — catches tools failing repeatedly in retry loops
  371. - **Stall detection** — sessions spending money but producing no edits
  372. - **File conflicts** — detects when multiple sessions edit the same file
  373. ## Spend Control
  374. ```bash
  375. claudectl --budget 5 --kill-on-budget # Auto-kill at $5
  376. claudectl --notify # Desktop notifications on blocks
  377. claudectl --stats --since 24h # Aggregated cost statistics
  378. ```
  379. ## Auto-Rules
  380. ```toml
  381. [[rules]]
  382. name = "approve-cargo"
  383. match_tool = ["Bash"]
  384. match_command = ["cargo"]
  385. action = "approve"
  386. [[rules]]
  387. name = "deny-rm-rf"
  388. match_command = ["rm -rf"]
  389. action = "deny"
  390. [[rules]]
  391. name = "kill-runaway"
  392. match_cost_above = 20.0
  393. action = "terminate"
  394. ```
  395. Rules support matching by tool, command, project, cost, and error state. Deny rules always take precedence.
  396. <details>
  397. <summary>More features</summary>
  398. ### Idle Mode
  399. When you step away, claudectl can run pre-configured low-risk tasks. A morning report summarizes what happened.
  400. ### Session Lifecycle
  401. Auto-restart sessions on context saturation with checkpoint + summary handoff.
  402. ### Record and Share
  403. Press `R` on any session for a highlight reel GIF (edits, commands, errors — idle time stripped). Or `claudectl --record demo.gif` for the full dashboard.
  404. ### Launch and Resume
  405. `claudectl --new --cwd ./backend --prompt "Add auth"` or press `n` in the dashboard.
  406. ### Filter and Search
  407. `--filter-status NeedsInput`, `--focus attention`, `--search "project"`, `--watch` for streaming.
  408. </details>
  409. ## Docs
  410. | | |
  411. |---|---|
  412. | [Quick Start](docs/quickstart.md) | Install, init, first dashboard |
  413. | [Reference](docs/reference.md) | All flags, keybindings, modes |
  414. | [Configuration](docs/configuration.md) | Config files, hooks, rules |
  415. | [Relay & Hive Mind](docs/relay.md) | Connect instances, share knowledge |
  416. | [Capability Grants](docs/access.md) | Scoped read-only access for a third party |
  417. | [Terminal Support](docs/terminal-support.md) | Compatibility matrix |
  418. | [Troubleshooting](docs/troubleshooting.md) | Common issues and FAQ |
  419. | [Contributing](docs/contributing.md) | Setup and guidelines |
  420. | [Changelog](CHANGELOG.md) | Release history |
  421. Design specs — the reasoning, not the current surface:
  422. | | |
  423. |---|---|
  424. | [Open Cluster](docs/open-cluster.md) | Capability grants and the read-only query surface |
  425. | [Agent Bus](docs/AGENT_BUS.md) | Role directory, mailbox, supervisor |
  426. | [Relay & Hive](docs/relay-and-hive.md) | Why transport, coordination and knowledge are three layers |
  427. | [Relay Discovery](docs/relay-discovery.md) | Pairing UX: codes, phrases, QR, LAN |
  428. | [Hive Storage](docs/hive-storage.md) | Tiered knowledge, archive, distillation |
  429. | [Agent Protocol](docs/agent-protocol.md) | Any coding agent on the hive; the relay wire protocol (proposed) |
  430. ## Community
  431. - Questions or ideas? [Start a Discussion](https://github.com/mercurialsolo/claudectl/discussions)
  432. - Found a bug? [Open an issue](https://github.com/mercurialsolo/claudectl/issues/new)
  433. - Share your setup in [Show & Tell](https://github.com/mercurialsolo/claudectl/discussions/categories/show-and-tell)
  434. ## License
  435. MIT
claude-plugin/hooks/scripts/brain-gate.sh · Bundled script · 172 lines · 1 finding marked
  1. #!/usr/bin/env bash
  2. # claudectl brain-gate: PreToolUse hook that queries the local LLM brain
  3. # for approve/deny decisions on tool calls.
  4. #
  5. # Receives tool call JSON on stdin from Claude Code:
  6. # {"tool_name": "Bash", "tool_input": {"command": "rm -rf /"}}
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 6 on GitHub
  7. #
  8. # Emits a hook response on stdout. For denies we emit both the legacy
  9. # `{"decision":"deny","reason":...}` field (for older Claude Code) and a
  10. # `hookSpecificOutput` envelope with `continueOnBlock:true` plus the brain's
  11. # reasoning as `systemMessage` / `permissionDecisionReason`, so newer runtimes
  12. # surface *why* the brain blocked into Claude's next turn (#249).
  13. #
  14. # Falls through silently (no output) when the brain abstains or is unavailable,
  15. # letting Claude Code's normal permission flow handle it.
  16. set -euo pipefail
  17. # Check if claudectl is installed
  18. if ! command -v claudectl &>/dev/null; then
  19. exit 0 # Not installed — fall through to normal permission flow
  20. fi
  21. # Check brain gate mode (on/off/auto). Default is "on" (file absent = on).
  22. GATE_MODE_FILE="$HOME/.claudectl/brain/gate-mode"
  23. GATE_MODE="on"
  24. if [ -f "$GATE_MODE_FILE" ]; then
  25. GATE_MODE=$(cat "$GATE_MODE_FILE" 2>/dev/null || echo "on")
  26. GATE_MODE=$(echo "$GATE_MODE" | tr -d '[:space:]')
  27. fi
  28. if [ "$GATE_MODE" = "off" ]; then
  29. exit 0 # Brain disabled — fall through
  30. fi
  31. # Read the tool call from stdin
  32. INPUT=$(cat)
  33. # Minimal JSON-string escaper for the no-jq fallback. Handles the chars that
  34. # would otherwise break a JSON literal: backslash, double quote, CR/LF, tab.
  35. json_escape() {
  36. local s="$1"
  37. s="${s//\\/\\\\}"
  38. s="${s//\"/\\\"}"
  39. s="${s//$'\n'/\\n}"
  40. s="${s//$'\r'/\\r}"
  41. s="${s//$'\t'/\\t}"
  42. printf '%s' "$s"
  43. }
  44. if command -v jq &>/dev/null; then
  45. TOOL_NAME=$(printf '%s' "$INPUT" | jq -r '.tool_name // empty')
  46. case "$TOOL_NAME" in
  47. Bash) COMMAND=$(printf '%s' "$INPUT" | jq -r '.tool_input.command // empty') ;;
  48. Write|Edit|NotebookEdit)
  49. COMMAND=$(printf '%s' "$INPUT" | jq -r '.tool_input.file_path // empty') ;;
  50. *) COMMAND=$(printf '%s' "$INPUT" | jq -c '.tool_input // {}' | head -c 200) ;;
  51. esac
  52. else
  53. TOOL_NAME=$(echo "$INPUT" | sed -n 's/.*"tool_name" *: *"\([^"]*\)".*/\1/p')
  54. COMMAND=""
  55. case "$TOOL_NAME" in
  56. Bash)
  57. COMMAND=$(echo "$INPUT" | sed -n 's/.*"command" *: *"\([^"]*\)".*/\1/p')
  58. ;;
  59. Write|Edit|NotebookEdit)
  60. COMMAND=$(echo "$INPUT" | sed -n 's/.*"file_path" *: *"\([^"]*\)".*/\1/p')
  61. ;;
  62. *)
  63. COMMAND=$(echo "$INPUT" | sed -n 's/.*"tool_input" *: *\({[^}]*}\).*/\1/p' | head -c 200)
  64. ;;
  65. esac
  66. fi
  67. if [ -z "$TOOL_NAME" ]; then
  68. exit 0
  69. fi
  70. # Resolve project name from cwd
  71. PROJECT=$(basename "${PWD:-unknown}")
  72. # Query the brain (--brain enables it even without config).
  73. # We pipe the full hook payload on stdin so that claudectl can extract a
  74. # structured diff digest (file_path, old/new_string, content, ...) for
  75. # richer prompt context — see #237.
  76. RESULT=$(printf '%s' "$INPUT" | claudectl --brain --brain-query --tool "$TOOL_NAME" --tool-input "$COMMAND" --project "$PROJECT" 2>/dev/null) || exit 0
  77. # Parse the action from the JSON result. Prefer jq so multi-line / escaped
  78. # reasoning round-trips correctly; fall back to the existing sed pattern when
  79. # jq is missing.
  80. if command -v jq &>/dev/null; then
  81. ACTION=$(printf '%s' "$RESULT" | jq -r '.action // empty')
  82. REASONING=$(printf '%s' "$RESULT" | jq -r '.reasoning // empty')
  83. SOURCE=$(printf '%s' "$RESULT" | jq -r '.source // empty')
  84. BELOW=$(printf '%s' "$RESULT" | jq -r '.below_threshold // false')
  85. else
  86. ACTION=$(echo "$RESULT" | sed -n 's/.*"action" *: *"\([^"]*\)".*/\1/p')
  87. REASONING=$(echo "$RESULT" | sed -n 's/.*"reasoning" *: *"\([^"]*\)".*/\1/p')
  88. SOURCE=$(echo "$RESULT" | sed -n 's/.*"source" *: *"\([^"]*\)".*/\1/p')
  89. BELOW=$(echo "$RESULT" | sed -n 's/.*"below_threshold" *: *\(true\|false\).*/\1/p')
  90. fi
  91. emit_advisory() {
  92. # Below-threshold approval — surface the brain's hesitation as
  93. # additionalContext so Claude sees the reasoning even though we let the
  94. # tool call proceed. No `decision` field → does not block.
  95. local msg="claudectl brain is uncertain: $1"
  96. if command -v jq &>/dev/null; then
  97. jq -n --arg msg "$msg" '{hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:$msg}}'
  98. else
  99. local em
  100. em=$(json_escape "$msg")
  101. printf '{"hookSpecificOutput":{"hookEventName":"PreToolUse","additionalContext":"%s"}}\n' "$em"
  102. fi
  103. }
  104. emit_deny() {
  105. # Emit both the legacy `decision`/`reason` (for older Claude Code) and the
  106. # new `hookSpecificOutput.continueOnBlock` envelope (#249) so the brain's
  107. # reasoning surfaces back into Claude's next turn instead of just stopping
  108. # the call.
  109. local reasoning="$1"
  110. local sysmsg="claudectl brain blocked this call: $reasoning"
  111. if command -v jq &>/dev/null; then
  112. jq -n \
  113. --arg r "claudectl: $reasoning" \
  114. --arg dr "$reasoning" \
  115. --arg sm "$sysmsg" \
  116. '{
  117. decision: "deny",
  118. reason: $r,
  119. hookSpecificOutput: {
  120. hookEventName: "PreToolUse",
  121. permissionDecision: "deny",
  122. permissionDecisionReason: $dr,
  123. continueOnBlock: true,
  124. systemMessage: $sm
  125. }
  126. }'
  127. else
  128. local er em
  129. er=$(json_escape "$reasoning")
  130. em=$(json_escape "$sysmsg")
  131. printf '{"decision":"deny","reason":"claudectl: %s","hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"%s","continueOnBlock":true,"systemMessage":"%s"}}\n' "$er" "$er" "$em"
  132. fi
  133. }
  134. case "$ACTION" in
  135. approve)
  136. # In "on" mode: only auto-approve when confidence is above threshold
  137. # In "auto" mode: approve all brain approvals regardless of confidence
  138. if [ "$GATE_MODE" != "auto" ] && [ "$BELOW" = "true" ] && [ "$SOURCE" = "brain" ]; then
  139. # #249: surface the brain's hesitation without blocking so Claude
  140. # picks up the same context a human reviewer would have used.
  141. if [ -n "$REASONING" ]; then
  142. emit_advisory "$REASONING"
  143. fi
  144. exit 0
  145. fi
  146. echo '{"decision":"approve"}'
  147. ;;
  148. deny)
  149. if [ -z "$REASONING" ]; then
  150. REASONING="claudectl brain denied this action"
  151. fi
  152. emit_deny "$REASONING"
  153. ;;
  154. *)
  155. # abstain, error, or unknown — fall through
  156. exit 0
  157. ;;
  158. esac

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.