Skip to content
Back to search

ruflo

MarketplaceWorks with Claude CodeGitHub

RuFlo Marketplace: Claude Code native agents, swarms, workers, and MCP tools for continuous software engineering

Safety scan

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

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026. Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/ruvnet/ruflo with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/ruvnet/ruflo'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/ruvnet-ruflo/badge.svg)](/listings/ruvnet-ruflo)

HTML

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

Install

Install instructions from the README

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

There are **two different install paths** with very different surface areas. Pick based on what you need (#1744):

| | **Claude Code Plugin** | **CLI install (`npx ruflo init`)** | |---|---|---| | What it gives you | Slash commands + a few skills + agent definitions per-plugin | Full Ruflo loop — 98 agents, 60+ commands, 30 skills, MCP server, hooks, daemon | | Files in your workspace | **Zero** | `.claude/`, `.claude-flow/`, `CLAUDE.md`, helpers, settings | | MCP server registered | Only if `ruflo-core` is installed (it ships its own `.mcp.json`) — most other plugins don't | Yes | | Hooks installed | No | Yes | | Best for | Try a single plugin's commands without committing to the full install | Production use — everything works as documented |

Path A — Claude Code Plugins (lite, slash commands only)

# Add the marketplace
/plugin marketplace add ruvnet/ruflo

# Install core + any plugins you need
/plugin install ruflo-core@ruflo
/plugin install ruflo-swarm@ruflo
/plugin install ruflo-rag-memory@ruflo
/plugin install ruflo-neural-trader@ruflo

This adds slash commands and agent definitions. `ruflo-core` (installed above) does register its own MCP server on install — its tools are callable as `mcp__plugin_ruflo-core_ruflo__*` (e.g. `mcp__plugin_ruflo-core_ruflo__memory_store`), not the bare `memory_store`/`swarm_init`/`agent_spawn` names the CLI-track scaffold uses. Other plugins generally don't ship their own MCP server. For the full loop with the CLI-track tool names, use Path B below.

<details> <summary><strong>🔌 All 48 plugins</strong> (plus 3 external)</summary>

Core & Orchestration

| Plugin | What it does | |--------|-------------| | [**ruflo-core**](plugins/ruflo-core/README.md) | Foundation — server, health checks, plugin discovery | | [**ruflo-swarm**](plugins/ruflo-swarm/README.md) | Coordinate multiple agents as a team | | [**ruflo-autopilot**](plugins/ruflo-autopilot/README.md) | Let agents run autonomously in a loop | | [**ruflo-loop-workers**](plugins/ruflo-loop-workers/README.md) | Schedule background tasks on a timer | | [**ruflo-workflows**](plugins/ruflo-workflows/README.md) | Reusable multi-step task templates | | [**ruflo-federation**](plugins/ruflo-federation/README.md) | Agents on different machines collaborate securely | | [**ruflo-console**](plugins/ruflo-console/README.md) | Cockpit inside Claude Code, and the `/ruflo` command for ruflo mods | | [**ruflo-mods**](plugins/ruflo-mods/README.md) | In-process Claude Code mod — routing, learning signals, and policy checks | | [**ruflo-ai-team**](plugins/ruflo-ai-team/README.md) | Tenant-isolated team that divides work and returns evidence | | [**ruflo-agntcy**](plugins/ruflo-agntcy/README.md) | AGNTCY/Outshift transport and intent-scoped tool authorization | | [**ruflo-bbs-federation**](plugins/ruflo-bbs-federation/README.md) | AgentBBS rooms so agents on different hosts can coordinate | | [**ruflo-chatgpt-federation**](plugins/ruflo-chatgpt-federation/README.md) | ChatGPT federation publisher with its own signing keys | | [**ruflo-x-gateway**](plugins/ruflo-x-gateway/README.md) | Signed federation messages, channels, and work claims | | [**ruflo-business-pods**](plugins/ruflo-business-pods/README.md) | Business-domain pod templates and a dry-run tick runner |

Memory & Knowledge

| Plugin | What it does | |--------|-------------| | [**ruflo-agentdb**](plugins/ruflo-agentdb/README.md) | Fast vector database for agent memory | | [**ruflo-rag-memory**](plugins/ruflo-rag-memory/README.md) | Smart retrieval — hybrid search, graph hops, diversity ranking | | [**ruflo-rvf**](plugins/ruflo-rvf/README.md) | Save and restore agent memory across sessions | | [**ruflo-ruvector**](plugins/ruflo-ruvector/README.md) | [`ruvector`](https://npmjs.com/package/ruvector) — GPU-accelerated search, Graph RAG, 103 tools | | [**ruflo-knowledge-graph**](plugins/ruflo-knowledge-graph/README.md) | Build and traverse entity relationship maps |

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 · 273 lines

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

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. {
  2. "name": "ruflo",
  3. "description": "RuFlo Marketplace: Claude Code native agents, swarms, workers, and MCP tools for continuous software engineering",
  4. "owner": {
  5. "name": "ruvnet",
  6. "url": "https://github.com/ruvnet"
  7. },
  8. "plugins": [
  9. {
  10. "name": "ruflo-core",
  11. "source": "./plugins/ruflo-core",
  12. "description": "Core Ruflo MCP tools, commands, and Claude Code orchestration patterns"
  13. },
  14. {
  15. "name": "ruflo-ai-team",
  16. "source": "./plugins/ruflo-ai-team/directory",
  17. "description": "Tenant-isolated AI teams that plan work, coordinate tasks, recall approved context, and return evidence-backed results"
  18. },
  19. {
  20. "name": "ruflo-x-gateway",
  21. "source": "./plugins/ruflo-x-gateway/directory",
  22. "description": "Remote RuFlo Federation MCP connector for signed channels, work claims, evidence, and cross-agent coordination"
  23. },
  24. {
  25. "name": "ruflo-deepseek-harness",
  26. "source": "./plugins/ruflo-deepseek-harness",
  27. "description": "DeepSeek model harness with focused agents, commands, and skills for swarm-backed reasoning workflows"
  28. },
  29. {
  30. "name": "ruflo-swarm",
  31. "source": "./plugins/ruflo-swarm",
  32. "description": "Agent teams, swarm coordination, Monitor streams, and worktree isolation"
  33. },
  34. {
  35. "name": "ruflo-loop-workers",
  36. "source": "./plugins/ruflo-loop-workers",
  37. "description": "Cache-aware /loop workers and CronCreate background automation"
  38. },
  39. {
  40. "name": "ruflo-security-audit",
  41. "source": "./plugins/ruflo-security-audit",
  42. "description": "Security review, dependency scanning, policy gates, and CVE monitoring"
  43. },
  44. {
  45. "name": "ruflo-rag-memory",
  46. "source": "./plugins/ruflo-rag-memory",
  47. "description": "RuVector memory with HNSW search, AgentDB, and semantic retrieval"
  48. },
  49. {
  50. "name": "ruflo-testgen",
  51. "source": "./plugins/ruflo-testgen",
  52. "description": "Test gap detection, coverage analysis, and automated test generation"
  53. },
  54. {
  55. "name": "agentic-qe-fleet",
  56. "source": {
  57. "source": "git-subdir",
  58. "url": "https://github.com/proffesor-for-testing/agentic-qe.git",
  59. "path": "plugins/agentic-qe-fleet",
  60. "ref": "v3.15.17",
  61. "sha": "b177b2315521376b83f2eed40e4994fd7581d067"
  62. },
  63. "description": "Agentic QE (external: maintained in proffesor-for-testing/agentic-qe, pinned to v3.15.17): a quality-engineering fleet with 11 QE agents, 9 skills, 9 commands, the agentic-qe MCP server pinned to the plugin version, and the aqe-mod guard that refuses destructive operations on AQE learning data"
  64. },
  65. {
  66. "name": "agentdb",
  67. "source": {
  68. "source": "git-subdir",
  69. "url": "https://github.com/ruvnet/agentdb.git",
  70. "path": "plugins/agentdb",
  71. "ref": "main",
  72. "sha": "27678c302e6c70d6db800c9ad1259b41800f420e"
  73. },
  74. "description": "AgentDB (external: maintained in ruvnet/agentdb, pinned to commit 27678c3, plugin 3.6.0): agentdb's own standalone MCP server pinned to agentdb@3.6.0 (vector memory with get/list/update/delete for records, patterns and skills, hybrid keyword + vector episode search and an opt-in local cross-encoder, an opt-in aidefence injection guard on memory writes, reflexion, skills, outcome feedback, capabilities report), a memory-specialist agent, 3 skills, /agentdb-status, and the agentdb mod guard that keeps secrets out of memory and refuses delete/reset unless allowed. Complements ruflo-agentdb, which reaches AgentDB through ruflo's server"
  75. },
  76. {
  77. "name": "agentic-flow",
  78. "source": {
  79. "source": "git-subdir",
  80. "url": "https://github.com/ruvnet/agentic-flow.git",
  81. "path": "plugins/agentic-flow",
  82. "ref": "main",
  83. "sha": "d19737b8574c956d17d695f09113e8b445d965b0"
  84. },
  85. "description": "agentic-flow (external: maintained in ruvnet/agentic-flow, pinned to commit d19737b, plugin 3.4.0): the agentic-flow MCP server pinned to agentic-flow@3.4.0 (ReasoningBank learning, ecosystem tools prompt_injection_scan, swarm_partition_tasks, sublinear_solve, sublinear_pagerank and ecosystem_status, multi-provider routing, autopilot learning; readonly profile by default, no tool pre-approved), 2 agents, 4 skills, /agentic-flow-status, and a mod guard on agentic_flow_agent with /agentic-flow-guard"
  86. },
  87. {
  88. "name": "ruflo-docs",
  89. "source": "./plugins/ruflo-docs",
  90. "description": "Documentation generation, drift detection, and API docs automation"
  91. },
  92. {
  93. "name": "ruflo-autopilot",
  94. "source": "./plugins/ruflo-autopilot",
  95. "description": "Autonomous /loop-driven task completion with learning, prediction, and progress tracking"
  96. },
  97. {
  98. "name": "ruflo-intelligence",
  99. "source": "./plugins/ruflo-intelligence",
  100. "description": "Self-learning neural intelligence with SONA patterns, trajectory learning, and model routing"
  101. },
  102. {
  103. "name": "ruflo-agentdb",
  104. "source": "./plugins/ruflo-agentdb",
  105. "description": "AgentDB memory controllers with HNSW vector search, RuVector embeddings, and causal graphs"
  106. },
  107. {
  108. "name": "ruflo-aidefence",
  109. "source": "./plugins/ruflo-aidefence",
  110. "description": "AI safety scanning, PII detection, prompt injection defense, and adaptive threat learning"
  111. },
  112. {
  113. "name": "ruflo-protector",
  114. "source": "./plugins/ruflo-protector",
  115. "description": "Project Anatole: an optional, learning watchdog for unattended agents (OWASP-mapped rules, a per-project baseline, learn / notify / enforce modes). Default off."
  116. },
  117. {
  118. "name": "ruflo-browser",
  119. "source": "./plugins/ruflo-browser",
  120. "description": "Agentic browser automation with Playwright for testing, scraping, and UI interaction"
  121. },
  122. {
  123. "name": "ruflo-jujutsu",
  124. "source": "./plugins/ruflo-jujutsu",
  125. "description": "Advanced git workflows with diff analysis, risk scoring, and reviewer recommendations"
  126. },
  127. {
  128. "name": "ruflo-agent",
  129. "source": "./plugins/ruflo-agent",
  130. "description": "Agent runtimes \u2014 local WASM-sandboxed agents (rvagent) + Anthropic Claude Managed Agents (cloud); one interface, local-vs-cloud backends"
  131. },
  132. {
  133. "name": "ruflo-workflows",
  134. "source": "./plugins/ruflo-workflows",
  135. "description": "Visual workflow automation with templates, orchestration, and lifecycle management"
  136. },
  137. {
  138. "name": "ruflo-daa",
  139. "source": "./plugins/ruflo-daa",
  140. "description": "Dynamic Agentic Architecture with cognitive patterns, knowledge sharing, and adaptive agents"
  141. },
  142. {
  143. "name": "ruflo-ruvllm",
  144. "source": "./plugins/ruflo-ruvllm",
  145. "description": "RuVLLM local inference with chat formatting, MicroLoRA fine-tuning, and SONA adaptation"
  146. },
  147. {
  148. "name": "ruflo-rvf",
  149. "source": "./plugins/ruflo-rvf",
  150. "description": "RVF format for portable agent memory, session persistence, and cross-platform transfer"
  151. },
  152. {
  153. "name": "ruflo-plugin-creator",
  154. "source": "./plugins/ruflo-plugin-creator",
  155. "description": "Scaffold, validate, and publish new Claude Code plugins with proper structure"
  156. },
  157. {
  158. "name": "ruflo-goals",
  159. "source": "./plugins/ruflo-goals",
  160. "description": "Long-horizon goal planning, deep research orchestration, and adaptive replanning using GOAP"
  161. },
  162. {
  163. "name": "ruflo-adr",
  164. "source": "./plugins/ruflo-adr",
  165. "description": "ADR lifecycle management \u2014 create, index, supersede, and link Architecture Decision Records to code"
  166. },
  167. {
  168. "name": "ruflo-cost-tracker",
  169. "source": "./plugins/ruflo-cost-tracker",
  170. "description": "Token usage tracking, model cost attribution per agent, budget alerts, and optimization recommendations"
  171. },
  172. {
  173. "name": "ruflo-ddd",
  174. "source": "./plugins/ruflo-ddd",
  175. "description": "Domain-Driven Design scaffolding \u2014 bounded contexts, aggregate roots, domain events, and anti-corruption layers"
  176. },
  177. {
  178. "name": "ruflo-federation",
  179. "source": "./plugins/ruflo-federation",
  180. "description": "Cross-installation agent federation with zero-trust security, PII-gated data flow, and compliance-grade audit trails"
  181. },
  182. {
  183. "name": "ruflo-graph-intelligence",
  184. "source": "./plugins/ruflo-graph-intelligence",
  185. "description": "Real-time graph intelligence \u2014 personalized PageRank, streaming delta updates, witness-signed reasoning, and federation-distributable vectors"
  186. },
  187. {
  188. "name": "ruflo-iot-cognitum",
  189. "source": "./plugins/ruflo-iot-cognitum",
  190. "description": "IoT device lifecycle, telemetry anomaly detection, fleet management, and witness chain verification for Cognitum Seed hardware"
  191. },
  192. {
  193. "name": "ruflo-knowledge-graph",
  194. "source": "./plugins/ruflo-knowledge-graph",
  195. "description": "Knowledge graph construction \u2014 entity extraction, relation mapping, and pathfinder graph traversal"
  196. },
  197. {
  198. "name": "ruflo-market-data",
  199. "source": "./plugins/ruflo-market-data",
  200. "description": "Market data ingestion \u2014 feed normalization, OHLCV vectorization, and HNSW-indexed pattern matching"
  201. },
  202. {
  203. "name": "ruflo-migrations",
  204. "source": "./plugins/ruflo-migrations",
  205. "description": "Schema migration management \u2014 generate, validate, dry-run, and rollback database migrations"
  206. },
  207. {
  208. "name": "ruflo-neural-trader",
  209. "source": "./plugins/ruflo-neural-trader",
  210. "description": "Neural trading strategies \u2014 self-learning LSTM/Transformer/N-BEATS models with Rust/NAPI backtesting"
  211. },
  212. {
  213. "name": "ruflo-observability",
  214. "source": "./plugins/ruflo-observability",
  215. "description": "Structured logging, distributed tracing, and metrics \u2014 correlate agent swarm activity with application telemetry"
  216. },
  217. {
  218. "name": "ruflo-ruvector",
  219. "source": "./plugins/ruflo-ruvector",
  220. "description": "Self-learning vector database \u2014 HNSW, FlashAttention-3, Graph RAG, hybrid search, DiskANN, and Brain AGI"
  221. },
  222. {
  223. "name": "ruflo-sparc",
  224. "source": "./plugins/ruflo-sparc",
  225. "description": "SPARC methodology \u2014 Specification, Pseudocode, Architecture, Refinement, Completion phases with quality gates"
  226. },
  227. {
  228. "name": "ruflo-metaharness",
  229. "source": "./plugins/ruflo-metaharness",
  230. "description": "MetaHarness integration \u2014 surfaces score/genome/mint/mcp-scan/threat-model via skills; pairs with @metaharness/router (ADR-148/149) for cost-optimal model routing; honors ADR-150 optional-augmentation constraint"
  231. },
  232. {
  233. "name": "ruflo-arena",
  234. "source": "./plugins/ruflo-arena",
  235. "description": "Competitive ruliology for ruflo swarms \u2014 arenas, tournaments, and adaptive co-evolution of program strategies (ADR-147/148); strategies-as-programs compete under payoff games"
  236. },
  237. {
  238. "name": "ruflo-agntcy",
  239. "source": "./plugins/ruflo-agntcy",
  240. "description": "AGNTCY/Outshift Internet-of-Cognition runtime integration \u2014 SLIM secure transport, CASA intent-scoped tool authorization, and AGNTCY identity/observability spans (ADR-380); optional, removable augmentation per ADR-150"
  241. },
  242. {
  243. "name": "ruflo-bbs-federation",
  244. "source": "./plugins/ruflo-bbs-federation",
  245. "description": "AgentBBS cross-host agent federation (ADR-164). Phase 1: register/publish/watch/human-join room coordination. Phase 2 (v3.40.0): signed cross-host federation \u2014 identity, peer_add (pin by nodeId+Ed25519 key), peers, serve (read-only pull), sync (pull + union-merge what verifies). Registry-anchored pinning; works on any network (no tailnet required); coordinates work claims (ClaimIssued/Released/Handoff/Ack). Degrades gracefully when agentbbs is absent."
  246. },
  247. {
  248. "name": "ruflo-business-pods",
  249. "source": "./plugins/ruflo-business-pods",
  250. "description": "Business-domain pod templates for the federated business autopilot (ADR-164 Phase 2) \u2014 pod templates plus a dry-run-by-default single-tick runner that validates, reserves budget, and resolves agent roles before posting to the BBS room"
  251. },
  252. {
  253. "name": "ruflo-music",
  254. "source": "./plugins/ruflo-music",
  255. "description": "AI music generation via Cognitum Music (cogmusic MCP) \u2014 compose lyrics/prompts, generate tracks, separate stems, extract MIDI, and master through your own music.cognitum.one account"
  256. },
  257. {
  258. "name": "ruflo-mods",
  259. "source": "./plugins/ruflo-mods",
  260. "description": "Early access (ADR-404): ruflo as a Claude Code mod (function hooks) \u2014 in-process routing, edit learning signals, tighten-only tool checks from ruflo policy, and the cost budget ladder. Opt-in via `ruflo mods install`; classic hooks stay the fallback"
  261. },
  262. {
  263. "name": "ruflo-ruos",
  264. "source": "./plugins/ruflo-ruos",
  265. "description": "Run ruflo swarm agents on your own ruOS cloud desktops via the tenant-authenticated fleet MCP or per-tenant SSH; optional, removable"
  266. },
  267. {
  268. "name": "ruflo-console",
  269. "source": "./plugins/ruflo-console",
  270. "description": "Early access: ruflo's cockpit as a Claude Code mod (function hooks) and the one /ruflo command for every ruflo mod \u2014 overview with health alerts, swarm topology, claims flow, federation map, plugin health, learning pipeline, MetaHarness radar, memory, cost gauge, agent timeline, approvals and events; a command palette for confirm-gated actions through the ruflo CLI; auto-opens where it docks; no network by default"
  271. }
  272. ]
  273. }
README.md · README · 545 lines

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

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. <div align="center">
  2. <a href="https://cognitum.one/ruPro"><img src="ruflo/assets/ruflo-neon-flicker.gif" alt="Ruflo animated neon sign" width="100%"></a>
  3. <a href="https://cognitum.one/ruPro"><img src="docs/assets/readme/rupro-workspace-all-platforms.webp" alt="ruPro workspace for agents across desktop, mobile, and cloud" width="100%"></a>
  4. **[Explore ruPro interactive demo](https://cognitum.one/ruPro)** · Manage agents and projects across desktop, mobile, and cloud.
  5. **An agent meta-harness for Claude Code and Codex.**
  6. <!-- Try Ruflo — the 3 badges first-time visitors actually act on -->
  7. [![npm version (ruflo)](https://img.shields.io/npm/v/ruflo?label=npx%20ruflo&style=for-the-badge&logo=npm&color=cb3837)](https://www.npmjs.com/package/ruflo)
  8. [![MIT License](https://img.shields.io/badge/License-MIT-yellow?style=for-the-badge)](https://opensource.org/licenses/MIT)
  9. [![Star on GitHub](https://img.shields.io/github/stars/ruvnet/ruflo?style=for-the-badge&logo=github&color=gold)](https://github.com/ruvnet/ruflo)
  10. [![Follow @rUv on X](https://img.shields.io/badge/Follow-@rUv-000000?style=for-the-badge&logo=x&logoColor=white)](https://x.com/rUv)
  11. <p align="center">
  12. <a href="docs/harness-origins.md"><img src="https://raw.githubusercontent.com/ruvnet/ruflo/e69e4b95aa08d65ea0f7715489bbf8e62a83a0d2/docs/assets/readme/badges/first-commit.svg" width="300" height="76" alt="Claude Flow lineage: first commit June 2, 2025 by rUv; inspect the evidence"></a>
  13. <a href="https://github.com/ruvnet/ruvnet/blob/main/data/ecosystem-running-totals.json"><img src="docs/assets/readme/badges/downloads.svg" width="300" height="76" alt="120.95 million observed npm download events since October 1, 2025, across 429 packages. Verified November 16, 2026. Lower bound; not unique users or lifetime downloads."></a>
  14. <br>
  15. <a href="https://github.com/ruvnet/claude-flow"><img src="https://raw.githubusercontent.com/ruvnet/ruflo/d1e80400bdefe01d3b13e70395f88fffab76bb18/docs/assets/readme/badges/claude.svg" width="300" height="76" alt="Claude Code plugin"></a>
  16. <a href="https://claude.ai/customize/plugins/id/e74b8927-3c53-4082-b0d9-fe82bf1235ce%40anthropic-plugin-directory"><img src="docs/assets/readme/badges/claude-directory.svg" width="300" height="76" alt="View Claude plugin listing in the Claude plugin directory"></a>
  17. <a href="https://www.npmjs.com/package/@claude-flow/codex"><img src="https://raw.githubusercontent.com/ruvnet/ruflo/d1e80400bdefe01d3b13e70395f88fffab76bb18/docs/assets/readme/badges/codex.svg" width="300" height="76" alt="Codex plugin"></a>
  18. <a href="https://chatgpt.com/plugins/plugin_asdk_app_6ab674ff53c48191bb37040c343e31f3"><img src="docs/assets/readme/badges/chatgpt.svg" width="300" height="76" alt="ChatGPT plugin: RuFlo Federation"></a>
  19. </p>
  20. </div>
  21. <a id="start-here"></a>
  22. ## <img src="docs/assets/readme/icons/terminal.svg" width="32" height="32" alt=""> Get started in one command
  23. Run this in your project folder:
  24. ```bash
  25. npx ruflo@latest init
  26. ```
  27. Then open Claude Code in the same folder and give it a real task, for example:
  28. ```text
  29. Use a ruflo swarm to review this repo: find the riskiest module, write tests for it, and summarise what you changed.
  30. ```
  31. `init` adds ruflo's agents, hooks, memory and MCP server to the project, and Claude Code picks them up on its next start. Codex and other MCP clients work too: point them at `npx -y ruflo@latest mcp start`.
  32. <p align="center"><img src="docs/assets/ruflo-console-tour.gif" width="720" alt="Looping recording of the ruflo console: overview, swarm view and missions in a sample project"></p>
  33. [First useful task, step by step](docs/ruflo-explained.md) · [User guide](docs/USERGUIDE.md) · [Compare install paths](#quick-start)
  34. <a href="https://github.com/ruvnet/ruflo/blob/main/docs/recipes/rvf-mcp-search.md"><img src="https://raw.githubusercontent.com/ruvnet/ruflo/main/docs/assets/readme/rvf-mcp-search.svg" width="720" alt="Search a local RVF index from a Ruflo project using the stdio RVF MCP server and a read-only handle"></a>
  35. [Optional recipe: local vector search with RVF and MCP](https://github.com/ruvnet/ruflo/blob/main/docs/recipes/rvf-mcp-search.md) · [Ruvnet ecosystem](https://ruv.io)
  36. <details>
  37. <summary><b>Other ways to install</b> (Claude Code plugins only, MCP-only clients, terminal UI)</summary>
  38. **Claude Code plugins only.** This route installs core tools, the visual console and runtime mods, with no files added to your project. It needs Claude Code **2.1.287 or later**. Run inside Claude Code:
  39. ```text
  40. /plugin marketplace add ruvnet/ruflo
  41. /plugin install ruflo-core@ruflo
  42. /plugin install ruflo-console@ruflo
  43. /plugin install ruflo-mods@ruflo
  44. /reload-plugins
  45. /ruflo
  46. ```
  47. From a terminal, on Claude Code 2.1.292 or later: `claude plugin install ruflo-core@ruflo --marketplace ruvnet/ruflo`. Mods run with your account's permissions, so review their code before installing.
  48. **Codex or another MCP client, without project setup.** Configure the **command** `npx` with the **arguments** `["-y", "ruflo@latest", "mcp", "start"]`. To set up a project interactively, run `npx ruflo@latest init wizard`.
  49. **Plain terminal.** The console also runs on its own, without Claude Code: `npx ruflo tui`. Add `--plain` to print one frame for scripts. See the [terminal UI guide](docs/USERGUIDE.md#terminal-ui-optional).
  50. <p align="center"><img src="docs/assets/ruflo-tui-compact.svg" width="640" alt="Looping recording of the optional ruflo terminal UI with its pictures: Overview in the Classic BBS look, the Orbital look with its moving globe, and the Swarm graph, in a sample project"></p>
  51. </details>
  52. <div align="center">
  53. ### Optional: ruOS Desktop
  54. <a href="https://ruos.cognitum.one"><img src="ruflo/assets/ruos-animated.svg" alt="ruOS — A desktop that runs itself" width="100%"></a>
  55. **Connect ruOS to ChatGPT or Claude via MCP:**
  56. ```text
  57. https://ruos.cognitum.one/mcp
  58. ```
  59. <!-- RuVector promo -->
  60. <a href="https://github.com/ruvnet/ruvector"><img src="docs/assets/readme/ruvector-promo-depth.svg" width="100%" alt="RuVector: Give your agents memory. Local vector search, persistent context, graph relationships and feedback learning. Explore RuVector."></a>
  61. ```bash
  62. npx ruvector
  63. ```
  64. # Ruflo
  65. [English](README.md) · [简体中文](README.zh-CN.md)
  66. [![RuFlo Explained — build an AI team that plans, remembers, tests, and improves](docs/assets/ruflo-explained/ch14.jpg)](docs/ruflo-explained.md)
  67. **[📖 RuFlo Explained — Build an AI Team That Plans, Remembers, Tests, and Improves](docs/ruflo-explained.md)**
  68. A 14-chapter guide: from the basic idea to a first useful task, then memory, agent teams, plugins, cost and verification.
  69. </div>
  70. > **Agent = Model + Harness.** The model writes; the harness gives it tools, memory, loops, sandboxes, and controls so it can actually work. **Ruflo is the harness** — the execution layer around Claude Code and Codex that adds 100+ specialized agents, coordinated swarms, self-learning memory, federated comms across machines, and enterprise security guardrails. So agents don't just run, they collaborate.
  71. One `npx ruflo init` gives Claude Code a nervous system: agents self-organize into swarms, learn from every task, remember across sessions, and — with federation — securely talk to agents on other machines without leaking data. You keep writing code. Ruflo handles the coordination.
  72. <p align="center"><img src="docs/assets/readme/learning-cinematic-compact.svg" width="100%" alt="Ruflo trajectory learning: branching memory paths, outcome feedback, contrastive AI and local learning. No LLM required for local vector retrieval and contrastive updates; agent execution may still use an LLM."></p>
  73. <sub>Conceptual learning loop. Local vector retrieval and contrastive updates can run without an LLM; embeddings and configured learning modules are still required. See the <a href="v3/@claude-flow/cli/src/services/ruvector-training.ts">RuVector training integration</a> and <a href="v3/@claude-flow/neural/src/modes/balanced.ts">trajectory contrastive learning</a>.</sub>
  74. <details>
  75. <summary>Architecture in text</summary>
  76. User → Ruflo (CLI/MCP) → Router → Swarm → Agents → Memory → LLM providers. Memory feeds useful experience back into routing. This is a conceptual flow, not a live execution trace.
  77. </details>
  78. > **New to Ruflo?** You don't need to learn 406 MCP tools or 61 CLI commands. After `init`, just use Claude Code normally — the hooks system automatically routes tasks, learns from successful patterns, and coordinates agents in the background.
  79. ### An origin you can inspect
  80. [![Claude Flow to Ruflo: founding idea on June 2, 2025, orchestration source on June 10, and the continuing Ruflo lineage.](docs/assets/readme/harness-origins.svg)](docs/harness-origins.md)
  81. **Built by [Reuven Cohen (rUv)](https://github.com/ruvnet), originally as Claude Flow.** The [first commit, June 2, 2025](https://github.com/ruvnet/ruflo/commit/7c1f9402d70e7af56c01a879073cbac92564dc4e), describes a code orchestration layer for recursive agent cycles: Claude writes, edits, tests and improves. The [June 10 source snapshot](https://github.com/ruvnet/ruflo/tree/dba545f012ea92a2375a26332bbf3797495e93c9) adds orchestration, task scheduling, memory and terminal modules.
  82. A harness is the workbench around the model: it organizes tasks, carries context between steps and helps check results. **This establishes Ruflo's lineage, not a universal first across every Claude Code tool.** [See the illustrated explainer, exact commits and earlier ecosystem context](docs/harness-origins.md).
  83. **Grok Build:** `npx ruflo init --grok` writes the project host surface (`.grok/`, the team bus, and the operator guide) and nothing outside the project; add `--dry-run` to preview. Setup, the `spawn_subagent` contract, the optional status row, and what to re-check when Grok updates: [the Grok operator guide](v3/@claude-flow/cli/templates/grok/docs/README.md).
  84. <details>
  85. <summary><strong>📖 Background — where the name comes from</strong></summary>
  86. > Claude Flow is now Ruflo — named by [`rUv`](https://ruv.io), who loves Rust, flow states, and building things that feel inevitable. The "Ru" is the rUv. The "flo" is working until 3am. Underneath, powered by [`Cognitum.One`](https://cognitum.one/?RuFlo) agentic architecture, running a supercharged Rust-based AI engine, embeddings, memory, and plugin system.
  87. </details>
  88. ---
  89. <p align="center"><img src="docs/assets/readme/console.svg" alt="Mission control: inspect agent work" width="100%"></p>
  90. <p align="center"><a href="https://raw.githubusercontent.com/ruvnet/ruflo/main/docs/assets/ruflo-console-theme-compact.svg"><img src="docs/assets/ruflo-console-theme-compact.svg" width="100%" alt="Ruflo Orbital theme: animated boot checks, block logo, menu icons, rotating globe, swarm routing, six color palettes and responsive Theme Studio"></a></p>
  91. [Open animated demo](https://raw.githubusercontent.com/ruvnet/ruflo/main/docs/assets/ruflo-console-theme-compact.svg) · [Theme Studio guide](plugins/ruflo-console/README.md) · [Workflow demo](docs/assets/ruflo-console-workflows.svg)
  92. <img src="docs/assets/readme/console-icon-workflows.svg" width="28" height="28" alt=""> **Your agent cockpit.** Track workflows, agents, models, tokens and cost beside Claude Code. The 38 second animation shows **Orbital and Theme Studio** through actual renderer frames, including boot checks, six palettes, customization, saved themes, JSON import and resizing. This compact 3.84 MB SVG retains all 456 frames. Native host and AI provider execution are not demonstrated.
  93. <img src="docs/assets/readme/console-icon-inspect.svg" width="28" height="28" alt=""> **Inspect any run.** Open agent logs and results, search, triage failures, replay and compare. Start with `npx ruflo init`, restart Claude Code, then `/ruflo`. [Full console tour](docs/assets/ruflo-console-walkthrough-wide.gif).
  94. <img src="docs/assets/readme/console-icon-control.svg" width="28" height="28" alt=""> **Let Claude drive. You set the limits.** Enable **Settings → Claude control** to navigate and run console actions. Choose `read`, `write`, `manage` or `full`, with `ask` or `auto` approval. The current default is **read + ask**; raising the level is your choice. Actions above your permission level are refused, and network, spending and destructive actions require confirmation even in `auto`. Review the live action log or press **Take back control** to stop Claude control. [Details](v3/docs/adr/ADR-444-claude-controls-the-console.md).
  95. <a id="console-walkthrough"></a>
  96. ### One task: create a mission with Claude
  97. <img src="docs/assets/readme/console-icon-workflows.svg" width="28" height="28" alt=""> **Watch the recorded console session below.** Claude creates a mission, opens the Learning and Security pages, and reports its actions in Overview.
  98. 1. **Set the boundary.** Install the console using the commands below, open `/ruflo`, then choose **Settings → Claude control → write + ask**.
  99. 2. **Give a concrete request.** Try: “Create a mission to add a dark mode toggle. Show me the mission and its status.”
  100. 3. **Approve creation.** Claude opens Missions and sets the goal. Confirm the pending create action in the console.
  101. 4. **Verify the result.** Check that Missions contains the goal and Overview records the action. Creating a mission does not mean the feature has been implemented.
  102. 5. **Keep control.** **Take back control** pauses Claude's console tools. A later call should be refused until you restore control.
  103. **What the recording demonstrates:** a real Claude Haiku session with `write + auto`, mission creation, page navigation, a refused swarm stop, and control being taken back. The steps above use `ask` so you approve creation yourself. The linked workflow animation uses sample data, while the theme demo replays renderer frames. Neither is evidence of completed swarm work or memory recall.
  104. [Implementation and recorded test findings](v3/docs/adr/ADR-444-claude-controls-the-console.md) · [Reproduction script](plugins/ruflo-console/scripts/e2e-control.sh)
  105. <p align="center"><img src="docs/assets/ruflo-console-claude-control.gif" alt="Claude Code with the ruflo console beside it: Claude sets a mission goal, creates the mission and opens the Learning, Security and Overview pages through the console tools; the Claude control dashboard logs each action; swarm-stop is refused because it needs the full level; the person clicks Take back control and the next request is refused"></p>
  106. **Install the mods from the ruflo marketplace** (Claude Code 2.1.287 or later; mods run with your account's permissions and are not sandboxed, so read the code first):
  107. ```text
  108. /plugin marketplace add ruvnet/ruflo
  109. /plugin install ruflo-console@ruflo
  110. /plugin install ruflo-mods@ruflo
  111. /reload-plugins
  112. ```
  113. `ruflo-console` is the cockpit above, `ruflo-mods` routes prompts and enforces policy in-process, `ruflo-swarm` shows the swarm in a pane, and `ruflo-ruos` adds the ruOS status segment. Open `/plugin` to confirm they appear in the active mods line. Inside the console, `/ruflo market` is the Plugin Catalog: every ruflo plugin, mod and skill with what it ships, and buttons to install, enable, disable and update (each asks first).
  114. ## Quick Start
  115. <p align="center"><img src="docs/assets/readme/quick-start.svg" alt="Start building with Ruflo" width="100%"></p>
  116. There are **two different install paths** with very different surface areas. Pick based on what you need (#1744):
  117. | | **Claude Code Plugin** | **CLI install (`npx ruflo init`)** |
  118. |---|---|---|
  119. | What it gives you | Slash commands + a few skills + agent definitions per-plugin | Full Ruflo loop — 98 agents, 60+ commands, 30 skills, MCP server, hooks, daemon |
  120. | Files in your workspace | **Zero** | `.claude/`, `.claude-flow/`, `CLAUDE.md`, helpers, settings |
  121. | MCP server registered | Only if `ruflo-core` is installed (it ships its own `.mcp.json`) — most other plugins don't | Yes |
  122. | Hooks installed | No | Yes |
  123. | Best for | Try a single plugin's commands without committing to the full install | Production use — everything works as documented |
  124. ### Path A — Claude Code Plugins (lite, slash commands only)
  125. ```bash
  126. # Add the marketplace
  127. /plugin marketplace add ruvnet/ruflo
  128. # Install core + any plugins you need
  129. /plugin install ruflo-core@ruflo
  130. /plugin install ruflo-swarm@ruflo
  131. /plugin install ruflo-rag-memory@ruflo
  132. /plugin install ruflo-neural-trader@ruflo
  133. ```
  134. This adds slash commands and agent definitions. `ruflo-core` (installed above) does register its own MCP server on install — its tools are callable as `mcp__plugin_ruflo-core_ruflo__*` (e.g. `mcp__plugin_ruflo-core_ruflo__memory_store`), not the bare `memory_store`/`swarm_init`/`agent_spawn` names the CLI-track scaffold uses. Other plugins generally don't ship their own MCP server. For the full loop with the CLI-track tool names, use Path B below.
  135. <details>
  136. <summary><strong>🔌 All 48 plugins</strong> (plus 3 external)</summary>
  137. #### Core & Orchestration
  138. | Plugin | What it does |
  139. |--------|-------------|
  140. | [**ruflo-core**](plugins/ruflo-core/README.md) | Foundation — server, health checks, plugin discovery |
  141. | [**ruflo-swarm**](plugins/ruflo-swarm/README.md) | Coordinate multiple agents as a team |
  142. | [**ruflo-autopilot**](plugins/ruflo-autopilot/README.md) | Let agents run autonomously in a loop |
  143. | [**ruflo-loop-workers**](plugins/ruflo-loop-workers/README.md) | Schedule background tasks on a timer |
  144. | [**ruflo-workflows**](plugins/ruflo-workflows/README.md) | Reusable multi-step task templates |
  145. | [**ruflo-federation**](plugins/ruflo-federation/README.md) | Agents on different machines collaborate securely |
  146. | [**ruflo-console**](plugins/ruflo-console/README.md) | Cockpit inside Claude Code, and the `/ruflo` command for ruflo mods |
  147. | [**ruflo-mods**](plugins/ruflo-mods/README.md) | In-process Claude Code mod — routing, learning signals, and policy checks |
  148. | [**ruflo-ai-team**](plugins/ruflo-ai-team/README.md) | Tenant-isolated team that divides work and returns evidence |
  149. | [**ruflo-agntcy**](plugins/ruflo-agntcy/README.md) | AGNTCY/Outshift transport and intent-scoped tool authorization |
  150. | [**ruflo-bbs-federation**](plugins/ruflo-bbs-federation/README.md) | AgentBBS rooms so agents on different hosts can coordinate |
  151. | [**ruflo-chatgpt-federation**](plugins/ruflo-chatgpt-federation/README.md) | ChatGPT federation publisher with its own signing keys |
  152. | [**ruflo-x-gateway**](plugins/ruflo-x-gateway/README.md) | Signed federation messages, channels, and work claims |
  153. | [**ruflo-business-pods**](plugins/ruflo-business-pods/README.md) | Business-domain pod templates and a dry-run tick runner |
  154. #### Memory & Knowledge
  155. | Plugin | What it does |
  156. |--------|-------------|
  157. | [**ruflo-agentdb**](plugins/ruflo-agentdb/README.md) | Fast vector database for agent memory |
  158. | [**ruflo-rag-memory**](plugins/ruflo-rag-memory/README.md) | Smart retrieval — hybrid search, graph hops, diversity ranking |
  159. | [**ruflo-rvf**](plugins/ruflo-rvf/README.md) | Save and restore agent memory across sessions |
  160. | [**ruflo-ruvector**](plugins/ruflo-ruvector/README.md) | [`ruvector`](https://npmjs.com/package/ruvector) — GPU-accelerated search, Graph RAG, 103 tools |
  161. | [**ruflo-knowledge-graph**](plugins/ruflo-knowledge-graph/README.md) | Build and traverse entity relationship maps |
  162. #### Intelligence & Learning
  163. | Plugin | What it does |
  164. |--------|-------------|
  165. | [**ruflo-intelligence**](plugins/ruflo-intelligence/README.md) | Agents learn from past successes and get smarter |
  166. | [**ruflo-graph-intelligence**](plugins/ruflo-graph-intelligence/) | Sublinear graph reasoning — PageRank, delta updates, complexity-aware execution (ADR-123) |
  167. | [**ruflo-daa**](plugins/ruflo-daa/README.md) | Dynamic agent behavior and cognitive patterns |
  168. | [**ruflo-ruvllm**](plugins/ruflo-ruvllm/README.md) | Run local LLMs (Ollama, etc.) with smart routing |
  169. | [**ruflo-goals**](plugins/ruflo-goals/README.md) | Break big goals into plans and track progress |
  170. | [**ruflo-deepseek-harness**](plugins/ruflo-deepseek-harness/README.md) | Agents, commands, and skills for DeepSeek-backed workflows |
  171. #### Code Quality & Testing
  172. | Plugin | What it does |
  173. |--------|-------------|
  174. | [**ruflo-testgen**](plugins/ruflo-testgen/README.md) | Find missing tests and generate them automatically |
  175. | [**ruflo-browser**](plugins/ruflo-browser/README.md) | Automate browser testing with Playwright |
  176. | [**ruflo-jujutsu**](plugins/ruflo-jujutsu/README.md) | Analyze git diffs, score risk, suggest reviewers |
  177. | [**ruflo-rure**](plugins/ruflo-rure/) | Static analysis of a local JS/Electron app you are authorized to study, with file and line evidence |
  178. | [**ruflo-docs**](plugins/ruflo-docs/README.md) | Generate and maintain documentation automatically |
  179. | [**agentic-qe-fleet**](https://github.com/proffesor-for-testing/agentic-qe/tree/v3.15.17/plugins/agentic-qe-fleet) | External, maintained by [Agentic QE](https://github.com/proffesor-for-testing/agentic-qe): 11 QE agents, test generation, coverage, chaos and TDD skills, the `agentic-qe` MCP server, and a guard for AQE learning data (`/plugin install agentic-qe-fleet@ruflo`). Install it from one marketplace only, `agentic-qe` or `ruflo`: enabled from both, its mod and commands load twice |
  180. | [**agentdb**](https://github.com/ruvnet/agentdb/tree/plugin-v3.2.0/plugins/agentdb) | External, maintained in [ruvnet/agentdb](https://github.com/ruvnet/agentdb): agentdb's own MCP server (pinned `agentdb@3.2.0`: hybrid keyword + vector search, opt-in cross-encoder rerank), a memory-specialist agent, vector-memory / learning / diagnostics skills, `/agentdb-status`, and a guard that keeps secrets out of memory and refuses delete/reset unless allowed (`/plugin install agentdb@ruflo`). Use `ruflo-agentdb` instead if you want AgentDB through ruflo's server; the two can coexist. Install it from one marketplace only, `agentdb` or `ruflo` |
  181. | [**agentic-flow**](https://github.com/ruvnet/agentic-flow/tree/plugin-v3.1.0/plugins/agentic-flow) | External, maintained in [ruvnet/agentic-flow](https://github.com/ruvnet/agentic-flow): the agentic-flow MCP server (pinned `agentic-flow@3.1.0`, `readonly` profile by default, nothing pre-approved), ReasoningBank and model-router agents, routing / learning / autopilot skills, `/agentic-flow-status`, and a guard on `agentic_flow_agent` (`/plugin install agentic-flow@ruflo`). Install it from one marketplace only, `agentic-flow` or `ruflo` |
  182. #### Security & Compliance
  183. | Plugin | What it does |
  184. |--------|-------------|
  185. | [**ruflo-security-audit**](plugins/ruflo-security-audit/README.md) | Scan for vulnerabilities and CVEs |
  186. | [**ruflo-aidefence**](plugins/ruflo-aidefence/README.md) | Block prompt injection, detect PII, safety scanning |
  187. | [**ruflo-protector**](plugins/ruflo-protector/README.md) | Optional watchdog for unattended agents — learn, notify, or enforce |
  188. #### Architecture & Methodology
  189. | Plugin | What it does |
  190. |--------|-------------|
  191. | [**ruflo-adr**](plugins/ruflo-adr/README.md) | Track architecture decisions with a living record |
  192. | [**ruflo-ddd**](plugins/ruflo-ddd/README.md) | Scaffold domain-driven design — contexts, aggregates, events |
  193. | [**ruflo-sparc**](plugins/ruflo-sparc/README.md) | Guided 5-phase development methodology with quality gates |
  194. | [**ruflo-metaharness**](plugins/ruflo-metaharness/README.md) | Grade your agent setup, scan tool configs for security risks, and track changes over time ([guide](docs/metaharness-user-guide.md)) |
  195. | [**ruflo-arena**](plugins/ruflo-arena/README.md) | Competitive ruliology — pit agent strategies against each other in tournaments, hill-climb and co-evolve the winners (ADR-147/148) |
  196. #### DevOps & Observability
  197. | Plugin | What it does |
  198. |--------|-------------|
  199. | [**ruflo-migrations**](plugins/ruflo-migrations/README.md) | Manage database schema changes safely |
  200. | [**ruflo-observability**](plugins/ruflo-observability/README.md) | Structured logs, traces, and metrics in one place |
  201. | [**ruflo-cost-tracker**](plugins/ruflo-cost-tracker/README.md) | Track token usage, set budgets, get cost alerts |
  202. | [**ruflo-ruos**](plugins/ruflo-ruos/README.md) | Run swarm agents on your own ruOS cloud desktops |
  203. #### Extensibility
  204. | Plugin | What it does |
  205. |--------|-------------|
  206. | [**ruflo-agent**](plugins/ruflo-agent/README.md) | Run agents — local WASM sandbox (rvagent) + Anthropic Claude Managed Agents (cloud), with opt-in bounded dynamic workflows, gated session controls and verified advisory learning |
  207. | [**ruflo-plugin-creator**](plugins/ruflo-plugin-creator/README.md) | Scaffold, validate, and publish your own plugins |
  208. #### Domain-Specific
  209. | Plugin | What it does |
  210. |--------|-------------|
  211. | [**ruflo-iot-cognitum**](plugins/ruflo-iot-cognitum/README.md) | IoT device management — trust scoring, anomaly detection, fleets |
  212. | [**ruflo-neural-trader**](plugins/ruflo-neural-trader/README.md) | [`neural-trader`](https://npmjs.com/package/neural-trader) — AI trading with 4 agents, backtesting, 112+ tools |
  213. | [**ruflo-market-data**](plugins/ruflo-market-data/README.md) | Ingest market data, vectorize OHLCV, detect patterns |
  214. | [**ruflo-music**](plugins/ruflo-music/README.md) | Compose and generate music through a Cognitum Music account |
  215. </details>
  216. ### <img src="docs/assets/readme/icons/terminal.svg" width="28" height="28" alt=""> CLI Install
  217. **macOS / Linux / WSL / Git-Bash:**
  218. ```bash
  219. # One-line install (POSIX shells only — see Windows note below)
  220. curl -fsSL https://cdn.jsdelivr.net/gh/ruvnet/ruflo@main/scripts/install.sh | bash
  221. ```
  222. **All platforms (including native Windows PowerShell / cmd):**
  223. ```bash
  224. # Interactive setup wizard — runs identically on every platform
  225. npx ruflo@latest init wizard
  226. # Quick non-interactive init
  227. # npx ruflo@latest init
  228. # Or install globally
  229. npm install -g ruflo@latest
  230. ```
  231. > 💡 **Windows users:** the `curl ... | bash` form needs a POSIX shell (Git-Bash, WSL, MSYS). The `npx ruflo@latest init wizard` line works natively in PowerShell and cmd. If you hit an `'bash' is not recognized` error, use the `npx` line instead — both end up running the same init flow.
  232. ### <img src="docs/assets/readme/icons/network.svg" width="28" height="28" alt=""> MCP Server
  233. ```bash
  234. # Add Ruflo as an MCP server in Claude Code
  235. claude mcp add claude-flow -- npx ruflo@latest mcp start
  236. ```
  237. For static inspection of local applications and binaries, see the [ruRE plugin guide](plugins/ruflo-rure/README.md).
  238. ---
  239. ## What You Get
  240. <p align="center"><img src="docs/assets/readme/capabilities.svg" alt="Your agent toolkit" width="100%"></p>
  241. <table>
  242. <tr><td width="50%"><a href="plugins/ruflo-swarm/README.md"><img src="docs/assets/readme/card-swarm.svg" width="100%" alt="Agent teams"></a></td><td width="50%"><a href="plugins/ruflo-rag-memory/README.md"><img src="docs/assets/readme/card-memory.svg" width="100%" alt="Persistent memory"></a></td></tr>
  243. <tr><td width="50%"><a href="plugins/ruflo-intelligence/README.md"><img src="docs/assets/readme/card-learning.svg" width="100%" alt="Learning loops"></a></td><td width="50%"><a href="plugins/ruflo-security-audit/README.md"><img src="docs/assets/readme/card-security.svg" width="100%" alt="Security controls"></a></td></tr>
  244. <tr><td width="50%"><a href="https://ruvnet.github.io/ruflo"><img src="docs/assets/readme/card-plugins.svg" width="100%" alt="Plugin marketplace"></a></td><td width="50%"><a href="plugins/ruflo-ruvllm/README.md"><img src="docs/assets/readme/card-routing.svg" width="100%" alt="Models and routing"></a></td></tr>
  245. </table>
  246. | Capability | Description |
  247. |------------|-------------|
  248. | <img src="docs/assets/readme/icons/agents.svg" width="28" height="28" alt=""> **100+ Agents** | Specialized agents for coding, testing, security, docs, architecture |
  249. | <img src="docs/assets/readme/icons/network.svg" width="28" height="28" alt=""> **Comms Layer** | Zero-trust federation — agents across machines/orgs discover, authenticate, and exchange work securely |
  250. | <img src="docs/assets/readme/icons/swarm.svg" width="28" height="28" alt=""> **Swarm Coordination** | Hierarchical, mesh, and adaptive topologies with consensus |
  251. | <img src="docs/assets/readme/icons/learning.svg" width="28" height="28" alt=""> **Self-Learning** | SONA neural patterns, ReasoningBank, trajectory learning |
  252. | <img src="docs/assets/readme/icons/memory.svg" width="28" height="28" alt=""> **Vector Memory** | HNSW-indexed AgentDB — measured ~1.9x faster at N=20k, ~3.2x–4.7x at N=5k vs brute force (recall@10 ~0.99); ANN wins above the crossover, ties/loses at small N. See [audit](docs/reviews/intelligence-system-audit-2026-05-29.md) + [`scripts/benchmark-intelligence.mjs`](scripts/benchmark-intelligence.mjs) |
  253. | <img src="docs/assets/readme/icons/workers.svg" width="28" height="28" alt=""> **Background Workers** | 12 auto-triggered workers (audit, optimize, testgaps, etc.) |
  254. | <img src="docs/assets/readme/icons/plugins.svg" width="28" height="28" alt=""> **Plugin Marketplace** | 48 native Claude Code plugins + 14 in-tree npm plugins |
  255. | <img src="docs/assets/readme/icons/routing.svg" width="28" height="28" alt=""> **Multi-Provider** | Claude, GPT, Gemini, Cohere, Ollama with smart routing |
  256. | <img src="docs/assets/readme/icons/security.svg" width="28" height="28" alt=""> **Security** | AIDefence, input validation, CVE remediation, path traversal prevention |
  257. | <img src="docs/assets/readme/icons/federation.svg" width="28" height="28" alt=""> **Agent Federation** | Cross-installation agent collaboration with zero-trust security |
  258. | <img src="docs/assets/readme/icons/audit.svg" width="28" height="28" alt=""> **[MetaHarness](docs/metaharness-user-guide.md)** | Audit your AI agent setup before you ship. Grade readiness (1-100), scan tool configs for security issues, snapshot the whole project to catch regressions over time, and find templates that match your repo. `ruflo eject` turns a ruflo project into a standalone agent toolkit with its own name. [Full guide](docs/metaharness-user-guide.md). |
  259. ### <img src="docs/assets/readme/icons/learning.svg" width="28" height="28" alt=""> Learning from experience
  260. <p align="center"><img src="docs/assets/readme/learning-flow.svg" width="100%" alt="Recall, execute, evaluate, store, adapt and reuse: an illustrative agent learning cycle."></p>
  261. Useful trajectories and task feedback can inform future work. Results depend on the configured memory, learning components and quality of feedback. [Learning plugin](plugins/ruflo-intelligence/README.md).
  262. ### Agent Federation — Slack for Agents
  263. <p align="center"><img src="docs/assets/readme/federation.svg" alt="Connected intelligence across machines" width="100%"></p>
  264. <p align="center"><img src="docs/assets/readme/federation-flow.svg" width="100%" alt="Outbound agent, data filtering, signing and encryption, identity verification, input checks and receiving agent."></p>
  265. Slack gave teams channels. Federation gives agents the same thing — **shared workspaces across trust boundaries**, where agents on different machines, orgs, or cloud regions can discover each other, prove who they are, and collaborate on tasks.
  266. The difference: some channels are trusted, some aren't. [`@claude-flow/plugin-agent-federation`](https://github.com/ruvnet/ruflo/issues/1669) handles that automatically. Your agents join a federation, get verified via mTLS + ed25519, and start exchanging work — with PII stripped before anything leaves your node and every message auditable. Untrusted agents can still participate at lower privilege: they see discovery info, not your memory. As they prove reliable, trust upgrades. If they misbehave, they get downgraded instantly — no human in the loop required.
  267. You don't configure handshakes or manage certificates. You `federation init`, `federation join`, and your agents start talking. The protocol handles identity, the PII pipeline handles data safety, and the audit trail handles compliance.
  268. > **📘 Full user guide:** [`docs/federation/`](./docs/federation/) — setup, MCP tools, trust levels, circuit breaker, and the (opt-in) WireGuard mesh layer that ties packet-layer reachability to federation trust. ADR-111 deep-dive at [`docs/federation/phase7-mesh-bringup.md`](./docs/federation/phase7-mesh-bringup.md).
  269. <details>
  270. <summary><strong>Federation capabilities</strong></summary>
  271. | | Capability | How it works |
  272. |---|---|---|
  273. | 🔒 | **Zero-trust federation** | Remote agents start untrusted. Identity proven via mTLS + ed25519 challenge-response. No API keys, no shared secrets. |
  274. | 🛡️ | **PII-gated data flow** | 14-type detection pipeline scans every outbound message. Per-trust-level policies: BLOCK, REDACT, HASH, or PASS. Adaptive calibration reduces false positives. |
  275. | 📊 | **Behavioral trust scoring** | Formula (`0.4×success + 0.2×uptime + 0.2×threat + 0.2×integrity`) continuously evaluates peers. Upgrades require history; downgrades are instant. |
  276. | 📋 | **Compliance built-in** | HIPAA, SOC2, GDPR audit trails as compliance modes. Every federation event produces a structured record searchable via HNSW. |
  277. | 🤝 | **9 MCP tools + 10 CLI commands** | Full lifecycle: `federation_init`, `federation_send`, `federation_trust`, `federation_audit`, and more. |
  278. </details>
  279. <details>
  280. <summary><strong>Example: two teams sharing fraud signals without sharing customer data</strong></summary>
  281. ```bash
  282. # Team A: initialize federation and generate keypair
  283. npx claude-flow@latest federation init
  284. # Team A: join Team B's federation endpoint
  285. npx claude-flow@latest federation join wss://team-b.example.com:8443
  286. # Team A: send a task — PII is stripped automatically before it leaves
  287. npx claude-flow@latest federation send --to team-b --type task-request \
  288. --message "Analyze transaction patterns for account anomalies"
  289. # Team A: check peer trust levels and session health
  290. npx claude-flow@latest federation status
  291. ```
  292. </details>
  293. See [issue #1669](https://github.com/ruvnet/ruflo/issues/1669) for the complete architecture, trust model, and implementation roadmap.
  294. ```bash
  295. # Claude Code plugin
  296. /plugin install ruflo-federation@ruflo
  297. # Or via CLI
  298. npx claude-flow@latest plugins install @claude-flow/plugin-agent-federation
  299. ```
  300. <details>
  301. <summary><strong>Claude Code: With vs Without Ruflo</strong></summary>
  302. | Capability | Claude Code Alone | + Ruflo |
  303. |------------|-------------------|---------|
  304. | Agent Collaboration | Isolated, no shared context | Swarms with shared memory and consensus |
  305. | Coordination | Manual orchestration | Queen-led hierarchy (Raft, Byzantine, Gossip) |
  306. | Memory | Session-only | HNSW vector memory with sub-ms retrieval |
  307. | Learning | Static behavior | SONA self-learning with pattern matching |
  308. | Task Routing | You decide | Intelligent routing (89% accuracy) |
  309. | Background Workers | None | 12 auto-triggered workers |
  310. | LLM Providers | Anthropic only | 5 providers with failover |
  311. | Security | Standard | CVE-hardened with AIDefence |
  312. </details>
  313. <details>
  314. <summary><strong>Architecture overview</strong></summary>
  315. ```
  316. User --> Claude Code / CLI
  317. |
  318. v
  319. Orchestration Layer
  320. (MCP Server, Router, 27 Hooks)
  321. |
  322. v
  323. Swarm Coordination
  324. (Queen, Topology, Consensus)
  325. |
  326. v
  327. 100+ Specialized Agents
  328. (coder, tester, reviewer, architect, security...)
  329. |
  330. v
  331. Memory & Learning
  332. (AgentDB, HNSW, SONA, ReasoningBank)
  333. |
  334. v
  335. LLM Providers
  336. (Claude, GPT, Gemini, Cohere, Ollama)
  337. ```
  338. </details>
  339. ---
  340. ## Documentation
  341. <p align="center"><img src="docs/assets/readme/documentation.svg" alt="Guides, architecture and verification" width="100%"></p>
  342. Four docs for four audiences:
  343. | Doc | When to read it |
  344. |-----|-----------------|
  345. | **[Status](docs/STATUS.md)** | See what currently works — capability counts, test baselines, recent fixes, what's next. The *is-it-ready* doc. |
  346. | **[User Guide](docs/USERGUIDE.md)** | Daily reference — every command, every config flag, every plugin. The *how-do-I* doc. |
  347. | **[Compare frameworks](docs/compare.md)** | Deciding between Ruflo, Claude Code built-in agents, CrewAI, LangGraph, or AutoGen. The *which-one-for-me* doc. |
  348. | **[MetaHarness Guide](docs/metaharness-user-guide.md)** | How to grade your agent setup, scan tool configs for security, detect changes between runs, and eject a project into a standalone agent toolkit. The *audit-my-setup* doc. |
  349. | **[Benchmarks](https://gist.github.com/ruvnet/298f8c668c8859b369f91734a0e9cbbe)** | v3.8.0 SOTA matrix vs LangGraph / AutoGen / CrewAI on darwin-arm64 + linux-x64. ruflo wins cold start, single turn, RSS by 1.3×–1953×. The *is-it-fast* doc. |
  350. | **[Verification](verification.md)** | Cryptographically prove your installed bytes match the signed witness — `ruflo verify`. The *trust-but-verify* doc. |
  351. | **[Team Gateway Checklist](docs/TEAM-GATEWAY-CHECKLIST.md)** | Before-merge gates, dual-mode handoff, memory namespace sharing, and witness manifest entry per merge. The *safer-team-workflows* doc. |
  352. Benchmark internals (for reproduction): [`sota-workload-spec.md`](https://github.com/ruvnet/ruflo/blob/perf/sota-comparator-benchmarks/docs/benchmarks/sota-workload-spec.md) · [`SOTA-PROGRESS.md`](https://github.com/ruvnet/ruflo/blob/perf/sota-comparator-benchmarks/docs/benchmarks/SOTA-PROGRESS.md) · [raw matrix JSON: darwin](https://github.com/ruvnet/ruflo/blob/perf/sota-comparator-benchmarks/docs/benchmarks/sota-matrix.json) · [linux](https://github.com/ruvnet/ruflo/blob/perf/sota-comparator-benchmarks/docs/benchmarks/sota-matrix-linux.json)
  353. User Guide section index:
  354. | Section | Topics |
  355. |---------|--------|
  356. | [Quick Start](docs/USERGUIDE.md#quick-start) | Installation, prerequisites, install profiles |
  357. | [Core Features](docs/USERGUIDE.md#-core-features) | MCP tools, agents, memory, neural learning |
  358. | [Intelligence & Learning](docs/USERGUIDE.md#-intelligence--learning) | Hooks, workers, SONA, model routing |
  359. | [Swarm & Coordination](docs/USERGUIDE.md#-swarm--coordination) | Topologies, consensus, hive mind |
  360. | [Security](docs/USERGUIDE.md#%EF%B8%8F-security) | AIDefence, CVE remediation, validation |
  361. | [Ecosystem](docs/USERGUIDE.md#-ecosystem--integrations) | RuVector, agentic-flow, Flow Nexus |
  362. | [Configuration](docs/USERGUIDE.md#%EF%B8%8F-configuration--reference) | Environment variables, config schema |
  363. | [Plugin Marketplace](https://ruvnet.github.io/ruflo) | Browse and install plugins |
  364. ---
  365. ## Support
  366. <p align="center"><img src="docs/assets/readme/support.svg" alt="Build with the Ruflo community" width="100%"></p>
  367. | Resource | Link |
  368. |----------|------|
  369. | Documentation | [User Guide](docs/USERGUIDE.md) |
  370. | Issues & Bugs | [GitHub Issues](https://github.com/ruvnet/claude-flow/issues) |
  371. | Enterprise | [ruv.io](https://ruv.io) |
  372. | Community | [Agentics Foundation Discord](https://discord.com/invite/dfxmpwkG2D) |
  373. | Powered by | [Cognitum.one](https://cognitum.one) |
  374. <p align="center"><img src="docs/assets/readme/signal-divider.svg" alt="Ruflo" width="100%"></p>
  375. ## License
  376. MIT - [RuvNet](https://github.com/ruvnet)
  377. <a href="https://cognitum.one"><img src="docs/assets/readme/cognitum-banner-v2.svg" width="100%" alt="Cognitum One: Ambient Intelligence at the edge of the Physical World. Explore cognitum.one."></a>
.claude/helpers/hook-handler.cjs · Bundled script · 1,359 lines · 5 findings marked
  1. #!/usr/bin/env node
  2. /**
  3. * Claude Flow Hook Handler (Cross-Platform)
  4. * Dispatches hook events to the appropriate helper modules.
  5. *
  6. * Usage: node hook-handler.cjs <command> [args...]
  7. *
  8. * Commands:
  9. * route - Route a task to optimal agent (reads PROMPT from env/stdin)
  10. * pre-bash - Validate command safety before execution
  11. * post-edit - Record edit outcome for learning
  12. * session-restore - Restore previous session state
  13. * session-end - End session and persist state
  14. */
  15. const path = require('path');
  16. const fs = require('fs');
  17. const os = require('os');
  18. const helpersDir = __dirname;
  19. // The helper's own install root: the project for a project-local helper,
  20. // $HOME for a home-level one. CLI resolution starts here, never at the opened
  21. // project, so a home-level helper does not run code the project supplies.
  22. const helperRoot = path.resolve(helpersDir, '..', '..');
  23. // Resolve an installed @claude-flow/cli (or ruflo) bin — mirrors
  24. // statusline-generator.ts's resolveCliBin() candidate list, then looks for a
  25. // global install (resolveGlobalCliBin() below, #3368). Used only to spawn the
  26. // detached funnel-refresh helper below; failures are silent (no candidate
  27. // found just means the refresh falls back to npx).
  28. //
  29. // Verifies dist/src/index.js exists alongside bin/cli.js, not just the bin
  30. // itself — Claude Code's own plugin marketplace mechanism installs by
  31. // `git clone`/`git pull` with no build step, so `~/.claude/plugins/
  32. // marketplaces/ruflo` is a SOURCE-ONLY checkout by construction: bin/cli.js
  33. // is present on disk but importing dist/src/index.js throws
  34. // ERR_MODULE_NOT_FOUND on every real command (confirmed live — only
  35. // `--version` happens to survive it, since it reads package.json directly).
  36. // Without this check, resolveCliBinForHook() picked that doomed candidate
  37. // first every time and spawnDetachedFunnelRefresh() below had no fallback,
  38. // so the promo/disclosure row could never populate for any marketplace
  39. // install, on any OS.
  40. // session-restore asks up to three times (first-run enable, then the two
  41. // refreshes). The answer cannot change inside one short-lived hook process,
  42. // so resolve once: `undefined` means "not looked up yet", null means "no
  43. // local or global CLI — use npx".
  44. let cliBinCache;
  45. function resolveCliBinForHook() {
  46. if (cliBinCache === undefined) cliBinCache = resolveCliBinUncached();
  47. return cliBinCache;
  48. }
  49. function resolveCliBinUncached() {
  50. try {
  51. const home = os.homedir();
  52. const candidates = [
  53. path.join(home, '.claude', 'plugins', 'marketplaces', 'ruflo', 'bin', 'cli.js'),
  54. path.join(helperRoot, 'node_modules', '@claude-flow', 'cli', 'bin', 'cli.js'),
  55. path.join(helperRoot, 'node_modules', 'ruflo', 'bin', 'cli.js'),
  56. path.join(helperRoot, 'v3', '@claude-flow', 'cli', 'bin', 'cli.js'),
  57. // helpersDir is .claude/helpers/ inside the package itself when this
  58. // file is running from a real @claude-flow/cli install (not a project
  59. // that merely copied the helper) — its bin/ is two levels up.
  60. path.join(helpersDir, '..', '..', 'bin', 'cli.js'),
  61. ];
  62. for (const p of candidates) {
  63. if (isRunnableCli(p)) return p;
  64. }
  65. return resolveGlobalCliBin();
  66. } catch (e) { /* ignore */ }
  67. return null;
  68. }
  69. function isRunnableCli(p) {
  70. try {
  71. return fs.existsSync(p) && fs.existsSync(path.join(path.dirname(p), '..', 'dist', 'src', 'index.js'));
  72. } catch (e) { return false; }
  73. }
  74. // #3368: a global install — the README's `npm install -g ruflo@latest` — keeps
  75. // the CLI at <prefix>/lib/node_modules/ruflo/node_modules/@claude-flow/cli,
  76. // which none of the project-relative candidates above cover, so on those
  77. // machines every refresh fell back to npx: a second, separately cached copy
  78. // of the CLI that follows the registry's latest rather than the version the
  79. // user pinned (the same npx-cache skew as #3306), and that cannot start
  80. // offline on a cold cache.
  81. //
  82. // Three lookups, fs calls only (no child process), reached only after every
  83. // candidate above missed:
  84. // 1. npm's global prefix, resolved the way npm resolves it
  85. // (npmGlobalPrefix() below). First because it does not depend on PATH:
  86. // a hook inherits the host process's PATH, which need not contain the
  87. // prefix's bin/ even when the user's interactive shell does (observed:
  88. // the Claude Code process spawning hooks lacked ~/.npm-global/bin while
  89. // a login zsh on the same machine had it).
  90. // 2. `ruflo`, then `claude-flow`, on PATH — the order plugins/ruflo-core/
  91. // scripts/ruflo-hook.cjs uses — for globals npm did not install (yarn
  92. // classic, bun). Only a symlinked bin counts, and only when it lands in
  93. // a package that declares one of the three known names, so a wrapper
  94. // script or a version-manager shim (Volta) is never mistaken for an
  95. // install. The <dir>/node_modules/<name> layout npm uses on Windows,
  96. // where ruflo.cmd sits beside node_modules\ruflo (what resolveNpmShim()
  97. // in ruflo-hook.cjs maps), is only consulted on win32: on POSIX every
  98. // manager symlinks, and probing it there would follow a Windows install
  99. // exposed to WSL through the appended Windows PATH.
  100. // Relative PATH entries (`.` or an empty entry) are skipped, so a bare
  101. // `./ruflo` in the working directory is never picked up.
  102. // 3. ~/.npm-global, npm's documented no-sudo prefix, when 1 and 2 both
  103. // missed: the prefix setting may live where this hook's node never
  104. // reads it, and a wrapper script on PATH is skipped by 2.
  105. // `env`/`platform`/`execPath` are parameters so any layout is testable
  106. // from any OS.
  107. function resolveGlobalCliBin(env = process.env, platform = process.platform, execPath = process.execPath) {
  108. const prefix = npmGlobalPrefix(env, platform, execPath);
  109. if (prefix) {
  110. const hit = cliUnderPrefix(prefix, platform);
  111. if (hit) return hit;
  112. }
  113. const dirs = String(env.PATH || env.Path || '').split(platform === 'win32' ? ';' : ':');
  114. const exts = platform === 'win32' ? ['.cmd', ''] : [''];
  115. for (const name of ['ruflo', 'claude-flow']) {
  116. for (const dir of dirs) {
  117. if (!dir || !path.isAbsolute(dir)) continue;
  118. for (const ext of exts) {
  119. const shim = path.join(dir, name + ext);
  120. if (!fs.existsSync(shim)) continue;
  121. const roots = [];
  122. try {
  123. if (fs.lstatSync(shim).isSymbolicLink()) {
  124. const root = path.dirname(path.dirname(fs.realpathSync(shim)));
  125. if (isKnownPackageRoot(root)) roots.push(root);
  126. }
  127. } catch (e) { /* unreadable link — fall back to the layout roots */ }
  128. if (platform === 'win32') {
  129. roots.push(path.join(dir, 'node_modules', name));
  130. if (name === 'claude-flow') roots.push(path.join(dir, 'node_modules', '@claude-flow', 'cli'));
  131. }
  132. for (const root of roots) {
  133. const hit = cliInPackage(root);
  134. if (hit) return hit;
  135. }
  136. }
  137. }
  138. }
  139. // Last resort: ~/.npm-global, the prefix npm's own docs recommend for
  140. // global installs without sudo ("Resolving EACCES permissions errors").
  141. // The setting that points npm there can live where this hook's node never
  142. // looks (another node's builtin npmrc, or a wrapper script that sets it
  143. // per call), and a `ruflo` wrapper script on PATH is skipped above by
  144. // design. Without this, such a machine fell back to npx @latest on every
  145. // hook. Checked only after the configured prefix and PATH both miss, so it
  146. // can never override either.
  147. const home = env.HOME || env.USERPROFILE;
  148. if (home && path.isAbsolute(home)) {
  149. const hit = cliUnderPrefix(path.join(home, '.npm-global'), platform);
  150. if (hit) return hit;
  151. }
  152. return null;
  153. }
  154. // The CLI of a global install under an npm prefix: <prefix>/lib/node_modules
  155. // on POSIX, <prefix>\node_modules on Windows, trying the three published
  156. // package names in order.
  157. function cliUnderPrefix(prefix, platform) {
  158. const modules = platform === 'win32'
  159. ? path.join(prefix, 'node_modules')
  160. : path.join(prefix, 'lib', 'node_modules');
  161. for (const pkg of ['ruflo', 'claude-flow', path.join('@claude-flow', 'cli')]) {
  162. const hit = cliInPackage(path.join(modules, pkg));
  163. if (hit) return hit;
  164. }
  165. return null;
  166. }
  167. // A bin on PATH only counts as an install when the package it points into
  168. // declares one of the three published names. This is a narrower check than
  169. // resolveNpmShim() in ruflo-hook.cjs, which never reads `name`: that one takes
  170. // the package name from the shim's own filename, then validates package.json's
  171. // `bin` entry and that its realpath stays inside the package. Here the bin has
  172. // already been resolved to a package root, so the manifest `name` is what
  173. // identifies it.
  174. function isKnownPackageRoot(root) {
  175. try {
  176. const name = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf-8')).name;
  177. return name === 'ruflo' || name === 'claude-flow' || name === '@claude-flow/cli';
  178. } catch (e) { return false; }
  179. }
  180. // Map an installed ruflo / claude-flow / @claude-flow/cli package root to the
  181. // CLI it runs: <root>/bin/cli.js (@claude-flow/cli itself),
  182. // <root>/v3/@claude-flow/cli/bin/cli.js (the claude-flow umbrella bundles
  183. // it), or @claude-flow/cli in the node_modules npm nests inside <root> —
  184. // or, for the flat layout yarn classic and bun use, in the node_modules
  185. // folder that holds <root> itself. That is the dependency edge
  186. // ruflo/bin/ruflo.js's findCliPath() follows. The search stops at that one
  187. // enclosing node_modules: walking further up would reach unrelated trees,
  188. // such as a stray ~/node_modules left by an `npm i` in a home directory.
  189. // Every hit must still pass isRunnableCli().
  190. function cliInPackage(root) {
  191. if (!fs.existsSync(root)) return null;
  192. const candidates = [
  193. path.join(root, 'bin', 'cli.js'),
  194. path.join(root, 'v3', '@claude-flow', 'cli', 'bin', 'cli.js'),
  195. path.join(root, 'node_modules', '@claude-flow', 'cli', 'bin', 'cli.js'),
  196. ];
  197. for (let dir = path.dirname(root), i = 0; i < 4 && dir !== path.dirname(dir); i++, dir = path.dirname(dir)) {
  198. if (path.basename(dir) === 'node_modules') {
  199. candidates.push(path.join(dir, '@claude-flow', 'cli', 'bin', 'cli.js'));
  200. break;
  201. }
  202. }
  203. return candidates.find(isRunnableCli) || null;
  204. }
  205. // npm's global prefix without spawning npm (`npm prefix -g` measured 70-80 ms
  206. // per call, paid on every SessionStart that gets this far). Same precedence
  207. // npm applies:
  208. // 1. npm_config_prefix in the environment (npm accepts either case);
  209. // 2. `prefix=` in the user npmrc ($npm_config_userconfig, else ~/.npmrc),
  210. // where `npm config set prefix ~/.npm-global` (the npm docs' fix for
  211. // EACCES on global installs) writes it;
  212. // 3. `prefix=` in npm's builtin npmrc (<npm package>/npmrc), found through
  213. // the `npm` link beside node: Homebrew writes `prefix = /opt/homebrew`
  214. // there (its process.execPath is the Cellar path, so step 4 alone would
  215. // be wrong), and the Node.js Windows installer ships
  216. // `prefix=${APPDATA}\npm`;
  217. // 4. npm's default: $PREFIX, else the directory above node's bin/ (POSIX)
  218. // or node.exe's own directory (Windows).
  219. // Values follow npm's ini handling for the cases that decide a path: a
  220. // quoted value is taken literally, an unquoted `;`/`#` starts a comment,
  221. // keys below a `[section]` header are ignored, `${VAR}` expands when the
  222. // variable is set (and `${VAR?}` to empty when it is not) but otherwise
  223. // stays literal like npm — which leaves the value relative, so the
  224. // isAbsolute() check below rejects it instead of pointing at the drive root.
  225. // Not emulated: escaped characters and npm's other ini corner cases; each of
  226. // those produces a miss, never a wrong CLI. The npmrc is read into memory,
  227. // but only the value of its last top-level `prefix =` line is kept: no other
  228. // line (an `_authToken`, say) is returned, stored or logged.
  229. function npmGlobalPrefix(env = process.env, platform = process.platform, execPath = process.execPath) {
  230. const home = (platform === 'win32' ? env.USERPROFILE : env.HOME) || os.homedir();
  231. const readPrefix = (file) => {
  232. let value = null;
  233. try {
  234. for (const line of fs.readFileSync(file, 'utf-8').split(/\r?\n/)) {
  235. if (/^\s*\[/.test(line)) break; // only the top-level section applies
  236. const m = /^\s*prefix\s*=\s*(.*?)\s*$/.exec(line);
  237. if (m) value = m[1]; // last one wins, as in npm's ini parser
  238. }
  239. } catch (e) { /* no such npmrc */ }
  240. return value;
  241. };
  242. const nodeDir = path.dirname(execPath);
  243. // npm's builtin npmrc sits in npm's own package dir. On Windows that is
  244. // node_modules\npm beside node.exe; elsewhere follow the `npm` link beside
  245. // node (<npm>/bin/npm-cli.js) — on Homebrew it points out of the node keg
  246. // to /opt/homebrew/lib/node_modules/npm.
  247. let builtinRc = path.join(nodeDir, 'node_modules', 'npm', 'npmrc');
  248. if (platform !== 'win32') {
  249. try {
  250. builtinRc = path.join(path.dirname(path.dirname(fs.realpathSync(path.join(nodeDir, 'npm')))), 'npmrc');
  251. } catch (e) { /* no npm beside node */ }
  252. }
  253. const raw = env.npm_config_prefix || env.NPM_CONFIG_PREFIX
  254. || readPrefix(env.npm_config_userconfig || env.NPM_CONFIG_USERCONFIG || path.join(home, '.npmrc'))
  255. || readPrefix(builtinRc)
  256. || env.PREFIX
  257. || (platform === 'win32' ? nodeDir : path.dirname(nodeDir));
  258. let value = String(raw).trim();
  259. const quoted = /^(["'])([\s\S]*)\1$/.exec(value);
  260. if (quoted) value = quoted[2];
  261. else value = value.replace(/(^|[^\\])[;#].*$/, '$1').trim();
  262. value = value
  263. .replace(/\$\{([^}?]+)(\?)?\}/g, (whole, name, optional) => (
  264. env[name] !== undefined ? env[name] : (optional ? '' : whole)
  265. ))
  266. .replace(/^~(?=$|[\\/])/, home);
  267. return path.isAbsolute(value) ? path.resolve(value) : null;
  268. }
  269. // Fire-and-forget doesn't work when the CALLER is itself a short-lived
  270. // subprocess (confirmed live: two consecutive statusline renders 5s apart
  271. // both saw an empty funnel-messages-cache, because the async HTTPS fetch
  272. // inside a `void refreshRemoteMessages()` call gets killed when the spawning
  273. // process exits before the request completes). Spawning fully DETACHED +
  274. // unref'd decouples the refresh's lifetime from this hook's — it keeps
  275. // running (up to message-transport.ts's own 4s fetch timeout) even after
  276. // session-restore's own process has already exited, so it actually gets a
  277. // chance to write the cache. Never awaited here — must not add to
  278. // SessionStart's own timeout budget.
  279. //
  280. // No usable local or global candidate (resolveCliBinForHook() returned null)
  281. // falls back to npx: this call is detached/unref'd, so a slower npx cold-start
  282. // costs nothing perceptible — unlike the statusline's own synchronous
  283. // render path, where local-first exists purely for per-render latency.
  284. // `--prefer-offline` avoids a registry round trip for the tarball when
  285. // already cached while still resolving the current `@latest` version.
  286. //
  287. // `--prefix helperRoot` makes npx resolve @claude-flow/cli from the helper's
  288. // install root instead of the cwd (the opened project); the spawned CLI still
  289. // runs with the project as its cwd.
  290. function cliSpawnArgs(cliBin, args, platform = process.platform) {
  291. if (cliBin) return [process.execPath, [cliBin, ...args]];
  292. return [platform === 'win32' ? 'npx.cmd' : 'npx', ['--prefer-offline', '--prefix', helperRoot, '@claude-flow/cli', ...args]];
  293. }
  294. function spawnDetachedHookRefresh(subcommand) {
  295. try {
  296. const { spawn } = require('child_process');
  297. const spawnArgs = cliSpawnArgs(resolveCliBinForHook(), ['hooks', subcommand, '--quiet']);
  298. const child = spawn(spawnArgs[0], spawnArgs[1], {
  299. detached: true,
  300. stdio: 'ignore',
  301. env: process.env,
  302. windowsHide: true,
  303. });
  304. child.unref();
  305. } catch (e) { /* best-effort only */ }
  306. }
  307. function spawnDetachedFunnelRefresh() {
  308. spawnDetachedHookRefresh('refresh-funnel');
  309. }
  310. // ADR-318/319: first-run auto-enable of spinner verbs (default ON) +
  311. // announcements (default OFF, explicit opt-in). Fires ONCE per install
  312. // (marker at ~/.ruflo/first-run-enabled.json), then never again —
  313. // subsequent sessions see the marker and skip.
  314. //
  315. // Split posture rationale:
  316. // - Spinner verbs = low-intrusion (per-spin flash, append-mode mix
  317. // with Claude Code defaults, moderate visibility over time). Default ON.
  318. // Disclosure notification + one-command disable satisfies the ethical bar.
  319. // - Announcements = higher-intrusion (prominent line at every Claude Code
  320. // startup, more attention per view). Default OFF; opt-in via
  321. // RUFLO_AUTO_ENABLE_ANNOUNCEMENTS=1 or explicit `ruflo announcements enable`.
  322. //
  323. // Gates (spinner is default-on unless any is TRUE):
  324. // - RUFLO_NO_AUTO_ENABLE truthy (master opt-out — kills both)
  325. // - RUFLO_NO_AUTO_ENABLE_SPINNER truthy (spinner-only opt-out)
  326. // - CI / GITHUB_ACTIONS truthy
  327. // - stdout is not a TTY (piped, non-interactive)
  328. // - Marker file already exists
  329. //
  330. // Announcements needs the same gates PLUS RUFLO_AUTO_ENABLE_ANNOUNCEMENTS=1.
  331. //
  332. // Marker is written even if the spawns fail — auto-enable is a "we tried once"
  333. // contract, not "keep trying until success." Users can run enable manually.
  334. function firstRunAutoEnableIfEligible() {
  335. try {
  336. const path = require('path');
  337. const fs = require('fs');
  338. const os = require('os');
  339. const truthy = (v) => v && !/^(0|false|off|no)$/i.test(String(v));
  340. if (truthy(process.env.RUFLO_NO_AUTO_ENABLE)) return;
  341. if (process.env.CI || process.env.GITHUB_ACTIONS) return;
  342. if (process.stdout && process.stdout.isTTY === false) return;
  343. const markerPath = path.join(os.homedir(), '.ruflo', 'first-run-enabled.json');
  344. if (fs.existsSync(markerPath)) return;
  345. const enableSpinner = !truthy(process.env.RUFLO_NO_AUTO_ENABLE_SPINNER);
  346. const enableAnnouncements = truthy(process.env.RUFLO_AUTO_ENABLE_ANNOUNCEMENTS);
  347. // Nothing to do — user opted out of both. Skip marker write so if they
  348. // change their mind and re-enable env vars later, first-run still fires.
  349. if (!enableSpinner && !enableAnnouncements) return;
  350. // Spawn the enable commands detached + non-blocking. Any failure
  351. // (missing CLI, refused state, etc.) is silent — auto-enable is
  352. // best-effort and MUST NOT block session-restore. Uses execPath +
  353. // resolved cli.js directly rather than spawnDetachedHookRefresh
  354. // because that helper hardcodes 'hooks' as the top-level command.
  355. const { spawn } = require('child_process');
  356. const cliBin = resolveCliBinForHook();
  357. const runDetached = (args) => {
  358. try {
  359. const spawnArgs = cliSpawnArgs(cliBin, args);
  360. const child = spawn(spawnArgs[0], spawnArgs[1], {
  361. detached: true, stdio: 'ignore', env: process.env, windowsHide: true,
  362. });
  363. child.unref();
  364. } catch { /* best-effort */ }
  365. };
  366. if (enableSpinner) runDetached(['spinner', 'enable', '--yes']);
  367. if (enableAnnouncements) runDetached(['announcements', 'enable', '--yes']);
  368. try {
  369. fs.mkdirSync(path.dirname(markerPath), { recursive: true, mode: 0o700 });
  370. fs.writeFileSync(
  371. markerPath,
  372. JSON.stringify({
  373. _ts: Date.now(),
  374. source: 'session-restore-hook',
  375. enabled: { spinner: enableSpinner, announcements: enableAnnouncements },
  376. }, null, 2),
  377. { encoding: 'utf-8', mode: 0o600 }
  378. );
  379. } catch { /* ignore — best effort */ }
  380. // Notification tells user exactly what happened. stderr so it doesn't
  381. // corrupt any downstream JSON stdout consumer.
  382. try {
  383. const parts = [];
  384. if (enableSpinner) parts.push('spinner verbs');
  385. if (enableAnnouncements) parts.push('startup announcements');
  386. const disableCmds = [];
  387. if (enableSpinner) disableCmds.push('`ruflo spinner disable`');
  388. if (enableAnnouncements) disableCmds.push('`ruflo announcements disable`');
  389. process.stderr.write(
  390. '[ruflo] First-run: enabled ' + parts.join(' + ') + '. ' +
  391. 'Disable anytime with ' + disableCmds.join(' / ') + '. ' +
  392. (enableSpinner && !enableAnnouncements
  393. ? 'Announcements stay opt-in — set RUFLO_AUTO_ENABLE_ANNOUNCEMENTS=1 to enable those too. '
  394. : '') +
  395. 'Restart Claude Code once to see the changes take effect.\n'
  396. );
  397. } catch { /* ignore */ }
  398. } catch { /* auto-enable must never break session-restore */ }
  399. }
  400. // Same fallback-aware pattern as spawnDetachedFunnelRefresh() above, for
  401. // ADR-316's co-pilot advisor tip. Safe to call on EVERY session-restore:
  402. // refresh-advisor's own action checks consent + a 24h TTL BEFORE spending
  403. // anything, so an unconsented or already-fresh install is a fast no-op file
  404. // read, never a network call. Never awaited here — must not add to
  405. // SessionStart's own timeout budget.
  406. function spawnDetachedAdvisorRefresh() {
  407. spawnDetachedHookRefresh('refresh-advisor');
  408. }
  409. // ── Settings-risk scan for the automatic SessionStart hook ────────────────
  410. //
  411. // Mirrors v3/@claude-flow/cli/src/init/settings-risk-scanner.ts's
  412. // `scanSettingsForRisk()`/`formatRiskFindingsAsWarnings()`. That TS scanner
  413. // already runs at `ruflo init`/`--upgrade` time and (via the
  414. // `hooks_session-restore` MCP/CLI tool handler) on an explicit
  415. // `session-restore` call — but neither covers the one path that actually
  416. // fires automatically, unconditionally, on every real Claude Code session
  417. // boot: THIS file, invoked as the `SessionStart` hook configured in
  418. // .claude/settings.json itself. That is precisely the persistence mechanism
  419. // used by the real 2026 "Mini Shai-Hulud" npm-worm campaign (a malicious
  420. // SessionStart hook written into settings.json re-fires on every session,
  421. // surviving removal of the original infected package) and the escalation
  422. // path closed by CVE-2026-25725 in Claude Code's own sandbox. hook-handler.cjs
  423. // has no build step and cannot import the TS module, so this is a deliberate
  424. // CJS port — keep the pattern lists in sync with settings-risk-scanner.ts;
  425. // see the logic-parity test guarding this.
  426. //
  427. // Advisory-only: never mutates settings.json, never blocks session-restore.
  428. // A missing settings.json or any JSON.parse failure yields zero findings
  429. // silently. Unlike the opt-in `hooks_session-restore` MCP-tool path (#3835,
  430. // which narrows its catch to SyntaxError only so a real scanner bug
  431. // surfaces), THIS path fires unconditionally on every real session boot —
  432. // an adversarial review of this exact candidate flagged that narrowing the
  433. // same way here would let a non-SyntaxError JSON.parse failure (e.g. a V8
  434. // RangeError on deeply-nested JSON) abort session-restore itself, not just
  435. // skip the scan. "Can't scan it" and "can't parse it" are the same case
  436. // here, so any parse failure degrades to zero findings.
  437. const SR_DANGEROUS_COMMAND_WORDS = [
  438. 'rm', 'rmdir', 'del', 'format', 'mkfs', 'dd', 'chmod', 'chown',
  439. 'kill', 'killall', 'pkill', 'reboot', 'shutdown', 'poweroff', 'halt',
  440. 'sudo', 'eval',
  441. ];
  442. const SR_SHELL_EXEC_WORDS = ['bash', 'sh', 'zsh', 'python', 'python3', 'perl', 'ruby', 'eval'];
  443. const SR_DOWNLOADER_WORDS = ['curl', 'wget'];
  444. const SR_STANDALONE_RISK_PATTERNS = [
  445. /\bInvoke-Expression\b/i,
  446. /\biex\s*\(/i,
  447. /\/dev\/tcp\//i,
  448. /\bnc\s+-e\b/i,
  449. /base64\s+(-d|--decode)\b/i,
  450. ];
  451. const SR_RISKY_PREAPPROVE_WORDS = [...SR_DANGEROUS_COMMAND_WORDS, ...SR_SHELL_EXEC_WORDS, ...SR_DOWNLOADER_WORDS];
  452. // Encoded PowerShell (`powershell[.exe] ... -e|-enc|-encodedcommand <payload>`),
  453. // matched on whitespace-separated tokens in ONE linear pass. The earlier regex
  454. // (`powershell\\s+(?:\\S+\\s+)*?-e...`) is quadratic on repeated "powershell "
  455. // tokens (every start rescans the tail: 256KB measured ~2.5s, 1MB ~40s) because
  456. // the lazy token loop re-runs from each start. Same semantics: a token ending in
  457. // powershell/powershell.exe, then LATER a token that is exactly -e/-enc/
  458. // -encodedcommand, then at least one more token.
  459. function srHasEncodedPowershell(command) {
  460. let seenPs = false;
  461. let pendingEnc = false;
  462. for (const raw of String(command).split(/\s+/)) {
  463. if (!raw) continue;
  464. if (pendingEnc) return true;
  465. const t = raw.toLowerCase();
  466. if (seenPs && (t === '-e' || t === '-enc' || t === '-encodedcommand')) pendingEnc = true;
  467. else if (t.endsWith('powershell') || t.endsWith('powershell.exe')) seenPs = true;
  468. }
  469. return false;
  470. }
  471. function srWordBoundaryMatches(text, word) {
  472. return new RegExp(`\\b${word}\\b`, 'i').test(text);
  473. }
  474. function srScanCommandStringForRisk(command) {
  475. const reasons = [];
  476. if (srHasEncodedPowershell(command) || SR_STANDALONE_RISK_PATTERNS.some((pattern) => pattern.test(command))) {
  477. reasons.push('matches a known-dangerous execution pattern (encoded/remote command execution)');
  478. }
  479. const hasDownloader = SR_DOWNLOADER_WORDS.some((w) => srWordBoundaryMatches(command, w));
  480. const hasShellExec = SR_SHELL_EXEC_WORDS.some((w) => srWordBoundaryMatches(command, w));
  481. if (hasDownloader && hasShellExec) {
  482. reasons.push('combines a downloader (curl/wget) with a shell/interpreter invocation in the same command');
  483. }
  484. for (const word of SR_DANGEROUS_COMMAND_WORDS) {
  485. if (srWordBoundaryMatches(command, word)) {
  486. reasons.push(`invokes dangerous command "${word}"`);
  487. }
  488. }
  489. return reasons;
  490. }
  491. function srScanAllowRuleForRisk(rule) {
  492. const trimmed = rule.trim();
  493. const reasons = [];
  494. if (/^Bash\(\s*\*\s*(:\s*\*\s*)?\)$/i.test(trimmed)) {
  495. reasons.push('grants unrestricted Bash execution (wildcard allow rule)');
  496. }
  497. for (const word of SR_RISKY_PREAPPROVE_WORDS) {
  498. if (new RegExp(`^Bash\\(\\s*${word}\\s*(:| |\\))`, 'i').test(trimmed)) {
  499. reasons.push(`pre-allows "${word}" with no per-call confirmation`);
  500. }
  501. }
  502. return reasons;
  503. }
  504. // Strips ANSI/control characters from untrusted text before it's ever
  505. // embedded in a warning string printed to the terminal (same rationale as
  506. // settings-risk-scanner.ts's sanitizeForDisplay()).
  507. function srSanitizeForDisplay(text) {
  508. // eslint-disable-next-line no-control-regex
  509. return text.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '');
  510. }
  511. function srBuildSnippet(text) {
  512. const clean = srSanitizeForDisplay(text);
  513. return clean.length > 120 ? `${clean.slice(0, 120)}…` : clean;
  514. }
  515. function srScanSettingsForRisk(settings) {
  516. const findings = [];
  517. const hooks = settings && settings.hooks;
  518. if (hooks && typeof hooks === 'object') {
  519. for (const [eventName, groups] of Object.entries(hooks)) {
  520. if (!Array.isArray(groups)) continue;
  521. groups.forEach((group, groupIdx) => {
  522. const hookList = group && group.hooks;
  523. if (!Array.isArray(hookList)) return;
  524. hookList.forEach((h, hookIdx) => {
  525. if (!h || typeof h.command !== 'string') return;
  526. for (const reason of srScanCommandStringForRisk(h.command)) {
  527. findings.push({
  528. location: `hooks.${eventName}[${groupIdx}].hooks[${hookIdx}]`,
  529. snippet: srBuildSnippet(h.command),
  530. reason,
  531. });
  532. }
  533. });
  534. });
  535. }
  536. }
  537. const allow = settings && settings.permissions && settings.permissions.allow;
  538. if (Array.isArray(allow)) {
  539. allow.forEach((rule, idx) => {
  540. if (typeof rule !== 'string') return;
  541. for (const reason of srScanAllowRuleForRisk(rule)) {
  542. findings.push({
  543. location: `permissions.allow[${idx}]`,
  544. snippet: srBuildSnippet(rule),
  545. reason,
  546. });
  547. }
  548. });
  549. }
  550. return findings;
  551. }
  552. function srFormatRiskFindingsAsWarnings(findings) {
  553. return findings.map((f) => `${f.location}: ${f.reason} — "${f.snippet}"`);
  554. }
  555. // Location + reason only, no snippet — see scanSessionStartSettingsForRisk's
  556. // doc comment for why the automatic boot path deliberately drops it.
  557. function srFormatRiskFindingsForAutomaticBoot(findings) {
  558. return findings.map((f) => `${f.location}: ${f.reason}`);
  559. }
  560. // Reads and scans THIS project's own .claude/settings.json. Returns a
  561. // (possibly empty) array of warning strings; never throws on a
  562. // missing/malformed file.
  563. //
  564. // Deliberately omits the matched snippet (unlike srFormatRiskFindingsAsWarnings,
  565. // which `init`/`--upgrade` uses and which DOES include it): this function's
  566. // only caller is the 'session-restore' handler below, whose stdout is read
  567. // back into the live Claude Code session as context — not a human reading a
  568. // terminal. Printing up to 120 characters of attacker-controlled settings.json
  569. // content into that context is a prompt-injection path even with control
  570. // characters stripped (flagged by review on PR #4053). The location and
  571. // static reason string are both scanner-generated, never attacker content.
  572. function scanSessionStartSettingsForRisk() {
  573. const projectRoot = process.env.CLAUDE_PROJECT_DIR || process.cwd();
  574. const settingsPath = path.join(projectRoot, '.claude', 'settings.json');
  575. let raw;
  576. try {
  577. raw = fs.readFileSync(settingsPath, 'utf-8');
  578. } catch (e) {
  579. return []; // no settings.json (or unreadable) — nothing to scan
  580. }
  581. let settings;
  582. try {
  583. settings = JSON.parse(raw);
  584. } catch (e) {
  585. return []; // can't parse it, so can't scan it — never block session-restore for this
  586. }
  587. if (!settings || typeof settings !== 'object') return [];
  588. return srFormatRiskFindingsForAutomaticBoot(srScanSettingsForRisk(settings));
  589. }
  590. // Safe require with stdout suppression - the helper modules have CLI
  591. // sections that run unconditionally on require(), so we mute console
  592. // during the require to prevent noisy output.
  593. function safeRequire(modulePath) {
  594. try {
  595. if (fs.existsSync(modulePath)) {
  596. const origLog = console.log;
  597. const origError = console.error;
  598. console.log = () => {};
  599. console.error = () => {};
  600. try {
  601. const mod = require(modulePath);
  602. return mod;
  603. } finally {
  604. console.log = origLog;
  605. console.error = origError;
  606. }
  607. }
  608. } catch (e) {
  609. // silently fail
  610. }
  611. return null;
  612. }
  613. const router = safeRequire(path.join(helpersDir, 'router.cjs'));
  614. const session = safeRequire(path.join(helpersDir, 'session.cjs'));
  615. const memory = safeRequire(path.join(helpersDir, 'memory.cjs'));
  616. const intelligence = safeRequire(path.join(helpersDir, 'intelligence.cjs'));
  617. // ADR-512: the verified-outcome learning loop, bundled from the ruflo-mods loop source.
  618. const learningLoop = safeRequire(path.join(helpersDir, 'learning-loop.cjs'));
  619. // ── Intelligence timeout protection (fixes #1530, #1531) ───────────────────
  620. const INTELLIGENCE_TIMEOUT_MS = 3000;
  621. // Race the (possibly-async) work against a real timeout. The previous version
  622. // called fn() and clearTimeout(timer) immediately, so an async fn returned a
  623. // pending promise that resolved THROUGH the race — the timeout protected
  624. // nothing. This settles on whichever finishes first, then clears the timer.
  625. //
  626. // LIMITATION: a synchronous blocking fn (the current intelligence.init() does
  627. // blocking fs reads) cannot be interrupted by any in-process timer — the event
  628. // loop is blocked. The real guard for that case is the readJSON file-size
  629. // limit in intelligence.cjs. This util only bounds work that yields (async I/O).
  630. function runWithTimeout(fn, label) {
  631. let timer;
  632. const timeout = new Promise((resolve) => {
  633. timer = setTimeout(() => {
  634. process.stderr.write("[WARN] " + label + " timed out after " + INTELLIGENCE_TIMEOUT_MS + "ms, skipping\n");
  635. resolve(null);
  636. }, INTELLIGENCE_TIMEOUT_MS);
  637. });
  638. const work = Promise.resolve().then(fn).catch(() => null);
  639. return Promise.race([work, timeout]).then((result) => {
  640. clearTimeout(timer);
  641. return result;
  642. });
  643. }
  644. // Get the command from argv
  645. const [,, command, ...args] = process.argv;
  646. // Read stdin with timeout — Claude Code sends hook data as JSON via stdin.
  647. // Timeout prevents hanging when stdin is not properly closed (common on Windows).
  648. async function readStdin(windowMs = 500) {
  649. if (process.stdin.isTTY) return '';
  650. return new Promise((resolve) => {
  651. let data = '';
  652. const timer = setTimeout(() => {
  653. process.stdin.removeAllListeners();
  654. process.stdin.pause();
  655. resolve(data);
  656. }, windowMs);
  657. process.stdin.setEncoding('utf8');
  658. process.stdin.on('data', (chunk) => { data += chunk; });
  659. process.stdin.on('end', () => { clearTimeout(timer); resolve(data); });
  660. process.stdin.on('error', () => { clearTimeout(timer); resolve(data); });
  661. process.stdin.resume();
  662. });
  663. }
  664. // ADR-404: the ruflo mod (plugins/ruflo-mods) runs these events in-process
  665. // inside Claude Code and sets RUFLO_MODS_OWNS on the process, which every hook
  666. // started after inherits. An event named there is the mod's; returning here
  667. // keeps it from firing twice. Only side-effect events can be handed over:
  668. // guards such as pre-bash always run, whatever the variable says.
  669. const MOD_OWNABLE_EVENTS = new Set(['route', 'post-edit']);
  670. // ADR-512: classic hooks run the verified-outcome learning loop for users without the mod. A
  671. // mod that records turns itself says so with `learning-loop` (or, before ADR-512, owns
  672. // `route`), so a turn is never recorded twice.
  673. function modRecordsTurns(env = process.env) {
  674. return String(env.RUFLO_MODS_OWNS || '').split(',').some((owned) => ['learning-loop', 'route'].includes(owned.trim()));
  675. }
  676. function learningLoopRoot() {
  677. return process.env.CLAUDE_PROJECT_DIR || process.cwd();
  678. }
  679. // Records the turns the session transcript gained since the last look (all of them when the
  680. // session ends). Returns the number recorded; never throws.
  681. function recordLearningTurns(hookInput, final) {
  682. try {
  683. const root = learningLoopRoot();
  684. if (!learningLoop || modRecordsTurns() || !learningLoop.enabled(root)) return 0;
  685. const agentFor = (text) => {
  686. try { return (router && router.routeTask && router.routeTask(text).agent) || 'coder'; } catch (e) { return 'coder'; }
  687. };
  688. return learningLoop.recordTurns({
  689. root,
  690. transcriptPath: hookInput.transcript_path || hookInput.transcriptPath,
  691. session: hookInput.session_id || hookInput.sessionId,
  692. final,
  693. agentFor,
  694. });
  695. } catch (e) { return 0; }
  696. }
  697. // Trains SONA from the recorded turns in a detached `ruflo hooks verified-ingest` (a hook has
  698. // seconds; an ingest may take longer). At most one spawn a minute per project.
  699. function spawnLearningIngest() {
  700. try {
  701. const root = learningLoopRoot();
  702. if (!learningLoop || !learningLoop.enabled(root) || !learningLoop.ingestDue(root)) return;
  703. const stamp = path.join(root, '.claude-flow', 'data', 'verified-ingest.spawned');
  704. try { if (Date.now() - fs.statSync(stamp).mtimeMs < 60 * 1000) return; } catch (e) { /* never spawned */ }
  705. fs.mkdirSync(path.dirname(stamp), { recursive: true });
  706. fs.writeFileSync(stamp, String(Date.now()));
  707. spawnDetachedHookRefresh('verified-ingest');
  708. } catch (e) { /* best-effort only */ }
  709. }
  710. function ownedByMod(cmd, env = process.env) {
  711. if (!MOD_OWNABLE_EVENTS.has(cmd)) return false;
  712. return String(env.RUFLO_MODS_OWNS || '').split(',').some((owned) => owned.trim() === cmd);
  713. }
  714. function claimSideEffectEvent(family, stdinData, event) {
  715. if (/^(1|true|yes|on)$/i.test(process.env.RUFLO_DISABLE_HOOK_DEDUP || '')) return true;
  716. try {
  717. const crypto = require('crypto');
  718. const eventId = event?.tool_use_id || event?.toolUseId ||
  719. event?.session_id || event?.sessionId || event?.hook_event_id;
  720. const payloadIdentity = eventId
  721. ? `event:${eventId}`
  722. : `payload:${(stdinData || '').trim()}|bucket:${Math.floor(Date.now() / 2000)}`;
  723. const projectRoot = process.env.CLAUDE_PROJECT_DIR || process.cwd();
  724. const digest = crypto.createHash('sha256')
  725. .update(`ruflo-hook-dedup-v1\0${path.resolve(projectRoot)}\0${family}\0${payloadIdentity}`)
  726. .digest('hex');
  727. const dir = process.env.RUFLO_HOOK_DEDUP_DIR ||
  728. path.join(os.tmpdir(), 'ruflo-hook-dedup-v1');
  729. fs.mkdirSync(dir, { recursive: true });
  730. const fd = fs.openSync(path.join(dir, digest), 'wx', 0o600);
  731. fs.writeFileSync(fd, String(Date.now()));
  732. fs.closeSync(fd);
  733. return true;
  734. } catch (error) {
  735. return error?.code === 'EEXIST' ? false : true;
  736. }
  737. }
  738. // pre-bash is a gate (#4743): a path that cannot vouch for the command blocks it.
  739. function blockPreBash(reason) {
  740. console.error(`[BLOCKED] ${reason}`);
  741. process.exit(2);
  742. }
  743. async function main() {
  744. if (ownedByMod(command)) return;
  745. // Global safety timeout: hooks must NEVER hang (#1530, #1531)
  746. const safetyTimer = setTimeout(() => {
  747. process.stderr.write("[WARN] Hook handler global timeout (5s), forcing exit\n");
  748. if (command === 'pre-bash') blockPreBash('pre-bash timed out before the command was validated');
  749. process.exit(0);
  750. }, 5000);
  751. safetyTimer.unref(); // don't keep process alive just for this timer
  752. let stdinData = '';
  753. // pre-bash blocks when it gets no command (#4743), so a slow host gets a
  754. // wider window. The read ends at EOF, so a prompt host waits no longer.
  755. try { stdinData = await readStdin(command === 'pre-bash' ? 3000 : 500); } catch (e) { /* ignore stdin errors */ }
  756. let hookInput = {};
  757. let stdinUnparsable = false;
  758. if (stdinData.trim()) {
  759. try { hookInput = JSON.parse(stdinData); } catch (e) { stdinUnparsable = true; }
  760. }
  761. // ADR-512: record what finished and train from it, before the dedup below: it keys session-end
  762. // on the session id, so after a PreCompact the real SessionEnd would never record the last turn.
  763. // Recording is idempotent (a per-session transcript offset, ids from transcript positions).
  764. // PreCompact runs mid-session, where the open turn may still edit and verify: only SessionEnd
  765. // closes it.
  766. if (command === 'session-end') {
  767. recordLearningTurns(hookInput, (hookInput.hook_event_name || hookInput.hookEventName) !== 'PreCompact');
  768. spawnLearningIngest();
  769. }
  770. if ((command === 'post-edit' || command === 'session-end') &&
  771. !claimSideEffectEvent(command, stdinData, hookInput)) {
  772. return;
  773. }
  774. // Normalize snake_case/camelCase: Claude Code sends tool_input/tool_name (snake_case)
  775. const toolInput = hookInput.toolInput || hookInput.tool_input || {};
  776. const toolName = hookInput.toolName || hookInput.tool_name || '';
  777. // Merge stdin data into prompt resolution: prefer stdin fields, then env, then argv.
  778. // `toolInput` is an object (e.g. {command:"ls"}) — it's truthy but not a string,
  779. // so falling back to it directly bound `prompt` to the object and tripped
  780. // `.toLowerCase()` / `.substring()` on every Bash hook (#1944). Use the
  781. // `.command` field instead, which is the actual string the hook needs.
  782. const prompt = hookInput.prompt || hookInput.command || toolInput.command
  783. || process.env.PROMPT || process.env.TOOL_INPUT_command || args.join(' ') || '';
  784. // ADR-174: capture FAILURES so the learning substrate has negative examples.
  785. // Claude Code's PostToolUse payload carries the tool result; a failed
  786. // Write/Edit/Bash surfaces as tool_response.is_error / an error string /
  787. // a non-zero exit code. Conservative — only a positive error signal counts
  788. // as failure (mirrors isToolFailure() in helpers-generator.ts).
  789. const toolFailed = (function (hi) {
  790. if (!hi || typeof hi !== 'object') return false;
  791. const tr = hi.tool_response != null ? hi.tool_response : (hi.toolResponse != null ? hi.toolResponse : hi.result);
  792. if (tr == null) return false;
  793. if (typeof tr === 'string') return /\b(error|failed|failure|exception|not found|no such|permission denied|traceback)\b/i.test(tr);
  794. if (typeof tr === 'object') {
  795. if (tr.is_error === true || tr.isError === true || tr.success === false || tr.error != null) return true;
  796. const code = tr.exit_code != null ? tr.exit_code : (tr.exitCode != null ? tr.exitCode : tr.code);
  797. if (typeof code === 'number' && code !== 0) return true;
  798. if (Array.isArray(tr.content) && tr.is_error === true) return true;
  799. }
  800. return false;
  801. })(hookInput);
  802. const handlers = {
  803. 'route': () => {
  804. // ADR-512: record the turns that finished, then cite the verified lessons that fit this prompt.
  805. recordLearningTurns(hookInput, false);
  806. if (learningLoop && !modRecordsTurns()) {
  807. try {
  808. if (learningLoop.enabled(learningLoopRoot())) {
  809. const block = learningLoop.lessonsForPrompt(learningLoopRoot(), prompt);
  810. if (block) console.log(block);
  811. }
  812. } catch (e) { /* non-fatal */ }
  813. }
  814. // Inject ranked intelligence context before routing
  815. // ADR-472: keep the detailed recall so ONE bounded log record (ids, scores, router pick; never the prompt) is appended after routing.
  816. let recall = null;
  817. if (intelligence && (intelligence.getContextDetailed || intelligence.getContext)) {
  818. try {
  819. if (intelligence.getContextDetailed) {
  820. recall = intelligence.getContextDetailed(prompt);
  821. if (recall && recall.text) console.log(recall.text);
  822. } else {
  823. const ctx = intelligence.getContext(prompt);
  824. if (ctx) console.log(ctx);
  825. }
  826. } catch (e) { /* non-fatal */ }
  827. }
  828. const logRecall = (result) => {
  829. try {
  830. if (recall && intelligence.appendRecall) {
  831. intelligence.appendRecall(recall, {
  832. sessionId: hookInput.session_id || hookInput.sessionId || null,
  833. agent: result && result.agent,
  834. confidence: result && result.confidence,
  835. });
  836. }
  837. } catch (e) { /* non-fatal: the log never blocks a prompt */ }
  838. };
  839. if (router && router.routeTask) {
  840. const result = router.routeTask(prompt);
  841. logRecall(result);
  842. // Format output for Claude Code hook consumption — real data only
  843. const row = (text) => `| ${text.substring(0, 60).padEnd(60)} |`;
  844. const output = [
  845. `[INFO] Routing task: ${prompt.substring(0, 80) || '(no prompt)'}`,
  846. '',
  847. '+------------------- Primary Recommendation -------------------+',
  848. row(`Agent: ${result.agent}`),
  849. row(`Confidence: ${(result.confidence * 100).toFixed(1)}%`),
  850. row(`Reason: ${result.reason || ''}`),
  851. '+--------------------------------------------------------------+',
  852. ];
  853. console.log(output.join('\n'));
  854. } else {
  855. logRecall(null);
  856. console.log('[INFO] Router not available, using default routing');
  857. }
  858. // Rate-limit -> sponsored-capacity nudge (ADR-312/313). Fires here,
  859. // client-side, BEFORE the API call this prompt would make — so it still
  860. // reaches the transcript even if that call then fails from the rate
  861. // limit. Cheap local file reads only; never a network call or a child
  862. // process, so it cannot add latency to prompt submission.
  863. try {
  864. const rlFunnelEnv = process.env.RUFLO_FUNNEL;
  865. const rlDisabledByEnv = rlFunnelEnv !== undefined && /^(0|false|off|no)$/i.test(String(rlFunnelEnv).trim());
  866. const rlCiVars = ['CI', 'GITHUB_ACTIONS', 'GITLAB_CI', 'CIRCLECI', 'TRAVIS', 'BUILDKITE', 'JENKINS_URL', 'TEAMCITY_VERSION', 'TF_BUILD'];
  867. const rlIsCi = rlCiVars.some((v) => {
  868. const val = process.env[v];
  869. return val !== undefined && val !== '' && val !== '0' && String(val).toLowerCase() !== 'false';
  870. });
  871. const rlHome = path.join(os.homedir(), '.ruflo');
  872. let rlUserDisabled = false;
  873. try {
  874. const rlUserCfg = JSON.parse(fs.readFileSync(path.join(rlHome, 'funnel.json'), 'utf8'));
  875. rlUserDisabled = !!(rlUserCfg && rlUserCfg.enabled === false);
  876. } catch (e) { /* absent/malformed = not disabled */ }
  877. let rlProjectDisabled = false;
  878. try {
  879. const rlProjCfg = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'claude-flow.config.json'), 'utf8'));
  880. rlProjectDisabled = !!(rlProjCfg && rlProjCfg.funnel && rlProjCfg.funnel.enabled === false);
  881. } catch (e) { /* absent/malformed = not disabled */ }
  882. if (!rlDisabledByEnv && !rlIsCi && !rlUserDisabled && !rlProjectDisabled) {
  883. let rlStatus = null;
  884. try { rlStatus = JSON.parse(fs.readFileSync(path.join(rlHome, 'rate-limit-status.json'), 'utf8')); } catch (e) { /* not flagged */ }
  885. let rlIsLimited = false;
  886. if (rlStatus && rlStatus.limited) {
  887. if (rlStatus.since) {
  888. const rlSinceMs = Date.parse(rlStatus.since);
  889. rlIsLimited = isNaN(rlSinceMs) ? true : (Date.now() - rlSinceMs) < 6 * 60 * 60 * 1000;
  890. } else {
  891. rlIsLimited = true;
  892. }
  893. }
  894. if (rlIsLimited) {
  895. let rlConsented = false;
  896. try {
  897. const rlConsentFile = JSON.parse(fs.readFileSync(path.join(rlHome, 'consent.json'), 'utf8'));
  898. const rlReceipt = rlConsentFile && rlConsentFile['sponsored-downtime'];
  899. rlConsented = !!(rlReceipt && rlReceipt.granted === true && rlReceipt.at !== null && rlReceipt.policyVersion === 1);
  900. } catch (e) { /* not consented */ }
  901. if (!rlConsented) {
  902. console.log('[COGNITUM] Hit your Claude usage limit? Free sponsored capacity is available at cognitum.one/meta-llm — run: ruflo proxy sponsor-enable --yes');
  903. }
  904. }
  905. }
  906. } catch (e) { /* nudge must never break the hook */ }
  907. },
  908. 'pre-bash': () => {
  909. // Basic command safety check — prefer stdin command data from Claude Code.
  910. // Only a non-empty string counts as the command (#2017, #4743): input that
  911. // arrived late, did not parse, or carried no command blocks instead of passing.
  912. if (stdinUnparsable) blockPreBash('pre-bash could not parse the hook input');
  913. const raw = [hookInput.command, toolInput.command, prompt].find((c) => typeof c === 'string' && c.trim());
  914. if (!raw) blockPreBash('pre-bash received no command to validate');
  915. const cmd = raw.toLowerCase();
  916. const dangerous = ['rm -rf /', 'format c:', 'del /s /q c:\\', ':(){:|:&};:'];
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Note: Quoted as data in code: Matches a classic shell fork-bomb pattern
    • Line 973 on GitHub
  917. // Join literal quote fragments and normalize root paths without shell evaluation.
  918. function hasRootDelete(command, depth = 0) {
  919. // mask has one letter per character of word: 'u' unquoted, 'q' quoted or escaped (only unquoted braces expand).
  920. let word = '', mask = '', quote = '', started = false, redirect = false
  921. let ansiNul = false // a NUL inside $'...' ends that string, as in bash
  922. let inRm = false, optionsEnded = false, recursive = false, force = false, root = false
  923. const isRoot = (operand) => {
  924. if (!operand.startsWith('/')) return false
  925. const parts = []
  926. for (const part of operand.split('/')) {
  927. if (!part || part === '.') continue
  928. if (part === '..') parts.pop()
  929. else parts.push(part)
  930. }
  931. return parts.length === 0 || /[*?\[]/.test(parts[0])
  932. }
  933. // One backslash escape inside $'...', from the character after the backslash.
  934. // Returns the text it stands for and the index of its last character. An unknown escape keeps its backslash.
  935. // The command arrives lowercased, so an uppercase-U escape reads as a lowercase one: eight digits starting 0000 are one code point.
  936. const ansiEscape = (s, at) => {
  937. const c = s[at]
  938. const simple = { a: '\x07', b: '\b', e: '\x1b', f: '\f', n: '\n', r: '\r', t: '\t', v: '\v', '\\': '\\', "'": "'", '"': '"', '?': '?' }
  939. if (simple[c] !== undefined) return [simple[c], at]
  940. const digits = (from, max, pattern) => pattern.exec(s.slice(from, from + max))?.[0]
  941. const octal = digits(at, 3, /^[0-7]+/)
  942. if (octal) return [String.fromCharCode(parseInt(octal, 8) & 255), at + octal.length - 1]
  943. const hex = c === 'x' ? digits(at + 1, 2, /^[0-9a-f]+/) : undefined
  944. if (hex) return [String.fromCharCode(parseInt(hex, 16)), at + hex.length]
  945. const wide = c === 'u' ? (digits(at + 1, 8, /^0000[0-9a-f]{4}$/) ?? digits(at + 1, 4, /^[0-9a-f]+/)) : undefined
  946. if (wide) return [String.fromCodePoint(parseInt(wide, 16)), at + wide.length]
  947. if (c === 'c' && at + 1 < s.length) return [String.fromCharCode(s.charCodeAt(at + 1) & 31), at + 1]
  948. return ['\\' + c, at]
  949. }
  950. // Past the rescan bound (or the brace budget), a string is judged by its tokens: an rm and a possible root operand
  951. // anywhere in it deny. Quote characters are dropped first, so r"m" is still rm; a path token with braces may expand to /.
  952. const looseRootDelete = (text) => {
  953. const tokens = text.replace(/["'\\]/g, '').split(/[\s;&|()\x60$]+/)
  954. return tokens.some(t => t === 'rm' || t.endsWith('/rm')) && tokens.some(t => isRoot(t) || (t.includes('/') && /[{}]/.test(t)))
  955. }
  956. // Bash brace expansion of one word ({a,b} lists, nested or glued to text), and nothing else: no {1..3} sequences, and
  957. // nothing inside parameter braces after a dollar sign. Only unquoted braces and commas count. Iterative and bounded:
  958. // past BRACE_WORDS words or BRACE_CHARS characters of work in this call it returns undefined.
  959. const BRACE_WORDS = 4096
  960. let braceChars = 1_000_000
  961. // The leftmost expandable group: an unquoted {...} with an unquoted comma at its own level, outside any dollar-brace parameter. One pass.
  962. const firstGroup = (text, marks) => {
  963. const stack = []
  964. let dollars = 0
  965. let best
  966. for (let k = 0; k < text.length; k++) {
  967. if (marks[k] !== 'u') continue
  968. const c = text[k]
  969. if (c === '{') {
  970. const dollar = k > 0 && text[k - 1] === '$' && marks[k - 1] === 'u'
  971. if (dollar) dollars++
  972. stack.push({ open: k, commas: [], dollar: dollar || dollars > 0 })
  973. } else if (c === ',' && stack.length > 0) stack[stack.length - 1].commas.push(k)
  974. else if (c === '}' && stack.length > 0) {
  975. const top = stack.pop()
  976. if (top.dollar && text[top.open - 1] === '$' && marks[top.open - 1] === 'u') dollars--
  977. if (!top.dollar && top.commas.length > 0 && (best === undefined || top.open < best[0])) best = [top.open, top.commas, k]
  978. }
  979. }
  980. return best
  981. }
  982. const braceExpand = (text, marks) => {
  983. const out = []
  984. const todo = [[text, marks]]
  985. while (todo.length > 0) {
  986. const [t, m] = todo.pop()
  987. if ((braceChars -= t.length) < 0) return undefined
  988. const group = firstGroup(t, m)
  989. if (group === undefined) {
  990. out.push(t)
  991. if (out.length > BRACE_WORDS) return undefined
  992. continue
  993. }
  994. const [open, commas, close] = group
  995. const cuts = [open, ...commas, close]
  996. // Pushed in reverse, so the words come out in bash's left-to-right order.
  997. for (let c = cuts.length - 2; c >= 0; c--) {
  998. const from = cuts[c] + 1, to = cuts[c + 1]
  999. todo.push([t.slice(0, open) + t.slice(from, to) + t.slice(close + 1), m.slice(0, open) + m.slice(from, to) + m.slice(close + 1)])
  1000. }
  1001. if (todo.length > BRACE_WORDS) return undefined
  1002. }
  1003. return out
  1004. }
  1005. const takeWord = (w) => {
  1006. if (!inRm) inRm = w === 'rm' || w.endsWith('/rm')
  1007. else if (!optionsEnded && w === '--') optionsEnded = true
  1008. else if (!optionsEnded && w.startsWith('-')) {
  1009. // GNU getopt accepts any unambiguous long-option prefix: --r, --recur, --forc.
  1010. recursive = recursive || (w.length > 2 && '--recursive'.startsWith(w)) || (/^-[a-z]*$/.test(w) && w.includes('r'))
  1011. force = force || (w.length > 2 && '--force'.startsWith(w)) || (/^-[a-z]*$/.test(w) && w.includes('f'))
  1012. } else root = root || isRoot(w)
  1013. return inRm && recursive && force && root
  1014. }
  1015. const finishWord = () => {
  1016. if (!started) return false
  1017. const text = word, marks = mask
  1018. word = ''; mask = ''; started = false
  1019. // Literal shell strings (e.g. sh -c 'rm -rf /', or sh -c '{rm,-rf,/}') also carried the old guard.
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 1,076 on GitHub
  1020. // Bound rescanning to four levels; beyond that judge the string by its tokens.
  1021. if (/[\s;&|()\x60{]/.test(text)) {
  1022. if (depth < 4 ? hasRootDelete(text, depth + 1) : looseRootDelete(text)) return true
  1023. }
  1024. // An unquoted {a,b} becomes separate words, as bash expands it: rm -rf {/*,} is rm -rf /*.
  1025. const words = text.includes('{') ? braceExpand(text, marks) : [text]
  1026. if (words === undefined) {
  1027. // Too many alternatives to check: one of them may be the root (an rm in progress fails closed), or the
  1028. // list itself may spell the rm: judge its tokens.
  1029. if (inRm) root = true
  1030. if (looseRootDelete(text.replace(/[{},]/g, ' '))) return true
  1031. return takeWord(text)
  1032. }
  1033. for (const w of words) if (w !== '' && takeWord(w)) return true
  1034. return false
  1035. }
  1036. // A command substitution's body, from just after its opening backtick. Bash removes a
  1037. // backslash only before $, a backtick or a backslash (and " inside double quotes) and
  1038. // drops backslash-newline; any other backslash stays for the nested scan.
  1039. const substitution = (from, inDouble) => {
  1040. let body = '', j = from
  1041. for (; j < command.length && command[j] !== '\x60'; j++) {
  1042. const next = command[j + 1]
  1043. if (command[j] === '\\' && j + 1 < command.length) {
  1044. if (next === '\n') { j++; continue }
  1045. if (next === '$' || next === '\x60' || next === '\\' || (inDouble && next === '"')) { body += next; j++; continue }
  1046. }
  1047. body += command[j]
  1048. }
  1049. return [j, depth < 4 ? hasRootDelete(body, depth + 1) : looseRootDelete(body)]
  1050. }
  1051. const finishCommand = () => {
  1052. const denied = inRm && recursive && force && root
  1053. inRm = optionsEnded = recursive = force = root = false
  1054. return denied
  1055. }
  1056. for (let i = 0; i < command.length; i++) {
  1057. const char = command[i]
  1058. const redirectionAmpersand = char === '&' && (redirect || command[i + 1] === '>')
  1059. redirect = false
  1060. if (quote) {
  1061. if (quote === "$'") {
  1062. if (char === "'") { quote = ''; ansiNul = false }
  1063. else if (char === '\\' && i + 1 < command.length) {
  1064. const [text, last] = ansiEscape(command, i + 1)
  1065. i = last
  1066. if (!ansiNul) { const nul = text.indexOf('\0'); const kept = nul < 0 ? text : text.slice(0, nul); word += kept; mask += 'q'.repeat(kept.length); if (nul >= 0) ansiNul = true }
  1067. } else if (!ansiNul) { word += char; mask += 'q' }
  1068. continue
  1069. }
  1070. if (char === quote) quote = ''
  1071. else if (quote === '"' && char === '\x60' && command.indexOf('\x60', i + 1) > i) {
  1072. const [end, denied] = substitution(i + 1, true)
  1073. if (denied) return true
  1074. // The substitution is gone from the word, as bash's empty output is (a quoted empty substitution glued to -rf leaves -rf).
  1075. // A # right after it is still inside the word: a placeholder keeps a rescan (sh -c "...")
  1076. // from reading it as the start of a comment.
  1077. if (command[end + 1] === '#') { word += '\u0001'; mask += 'q' }
  1078. i = end
  1079. }
  1080. else if (quote === '"' && char === '\\' && i + 1 < command.length &&
  1081. (command[i + 1] === '"' || command[i + 1] === '\\' || command[i + 1] === '$' ||
  1082. command.charCodeAt(i + 1) === 96 || command[i + 1] === '\n')) {
  1083. const next = command[++i]
  1084. if (next !== '\n') { word += next; mask += 'q' }
  1085. } else { word += char; mask += 'q' }
  1086. continue
  1087. }
  1088. if (char === '\\' && i + 1 < command.length) {
  1089. const next = command[++i]
  1090. if (next !== '\n') { word += next; mask += 'q'; started = true }
  1091. } else if (char === '\x60' && command.indexOf('\x60', i + 1) > i) {
  1092. // Command substitution: scan the body as its own command; the substitution
  1093. // stays inside the enclosing word, so the rm being parsed keeps its state,
  1094. // and the word has started (a # right after it is not a comment).
  1095. const [end, denied] = substitution(i + 1, false)
  1096. if (denied) return true
  1097. i = end; started = true
  1098. } else if (char === '$' && (command[i + 1] === "'" || command[i + 1] === '"')) {
  1099. // ANSI-C ($'...': escapes decoded) and locale ($"...") quoting: the $ is not part of the word.
  1100. quote = command[i + 1] === "'" ? "$'" : '"'; started = true; i++
  1101. } else if (char === '"' || char === "'") {
  1102. quote = char; started = true
  1103. } else if (char === '#' && !started) {
  1104. while (i < command.length && command[i] !== '\n') i++
  1105. if (finishCommand()) return true
  1106. } else if (char === ' ' || char === '\t' || char === '\r' || char === '\n' ||
  1107. ';|&()<>'.includes(char)) {
  1108. if (finishWord()) return true
  1109. // Redirections separate words, but later operands still belong to rm.
  1110. redirect = char === '<' || char === '>'
  1111. if (!redirectionAmpersand && (char === '\n' || ';|&()'.includes(char)) && finishCommand()) return true
  1112. } else {
  1113. word += char; mask += 'u'; started = true
  1114. }
  1115. }
  1116. return finishWord() || finishCommand()
  1117. }
  1118. // A fork bomb's definition as bash reads it, whatever the spacing or the name: f(){ f|f& }, function f { f|f& },
  1119. // function f(){ f|f& }. Defining one is the danger: the call may come anywhere later.
  1120. function hasForkBomb(command) {
  1121. const s = command.replace(/\s+/g, '')
  1122. for (let brace = s.indexOf('{'); brace >= 0; brace = s.indexOf('{', brace + 1)) {
  1123. const end = s.startsWith('()', brace - 2) ? brace - 2 : brace
  1124. let start = end
  1125. while (start > 0 && end - start < 72 && /[a-z0-9_:.-]/.test(s[start - 1])) start--
  1126. const run = s.slice(start, end)
  1127. for (const name of run.startsWith('function') && run.length > 8 ? [run, run.slice(8)] : [run]) {
  1128. if (name && s.startsWith(name + '|' + name + '&}', brace + 1)) return true
  1129. }
  1130. }
  1131. return false
  1132. }
  1133. for (const d of dangerous) {
  1134. if (d === 'rm -rf /' ? hasRootDelete(cmd) : d === ':(){:|:&};:' ? hasForkBomb(cmd) : cmd.includes(d)) {
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Note: Quoted as data in code: Matches a classic shell fork-bomb pattern
    • Line 1,192 on GitHub
  1135. console.error(`[BLOCKED] Dangerous command detected: ${d}`);
  1136. // Claude Code PreToolUse: exit 2 blocks execution; exit 1 is non-blocking.
  1137. process.exit(2);
  1138. }
  1139. }
  1140. console.log('[OK] Command validated');
  1141. },
  1142. 'post-edit': () => {
  1143. // Record edit for session metrics
  1144. if (session && session.metric) {
  1145. try { session.metric('edits'); } catch (e) { /* no active session */ }
  1146. }
  1147. // Record edit for intelligence consolidation — prefer stdin data from Claude Code
  1148. if (intelligence && intelligence.recordEdit) {
  1149. try {
  1150. const file = hookInput.file_path || toolInput.file_path
  1151. || process.env.TOOL_INPUT_file_path || args[0] || '';
  1152. intelligence.recordEdit(file, !toolFailed);
  1153. } catch (e) { /* non-fatal */ }
  1154. }
  1155. console.log(toolFailed ? '[LEARN] Edit FAILURE recorded' : '[OK] Edit recorded');
  1156. },
  1157. 'session-restore': async () => {
  1158. // ADR-318/319 first-run auto-enable — fire once per install, never
  1159. // re-fires after user disables. Respects RUFLO_NO_AUTO_ENABLE + CI.
  1160. // Fully non-blocking (detached spawn) so session-restore latency
  1161. // is unchanged.
  1162. firstRunAutoEnableIfEligible();
  1163. // Advisory-only settings.json risk scan — see scanSessionStartSettingsForRisk's
  1164. // own doc comment for why this runs specifically on this automatic path.
  1165. for (const warning of scanSessionStartSettingsForRisk()) {
  1166. console.log(`[WARN] ${warning}`);
  1167. }
  1168. if (session) {
  1169. // Try restore first, fall back to start
  1170. const existing = session.restore && session.restore();
  1171. if (!existing) {
  1172. session.start && session.start();
  1173. }
  1174. } else {
  1175. // Minimal session restore output
  1176. const sessionId = `session-${Date.now()}`;
  1177. console.log(`[INFO] Restoring session: %SESSION_ID%`);
  1178. console.log('');
  1179. console.log(`[OK] Session restored from %SESSION_ID%`);
  1180. console.log(`New session ID: ${sessionId}`);
  1181. console.log('');
  1182. console.log('Restored State');
  1183. console.log('+----------------+-------+');
  1184. console.log('| Item | Count |');
  1185. console.log('+----------------+-------+');
  1186. console.log('| Tasks | 0 |');
  1187. console.log('| Agents | 0 |');
  1188. console.log('| Memory Entries | 0 |');
  1189. console.log('+----------------+-------+');
  1190. }
  1191. // Initialize intelligence graph after session restore (with timeout — #1530)
  1192. if (intelligence && intelligence.init) {
  1193. const initResult = await runWithTimeout(() => intelligence.init(), 'intelligence.init()');
  1194. if (initResult && initResult.nodes > 0) {
  1195. console.log(`[INTELLIGENCE] Loaded ${initResult.nodes} patterns, ${initResult.edges} edges`);
  1196. }
  1197. }
  1198. // Warm the funnel message cache once per session (see
  1199. // spawnDetachedFunnelRefresh's doc comment for why this must happen
  1200. // here, detached, rather than as the statusline's own fire-and-forget).
  1201. spawnDetachedFunnelRefresh();
  1202. // ADR-316 co-pilot advisor tip — same detached pattern; cheap no-op
  1203. // when not consented or still within the 24h TTL (see refresh-advisor's
  1204. // own doc comment).
  1205. spawnDetachedAdvisorRefresh();
  1206. },
  1207. 'session-end': async () => {
  1208. // Consolidate intelligence before ending session (with timeout — #1530)
  1209. if (intelligence && intelligence.consolidate) {
  1210. const consResult = await runWithTimeout(() => intelligence.consolidate(), 'intelligence.consolidate()');
  1211. if (consResult && consResult.entries > 0) {
  1212. console.log(`[INTELLIGENCE] Consolidated: ${consResult.entries} entries, ${consResult.edges} edges${consResult.newEntries > 0 ? `, ${consResult.newEntries} new` : ''}, PageRank recomputed`);
  1213. }
  1214. }
  1215. if (session && session.end) {
  1216. session.end();
  1217. } else {
  1218. console.log('[OK] Session ended');
  1219. }
  1220. },
  1221. 'pre-task': () => {
  1222. if (session && session.metric) {
  1223. try { session.metric('tasks'); } catch (e) { /* no active session */ }
  1224. }
  1225. // Route the task if router is available
  1226. if (router && router.routeTask && prompt) {
  1227. const result = router.routeTask(prompt);
  1228. console.log(`[INFO] Task routed to: ${result.agent} (confidence: ${result.confidence})`);
  1229. } else {
  1230. console.log('[OK] Task started');
  1231. }
  1232. },
  1233. 'post-task': () => {
  1234. // ADR-174: feed the REAL outcome (feedback() boosts confidence on success,
  1235. // decays it on failure) instead of a hardcoded true — no more all-positive
  1236. // signal that the substrate can't learn from.
  1237. if (intelligence && intelligence.feedback) {
  1238. try {
  1239. intelligence.feedback(!toolFailed);
  1240. } catch (e) { /* non-fatal */ }
  1241. }
  1242. console.log(toolFailed ? '[LEARN] Task FAILURE recorded' : '[OK] Task completed');
  1243. },
  1244. 'stats': () => {
  1245. if (intelligence && intelligence.stats) {
  1246. intelligence.stats(args.includes('--json'));
  1247. } else {
  1248. console.log('[WARN] Intelligence module not available. Run session-restore first.');
  1249. }
  1250. },
  1251. };
  1252. // Execute the handler
  1253. if (command && handlers[command]) {
  1254. try {
  1255. await Promise.resolve(handlers[command]());
  1256. } catch (e) {
  1257. if (command === 'pre-bash') blockPreBash(`pre-bash failed: ${e && e.message}`);
  1258. // Hooks should never crash Claude Code - fail silently
  1259. console.log(`[WARN] Hook ${command} encountered an error: ${e.message}`);
  1260. }
  1261. } else if (command) {
  1262. // Unknown command - pass through without error
  1263. console.log(`[OK] Hook: ${command}`);
  1264. } else {
  1265. console.log('Usage: hook-handler.cjs <route|pre-bash|post-edit|session-restore|session-end|pre-task|post-task|stats>');
  1266. }
  1267. }
  1268. // Non-blocking hooks exit 0; pre-bash denials and failures exit 2 to block PreToolUse.
  1269. // A denial exits immediately, before the normal completion path below.
  1270. //
  1271. // Only dispatch when run directly (node hook-handler.cjs <cmd>). When
  1272. // require()'d by a test, expose the internals instead of reading stdin and
  1273. // calling process.exit — the 2026-06-15 fix (cb1e93e8d) added this guard and
  1274. // the exports for tests/hook-handler-runwithtimeout.test.cjs; the 2026-07-04
  1275. // helper sync (a5f86ad0a) dropped both, so the test died with
  1276. // "runWithTimeout is not a function" once the Test Suite job ran again.
  1277. if (require.main === module) {
  1278. process.exitCode = 0;
  1279. main().catch((e) => {
  1280. if (command === 'pre-bash') blockPreBash(`pre-bash failed: ${e && e.message}`);
  1281. try { console.log(`[WARN] Hook handler error: ${e.message}`); } catch (_) {}
  1282. }).finally(() => {
  1283. process.exit(0);
  1284. });
  1285. }
  1286. // Which sibling helpers loaded (all CommonJS, shipped as .cjs — #3555).
  1287. const loadedHelpers = { router: !!router, session: !!session, memory: !!memory, intelligence: !!intelligence };
  1288. // resolveGlobalCliBin/npmGlobalPrefix are exported for
  1289. // hook-handler-global-cli.test.ts; resolveCliBinForHook for anyone checking
  1290. // what a given machine resolves to without running a hook (#3368).
  1291. module.exports = { runWithTimeout, INTELLIGENCE_TIMEOUT_MS, loadedHelpers, ownedByMod, MOD_OWNABLE_EVENTS, resolveCliBinForHook, resolveGlobalCliBin, npmGlobalPrefix, cliSpawnArgs, helperRoot, scanSessionStartSettingsForRisk, srFormatRiskFindingsForAutomaticBoot, srScanSettingsForRisk, srScanCommandStringForRisk, srScanAllowRuleForRisk, SR_DANGEROUS_COMMAND_WORDS, SR_SHELL_EXEC_WORDS, SR_DOWNLOADER_WORDS, SR_STANDALONE_RISK_PATTERNS };
.claude/settings.json · Bundled script · 293 lines · 1 finding marked
  1. {
  2. "skillListingBudgetFraction": 0.06,
  3. "customInstructions": "Follow the project's CLAUDE.md guidelines. Use concurrent execution for all operations. Prioritize v3 implementation with security-first development, 15-agent swarm coordination, phased performance optimization, and cross-platform helper automation.",
  4. "env": {
  5. "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1",
  6. "CLAUDE_FLOW_V3_ENABLED": "true",
  7. "CLAUDE_FLOW_HOOKS_ENABLED": "true",
  8. "CLAUDE_CODE_ENABLE_FUNCTION_HOOKS": "1"
  9. },
  10. "permissions": {
  11. "allow": [
  12. "Bash(npx @claude-flow*)",
  13. "Bash(npx claude-flow*)",
  14. "Bash(node .claude/*)",
  15. "Bash(npm run:*)",
  16. "Bash(npm test:*)",
  17. "Bash(git status)",
  18. "Bash(git diff:*)",
  19. "Bash(git log:*)",
  20. "Bash(git add:*)",
  21. "Bash(git commit:*)",
  22. "Bash(git push)",
  23. "Bash(git config:*)",
  24. "Bash(git tag:*)",
  25. "Bash(git branch:*)",
  26. "Bash(git checkout:*)",
  27. "Bash(git stash:*)",
  28. "Bash(jq:*)",
  29. "Bash(node:*)",
  30. "Bash(which:*)",
  31. "Bash(pwd)",
  32. "Bash(ls:*)",
  33. "Bash(npx:*)",
  34. "mcp__claude-flow__*",
  35. "mcp__ruv-swarm__*",
  36. "mcp__flow-nexus__*"
  37. ],
  38. "deny": [
  39. "Read(./.env)",
  40. "Read(./.env.*)",
  41. "Bash(rm -rf /)"
    • Dismissed after review: Runs `rm -rf` against a root or home-directory path
    • Line 41 on GitHub
  42. ]
  43. },
  44. "hooks": {
  45. "PreToolUse": [
  46. {
  47. "matcher": "Bash",
  48. "hooks": [
  49. {
  50. "type": "command",
  51. "command": "node \"$CLAUDE_PROJECT_DIR/.claude/helpers/hook-handler.cjs\" pre-bash",
  52. "timeout": 5000,
  53. "onFailure": "block"
  54. }
  55. ]
  56. }
  57. ],
  58. "PostToolUse": [
  59. {
  60. "matcher": "Write|Edit|MultiEdit",
  61. "hooks": [
  62. {
  63. "type": "command",
  64. "command": "node \"$CLAUDE_PROJECT_DIR/.claude/helpers/hook-handler.cjs\" post-edit",
  65. "timeout": 10000
  66. }
  67. ]
  68. }
  69. ],
  70. "UserPromptSubmit": [
  71. {
  72. "hooks": [
  73. {
  74. "type": "command",
  75. "command": "node \"$CLAUDE_PROJECT_DIR/.claude/helpers/hook-handler.cjs\" route",
  76. "timeout": 10000
  77. }
  78. ]
  79. }
  80. ],
  81. "SessionStart": [
  82. {
  83. "hooks": [
  84. {
  85. "type": "command",
  86. "command": "node \"$CLAUDE_PROJECT_DIR/.claude/helpers/hook-handler.cjs\" session-restore",
  87. "timeout": 15000
  88. },
  89. {
  90. "type": "command",
  91. "command": "node \"$CLAUDE_PROJECT_DIR/.claude/helpers/auto-memory-hook.mjs\" import",
  92. "timeout": 8000
  93. }
  94. ]
  95. }
  96. ],
  97. "SessionEnd": [
  98. {
  99. "hooks": [
  100. {
  101. "type": "command",
  102. "command": "node \"$CLAUDE_PROJECT_DIR/.claude/helpers/hook-handler.cjs\" session-end",
  103. "timeout": 10000
  104. }
  105. ]
  106. }
  107. ],
  108. "Stop": [
  109. {
  110. "hooks": [
  111. {
  112. "type": "command",
  113. "command": "node \"$CLAUDE_PROJECT_DIR/.claude/helpers/auto-memory-hook.mjs\" sync",
  114. "timeout": 10000
  115. }
  116. ]
  117. }
  118. ],
  119. "PreCompact": [
  120. {
  121. "matcher": "manual",
  122. "hooks": [
  123. {
  124. "type": "command",
  125. "command": "node \"$CLAUDE_PROJECT_DIR/.claude/helpers/hook-handler.cjs\" compact-manual"
  126. },
  127. {
  128. "type": "command",
  129. "command": "node \"$CLAUDE_PROJECT_DIR/.claude/helpers/hook-handler.cjs\" session-end",
  130. "timeout": 5000
  131. }
  132. ]
  133. },
  134. {
  135. "matcher": "auto",
  136. "hooks": [
  137. {
  138. "type": "command",
  139. "command": "node \"$CLAUDE_PROJECT_DIR/.claude/helpers/hook-handler.cjs\" compact-auto"
  140. },
  141. {
  142. "type": "command",
  143. "command": "node \"$CLAUDE_PROJECT_DIR/.claude/helpers/hook-handler.cjs\" session-end",
  144. "timeout": 6000
  145. }
  146. ]
  147. }
  148. ],
  149. "SubagentStop": [
  150. {
  151. "hooks": [
  152. {
  153. "type": "command",
  154. "command": "node \"$CLAUDE_PROJECT_DIR/.claude/helpers/hook-handler.cjs\" post-task",
  155. "timeout": 5000
  156. }
  157. ]
  158. }
  159. ]
  160. },
  161. "attribution": {
  162. "commit": "Co-Authored-By: RuFlo <ruv@ruv.net>",
  163. "pr": "\ud83e\udd16 Generated with [RuFlo](https://github.com/ruvnet/ruflo)"
  164. },
  165. "claudeFlow": {
  166. "version": "3.6.11",
  167. "enabled": true,
  168. "modelPreferences": {
  169. "default": "claude-sonnet-5",
  170. "routing": "claude-haiku-4-5-20251001"
  171. },
  172. "agentTeams": {
  173. "enabled": true,
  174. "teammateMode": "auto",
  175. "taskListEnabled": true,
  176. "mailboxEnabled": true,
  177. "coordination": {
  178. "autoAssignOnIdle": false,
  179. "trainPatternsOnComplete": true,
  180. "notifyLeadOnComplete": true,
  181. "sharedMemoryNamespace": "agent-teams"
  182. },
  183. "hooks": {
  184. "teammateIdle": {
  185. "enabled": true,
  186. "autoAssign": false,
  187. "checkTaskList": true
  188. },
  189. "taskCompleted": {
  190. "enabled": true,
  191. "trainPatterns": true,
  192. "notifyLead": true
  193. }
  194. }
  195. },
  196. "swarm": {
  197. "topology": "hierarchical-mesh",
  198. "maxAgents": 15
  199. },
  200. "memory": {
  201. "backend": "hybrid",
  202. "enableHNSW": true,
  203. "learningBridge": { "enabled": true },
  204. "memoryGraph": { "enabled": true },
  205. "agentScopes": { "enabled": true }
  206. },
  207. "neural": {
  208. "enabled": true
  209. },
  210. "daemon": {
  211. "autoStart": true,
  212. "workers": [
  213. "map",
  214. "audit",
  215. "optimize",
  216. "consolidate",
  217. "testgaps",
  218. "ultralearn",
  219. "deepdive",
  220. "document",
  221. "refactor",
  222. "benchmark"
  223. ],
  224. "schedules": {
  225. "audit": { "interval": "1h", "priority": "critical" },
  226. "optimize": { "interval": "30m", "priority": "high" },
  227. "consolidate": { "interval": "2h", "priority": "low" },
  228. "document": { "interval": "1h", "priority": "normal" },
  229. "deepdive": { "interval": "4h", "priority": "normal" },
  230. "ultralearn": { "interval": "1h", "priority": "normal" }
  231. }
  232. },
  233. "learning": {
  234. "enabled": true,
  235. "autoTrain": true,
  236. "patterns": ["coordination", "optimization", "prediction"],
  237. "retention": {
  238. "shortTerm": "24h",
  239. "longTerm": "30d"
  240. }
  241. },
  242. "adr": {
  243. "autoGenerate": true,
  244. "directory": "/docs/adr",
  245. "template": "madr"
  246. },
  247. "ddd": {
  248. "trackDomains": true,
  249. "validateBoundedContexts": true,
  250. "directory": "/docs/ddd"
  251. },
  252. "security": {
  253. "autoScan": true,
  254. "scanOnEdit": true,
  255. "cveCheck": true,
  256. "threatModel": true
  257. }
  258. },
  259. "agents": {
  260. "source": ".claude/agents",
  261. "customAgents": []
  262. },
  263. "skills": {
  264. "source": ".claude/commands",
  265. "enabled": true
  266. },
  267. "statusLine": {
  268. "type": "command",
  269. "command": "sh -c 'exec node \"${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/statusline.cjs\"'"
  270. },
  271. "mcpServers": {
  272. "claude-flow": {
  273. "command": "npx",
  274. "args": [
  275. "-y",
  276. "ruflo@latest",
  277. "mcp",
  278. "start"
  279. ]
  280. }
  281. },
  282. "enabledMcpjsonServers": [
  283. "claude-flow"
  284. ],
  285. "enabledPlugins": {
  286. "ruflo-mods@ruflo": true,
  287. "ruflo-swarm@ruflo": true,
  288. "ruflo-console@ruflo": true
  289. },
  290. "extraKnownMarketplaces": {
  291. "ruflo": { "source": { "source": "github", "repo": "ruvnet/ruflo" } }
  292. }
  293. }

Ratings and comments

Sign in to rate this skill.

Sign in

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