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: implement autopilot persistent completion system (ADR-072)

rUvce80a9c28c6e
diff --git a/v3/@claude-flow/cli/src/commands/autopilot.ts b/v3/@claude-flow/cli/src/commands/autopilot.ts
new file mode 100644
index 0000000000..1b02670de4
--- /dev/null
+++ b/v3/@claude-flow/cli/src/commands/autopilot.ts
@@ -0,0 +1,604 @@
+/**
+ * V3 CLI Autopilot Command
+ * Persistent swarm completion β€” keeps agents working until ALL tasks are done.
+ *
+ * ADR-072: Autopilot Integration
+ */
+
+import type { Command, CommandContext, CommandResult } from '../types.js';
+import { output } from '../output.js';
+
+// ── State Management ──────────────────────────────────────────
+
+const STATE_DIR = '.claude-flow/data';
+const STATE_FILE = `${STATE_DIR}/autopilot-state.json`;
+const LOG_FILE = `${STATE_DIR}/autopilot-log.json`;
+
+interface AutopilotState {
+ sessionId: string;
+ enabled: boolean;
+ startTime: number;
+ iterations: number;
+ maxIterations: number;
+ timeoutMinutes: number;
+ taskSources: string[];
+ lastCheck: number | null;
+ history: Array<{ ts: number; iteration: number; completed: number; total: number }>;
+}
+
+interface AutopilotLogEntry {
+ ts: number;
+ event: string;
+ [key: string]: unknown;
+}
+
+interface TaskInfo {
+ id: string;
+ subject: string;
+ status: string;
+ source: string;
+}
+
+function getDefaultState(): AutopilotState {
+ const crypto = require('crypto') as typeof import('crypto');
+ return {
+ sessionId: crypto.randomUUID(),
+ enabled: false,
+ startTime: Date.now(),
+ iterations: 0,
+ maxIterations: 50,
+ timeoutMinutes: 240,
+ taskSources: ['team-tasks', 'swarm-tasks', 'file-checklist'],
+ lastCheck: null,
+ history: [],
+ };
+}
+
+function loadState(): AutopilotState {
+ const fs = require('fs') as typeof import('fs');
+ const path = require('path') as typeof import('path');
+ const filePath = path.resolve(STATE_FILE);
+ try {
+ if (fs.existsSync(filePath)) {
+ return { ...getDefaultState(), ...JSON.parse(fs.readFileSync(filePath, 'utf-8')) };
+ }
+ } catch { /* ignore */ }
+ return getDefaultState();
+}
+
+function saveState(state: AutopilotState): void {
+ const fs = require('fs') as typeof import('fs');
+ const path = require('path') as typeof import('path');
+ const dir = path.resolve(STATE_DIR);
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(path.resolve(STATE_FILE), JSON.stringify(state, null, 2));
+}
+
+function appendLog(entry: AutopilotLogEntry): void {
+ const fs = require('fs') as typeof import('fs');
+ const path = require('path') as typeof import('path');
+ const filePath = path.resolve(LOG_FILE);
+ const dir = path.resolve(STATE_DIR);
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
+ let log: AutopilotLogEntry[] = [];
+ try {
+ if (fs.existsSync(filePath)) {
+ log = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
+ }
+ } catch { /* ignore */ }
+ log.push(entry);
+ if (log.length > 1000) log = log.slice(-1000);
+ fs.writeFileSync(filePath, JSON.stringify(log, null, 2));
+}
+
+function loadLog(): AutopilotLogEntry[] {
+ const fs = require('fs') as typeof import('fs');
+ const path = require('path') as typeof import('path');
+ const filePath = path.resolve(LOG_FILE);
+ try {
+ if (fs.existsSync(filePath)) {
+ return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
+ }
+ } catch { /* ignore */ }
+ return [];
+}
+
+// ── Task Discovery ────────────────────────────────────────────
+
+export function discoverTasks(sources: string[]): TaskInfo[] {
+ const fs = require('fs') as typeof import('fs');
+ const path = require('path') as typeof import('path');
+ const os = require('os') as typeof import('os');
+ const tasks: TaskInfo[] = [];
+
+ for (const source of sources) {
+ if (source === 'team-tasks') {
+ const tasksDir = path.join(os.homedir(), '.claude', 'tasks');
+ try {
+ if (fs.existsSync(tasksDir)) {
+ const teams = fs.readdirSync(tasksDir, { withFileTypes: true });
+ for (const team of teams) {
+ if (!team.isDirectory()) continue;
+ const teamDir = path.join(tasksDir, team.name);
+ const files = fs.readdirSync(teamDir).filter((f: string) => f.endsWith('.json'));
+ for (const file of files) {
+ try {
+ const data = JSON.parse(fs.readFileSync(path.join(teamDir, file), 'utf-8'));
+ tasks.push({
+ id: data.id || file.replace('.json', ''),
+ subject: data.subject || data.title || file,
+ status: data.status || 'unknown',
+ source: 'team-tasks',
+ });
+ } catch { /* skip */ }
+ }
+ }
+ }
+ } catch { /* ignore */ }
+ }
+
+ if (source === 'swarm-tasks') {
+ const swarmFile = path.resolve('.claude-flow/swarm-tasks.json');
+ try {
+ if (fs.existsSync(swarmFile)) {
+ const data = JSON.parse(fs.readFileSync(swarmFile, 'utf-8'));
+ const swarmTasks = Array.isArray(data) ? data : (data.tasks || []);
+ for (const t of swarmTasks) {
+ tasks.push({
+ id: t.id || t.taskId || `swarm-${tasks.length}`,
+ subject: t.subject || t.description || t.name || 'Unnamed task',
+ status: t.status || 'unknown',
+ source: 'swarm-tasks',
+ });
+ }
+ }
+ } catch { /* ignore */ }
+ }
+
+ if (source === 'file-checklist') {
+ const checklistFile = path.resolve('.claude-flow/data/checklist.json');
+ try {
+ if (fs.existsSync(checklistFile)) {
+ const data = JSON.parse(fs.readFileSync(checklistFile, 'utf-8'));
+ const items = Array.isArray(data) ? data : (data.items || []);
+ for (const item of items) {
+ tasks.push({
+ id: item.id || `check-${tasks.length}`,
+ subject: item.subject || item.text || item.description || 'Unnamed item',
+ status: item.status || (item.done ? 'completed' : 'pending'),
+ source: 'file-checklist',
+ });
+ }
+ }
+ } catch { /* ignore */ }
+ }
+ }
+
+ return tasks;
+}
+
+const TERMINAL_STATUSES = new Set(['completed', 'done', 'cancelled', 'skipped', 'failed']);
+
+function isTerminal(status: string): boolean {
+ return TERMINAL_STATUSES.has(status.toLowerCase());
+}
+
+function getProgress(tasks: TaskInfo[]): { completed: number; total: number; percent: number; incomplete: TaskInfo[] } {
+ const completed = tasks.filter(t => isTerminal(t.status)).length;
+ const total = tasks.length;
+ const percent = total === 0 ? 100 : Math.round((completed / total) * 100);
+ const incomplete = tasks.filter(t => !isTerminal(t.status));
+ return { completed, total, percent, incomplete };
+}
+
+// ── Reward Calculation ────────────────────────────────────────
+
+function calculateReward(iterations: number, durationMs: number): number {
+ const iterFactor = (1 - iterations / (iterations + 10)) * 0.6;
+ const timeFactor = (1 - Math.min(durationMs / 3600000, 1)) * 0.4;
+ return Math.round((iterFactor + timeFactor) * 100) / 100;
+}
+
+// ── Learning Integration (graceful degradation) ───────────────
+
+async function tryLoadLearning(): Promise<{ initialize: () => Promise<boolean>; [key: string]: unknown } | null> {
+ try {
+ // Dynamic import β€” won't fail at compile time
+ const modPath = 'agentic-flow/dist/coordination/autopilot-learning.js';
+ const mod = await import(/* webpackIgnore: true */ modPath).catch(() => null);
+ if (mod?.AutopilotLearning) {
+ const instance = new mod.AutopilotLearning();
+ if (await instance.initialize()) return instance;
+ }
+ } catch { /* not available */ }
+ return null;
+}
+
+// ── Check Handler (for Stop hook) ─────────────────────────────
+
+export async function autopilotCheck(): Promise<{ allowStop: boolean; reason: string; continueWith?: string }> {
+ const state = loadState();
+
+ if (!state.enabled) {
+ return { allowStop: true, reason: 'Autopilot disabled' };
+ }
+
+ // Safety: max iterations
+ if (state.iterations >= state.maxIterations) {
+ state.enabled = false;
+ saveState(state);
+ appendLog({ ts: Date.now(), event: 'max-iterations-reached', iterations: state.iterations });
+ return { allowStop: true, reason: `Max iterations (${state.maxIterations}) reached` };
+ }
+
+ // Safety: timeout
+ const elapsed = Date.now() - state.startTime;
+ if (elapsed > state.timeoutMinutes * 60000) {
+ state.enabled = false;
+ saveState(state);
+ appendLog({ ts: Date.now(), event: 'timeout-reached', elapsed: Math.round(elapsed / 60000) });
+ return { allowStop: true, reason: `Timeout (${state.timeoutMinutes} min) reached` };
+ }
+
+ // Discover tasks
+ const tasks = discoverTasks(state.taskSources);
+ if (tasks.length === 0) {
+ return { allowStop: true, reason: 'No tasks discovered from any source' };
+ }
+
+ const progress = getProgress(tasks);
+
+ if (progress.incomplete.length === 0) {
+ const reward = calculateReward(state.iterations, elapsed);
+ state.enabled = false;
+ saveState(state);
+ appendLog({ ts: Date.now(), event: 'all-tasks-complete', total: progress.total, iterations: state.iterations, durationMs: elapsed, reward });
+ return { allowStop: true, reason: `All ${progress.total} tasks complete (${state.iterations} iterations, reward: ${reward})` };
+ }
+
+ // Stall detection
+ const recentHistory = state.history.slice(-5);
+ const isStalled = recentHistory.length >= 5 && recentHistory.every(h => h.completed === progress.completed);
+
+ if (isStalled && state.history.length >= 10) {
+ state.enabled = false;
+ saveState(state);
+ appendLog({ ts: Date.now(), event: 'stall-auto-disable', iterations: state.iterations, completed: progress.completed });
+ return { allowStop: true, reason: `Stalled: no progress in 10 iterations (${progress.completed}/${progress.total} complete)` };
+ }
+
+ // Re-engage
+ state.iterations++;
+ state.lastCheck = Date.now();
+ state.history.push({ ts: Date.now(), iteration: state.iterations, completed: progress.completed, total: progress.total });
+ saveState(state);
+
+ const stallWarning = isStalled
+ ? '\nWARNING: No progress in 5 iterations. Consider breaking tasks into smaller subtasks or trying a different approach.'
+ : '';
+
+ const taskList = progress.incomplete.slice(0, 5).map(t => `- ${t.subject} (${t.status})`).join('\n');
+ const moreCount = progress.incomplete.length > 5 ? `\n... and ${progress.incomplete.length - 5} more` : '';
+
+ const continuePrompt = [
+ `AUTOPILOT: ${progress.completed}/${progress.total} tasks complete (${progress.percent}%).`,
+ `Iteration ${state.iterations}/${state.maxIterations}.`,
+ `Remaining tasks:\n${taskList}${moreCount}`,
+ stallWarning,
+ `Continue working on the remaining tasks. Do not stop until all are complete.`,
+ ].join('\n');
+
+ appendLog({ ts: Date.now(), event: 're-engaging', iteration: state.iterations, completed: progress.completed, remaining: progress.incomplete.length });
+
+ return { allowStop: false, reason: `${progress.incomplete.length}/${progress.total} tasks remaining (iteration ${state.iterations}/${state.maxIterations})`, continueWith: continuePrompt };
+}
+
+// ── Subcommands ───────────────────────────────────────────────
+
+const statusCommand: Command = {
+ name: 'status',
+ description: 'Show autopilot state, iterations, and task progress',
+ options: [{ name: 'json', type: 'boolean', description: 'Output as JSON' }],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const state = loadState();
+ const tasks = discoverTasks(state.taskSources);
+ const progress = getProgress(tasks);
+ const elapsed = state.enabled ? Date.now() - state.startTime : 0;
+
+ if (ctx.flags?.json) {
+ output.printJson({
+ enabled: state.enabled, sessionId: state.sessionId, iterations: state.iterations,
+ maxIterations: state.maxIterations, timeoutMinutes: state.timeoutMinutes, elapsedMs: elapsed,
+ tasks: { completed: progress.completed, total: progress.total, percent: progress.percent },
+ taskSources: state.taskSources,
+ });
+ return { success: true };
+ }
+
+ output.writeln(`Autopilot: ${state.enabled ? 'βœ“ ENABLED' : 'βœ— DISABLED'}`);
+ output.writeln(`Session: ${state.sessionId.slice(0, 8)}...`);
+ output.writeln(`Iterations: ${state.iterations}/${state.maxIterations}`);
+ output.writeln(`Timeout: ${state.timeoutMinutes} min`);
+ output.writeln(`Elapsed: ${Math.round(elapsed / 60000)} min`);
+ output.writeln(`Tasks: ${progress.completed}/${progress.total} (${progress.percent}%)`);
+ output.writeln(`Sources: ${state.taskSources.join(', ')}`);
+
+ if (progress.incomplete.length > 0 && progress.incomplete.length <= 10) {
+ output.writeln('\nRemaining tasks:');
+ for (const t of progress.incomplete) {
+ output.writeln(` - [${t.source}] ${t.subject} (${t.status})`);
+ }
+ }
+ return { success: true };
+ },
+};
+
+const enableCommand: Command = {
+ name: 'enable',
+ description: 'Enable persistent completion',
+ action: async (): Promise<CommandResult> => {
+ const state = loadState();
+ state.enabled = true;
+ state.startTime = Date.now();
+ state.iterations = 0;
+ saveState(state);
+ appendLog({ ts: Date.now(), event: 'enabled', sessionId: state.sessionId, maxIterations: state.maxIterations });
+ output.writeln(output.success(`Autopilot enabled (max ${state.maxIterations} iterations, ${state.timeoutMinutes} min timeout)`));
+ return { success: true };
+ },
+};
+
+const disableCommand: Command = {
+ name: 'disable',
+ description: 'Disable re-engagement loop',
+ action: async (): Promise<CommandResult> => {
+ const state = loadState();
+ const wasEnabled = state.enabled;
+ state.enabled = false;
+ saveState(state);
+ if (wasEnabled) appendLog({ ts: Date.now(), event: 'disabled', iterations: state.iterations });
+ output.writeln('Autopilot disabled');
+ return { success: true };
+ },
+};
+
+const configCommand: Command = {
+ name: 'config',
+ description: 'Configure max iterations, timeout, and task sources',
+ options: [
+ { name: 'max-iterations', type: 'string', description: 'Max re-engagement iterations (1-1000)' },
+ { name: 'timeout', type: 'string', description: 'Timeout in minutes (1-1440)' },
+ { name: 'task-sources', type: 'string', description: 'Comma-separated task sources' },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const state = loadState();
+ const maxIter = ctx.flags?.['max-iterations'] as string | undefined;
+ const timeout = ctx.flags?.timeout as string | undefined;
+ const sources = ctx.flags?.['task-sources'] as string | undefined;
+
+ if (maxIter) state.maxIterations = Math.min(Math.max(1, parseInt(maxIter, 10) || 50), 1000);
+ if (timeout) state.timeoutMinutes = Math.min(Math.max(1, parseInt(timeout, 10) || 240), 1440);
+ if (sources) state.taskSources = sources.split(',').map(s => s.trim()).filter(Boolean);
+
+ saveState(state);
+ appendLog({ ts: Date.now(), event: 'config-updated', maxIterations: state.maxIterations, timeoutMinutes: state.timeoutMinutes, taskSources: state.taskSources });
+ output.writeln(`Config updated: maxIterations=${state.maxIterations}, timeout=${state.timeoutMinutes}min, sources=${state.taskSources.join(',')}`);
+ return { success: true };
+ },
+};
+
+const resetCommand: Command = {
+ name: 'reset',
+ description: 'Reset iteration counter and timer',
+ action: async (): Promise<CommandResult> => {
+ const state = loadState();
+ state.iterations = 0;
+ state.startTime = Date.now();
+ state.history = [];
+ state.lastCheck = null;
+ saveState(state);
+ appendLog({ ts: Date.now(), event: 'reset' });
+ output.writeln('Autopilot state reset (iterations=0, timer restarted)');
+ return { success: true };
+ },
+};
+
+const logCommand: Command = {
+ name: 'log',
+ description: 'View autopilot event log',
+ options: [
+ { name: 'last', type: 'string', description: 'Show last N entries' },
+ { name: 'json', type: 'boolean', description: 'Output as JSON' },
+ { name: 'clear', type: 'boolean', description: 'Clear the log' },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ if (ctx.flags?.clear) {
+ const fs = require('fs') as typeof import('fs');
+ const path = require('path') as typeof import('path');
+ try { fs.writeFileSync(path.resolve(LOG_FILE), '[]'); } catch { /* ignore */ }
+ output.writeln('Autopilot log cleared');
+ return { success: true };
+ }
+
+ const log = loadLog();
+ const last = ctx.flags?.last ? parseInt(ctx.flags.last as string, 10) : undefined;
+ const entries = last ? log.slice(-last) : log;
+
+ if (ctx.flags?.json) {
+ output.printJson(entries);
+ return { success: true };
+ }
+
+ if (entries.length === 0) {
+ output.writeln('No autopilot events logged');
+ return { success: true };
+ }
+
+ for (const e of entries) {
+ const time = new Date(e.ts).toISOString().slice(11, 19);
+ const details = Object.entries(e).filter(([k]) => k !== 'ts' && k !== 'event').map(([k, v]) => `${k}=${v}`).join(' ');
+ output.writeln(`[${time}] ${e.event} ${details}`);
+ }
+ return { success: true };
+ },
+};
+
+const learnCommand: Command = {
+ name: 'learn',
+ description: 'Discover success patterns from past completions',
+ options: [{ name: 'json', type: 'boolean', description: 'Output as JSON' }],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const learning = await tryLoadLearning();
+ if (!learning) {
+ output.writeln('Learning not available (AgentDB not initialized). Autopilot still works for task completion tracking.');
+ return { success: true };
+ }
+
+ const metrics = await (learning as any).getMetrics();
+ const patterns = await (learning as any).discoverSuccessPatterns();
+
+ if (ctx.flags?.json) {
+ output.printJson({ metrics, patterns });
+ return { success: true };
+ }
+
+ output.writeln(`Episodes: ${metrics.episodes}`);
+ output.writeln(`Patterns: ${metrics.patterns}`);
+ output.writeln(`Trajectories: ${metrics.trajectories}`);
+
+ if (patterns.length > 0) {
+ output.writeln('\nDiscovered patterns:');
+ for (const p of patterns) {
+ output.writeln(` - ${p.pattern} (freq: ${p.frequency}, reward: ${p.avgReward.toFixed(2)})`);
+ }
+ }
+ return { success: true };
+ },
+};
+
+const historyCommand: Command = {
+ name: 'history',
+ description: 'Search past completion episodes',
+ options: [
+ { name: 'query', type: 'string', description: 'Search query', required: true },
+ { name: 'limit', type: 'string', description: 'Max results (default 10)' },
+ { name: 'json', type: 'boolean', description: 'Output as JSON' },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const query = (ctx.flags?.query || '') as string;
+ const limit = parseInt((ctx.flags?.limit || '10') as string, 10);
+
+ if (!query) {
+ output.writeln('Usage: autopilot history --query "search terms" [--limit N]');
+ return { success: false, message: 'Missing --query' };
+ }
+
+ const learning = await tryLoadLearning();
+ if (!learning) {
+ output.writeln('Learning not available. No history to search.');
+ return { success: true };
+ }
+
+ const results = await (learning as any).recallSimilarTasks(query, limit);
+ if (ctx.flags?.json) {
+ output.printJson(results);
+ } else if (results.length === 0) {
+ output.writeln(`No matching episodes for: "${query}"`);
+ } else {
+ output.printJson(results);
+ }
+ return { success: true };
+ },
+};
+
+const predictCommand: Command = {
+ name: 'predict',
+ description: 'Predict optimal next action',
+ options: [{ name: 'json', type: 'boolean', description: 'Output as JSON' }],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const state = loadState();
+ const learning = await tryLoadLearning();
+
+ if (learning) {
+ const prediction = await (learning as any).predictNextAction(state);
+ if (ctx.flags?.json) {
+ output.printJson(prediction);
+ } else {
+ output.writeln(`Action: ${prediction?.action || 'unknown'}`);
+ output.writeln(`Confidence: ${prediction?.confidence || 0}`);
+ if (prediction?.alternatives?.length > 0) output.writeln(`Alternatives: ${prediction.alternatives.join(', ')}`);
+ }
+ return { success: true };
+ }
+
+ // Heuristic fallback
+ const tasks = discoverTasks(state.taskSources);
+ const progress = getProgress(tasks);
+
+ if (progress.incomplete.length === 0) {
+ output.writeln('All tasks complete. No action needed.');
+ return { success: true };
+ }
+
+ const next = progress.incomplete[0];
+ const result = { action: `Work on: ${next.subject}`, confidence: 0.5, remaining: progress.incomplete.length };
+ if (ctx.flags?.json) {
+ output.printJson(result);
+ } else {
+ output.writeln(`Action: ${result.action}`);
+ output.writeln(`Confidence: ${result.confidence} (heuristic β€” learning not available)`);
+ output.writeln(`Remaining: ${result.remaining} tasks`);
+ }
+ return { success: true };
+ },
+};
+
+const checkCommand: Command = {
+ name: 'check',
+ description: 'Run completion check (used by stop hook)',
+ options: [{ name: 'json', type: 'boolean', description: 'Output as JSON' }],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const result = await autopilotCheck();
+ if (ctx.flags?.json) {
+ output.printJson(result);
+ } else {
+ output.writeln(`${result.allowStop ? 'ALLOW STOP' : 'CONTINUE'}: ${result.reason}`);
+ }
+ return { success: true };
+ },
+};
+
+// ── Main Command ──────────────────────────────────────────────
+
+export const autopilotCommand: Command = {
+ name: 'autopilot',
+ description: 'Persistent swarm completion β€” keeps agents working until ALL tasks are done',
+ aliases: ['ap'],
+ subcommands: [statusCommand, enableCommand, disableCommand, configCommand, resetCommand, logCommand, learnCommand, historyCommand, predictCommand, checkCommand],
+ examples: [
+ { command: 'claude-flow autopilot status', description: 'Show current state and progress' },
+ { command: 'claude-flow autopilot enable', description: 'Enable persistent completion' },
+ { command: 'claude-flow autopilot config --max-iterations 100 --timeout 180', description: 'Configure limits' },
+ { command: 'claude-flow autopilot predict', description: 'Get recommended next action' },
+ ],
+ action: async (): Promise<CommandResult> => {
+ output.writeln(output.bold('Autopilot β€” Persistent Swarm Completion'));
+ output.writeln(output.dim('Keeps agents working until ALL tasks are done'));
+ output.writeln();
+ output.printList([
+ 'status β€” Show state, iterations, and task progress',
+ 'enable β€” Enable persistent completion',
+ 'disable β€” Disable re-engagement loop',
+ 'config β€” Configure max iterations, timeout, sources',
+ 'reset β€” Reset iteration counter and timer',
+ 'log β€” View autopilot event log',
+ 'learn β€” Discover success patterns',
+ 'history β€” Search past completion episodes',
+ 'predict β€” Predict optimal next action',
+ 'check β€” Run completion check (stop hook)',
+ ]);
+ return { success: true };
+ },
+};
+
+export default autopilotCommand;
diff --git a/v3/@claude-flow/cli/src/commands/index.ts b/v3/@claude-flow/cli/src/commands/index.ts
index 6b310040f9..e99eb43c16 100644
--- a/v3/@claude-flow/cli/src/commands/index.ts
+++ b/v3/@claude-flow/cli/src/commands/index.ts
@@ -73,6 +73,7 @@ const commandLoaders: Record<string, CommandLoader> = {
'appliance-advanced': () => import('./appliance-advanced.js'),
'transfer-store': () => import('./transfer-store.js'),
cleanup: () => import('./cleanup.js'),
+ autopilot: () => import('./autopilot.js'),
};
// Cache for loaded commands
@@ -150,6 +151,7 @@ import { processCommand } from './process.js';
import { guidanceCommand } from './guidance.js';
import { applianceCommand } from './appliance.js';
import { cleanupCommand } from './cleanup.js';
+import { autopilotCommand } from './autopilot.js';
// Pre-populate cache with core commands
loadedCommands.set('init', initCommand);
@@ -172,6 +174,7 @@ loadedCommands.set('ruvector', ruvectorCommand);
loadedCommands.set('hive-mind', hiveMindCommand);
loadedCommands.set('guidance', guidanceCommand);
loadedCommands.set('cleanup', cleanupCommand);
+loadedCommands.set('autopilot', autopilotCommand);
// =============================================================================
// Exports (maintain backwards compatibility)
@@ -199,6 +202,7 @@ export { hiveMindCommand } from './hive-mind.js';
export { guidanceCommand } from './guidance.js';
export { applianceCommand } from './appliance.js';
export { cleanupCommand } from './cleanup.js';
+export { autopilotCommand } from './autopilot.js';
// Lazy-loaded command re-exports (for backwards compatibility, but async-only)
export async function getConfigCommand() { return loadCommand('config'); }
@@ -225,6 +229,7 @@ export async function getRuvectorCommand() { return loadCommand('ruvector'); }
export async function getGuidanceCommand() { return loadCommand('guidance'); }
export async function getApplianceCommand() { return loadCommand('appliance'); }
export async function getCleanupCommand() { return loadCommand('cleanup'); }
+export async function getAutopilotCommand() { return loadCommand('autopilot'); }
/**
* Core commands loaded synchronously (available immediately)
@@ -252,6 +257,7 @@ export const commands: Command[] = [
hiveMindCommand,
guidanceCommand,
cleanupCommand,
+ autopilotCommand,
];
/**
@@ -278,6 +284,7 @@ export const commandsByCategory = {
hiveMindCommand,
ruvectorCommand,
guidanceCommand,
+ autopilotCommand,
],
utility: [
configCommand,
diff --git a/v3/@claude-flow/cli/src/mcp-client.ts b/v3/@claude-flow/cli/src/mcp-client.ts
index 923eb2ca71..a0797127cf 100644
--- a/v3/@claude-flow/cli/src/mcp-client.ts
+++ b/v3/@claude-flow/cli/src/mcp-client.ts
@@ -41,6 +41,7 @@ import { agentdbTools } from './mcp-tools/agentdb-tools.js';
import { ruvllmWasmTools } from './mcp-tools/ruvllm-tools.js';
import { wasmAgentTools } from './mcp-tools/wasm-agent-tools.js';
import { guidanceTools } from './mcp-tools/guidance-tools.js';
+import { autopilotTools } from './mcp-tools/autopilot-tools.js';
/**
* MCP Tool Registry
@@ -88,6 +89,8 @@ registerTools([
...wasmAgentTools,
// Guidance & discovery tools
...guidanceTools,
+ // Autopilot persistent completion tools
+ ...autopilotTools,
]);
/**
diff --git a/v3/@claude-flow/cli/src/mcp-tools/autopilot-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/autopilot-tools.ts
new file mode 100644
index 0000000000..d0cd4a91ff
--- /dev/null
+++ b/v3/@claude-flow/cli/src/mcp-tools/autopilot-tools.ts
@@ -0,0 +1,379 @@
+/**
+ * Autopilot MCP Tools
+ *
+ * 10 MCP tools for persistent swarm completion management.
+ * Allows programmatic control of the autopilot loop via MCP.
+ *
+ * ADR-072: Autopilot Integration
+ * @module @claude-flow/cli/mcp-tools/autopilot
+ */
+
+import type { MCPTool } from './types.js';
+import { autopilotCheck } from '../commands/autopilot.js';
+
+// ── State Helpers (shared with CLI command) ───────────────────
+
+const STATE_DIR = '.claude-flow/data';
+const STATE_FILE = `${STATE_DIR}/autopilot-state.json`;
+const LOG_FILE = `${STATE_DIR}/autopilot-log.json`;
+
+interface AutopilotState {
+ sessionId: string;
+ enabled: boolean;
+ startTime: number;
+ iterations: number;
+ maxIterations: number;
+ timeoutMinutes: number;
+ taskSources: string[];
+ lastCheck: number | null;
+ history: Array<{ ts: number; iteration: number; completed: number; total: number }>;
+}
+
+function loadState(): AutopilotState {
+ const fs = require('fs') as typeof import('fs');
+ const path = require('path') as typeof import('path');
+ const crypto = require('crypto') as typeof import('crypto');
+ const filePath = path.resolve(STATE_FILE);
+ const defaults: AutopilotState = {
+ sessionId: crypto.randomUUID(),
+ enabled: false,
+ startTime: Date.now(),
+ iterations: 0,
+ maxIterations: 50,
+ timeoutMinutes: 240,
+ taskSources: ['team-tasks', 'swarm-tasks', 'file-checklist'],
+ lastCheck: null,
+ history: [],
+ };
+ try {
+ if (fs.existsSync(filePath)) {
+ return { ...defaults, ...JSON.parse(fs.readFileSync(filePath, 'utf-8')) };
+ }
+ } catch { /* ignore */ }
+ return defaults;
+}
+
+function saveState(state: AutopilotState): void {
+ const fs = require('fs') as typeof import('fs');
+ const path = require('path') as typeof import('path');
+ const dir = path.resolve(STATE_DIR);
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(path.resolve(STATE_FILE), JSON.stringify(state, null, 2));
+}
+
+function appendLog(entry: Record<string, unknown>): void {
+ const fs = require('fs') as typeof import('fs');
+ const path = require('path') as typeof import('path');
+ const filePath = path.resolve(LOG_FILE);
+ const dir = path.resolve(STATE_DIR);
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
+ let log: Record<string, unknown>[] = [];
+ try {
+ if (fs.existsSync(filePath)) log = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
+ } catch { /* ignore */ }
+ log.push(entry);
+ if (log.length > 1000) log = log.slice(-1000);
+ fs.writeFileSync(filePath, JSON.stringify(log, null, 2));
+}
+
+function loadLog(): Record<string, unknown>[] {
+ const fs = require('fs') as typeof import('fs');
+ const path = require('path') as typeof import('path');
+ const filePath = path.resolve(LOG_FILE);
+ try {
+ if (fs.existsSync(filePath)) return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
+ } catch { /* ignore */ }
+ return [];
+}
+
+// Reuse the same task discovery from CLI
+function discoverTasks(sources: string[]): Array<{ id: string; subject: string; status: string; source: string }> {
+ const fs = require('fs') as typeof import('fs');
+ const path = require('path') as typeof import('path');
+ const os = require('os') as typeof import('os');
+ const tasks: Array<{ id: string; subject: string; status: string; source: string }> = [];
+ const TERMINAL = new Set(['completed', 'done', 'cancelled', 'skipped', 'failed']);
+
+ for (const source of sources) {
+ if (source === 'team-tasks') {
+ const dir = path.join(os.homedir(), '.claude', 'tasks');
+ try {
+ if (fs.existsSync(dir)) {
+ for (const team of fs.readdirSync(dir, { withFileTypes: true })) {
+ if (!team.isDirectory()) continue;
+ for (const f of fs.readdirSync(path.join(dir, team.name)).filter((n: string) => n.endsWith('.json'))) {
+ try {
+ const d = JSON.parse(fs.readFileSync(path.join(dir, team.name, f), 'utf-8'));
+ tasks.push({ id: d.id || f, subject: d.subject || f, status: d.status || 'unknown', source: 'team-tasks' });
+ } catch { /* skip */ }
+ }
+ }
+ }
+ } catch { /* ignore */ }
+ }
+ if (source === 'swarm-tasks') {
+ try {
+ const f = path.resolve('.claude-flow/swarm-tasks.json');
+ if (fs.existsSync(f)) {
+ const d = JSON.parse(fs.readFileSync(f, 'utf-8'));
+ for (const t of (Array.isArray(d) ? d : d.tasks || [])) {
+ tasks.push({ id: t.id || `swarm-${tasks.length}`, subject: t.subject || t.description || 'Unnamed', status: t.status || 'unknown', source: 'swarm-tasks' });
+ }
+ }
+ } catch { /* ignore */ }
+ }
+ if (source === 'file-checklist') {
+ try {
+ const f = path.resolve('.claude-flow/data/checklist.json');
+ if (fs.existsSync(f)) {
+ const d = JSON.parse(fs.readFileSync(f, 'utf-8'));
+ for (const item of (Array.isArray(d) ? d : d.items || [])) {
+ tasks.push({ id: item.id || `check-${tasks.length}`, subject: item.subject || item.text || 'Unnamed', status: item.status || (item.done ? 'completed' : 'pending'), source: 'file-checklist' });
+ }
+ }
+ } catch { /* ignore */ }
+ }
+ }
+ return tasks;
+}
+
+function ok(data: unknown) {
+ return { content: [{ type: 'text' as const, text: JSON.stringify(data, null, 2) }] };
+}
+
+// ── MCP Tool Definitions ──────────────────────────────────────
+
+const autopilotStatus: MCPTool = {
+ name: 'autopilot_status',
+ description: 'Get autopilot state including enabled status, iteration count, task progress, and learning metrics.',
+ category: 'autopilot',
+ inputSchema: { type: 'object', properties: {} },
+ handler: async () => {
+ const state = loadState();
+ const tasks = discoverTasks(state.taskSources);
+ const completed = tasks.filter(t => ['completed', 'done', 'cancelled', 'skipped', 'failed'].includes(t.status.toLowerCase())).length;
+ return ok({
+ enabled: state.enabled,
+ sessionId: state.sessionId,
+ iterations: state.iterations,
+ maxIterations: state.maxIterations,
+ timeoutMinutes: state.timeoutMinutes,
+ elapsedMs: state.enabled ? Date.now() - state.startTime : 0,
+ tasks: { completed, total: tasks.length, percent: tasks.length === 0 ? 100 : Math.round((completed / tasks.length) * 100) },
+ taskSources: state.taskSources,
+ });
+ },
+};
+
+const autopilotEnable: MCPTool = {
+ name: 'autopilot_enable',
+ description: 'Enable autopilot persistent completion. Agents will be re-engaged when tasks remain incomplete.',
+ category: 'autopilot',
+ inputSchema: { type: 'object', properties: {} },
+ handler: async () => {
+ const state = loadState();
+ state.enabled = true;
+ state.startTime = Date.now();
+ state.iterations = 0;
+ saveState(state);
+ appendLog({ ts: Date.now(), event: 'enabled', sessionId: state.sessionId });
+ return ok({ enabled: true, maxIterations: state.maxIterations, timeoutMinutes: state.timeoutMinutes });
+ },
+};
+
+const autopilotDisable: MCPTool = {
+ name: 'autopilot_disable',
+ description: 'Disable autopilot. Agents will be allowed to stop even if tasks remain.',
+ category: 'autopilot',
+ inputSchema: { type: 'object', properties: {} },
+ handler: async () => {
+ const state = loadState();
+ state.enabled = false;
+ saveState(state);
+ appendLog({ ts: Date.now(), event: 'disabled', iterations: state.iterations });
+ return ok({ enabled: false });
+ },
+};
+
+const autopilotConfig: MCPTool = {
+ name: 'autopilot_config',
+ description: 'Configure autopilot limits: max iterations (1-1000), timeout in minutes (1-1440), and task sources.',
+ category: 'autopilot',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ maxIterations: { type: 'number', description: 'Max re-engagement iterations (1-1000)' },
+ timeoutMinutes: { type: 'number', description: 'Timeout in minutes (1-1440)' },
+ taskSources: { type: 'array', items: { type: 'string' }, description: 'Task sources: team-tasks, swarm-tasks, file-checklist' },
+ },
+ },
+ handler: async (params: Record<string, unknown>) => {
+ const state = loadState();
+ if (params.maxIterations !== undefined) state.maxIterations = Math.min(Math.max(1, params.maxIterations as number), 1000);
+ if (params.timeoutMinutes !== undefined) state.timeoutMinutes = Math.min(Math.max(1, params.timeoutMinutes as number), 1440);
+ if (params.taskSources) state.taskSources = params.taskSources as string[];
+ saveState(state);
+ return ok({ maxIterations: state.maxIterations, timeoutMinutes: state.timeoutMinutes, taskSources: state.taskSources });
+ },
+};
+
+const autopilotReset: MCPTool = {
+ name: 'autopilot_reset',
+ description: 'Reset autopilot iteration counter and restart the timer.',
+ category: 'autopilot',
+ inputSchema: { type: 'object', properties: {} },
+ handler: async () => {
+ const state = loadState();
+ state.iterations = 0;
+ state.startTime = Date.now();
+ state.history = [];
+ state.lastCheck = null;
+ saveState(state);
+ appendLog({ ts: Date.now(), event: 'reset' });
+ return ok({ reset: true, iterations: 0 });
+ },
+};
+
+const autopilotLog: MCPTool = {
+ name: 'autopilot_log',
+ description: 'Retrieve the autopilot event log. Shows enable/disable events, re-engagements, completions.',
+ category: 'autopilot',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ last: { type: 'number', description: 'Return only the last N entries' },
+ },
+ },
+ handler: async (params: Record<string, unknown>) => {
+ const log = loadLog();
+ const last = params.last as number | undefined;
+ return ok(last ? log.slice(-last) : log);
+ },
+};
+
+const autopilotProgress: MCPTool = {
+ name: 'autopilot_progress',
+ description: 'Detailed task progress broken down by source (team-tasks, swarm-tasks, file-checklist).',
+ category: 'autopilot',
+ inputSchema: { type: 'object', properties: {} },
+ handler: async () => {
+ const state = loadState();
+ const tasks = discoverTasks(state.taskSources);
+ const bySource: Record<string, { completed: number; total: number; tasks: unknown[] }> = {};
+
+ for (const t of tasks) {
+ if (!bySource[t.source]) bySource[t.source] = { completed: 0, total: 0, tasks: [] };
+ bySource[t.source].total++;
+ if (['completed', 'done', 'cancelled', 'skipped', 'failed'].includes(t.status.toLowerCase())) {
+ bySource[t.source].completed++;
+ }
+ bySource[t.source].tasks.push(t);
+ }
+
+ const completed = tasks.filter(t => ['completed', 'done', 'cancelled', 'skipped', 'failed'].includes(t.status.toLowerCase())).length;
+ return ok({
+ overall: { completed, total: tasks.length, percent: tasks.length === 0 ? 100 : Math.round((completed / tasks.length) * 100) },
+ bySource,
+ });
+ },
+};
+
+const autopilotLearn: MCPTool = {
+ name: 'autopilot_learn',
+ description: 'Discover success patterns from past task completions. Requires AgentDB for full functionality.',
+ category: 'autopilot',
+ inputSchema: { type: 'object', properties: {} },
+ handler: async () => {
+ try {
+ const modPath = 'agentic-flow/dist/coordination/autopilot-learning.js';
+ const mod = await import(/* webpackIgnore: true */ modPath).catch(() => null);
+ if (mod?.AutopilotLearning) {
+ const learning = new mod.AutopilotLearning();
+ if (await learning.initialize()) {
+ const [metrics, patterns] = await Promise.all([learning.getMetrics(), learning.discoverSuccessPatterns()]);
+ return ok({ metrics, patterns });
+ }
+ }
+ } catch { /* not available */ }
+ return ok({ available: false, reason: 'AgentDB/AutopilotLearning not initialized', patterns: [] });
+ },
+};
+
+const autopilotHistory: MCPTool = {
+ name: 'autopilot_history',
+ description: 'Search past completion episodes by keyword. Requires AgentDB.',
+ category: 'autopilot',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ query: { type: 'string', description: 'Search query' },
+ limit: { type: 'number', description: 'Max results (default 10)' },
+ },
+ required: ['query'],
+ },
+ handler: async (params: Record<string, unknown>) => {
+ const query = params.query as string;
+ const limit = (params.limit as number) || 10;
+ try {
+ const modPath = 'agentic-flow/dist/coordination/autopilot-learning.js';
+ const mod = await import(/* webpackIgnore: true */ modPath).catch(() => null);
+ if (mod?.AutopilotLearning) {
+ const learning = new mod.AutopilotLearning();
+ if (await learning.initialize()) {
+ const results = await learning.recallSimilarTasks(query, limit);
+ return ok({ query, results });
+ }
+ }
+ } catch { /* not available */ }
+ return ok({ query, results: [], available: false });
+ },
+};
+
+const autopilotPredict: MCPTool = {
+ name: 'autopilot_predict',
+ description: 'Predict the optimal next action based on current state and learned patterns.',
+ category: 'autopilot',
+ inputSchema: { type: 'object', properties: {} },
+ handler: async () => {
+ const state = loadState();
+ try {
+ const modPath = 'agentic-flow/dist/coordination/autopilot-learning.js';
+ const mod = await import(/* webpackIgnore: true */ modPath).catch(() => null);
+ if (mod?.AutopilotLearning) {
+ const learning = new mod.AutopilotLearning();
+ if (await learning.initialize()) {
+ const prediction = await learning.predictNextAction(state);
+ return ok(prediction);
+ }
+ }
+ } catch { /* not available */ }
+
+ // Heuristic fallback
+ const tasks = discoverTasks(state.taskSources);
+ const incomplete = tasks.filter(t => !['completed', 'done', 'cancelled', 'skipped', 'failed'].includes(t.status.toLowerCase()));
+ if (incomplete.length === 0) {
+ return ok({ action: 'none', confidence: 1.0, reason: 'All tasks complete' });
+ }
+ return ok({
+ action: `Work on: ${incomplete[0].subject}`,
+ confidence: 0.5,
+ reason: 'Heuristic (learning not available)',
+ remaining: incomplete.length,
+ });
+ },
+};
+
+// ── Export ─────────────────────────────────────────────────────
+
+export const autopilotTools: MCPTool[] = [
+ autopilotStatus,
+ autopilotEnable,
+ autopilotDisable,
+ autopilotConfig,
+ autopilotReset,
+ autopilotLog,
+ autopilotProgress,
+ autopilotLearn,
+ autopilotHistory,
+ autopilotPredict,
+];
diff --git a/v3/@claude-flow/cli/src/mcp-tools/index.ts b/v3/@claude-flow/cli/src/mcp-tools/index.ts
index e9a7b2ece1..8491b7759f 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/index.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/index.ts
@@ -24,3 +24,4 @@ export { claimsTools } from './claims-tools.js';
export { wasmAgentTools } from './wasm-agent-tools.js';
export { ruvllmWasmTools } from './ruvllm-tools.js';
export { guidanceTools } from './guidance-tools.js';
+export { autopilotTools } from './autopilot-tools.js';