Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

feat: add ADR-072 autopilot persistent completion, bump to v3.5.44

rUvc70ff9ec4bf1
diff --git a/package.json b/package.json
index 5732822d76..4e7832ad87 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "claude-flow",
- "version": "3.5.43",
+ "version": "3.5.44",
"description": "Ruflo - Enterprise AI agent orchestration for Claude Code. Deploy 60+ specialized agents in coordinated swarms with self-learning, fault-tolerant consensus, vector memory, and MCP integration",
"main": "dist/index.js",
"type": "module",
diff --git a/ruflo/package.json b/ruflo/package.json
index 548b20a3d2..0115ab4b13 100644
--- a/ruflo/package.json
+++ b/ruflo/package.json
@@ -1,6 +1,6 @@
{
"name": "ruflo",
- "version": "3.5.43",
+ "version": "3.5.44",
"description": "Ruflo - Enterprise AI agent orchestration platform. Deploy 60+ specialized agents in coordinated swarms with self-learning, fault-tolerant consensus, vector memory, and MCP integration",
"main": "bin/ruflo.js",
"type": "module",
diff --git a/v3/@claude-flow/cli/package.json b/v3/@claude-flow/cli/package.json
index 696f3ca897..6c1ba5b195 100644
--- a/v3/@claude-flow/cli/package.json
+++ b/v3/@claude-flow/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@claude-flow/cli",
- "version": "3.5.43",
+ "version": "3.5.44",
"type": "module",
"description": "Ruflo CLI - Enterprise AI agent orchestration with 60+ specialized agents, swarm coordination, MCP server, self-learning hooks, and vector memory for Claude Code",
"main": "dist/src/index.js",
diff --git a/v3/@claude-flow/cli/src/mcp-tools/guidance-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/guidance-tools.ts
index 02e5fbd4b3..3213ea9ddb 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/guidance-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/guidance-tools.ts
@@ -327,7 +327,7 @@ function discoverAgents(): string[] {
} else if (entry.name.endsWith('.md') && entry.name !== 'MIGRATION_SUMMARY.md') {
const content = readFileSync(join(dir, entry.name), 'utf-8');
const nameMatch = content.match(/^name:\s*(.+)$/m);
- if (nameMatch) agents.push(nameMatch[1].trim());
+ if (nameMatch) agents.push(nameMatch[1].trim().replace(/^["']|["']$/g, ''));
}
}
} catch { /* ignore */ }
diff --git a/v3/implementation/adrs/ADR-066-v3524-audit-remediation.md b/v3/implementation/adrs/ADR-066-v3524-audit-remediation.md
new file mode 100644
index 0000000000..46e60cdca6
--- /dev/null
+++ b/v3/implementation/adrs/ADR-066-v3524-audit-remediation.md
@@ -0,0 +1,77 @@
+---
+# ADR-066: v3.5.24 Deep Audit Remediation
+
+**Status**: Accepted
+**Date**: 2026-03-17
+**Author**: RuvNet
+**Version**: v3.5.24 β†’ v3.5.25
+
+## Context
+
+A comprehensive 4-agent deep audit of the v3.5.24 CLI codebase identified 15 issues across security, runtime, and code quality categories. This ADR documents the systematic remediation of all findings.
+
+## Audit Agents
+
+| Agent | Focus | Duration | Findings |
+|-------|-------|----------|----------|
+| CLI Auditor | Commands, stubs, dead code, types, imports | ~3 min | 3 low issues |
+| MCP Auditor | 260 tools, services, hooks, memory, plugins | ~2 min | 4 stub tools |
+| Runtime Validator | Build, smoke tests, MCP server, test suite | ~3 min | 3 runtime issues |
+| Security Auditor | Input validation, secrets, resources, deps | ~2 min | 15 total findings |
+
+## Findings & Remediations
+
+### Critical (3) β€” Fixed
+
+| # | Issue | File | Fix Applied |
+|---|-------|------|-------------|
+| C-1 | Command injection via `execSync` with string concatenation | `browser-tools.ts:25` | Replaced `execSync(\`agent-browser \${...}\`)` with `execFileSync('agent-browser', fullArgs)` β€” array args prevent shell interpretation |
+| C-2 | Path traversal in GCS filename | `gcs.ts:119` | Added regex validation `^[a-zA-Z0-9._\-]+$` and `..` rejection before constructing objectPath |
+| C-3 | Prototype pollution via `setNestedValue()` | `config-tools.ts:100-111` | Added `DANGEROUS_KEYS` check for each key segment (`__proto__`, `constructor`, `prototype`) and max depth limit of 10 |
+
+### High (3) β€” Fixed
+
+| # | Issue | File | Fix Applied |
+|---|-------|------|-------------|
+| H-1 | `validateMemoryInput()` not called in retrieve/delete handlers | `memory-tools.ts` | Added `validateMemoryInput(key)` calls to `memory_retrieve` and `memory_delete` handlers |
+| H-2 | Unvalidated temp file deletion in GCS | `gcs.ts:158,176,205,211` | Added `path.resolve()` prefix validation before all 4 `unlinkSync()` calls β€” ensures file is within temp dir |
+| H-3 | Config key nesting unlimited | `config-tools.ts:100` | Added `MAX_NESTING_DEPTH = 10` guard in `setNestedValue()` |
+
+### Medium (5) β€” Fixed
+
+| # | Issue | File | Fix Applied |
+|---|-------|------|-------------|
+| M-1 | Config dir created world-readable | `config-tools.ts:47` | Added `mode: 0o700` to `mkdirSync()` |
+| M-2 | Swarm tools returning mock data | `swarm-tools.ts` | Complete rewrite: 4 tools now use file-based state persistence at `.claude-flow/swarm/swarm-state.json` with real CRUD operations |
+| M-3 | Missing commands in lazy-loader | `commands/index.ts` | Added `appliance-advanced` and `transfer-store` to `commandLoaders` map |
+| M-4 | Memory list hangs without daemon | Runtime | (Documented β€” requires daemon lifecycle change) |
+| M-5 | AgentDB controller warning noise | Runtime | (Documented β€” cosmetic, non-blocking) |
+
+### Swarm Tools Rewrite Details
+
+The 4 swarm MCP tools were completely rewritten from stubs to real implementations:
+
+- **swarm_init**: Validates topology against allowlist, clamps maxAgents 1-50, generates unique ID, persists to JSON
+- **swarm_status**: Loads from persistent store, returns most recent swarm if no ID specified, shows real agent/task counts
+- **swarm_shutdown**: Finds target swarm (by ID or most recent running), updates status to 'terminated', persists
+- **swarm_health**: Real health checks against persisted state β€” coordinator status, agent count, persistence file existence, topology info
+
+State file: `.claude-flow/swarm/swarm-state.json` (restrictive 0o700 permissions)
+
+## Validation
+
+- TypeScript build: PASS (zero errors)
+- Test suite: 1,640 tests passing, 0 failures
+- CLI smoke tests: All commands functional
+- MCP server: JSON-RPC 2.0 responding correctly
+
+## Decision
+
+All critical and high-severity security issues are remediated. Medium issues are either fixed or documented for future sprints. The codebase is now at 260/260 real MCP tool implementations (zero stubs).
+
+## Consequences
+
+- **Positive**: Eliminates command injection, path traversal, and prototype pollution attack vectors
+- **Positive**: All swarm tools now functional with state persistence
+- **Positive**: Input validation enforced consistently across memory tools
+- **Neutral**: Two runtime issues (memory list hang, AgentDB warning) deferred to future work
diff --git a/v3/implementation/adrs/ADR-071-guidance-tools-mcp-fixes.md b/v3/implementation/adrs/ADR-071-guidance-tools-mcp-fixes.md
new file mode 100644
index 0000000000..d0b57e44c7
--- /dev/null
+++ b/v3/implementation/adrs/ADR-071-guidance-tools-mcp-fixes.md
@@ -0,0 +1,80 @@
+# ADR-071: Guidance MCP Tools, Agent/Skill YAML Standardization, and MCP Server Fixes
+
+- **Status**: Implemented
+- **Date**: 2026-03-25
+- **PR**: #1438 (feat/implement-stub-commands)
+
+## Context
+
+Three areas needed attention in v3.5.43:
+
+1. **Capability discovery**: With 259 MCP tools, 26 CLI commands, 60+ agents, and 37 skills, the system had no way to navigate its own capabilities at runtime. Agents and the MCP client needed structured guidance to select the right tools for a task.
+
+2. **Agent/skill YAML frontmatter**: 98% of agent definitions (135 files) and many skill files used invalid YAML frontmatter fields not recognized by Claude Code (`type`, `color`, `capabilities`, `priority`, `triggers`, `version`, `metadata`, etc.). Six agent files used `.yaml` extension instead of `.md`. Two skill files used lowercase `skill.md` instead of `SKILL.md`. The `tools` field used YAML array format instead of the required comma-separated string.
+
+3. **MCP server startup failures**: Two bugs caused `mcp start` to fail with "MCP Server already running" even when no server was running:
+ - `getStatus()` reported `running: true` with the current process PID for stdio transport before the server actually started, causing `start()` to block itself.
+ - `isProcessRunning()` used `process.kill(pid, 0)` which returns true for any process owned by the user, not just the MCP server β€” leading to false positives when the OS recycled PIDs.
+
+## Decision
+
+### 1. Guidance MCP Tools
+
+Add 5 new MCP tools to the `@claude-flow/cli` package:
+
+| Tool | Purpose |
+|------|---------|
+| `guidance_capabilities` | List 16 capability areas with tools, commands, agents, skills, and when-to-use guidance |
+| `guidance_recommend` | Task-based routing β€” given a description, recommend capabilities and workflow template |
+| `guidance_discover` | Live filesystem scan of `.claude/agents/` and `.claude/skills/` |
+| `guidance_workflow` | Step-by-step workflow templates for 15 task types (bugfix, feature, refactor, security, etc.) |
+| `guidance_quickref` | Quick reference cards for 6 operational domains |
+
+The tools use a static capability catalog with pattern-matched task routing. `guidance_discover` dynamically reads agent/skill definitions from the filesystem using a multi-strategy project root finder (CWD, package-relative, walk-up).
+
+### 2. Agent/Skill YAML Standardization
+
+Batch-fix all agent and skill files to comply with Claude Code's YAML frontmatter spec:
+
+**Valid agent fields**: `name`, `description`, `tools` (comma-separated string), `disallowedTools`, `model`, `permissionMode`, `maxTurns`, `skills`, `mcpServers`, `hooks`, `memory`, `background`, `effort`, `isolation`, `initialPrompt`
+
+**Valid skill fields**: `name`, `description`, `argument-hint`, `disable-model-invocation`, `user-invocable`, `allowed-tools` (comma-separated), `model`, `effort`, `context`, `agent`, `hooks`
+
+Changes:
+- Convert 11 `.yaml` agent files to `.md`
+- Remove invalid fields from 100+ agents (`type`, `color`, `capabilities`, `priority`, `triggers`, `role`, `version`, `metadata`, etc.)
+- Remove malformed `hooks` fields (Python dict serialization artifacts)
+- Fix `tools` from YAML arrays to comma-separated strings
+- Rename 2 lowercase `skill.md` to `SKILL.md`
+- Remove invalid skill fields, map `invocable` β†’ `user-invocable`, `tools` β†’ `allowed-tools`
+- Update `init` executor to stop counting `.yaml` files
+
+### 3. MCP Server PID Fixes
+
+**Self-detection fix**: `start()` now skips the "already running" check when the reported PID matches the current process. `getStatus()` reports `running: true` with `process.pid` for stdio transport even before startup β€” this is correct for health checks but must not block the initial `start()` call.
+
+**PID reuse guard**: `isProcessRunning()` now verifies the process is actually `node`/`claude-flow`/`npx` by inspecting `/proc/{pid}/cmdline` (Linux) or `ps -p` (macOS). Falls back to `kill -0` on platforms where this isn't available.
+
+**Legacy cleanup**: `removePidFile()` now also removes `.claude-flow/mcp-server.pid` from older versions that wrote to a different path than the current `/tmp/claude-flow-mcp.pid`.
+
+## Consequences
+
+### Positive
+- Agents can now discover and navigate capabilities at runtime via MCP
+- All 107 agent files and 37 skill files have valid Claude Code frontmatter
+- MCP server starts reliably without false "already running" errors
+- `init` generates clean agents when scaffolding new projects
+
+### Negative
+- `hooks` fields were removed from agent frontmatter (they contained Claude Flow shell scripts, not Claude Code hook references β€” functionality preserved in CLI hooks system)
+- Guidance tools use a static catalog that must be updated when new capabilities are added
+
+## Files Changed
+
+- `v3/@claude-flow/cli/src/mcp-tools/guidance-tools.ts` β€” new (5 tools)
+- `v3/@claude-flow/cli/src/mcp-tools/index.ts` β€” export guidance tools
+- `v3/@claude-flow/cli/src/mcp-client.ts` β€” register guidance tools
+- `v3/@claude-flow/cli/src/mcp-server.ts` β€” PID self-detection + reuse guard + legacy cleanup
+- `v3/@claude-flow/cli/src/init/executor.ts` β€” stop counting .yaml files
+- `.claude/agents/**/*.md` β€” 100+ files standardized
+- `.claude/skills/**/SKILL.md` β€” 17 files standardized
diff --git a/v3/implementation/adrs/ADR-072-autopilot-persistent-completion.md b/v3/implementation/adrs/ADR-072-autopilot-persistent-completion.md
new file mode 100644
index 0000000000..dd0b7a3245
--- /dev/null
+++ b/v3/implementation/adrs/ADR-072-autopilot-persistent-completion.md
@@ -0,0 +1,544 @@
+# ADR-072: Autopilot Integration β€” Persistent Swarm Completion for Claude-Flow CLI
+
+- **Status**: Proposed
+- **Date**: 2026-03-25
+- **Depends on**: ADR-058 (Autopilot Swarm Completion in agentic-flow)
+- **Related**: ADR-037 (Autopilot Chat Mode in Ruflo UI), ADR-071 (Guidance MCP Tools)
+
+## Problem Statement
+
+Claude Code agents and swarms routinely stop before all tasks are complete. This happens because:
+
+1. **Context exhaustion**: Conversations hit context limits and lose track of remaining work
+2. **Premature satisfaction**: Agents declare "done" after completing 60-80% of tasks, skipping edge cases, tests, or documentation
+3. **No re-engagement**: When an agent stops, there is no mechanism to re-inject remaining task context and continue
+4. **No cross-session continuity**: If a session ends, the next session has no structured awareness of what was left incomplete
+5. **No learning**: The system doesn't learn from past completion patterns to predict and avoid failure modes
+
+The result is that complex multi-phase tasks (implement feature + write tests + update docs + security review) consistently require 2-4 manual "continue" prompts to reach 100% completion.
+
+## Decision
+
+Integrate agentic-flow's **Autopilot Persistent Completion System** (ADR-058) into the `@claude-flow/cli` package at three layers:
+
+1. **CLI commands** β€” 9 subcommands under `npx claude-flow autopilot`
+2. **MCP tools** β€” 10 tools registered in the MCP server
+3. **Stop hook integration** β€” Intercept agent stop events to check for remaining tasks
+4. **CLAUDE.md injection** β€” Auto-inject autopilot instructions into project configuration
+
+### Architecture
+
+```
+β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+β”‚ Claude Code Session β”‚
+β”‚ β”‚
+β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
+β”‚ β”‚ Agent 1 β”‚ β”‚ Agent 2 β”‚ β”‚ Agent 3 β”‚ β”‚ Agent N β”‚ β”‚
+β”‚ β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”˜ β”‚
+β”‚ β”‚ β”‚ β”‚ β”‚ β”‚
+β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
+β”‚ β–Ό β”‚
+β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
+β”‚ β”‚ Stop Hook β”‚ ← Intercepts every agent stop β”‚
+β”‚ β”‚ (pre-command) β”‚ β”‚
+β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
+β”‚ β–Ό β”‚
+β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
+β”‚ β”‚ Autopilot Coordinator β”‚ β”‚
+β”‚ β”‚ β”‚ β”‚
+β”‚ β”‚ 1. Discover tasks from 3 sources β”‚ β”‚
+β”‚ β”‚ 2. Check completion: all done? β”‚ β”‚
+β”‚ β”‚ YES β†’ Allow stop, record success episode β”‚ β”‚
+β”‚ β”‚ NO β†’ Build re-engagement context β”‚ β”‚
+β”‚ β”‚ β†’ Re-inject remaining tasks + learned patterns β”‚ β”‚
+β”‚ β”‚ β†’ Increment iteration counter β”‚ β”‚
+β”‚ β”‚ β†’ Continue execution β”‚ β”‚
+β”‚ β”‚ β”‚ β”‚
+β”‚ β”‚ Safety: max iterations (50), timeout (4hr), manual kill β”‚ β”‚
+β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
+β”‚ β–Ό β”‚
+β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
+β”‚ β”‚ AutopilotLearning (AgentDB) β”‚ β”‚
+β”‚ β”‚ β”‚ β”‚
+β”‚ β”‚ β€’ Record completion/failure episodes β”‚ β”‚
+β”‚ β”‚ β€’ SONA trajectory tracking β”‚ β”‚
+β”‚ β”‚ β€’ Pattern discovery from past completions β”‚ β”‚
+β”‚ β”‚ β€’ Predict optimal next action β”‚ β”‚
+β”‚ β”‚ β€’ Build re-engagement context with recommendations β”‚ β”‚
+β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
+β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
+```
+
+### Task Discovery Sources
+
+Autopilot discovers incomplete tasks from three sources, aggregated into a unified view:
+
+| Source | Location | Format | Priority |
+|--------|----------|--------|----------|
+| **Team Tasks** | `~/.claude/tasks/{team-name}/` | Claude Code task files | Highest |
+| **Swarm Tasks** | `.claude-flow/swarm-tasks.json` | agentic-flow swarm state | High |
+| **Checklist Files** | `.claude-flow/data/checklist.json` | Manual task checklists | Normal |
+
+A task is **incomplete** if its status is not one of: `completed`, `done`, `cancelled`, `skipped`.
+
+### Completion Criteria
+
+The autopilot loop exits (allows the agent to stop) when **any** of these conditions is true:
+
+1. **All tasks complete**: Every discovered task has a terminal status
+2. **Max iterations reached**: Default 50, configurable up to 1000
+3. **Timeout exceeded**: Default 240 minutes, configurable up to 24 hours
+4. **Manual disable**: User runs `npx claude-flow autopilot disable` or calls `autopilot_disable` MCP tool
+5. **No tasks found**: If all 3 sources return zero tasks (nothing to track)
+
+### Re-Engagement Protocol
+
+When the autopilot coordinator detects incomplete tasks and decides to continue, it builds a **re-engagement context** that includes:
+
+```typescript
+interface ReEngagementContext {
+ // From AutopilotLearning (AgentDB)
+ pastFailures: Array<{ task: string; critique?: string; reward: number }>;
+ pastSuccesses: Array<{ task: string; reward: number }>;
+ patterns: Array<{ pattern: string; frequency: number; avgReward: number }>;
+ recommendations: string[];
+ confidence: number; // 0-1, based on episode count
+
+ // From task discovery
+ remainingTasks: Array<{ id: string; subject: string; status: string; source: string }>;
+ completedTasks: number;
+ totalTasks: number;
+ progressPercent: number;
+}
+```
+
+This context is injected into the agent's prompt as:
+
+```
+AUTOPILOT: {completedTasks}/{totalTasks} tasks complete ({progressPercent}%).
+Remaining: {remainingTasks as bullet list}
+{if learning available: Past patterns suggest: {recommendations}}
+Continue working on the remaining tasks. Do not stop until all are complete.
+```
+
+---
+
+## Implementation Plan
+
+### Phase 1: CLI Command (npx claude-flow autopilot)
+
+**File**: `v3/@claude-flow/cli/src/commands/autopilot.ts`
+
+Add 9 subcommands that delegate to agentic-flow's `handleAutopilotCommand()`:
+
+| Subcommand | Description | Key Options |
+|------------|-------------|-------------|
+| `status` | Show autopilot state, iterations, progress | `--json` |
+| `enable` | Enable persistent completion | β€” |
+| `disable` | Disable re-engagement loop | β€” |
+| `config` | Set max iterations, timeout, task sources | `--max-iterations`, `--timeout`, `--task-sources` |
+| `reset` | Reset iteration counter and start time | β€” |
+| `log` | View autopilot event log | `--last N`, `--json`, `--clear` |
+| `learn` | Discover success patterns from AgentDB | `--json` |
+| `history` | Search past completion episodes | `--query`, `--limit`, `--json` |
+| `predict` | Predict optimal next action | `--json` |
+
+**Import path**: `agentic-flow/dist/agentic-flow/src/cli/autopilot-cli.js` (not yet re-exported from coordination index β€” needs agentic-flow export fix or direct path import)
+
+### Phase 2: MCP Tools Registration
+
+**File**: `v3/@claude-flow/cli/src/mcp-tools/autopilot-tools.ts`
+
+Register 10 MCP tools by wrapping agentic-flow's `registerAutopilotTools()` or implementing a thin adapter layer:
+
+| MCP Tool | Purpose | Input |
+|----------|---------|-------|
+| `autopilot_status` | Current state + task progress | `{ json?: boolean }` |
+| `autopilot_enable` | Enable persistent completion | `{}` |
+| `autopilot_disable` | Disable re-engagement | `{}` |
+| `autopilot_config` | Configure limits | `{ maxIterations?, timeoutMinutes?, taskSources? }` |
+| `autopilot_reset` | Reset counters | `{}` |
+| `autopilot_log` | Retrieve event log | `{ last?: number, json?: boolean }` |
+| `autopilot_progress` | Detailed per-source task progress | `{}` |
+| `autopilot_learn` | Discover success patterns | `{ json?: boolean }` |
+| `autopilot_history` | Search past episodes | `{ query: string, limit?: number }` |
+| `autopilot_predict` | Predict next action | `{ json?: boolean }` |
+
+**Registration**: Add to `mcp-tools/index.ts` exports and `mcp-client.ts` `registerTools()`.
+
+### Phase 3: Stop Hook Integration
+
+**File**: `v3/@claude-flow/cli/src/hooks/autopilot-stop-hook.ts`
+
+The stop hook is the critical integration point. It runs when an agent or the main Claude session attempts to end:
+
+```typescript
+// Pseudocode for the stop hook
+async function autopilotStopHook(context: StopHookContext): Promise<StopHookResult> {
+ // 1. Check if autopilot is enabled
+ const config = loadAutopilotConfig();
+ if (!config.enabled) return { allowStop: true };
+
+ // 2. Check safety limits
+ const state = loadAutopilotState();
+ if (state.iterations >= config.maxIterations) {
+ logEvent('max-iterations-reached', state);
+ return { allowStop: true, reason: `Max iterations (${config.maxIterations}) reached` };
+ }
+ if (Date.now() - state.startTime > config.timeoutMinutes * 60000) {
+ logEvent('timeout-reached', state);
+ return { allowStop: true, reason: `Timeout (${config.timeoutMinutes}min) reached` };
+ }
+
+ // 3. Discover tasks from all sources
+ const tasks = await discoverTasks(config.taskSources);
+ const incomplete = tasks.filter(t => !isTerminal(t.status));
+
+ if (incomplete.length === 0) {
+ // All done β€” record success and allow stop
+ await learning.recordTaskCompletion({
+ taskId: state.sessionId,
+ subject: `Session completion: ${tasks.length} tasks`,
+ status: 'completed',
+ iterations: state.iterations,
+ durationMs: Date.now() - state.startTime,
+ });
+ await learning.endSwarmTrajectory({ completed: tasks.length, total: tasks.length });
+ logEvent('all-tasks-complete', { total: tasks.length, iterations: state.iterations });
+ return { allowStop: true };
+ }
+
+ // 4. Tasks remain β€” build re-engagement context
+ state.iterations++;
+ saveAutopilotState(state);
+
+ const reEngagement = await learning.getReEngagementContext(
+ incomplete.map(t => ({ subject: t.subject, status: t.status }))
+ );
+
+ await learning.recordIterationStep(
+ { completed: tasks.length - incomplete.length, total: tasks.length, iterations: state.iterations, progress: (tasks.length - incomplete.length) / tasks.length },
+ [] // drift signals
+ );
+
+ logEvent('re-engaging', {
+ iteration: state.iterations,
+ completed: tasks.length - incomplete.length,
+ remaining: incomplete.length,
+ confidence: reEngagement.confidence,
+ });
+
+ // 5. Build continuation prompt
+ const prompt = buildReEngagementPrompt(incomplete, reEngagement, state);
+
+ return {
+ allowStop: false,
+ continueWith: prompt,
+ reason: `${incomplete.length}/${tasks.length} tasks remaining (iteration ${state.iterations}/${config.maxIterations})`,
+ };
+}
+```
+
+**Hook registration**: Add to `.claude/settings.json` via `init` command:
+
+```json
+{
+ "hooks": {
+ "Stop": [
+ {
+ "matcher": "",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "npx claude-flow@latest hooks autopilot-check"
+ }
+ ]
+ }
+ ]
+ }
+}
+```
+
+### Phase 4: CLAUDE.md Autopilot Instructions
+
+**File**: `v3/@claude-flow/cli/src/init/executor.ts`
+
+When `npx claude-flow init` runs, inject autopilot behavioral instructions into the generated CLAUDE.md:
+
+```markdown
+## Autopilot: Persistent Task Completion
+
+This project uses autopilot for persistent swarm completion. When enabled:
+
+1. **Do not stop early**: Continue working until ALL tasks in the task list are complete
+2. **Check task status**: Before finishing, verify every task is marked `completed`
+3. **Re-engage on incomplete**: If tasks remain, continue working on them
+4. **Report progress**: Periodically report completion percentage
+
+### Autopilot Commands
+- `npx claude-flow autopilot status` β€” Check current progress
+- `npx claude-flow autopilot enable` β€” Enable persistent completion
+- `npx claude-flow autopilot disable` β€” Disable (allow early stop)
+- `npx claude-flow autopilot predict` β€” Get AI-recommended next action
+```
+
+### Phase 5: agentic-flow Export Fix
+
+**File**: `agentic-flow/src/coordination/index.ts` (in agentic-flow repo)
+
+The autopilot modules exist in the build output but are not re-exported. Add:
+
+```typescript
+// coordination/index.ts
+export { AutopilotLearning } from './autopilot-learning.js';
+export type { AutopilotEpisode, ReEngagementContext, LearningMetrics } from './autopilot-learning.js';
+```
+
+```typescript
+// mcp/fastmcp/tools/index.ts
+export { registerAutopilotTools } from './autopilot-tools.js';
+```
+
+```typescript
+// cli/index.ts
+export { handleAutopilotCommand } from './autopilot-cli.js';
+```
+
+Add to `package.json` exports:
+
+```json
+{
+ "exports": {
+ "./autopilot": "./dist/coordination/autopilot-learning.js",
+ "./autopilot/cli": "./dist/cli/autopilot-cli.js",
+ "./autopilot/mcp": "./dist/mcp/fastmcp/tools/autopilot-tools.js"
+ }
+}
+```
+
+Publish as `[email protected]`.
+
+---
+
+## State Management
+
+### Autopilot State File
+
+**Location**: `.claude-flow/data/autopilot-state.json`
+
+```json
+{
+ "sessionId": "ulid-session-id",
+ "enabled": true,
+ "startTime": 1770837879989,
+ "iterations": 0,
+ "maxIterations": 50,
+ "timeoutMinutes": 240,
+ "taskSources": ["team-tasks", "swarm-tasks", "file-checklist"],
+ "lastCheck": null,
+ "history": []
+}
+```
+
+### Autopilot Event Log
+
+**Location**: `.claude-flow/data/autopilot-log.json`
+
+Array of events:
+
+```json
+[
+ { "ts": 1770837880000, "event": "enabled", "config": { "maxIterations": 50 } },
+ { "ts": 1770837890000, "event": "re-engaging", "iteration": 1, "completed": 3, "remaining": 5, "confidence": 0.72 },
+ { "ts": 1770837990000, "event": "re-engaging", "iteration": 2, "completed": 6, "remaining": 2, "confidence": 0.85 },
+ { "ts": 1770838090000, "event": "all-tasks-complete", "total": 8, "iterations": 3, "durationMs": 210000 }
+]
+```
+
+### Configuration Persistence
+
+**Location**: `.claude/settings.json` under `claudeFlow.autopilot`
+
+```json
+{
+ "claudeFlow": {
+ "autopilot": {
+ "enabled": true,
+ "maxIterations": 50,
+ "timeoutMinutes": 240,
+ "taskSources": ["team-tasks", "swarm-tasks", "file-checklist"],
+ "completionCriteria": "all-tasks-done",
+ "logFile": ".claude-flow/data/autopilot-log.json"
+ }
+ }
+}
+```
+
+---
+
+## Learning Integration
+
+### Episode Recording
+
+Every time autopilot allows a stop (success) or hits a limit (failure), it records an episode:
+
+**Success episode**:
+```typescript
+await learning.recordTaskCompletion({
+ taskId: sessionId,
+ subject: `Completed: ${taskSummary}`,
+ status: 'completed',
+ iterations: state.iterations,
+ durationMs: elapsed,
+});
+```
+
+**Failure episode** (max iterations or timeout):
+```typescript
+await learning.recordTaskFailure({
+ taskId: sessionId,
+ subject: `Incomplete: ${incompleteTasks.length} remaining`,
+ status: 'timeout',
+ iterations: state.iterations,
+ durationMs: elapsed,
+ critique: `Stopped at ${progressPercent}% β€” remaining: ${incompleteList}`,
+});
+```
+
+### Reward Calculation
+
+The reward formula balances efficiency (fewer iterations = better) and speed (shorter duration = better):
+
+```
+reward = (1 - iterations/(iterations + 10)) * 0.6 + (1 - min(durationMs/3600000, 1)) * 0.4
+```
+
+| Iterations | Duration | Reward | Interpretation |
+|-----------|----------|--------|----------------|
+| 1 | 5 min | 0.94 | Excellent β€” completed quickly with no re-engagement |
+| 3 | 15 min | 0.83 | Good β€” needed 3 iterations but stayed fast |
+| 10 | 60 min | 0.54 | Moderate β€” struggled but completed within an hour |
+| 50 | 240 min | 0.09 | Poor β€” hit max iterations, long duration |
+
+### SONA Trajectory Tracking
+
+For multi-step learning across sessions:
+
+1. **Begin**: `learning.beginSwarmTrajectory(sessionId)` at autopilot enable
+2. **Step**: `learning.recordIterationStep(state, driftSignals)` at each re-engagement
+3. **End**: `learning.endSwarmTrajectory(finalState)` at completion or timeout
+4. **Patterns**: `learning.discoverSuccessPatterns()` to extract reusable strategies
+
+---
+
+## Safety Mechanisms
+
+| Mechanism | Default | Max | Description |
+|-----------|---------|-----|-------------|
+| Max iterations | 50 | 1000 | Hard limit on re-engagement attempts |
+| Timeout | 240 min | 1440 min (24hr) | Wall-clock timeout from first enable |
+| Manual disable | β€” | β€” | `autopilot disable` stops immediately |
+| Task source validation | β€” | β€” | Only reads from known, safe paths |
+| No destructive actions | β€” | β€” | Re-engagement only injects prompts, never executes commands |
+| Progress monotonicity check | β€” | β€” | If progress hasn't increased in 5 iterations, warn and suggest different approach |
+| Cost awareness | β€” | β€” | Log estimated token usage per iteration for budget tracking |
+
+### Stall Detection
+
+If the completion count hasn't increased for 5 consecutive iterations, autopilot logs a warning and includes it in the re-engagement context:
+
+```
+WARNING: No progress in 5 iterations. Consider:
+- Breaking remaining tasks into smaller subtasks
+- Trying a different approach
+- Checking if tasks are blocked on external dependencies
+```
+
+After 10 stalled iterations, autopilot disables itself and records a failure episode with the stall pattern.
+
+---
+
+## Implementation Order
+
+| Phase | Effort | Dependency | Description |
+|-------|--------|------------|-------------|
+| **5** | 30 min | agentic-flow repo | Export autopilot modules, publish alpha.3 |
+| **1** | 2 hr | Phase 5 | CLI `autopilot` command with 9 subcommands |
+| **2** | 2 hr | Phase 5 | 10 MCP tools registered in MCP server |
+| **3** | 3 hr | Phase 1+2 | Stop hook integration with task discovery |
+| **4** | 1 hr | Phase 1 | CLAUDE.md injection in `init` command |
+
+**Total estimated effort**: 8-9 hours across both repos.
+
+### Acceptance Criteria
+
+1. `npx claude-flow autopilot status` returns current state (enabled, iterations, progress)
+2. `npx claude-flow autopilot enable/disable` toggles persistent completion
+3. `npx claude-flow autopilot config --max-iterations 100` persists to settings
+4. All 10 MCP tools respond correctly when called via MCP client
+5. Stop hook intercepts agent stop and re-engages when tasks remain
+6. Stop hook allows stop when all tasks are complete
+7. Stop hook respects max iterations and timeout limits
+8. AgentDB learning records episodes and can discover patterns
+9. `npx claude-flow autopilot predict` returns actionable recommendations
+10. `npx claude-flow init` includes autopilot configuration in generated settings
+11. Stall detection triggers after 5 iterations with no progress
+12. All existing tests continue to pass (no regressions)
+
+---
+
+## Consequences
+
+### Positive
+
+- Swarms run to 100% completion without manual "continue" prompts
+- System learns from every completion/failure, improving over time
+- Predictive actions reduce iteration count for familiar task patterns
+- Safety limits prevent runaway execution and cost overruns
+- Works without AgentDB (graceful degradation β€” no learning, but still completes)
+- Compatible with existing Claude Code task system, swarm tasks, and checklists
+
+### Negative
+
+- Additional agentic-flow dependency surface (autopilot modules must be published)
+- Stop hook adds latency to every agent stop event (task discovery scan)
+- Learning database grows over time (needs periodic pruning strategy)
+- Complex multi-source task discovery may have edge cases with conflicting task states
+- Re-engagement prompts consume tokens, adding to session cost
+
+### Risks
+
+- **False re-engagement**: Tasks marked as "in_progress" by a terminated agent could cause infinite re-engagement. Mitigation: stall detection + timeout.
+- **Context exhaustion**: Re-engagement injects text that consumes context window. Mitigation: compact re-engagement prompts, limit to top 5 remaining tasks.
+- **Cost runaway**: 50 iterations of re-engagement could be expensive. Mitigation: configurable limits, cost tracking in event log, budget-aware config option.
+
+---
+
+## Files to Create/Modify
+
+### New Files
+
+| File | Purpose |
+|------|---------|
+| `v3/@claude-flow/cli/src/commands/autopilot.ts` | CLI command with 9 subcommands |
+| `v3/@claude-flow/cli/src/mcp-tools/autopilot-tools.ts` | 10 MCP tools |
+| `v3/@claude-flow/cli/src/hooks/autopilot-stop-hook.ts` | Stop hook coordinator |
+| `v3/@claude-flow/cli/__tests__/autopilot.test.ts` | Unit tests |
+
+### Modified Files
+
+| File | Change |
+|------|--------|
+| `v3/@claude-flow/cli/src/commands/index.ts` | Register autopilot command |
+| `v3/@claude-flow/cli/src/mcp-tools/index.ts` | Export autopilotTools |
+| `v3/@claude-flow/cli/src/mcp-client.ts` | Register autopilot tools in registerTools() |
+| `v3/@claude-flow/cli/src/init/executor.ts` | Inject autopilot config in CLAUDE.md + settings |
+
+### agentic-flow Repo Changes
+
+| File | Change |
+|------|--------|
+| `src/coordination/index.ts` | Re-export AutopilotLearning |
+| `src/mcp/fastmcp/tools/index.ts` | Re-export registerAutopilotTools |
+| `src/cli/index.ts` | Re-export handleAutopilotCommand |
+| `package.json` | Add `./autopilot`, `./autopilot/cli`, `./autopilot/mcp` exports |