#!/usr/bin/env node "use strict"; /** * RuVector CLI - Command-line interface for RuVector vector database * * This CLI provides access to hooks, memory, learning, and swarm commands. * Supports PostgreSQL storage (preferred) with JSON fallback. * * Set RUVECTOR_POSTGRES_URL or DATABASE_URL for PostgreSQL support. */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); const commander_1 = require("commander"); const fs = __importStar(require("fs")); const path = __importStar(require("path")); const os = __importStar(require("os")); const INTEL_PATH = path.join(os.homedir(), '.ruvector', 'intelligence.json'); class Intelligence { constructor() { this.alpha = 0.1; this.lastEditedFile = null; this.data = this.load(); } load() { try { if (fs.existsSync(INTEL_PATH)) { return JSON.parse(fs.readFileSync(INTEL_PATH, 'utf-8')); } } catch { } return { patterns: {}, memories: [], trajectories: [], errors: {}, file_sequences: [], agents: {}, edges: [], stats: { total_patterns: 0, total_memories: 0, total_trajectories: 0, total_errors: 0, session_count: 0, last_session: 0 } }; } save() { const dir = path.dirname(INTEL_PATH); if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); } fs.writeFileSync(INTEL_PATH, JSON.stringify(this.data, null, 2)); } now() { return Math.floor(Date.now() / 1000); } embed(text) { const embedding = new Array(64).fill(0); for (let i = 0; i < text.length; i++) { const idx = (text.charCodeAt(i) + i * 7) % 64; embedding[idx] += 1.0; } const norm = Math.sqrt(embedding.reduce((a, b) => a + b * b, 0)); if (norm > 0) { for (let i = 0; i < embedding.length; i++) { embedding[i] /= norm; } } return embedding; } similarity(a, b) { if (a.length !== b.length) return 0; const dot = a.reduce((sum, v, i) => sum + v * b[i], 0); const normA = Math.sqrt(a.reduce((sum, v) => sum + v * v, 0)); const normB = Math.sqrt(b.reduce((sum, v) => sum + v * v, 0)); return normA > 0 && normB > 0 ? dot / (normA * normB) : 0; } remember(memoryType, content, metadata = {}) { const id = `mem_${this.now()}`; this.data.memories.push({ id, memory_type: memoryType, content, embedding: this.embed(content), metadata, timestamp: this.now() }); if (this.data.memories.length > 5000) { this.data.memories.splice(0, 1000); } this.data.stats.total_memories = this.data.memories.length; return id; } recall(query, topK) { const queryEmbed = this.embed(query); return this.data.memories .map(m => ({ score: this.similarity(queryEmbed, m.embedding), memory: m })) .sort((a, b) => b.score - a.score) .slice(0, topK) .map(r => r.memory); } getQ(state, action) { const key = `${state}|${action}`; return this.data.patterns[key]?.q_value ?? 0; } updateQ(state, action, reward) { const key = `${state}|${action}`; if (!this.data.patterns[key]) { this.data.patterns[key] = { state, action, q_value: 0, visits: 0, last_update: 0 }; } const p = this.data.patterns[key]; p.q_value = p.q_value + this.alpha * (reward - p.q_value); p.visits++; p.last_update = this.now(); this.data.stats.total_patterns = Object.keys(this.data.patterns).length; } learn(state, action, outcome, reward) { const id = `traj_${this.now()}`; this.updateQ(state, action, reward); this.data.trajectories.push({ id, state, action, outcome, reward, timestamp: this.now() }); if (this.data.trajectories.length > 1000) { this.data.trajectories.splice(0, 200); } this.data.stats.total_trajectories = this.data.trajectories.length; return id; } suggest(state, actions) { let bestAction = actions[0] ?? ''; let bestQ = -Infinity; for (const action of actions) { const q = this.getQ(state, action); if (q > bestQ) { bestQ = q; bestAction = action; } } return { action: bestAction, confidence: bestQ > 0 ? Math.min(bestQ, 1) : 0 }; } route(task, file, crateName, operation = 'edit') { const fileType = file ? path.extname(file).slice(1) : 'unknown'; const state = `${operation}_${fileType}_in_${crateName ?? 'project'}`; const agentMap = { rs: ['rust-developer', 'coder', 'reviewer', 'tester'], ts: ['typescript-developer', 'coder', 'frontend-dev'], tsx: ['typescript-developer', 'coder', 'frontend-dev'], js: ['coder', 'frontend-dev'], jsx: ['coder', 'frontend-dev'], py: ['python-developer', 'coder', 'ml-developer'], md: ['docs-writer', 'coder'] }; const agents = agentMap[fileType] ?? ['coder', 'reviewer']; const { action, confidence } = this.suggest(state, agents); const reason = confidence > 0.5 ? 'learned from past success' : confidence > 0 ? 'based on patterns' : `default for ${fileType} files`; return { agent: action, confidence, reason }; } shouldTest(file) { const ext = path.extname(file).slice(1); switch (ext) { case 'rs': { const crateMatch = file.match(/crates\/([^/]+)/); return crateMatch ? { suggest: true, command: `cargo test -p ${crateMatch[1]}` } : { suggest: true, command: 'cargo test' }; } case 'ts': case 'tsx': case 'js': case 'jsx': return { suggest: true, command: 'npm test' }; case 'py': return { suggest: true, command: 'pytest' }; default: return { suggest: false, command: '' }; } } // Record file edit sequence for prediction recordFileSequence(fromFile, toFile) { const existing = this.data.file_sequences.find(s => s.from_file === fromFile && s.to_file === toFile); if (existing) { existing.count++; } else { this.data.file_sequences.push({ from_file: fromFile, to_file: toFile, count: 1 }); } this.lastEditedFile = toFile; } // Suggest next files based on sequences suggestNext(file, limit = 3) { return this.data.file_sequences .filter(s => s.from_file === file) .sort((a, b) => b.count - a.count) .slice(0, limit) .map(s => ({ file: s.to_file, score: s.count })); } // Record error pattern recordError(command, message) { const codeMatch = message.match(/error\[([A-Z]\d+)\]/i) || message.match(/([A-Z]\d{4})/); const codes = []; if (codeMatch) { const code = codeMatch[1]; codes.push(code); if (!this.data.errors[code]) { this.data.errors[code] = { code, error_type: this.classifyError(code), message: message.slice(0, 500), fixes: [], occurrences: 0 }; } this.data.errors[code].occurrences++; this.data.errors[code].message = message.slice(0, 500); this.data.stats.total_errors = Object.keys(this.data.errors).length; } return codes; } classifyError(code) { if (code.startsWith('E0')) return 'type-error'; if (code.startsWith('E1')) return 'borrow-error'; if (code.startsWith('E2')) return 'lifetime-error'; if (code.startsWith('E3')) return 'trait-error'; if (code.startsWith('E4')) return 'macro-error'; if (code.startsWith('E5')) return 'pattern-error'; if (code.startsWith('E6')) return 'import-error'; if (code.startsWith('E7')) return 'async-error'; return 'unknown-error'; } // Get fix suggestions for error code suggestFix(code) { const error = this.data.errors[code]; if (!error) return null; return { code: error.code, type: error.error_type, fixes: error.fixes, occurrences: error.occurrences }; } // Classify command type classifyCommand(command) { const cmd = command.toLowerCase(); if (cmd.includes('cargo') || cmd.includes('rustc')) { return { category: 'rust', subcategory: cmd.includes('test') ? 'test' : 'build', risk: 'low' }; } if (cmd.includes('npm') || cmd.includes('node') || cmd.includes('yarn')) { return { category: 'javascript', subcategory: cmd.includes('test') ? 'test' : 'build', risk: 'low' }; } if (cmd.includes('git')) { const risk = cmd.includes('push') || cmd.includes('force') ? 'medium' : 'low'; return { category: 'git', subcategory: 'vcs', risk }; } if (cmd.includes('rm') || cmd.includes('delete')) { return { category: 'filesystem', subcategory: 'destructive', risk: 'high' }; } return { category: 'shell', subcategory: 'general', risk: 'low' }; } // Swarm methods swarmRegister(id, agentType, capabilities) { this.data.agents[id] = { id, agent_type: agentType, capabilities, success_rate: 1.0, task_count: 0, status: 'active' }; } swarmCoordinate(source, target, weight) { const existing = this.data.edges.find(e => e.source === source && e.target === target); if (existing) { existing.weight = (existing.weight + weight) / 2; existing.coordination_count++; } else { this.data.edges.push({ source, target, weight, coordination_count: 1 }); } } swarmOptimize(tasks) { return tasks.map(task => ({ task, agents: Object.keys(this.data.agents).length, edges: this.data.edges.length })); } swarmRecommend(taskType) { const agents = Object.values(this.data.agents); if (agents.length === 0) return null; // Find agent with matching capability or best success rate const matching = agents.filter(a => a.capabilities.some(c => taskType.toLowerCase().includes(c.toLowerCase()))); const best = matching.length > 0 ? matching.sort((a, b) => b.success_rate - a.success_rate)[0] : agents.sort((a, b) => b.success_rate - a.success_rate)[0]; return { agent: best.id, type: best.agent_type, score: best.success_rate }; } swarmHeal(failedAgentId) { const failed = this.data.agents[failedAgentId]; if (!failed) return { healed: false, replacement: null }; // Mark as failed failed.status = 'failed'; failed.success_rate = 0; // Find replacement with same type const replacement = Object.values(this.data.agents).find(a => a.agent_type === failed.agent_type && a.status === 'active' && a.id !== failedAgentId); return { healed: true, replacement: replacement?.id ?? null }; } swarmStats() { const agents = Object.keys(this.data.agents).length; const edges = this.data.edges.length; const activeAgents = Object.values(this.data.agents).filter(a => a.status === 'active'); const avgSuccess = activeAgents.length > 0 ? activeAgents.reduce((sum, a) => sum + a.success_rate, 0) / activeAgents.length : 0; return { agents, edges, avgSuccess }; } stats() { return this.data.stats; } sessionStart() { this.data.stats.session_count++; this.data.stats.last_session = this.now(); } sessionEnd() { const duration = this.now() - this.data.stats.last_session; const actions = this.data.trajectories.filter(t => t.timestamp >= this.data.stats.last_session).length; return { duration, actions }; } getLastEditedFile() { return this.lastEditedFile; } } // Generate Claude hooks configuration function generateClaudeHooksConfig() { return { hooks: { PreToolUse: [ { matcher: "Edit|Write|MultiEdit", hooks: [ "npx @ruvector/cli hooks pre-edit \"$TOOL_INPUT_file_path\"" ] }, { matcher: "Bash", hooks: [ "npx @ruvector/cli hooks pre-command \"$TOOL_INPUT_command\"" ] } ], PostToolUse: [ { matcher: "Edit|Write|MultiEdit", hooks: [ "npx @ruvector/cli hooks post-edit --success \"$TOOL_INPUT_file_path\"" ] }, { matcher: "Bash", hooks: [ "npx @ruvector/cli hooks post-command --success \"$TOOL_INPUT_command\"" ] } ], SessionStart: [ "npx @ruvector/cli hooks session-start" ], Stop: [ "npx @ruvector/cli hooks session-end" ], PreCompact: [ "npx @ruvector/cli hooks pre-compact" ] } }; } // CLI setup commander_1.program .name('ruvector') .description('RuVector CLI - High-performance vector database') .version('0.1.27'); const hooks = commander_1.program.command('hooks').description('Self-learning intelligence hooks for Claude Code'); // ============================================================================ // Core Commands // ============================================================================ hooks.command('init') .description('Initialize hooks in current project') .option('--force', 'Force overwrite existing configuration') .action((opts) => { const configPath = path.join(process.cwd(), '.ruvector', 'hooks.json'); const configDir = path.dirname(configPath); const claudeDir = path.join(process.cwd(), '.claude'); const settingsPath = path.join(claudeDir, 'settings.json'); // Check if already initialized if (fs.existsSync(settingsPath) && !opts.force) { console.log('Hooks already initialized. Use --force to overwrite.'); return; } // Create .ruvector config if (!fs.existsSync(configDir)) { fs.mkdirSync(configDir, { recursive: true }); } const config = { version: '1.0.0', enabled: true, storage: 'json', postgres_url: null, learning: { alpha: 0.1, gamma: 0.95, epsilon: 0.1 } }; fs.writeFileSync(configPath, JSON.stringify(config, null, 2)); // Create .claude/settings.json with hooks if (!fs.existsSync(claudeDir)) { fs.mkdirSync(claudeDir, { recursive: true }); } let settings = {}; if (fs.existsSync(settingsPath)) { try { settings = JSON.parse(fs.readFileSync(settingsPath, 'utf-8')); } catch { } } const hooksConfig = generateClaudeHooksConfig(); settings = { ...settings, ...hooksConfig }; fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2)); console.log('โ Hooks initialized!'); console.log(' Created: .ruvector/hooks.json'); console.log(' Created: .claude/settings.json'); console.log('\nNext steps:'); console.log(' 1. Restart Claude Code to activate hooks'); console.log(" 2. Run 'ruvector hooks stats' to verify"); }); hooks.command('install') .description('Install hooks into Claude settings') .option('--settings-dir
', 'Error code (e.g., E0308)')
.action((code) => {
const intel = new Intelligence();
const fix = intel.suggestFix(code);
if (fix) {
console.log(JSON.stringify(fix, null, 2));
}
else {
console.log(JSON.stringify({ code, fixes: [], occurrences: 0, type: 'unknown' }));
}
});
hooks.command('suggest-next')
.description('Suggest next files to edit based on patterns')
.argument('', 'Current file')
.option('-n, --limit ', 'Number of suggestions', '3')
.action((file, opts) => {
const intel = new Intelligence();
const suggestions = intel.suggestNext(file, parseInt(opts.limit));
console.log(JSON.stringify({
current_file: file,
suggestions: suggestions.map(s => ({ file: s.file, frequency: s.score }))
}, null, 2));
});
// ============================================================================
// Memory Commands
// ============================================================================
hooks.command('remember')
.description('Store content in semantic memory')
.requiredOption('-t, --type ', 'Memory type')
.argument('', 'Content to remember')
.action((content, opts) => {
const intel = new Intelligence();
const id = intel.remember(opts.type, content.join(' '));
intel.save();
console.log(JSON.stringify({ success: true, id }));
});
hooks.command('recall')
.description('Search memory semantically')
.argument('', 'Search query')
.option('-k, --top-k ', 'Number of results', '5')
.action((query, opts) => {
const intel = new Intelligence();
const results = intel.recall(query.join(' '), parseInt(opts.topK));
console.log(JSON.stringify({
query: query.join(' '),
results: results.map(r => ({
type: r.memory_type,
content: r.content.slice(0, 200),
timestamp: r.timestamp
}))
}, null, 2));
});
// ============================================================================
// Learning Commands
// ============================================================================
hooks.command('learn')
.description('Record a learning trajectory')
.argument('', 'State identifier')
.argument('', 'Action taken')
.option('-r, --reward ', 'Reward value', '0.0')
.action((state, action, opts) => {
const intel = new Intelligence();
const id = intel.learn(state, action, 'recorded', parseFloat(opts.reward));
intel.save();
console.log(JSON.stringify({ success: true, id, state, action, reward: parseFloat(opts.reward) }));
});
hooks.command('suggest')
.description('Get action suggestion for state')
.argument('', 'Current state')
.requiredOption('-a, --actions ', 'Available actions (comma-separated)')
.action((state, opts) => {
const intel = new Intelligence();
const actions = opts.actions.split(',').map(s => s.trim());
const result = intel.suggest(state, actions);
console.log(JSON.stringify({ state, ...result }, null, 2));
});
hooks.command('route')
.description('Route task to best agent')
.argument('', 'Task description')
.option('--file ', 'File being worked on')
.option('--crate-name ', 'Crate/module context')
.action((task, opts) => {
const intel = new Intelligence();
const result = intel.route(task.join(' '), opts.file, opts.crateName);
console.log(JSON.stringify({
task: task.join(' '),
recommended: result.agent,
confidence: result.confidence,
reasoning: result.reason
}, null, 2));
});
hooks.command('should-test')
.description('Check if tests should run')
.argument('', 'File that was edited')
.action((file) => {
const intel = new Intelligence();
console.log(JSON.stringify(intel.shouldTest(file), null, 2));
});
// ============================================================================
// Swarm Commands
// ============================================================================
hooks.command('swarm-register')
.description('Register agent in swarm')
.argument('', 'Agent ID')
.argument('', 'Agent type')
.option('--capabilities ', 'Capabilities (comma-separated)')
.action((id, type, opts) => {
const intel = new Intelligence();
const caps = opts.capabilities?.split(',').map(s => s.trim()) ?? [];
intel.swarmRegister(id, type, caps);
intel.save();
console.log(JSON.stringify({ success: true, agent_id: id, type }));
});
hooks.command('swarm-coordinate')
.description('Record agent coordination')
.argument('', 'Source agent ID')
.argument('', 'Target agent ID')
.option('-w, --weight ', 'Coordination weight', '1.0')
.action((source, target, opts) => {
const intel = new Intelligence();
intel.swarmCoordinate(source, target, parseFloat(opts.weight));
intel.save();
console.log(JSON.stringify({ success: true, source, target, weight: parseFloat(opts.weight) }));
});
hooks.command('swarm-optimize')
.description('Optimize task distribution')
.argument('', 'Tasks (comma-separated)')
.action((tasks) => {
const intel = new Intelligence();
const taskList = tasks.split(',').map(s => s.trim());
const result = intel.swarmOptimize(taskList);
console.log(JSON.stringify({ tasks: taskList.length, assignments: result }, null, 2));
});
hooks.command('swarm-recommend')
.description('Recommend agent for task type')
.argument('', 'Type of task')
.action((taskType) => {
const intel = new Intelligence();
const result = intel.swarmRecommend(taskType);
if (result) {
console.log(JSON.stringify({ task_type: taskType, recommended: result.agent, type: result.type, score: result.score }));
}
else {
console.log(JSON.stringify({ task_type: taskType, recommended: null, message: 'No matching agent found' }));
}
});
hooks.command('swarm-heal')
.description('Handle agent failure')
.argument('', 'Failed agent ID')
.action((agentId) => {
const intel = new Intelligence();
const result = intel.swarmHeal(agentId);
intel.save();
console.log(JSON.stringify({ failed_agent: agentId, healed: result.healed, replacement: result.replacement }));
});
hooks.command('swarm-stats')
.description('Show swarm statistics')
.action(() => {
const intel = new Intelligence();
const stats = intel.swarmStats();
console.log(JSON.stringify({
agents: stats.agents,
edges: stats.edges,
average_success_rate: stats.avgSuccess,
topology: 'mesh'
}, null, 2));
});
// ============================================================================
// Claude Code v2.0.55+ Features
// ============================================================================
hooks.command('lsp-diagnostic')
.description('Process LSP diagnostic events (Claude Code 2.0.55+)')
.option('--file ', 'File with diagnostic')
.option('--severity ', 'Diagnostic severity (error, warning, info, hint)')
.option('--message ', 'Diagnostic message')
.action((opts) => {
const intel = new Intelligence();
// Read hook input from stdin if available
let stdinData = null;
try {
const inputPath = process.env.CLAUDE_HOOK_INPUT;
if (inputPath && fs.existsSync(inputPath)) {
stdinData = JSON.parse(fs.readFileSync(inputPath, 'utf-8'));
}
}
catch { /* ignore */ }
const file = opts.file || stdinData?.tool_input?.file || 'unknown';
const severity = opts.severity || stdinData?.tool_input?.severity || 'info';
const message = opts.message || stdinData?.tool_input?.message || '';
// Learn from LSP diagnostics
if (severity === 'error' || severity === 'warning') {
// Record error and get codes
const codes = intel.recordError(`lsp:${file}`, message);
const errorCode = codes[0] || `${severity}-unknown`;
// Record trajectory for learning
const state = `lsp_${severity}_${path.extname(file).slice(1) || 'unknown'}`;
intel.learn(state, 'diagnostic', message.slice(0, 100), severity === 'error' ? -0.5 : -0.2);
intel.save();
// Output context for Claude
const fixInfo = intel.suggestFix(errorCode);
const learnedFixes = fixInfo?.fixes ?? [];
console.log(JSON.stringify({
file,
severity,
error_code: errorCode,
learned_fixes: learnedFixes.slice(0, 3),
recommendation: learnedFixes.length > 0 ? 'Apply learned fix' : 'Investigate error pattern'
}));
}
else {
console.log(JSON.stringify({ file, severity, message, action: 'logged' }));
}
});
hooks.command('suggest-ultrathink')
.description('Recommend ultrathink mode for complex tasks (Claude Code 2.0.55+)')
.argument('', 'Task description')
.option('--file ', 'File being worked on')
.action((task, opts) => {
const intel = new Intelligence();
const taskStr = task.join(' ').toLowerCase();
const file = opts.file;
// Complexity patterns that suggest ultrathink mode
const complexityPatterns = [
['algorithm', 0.8], ['optimize', 0.7], ['refactor', 0.6],
['debug', 0.7], ['performance', 0.7], ['concurrent', 0.8],
['async', 0.6], ['architecture', 0.8], ['security', 0.7],
['cryptograph', 0.9], ['distributed', 0.8], ['consensus', 0.9],
['neural', 0.8], ['ml', 0.7], ['complex', 0.6],
['migrate', 0.7], ['integration', 0.6], ['api design', 0.7],
['database schema', 0.7], ['state machine', 0.8], ['parser', 0.8],
['compiler', 0.9], ['memory management', 0.8], ['thread', 0.7],
];
let complexityScore = 0;
const triggers = [];
for (const [pattern, weight] of complexityPatterns) {
if (taskStr.includes(pattern)) {
complexityScore = Math.max(complexityScore, weight);
triggers.push(pattern);
}
}
// Check file extension complexity
if (file) {
const ext = path.extname(file).slice(1);
const complexExts = {
rs: 0.5, cpp: 0.5, c: 0.4, zig: 0.5,
asm: 0.7, wasm: 0.6, sql: 0.4
};
if (complexExts[ext]) {
complexityScore = Math.max(complexityScore, complexExts[ext]);
triggers.push(`${ext} file`);
}
}
// Check learned patterns
const state = `ultrathink_${triggers[0] || 'general'}`;
const suggested = intel.suggest(state, ['enable', 'skip']);
const recommendUltrathink = complexityScore >= 0.6;
// Record trajectory for learning
intel.learn(state, recommendUltrathink ? 'enable' : 'skip', taskStr.slice(0, 100), 0);
// Build output
const output = {
task: task.join(' '),
complexity_score: complexityScore,
triggers,
recommend_ultrathink: recommendUltrathink,
learned_preference: suggested
};
if (recommendUltrathink) {
output.message = '๐ง Complex task detected - ultrathink mode recommended';
output.reasoning_depth = complexityScore >= 0.8 ? 'deep' : 'moderate';
}
else {
output.message = 'Standard processing sufficient';
}
intel.save();
console.log(JSON.stringify(output, null, 2));
});
hooks.command('async-agent')
.description('Coordinate async sub-agent execution (Claude Code 2.0.55+)')
.option('--action ', 'Action: spawn, sync, complete', 'spawn')
.option('--agent-id ', 'Agent identifier')
.option('--task ', 'Task description (for spawn)')
.action((opts) => {
const intel = new Intelligence();
const action = opts.action;
const agentId = opts.agentId || `async-${Date.now()}`;
const task = opts.task || '';
switch (action) {
case 'spawn': {
// Register async agent
intel.swarmRegister(agentId, 'async-subagent', ['parallel', 'autonomous']);
// Record spawn event
const state = `async_spawn_${task.split(' ')[0] || 'general'}`;
intel.learn(state, 'spawn', task.slice(0, 100), 0.1);
// Get learned patterns for similar tasks
const suggested = intel.suggest(state, ['coder', 'researcher', 'tester', 'reviewer']);
intel.save();
console.log(JSON.stringify({
action: 'spawned',
agent_id: agentId,
task,
suggested_type: suggested.action,
status: 'running',
async: true
}));
break;
}
case 'sync': {
// Check agent status and coordinate
const stats = intel.swarmStats();
console.log(JSON.stringify({
action: 'sync',
agent_id: agentId,
swarm_agents: stats.agents,
status: 'synchronized',
pending_results: 0
}));
break;
}
case 'complete': {
// Mark agent complete and record success
const state = `async_complete_${agentId}`;
intel.learn(state, 'complete', task.slice(0, 100), 1.0);
// Update agent status
intel.swarmHeal(agentId); // Resets/removes the agent
intel.save();
console.log(JSON.stringify({
action: 'completed',
agent_id: agentId,
status: 'success',
learning_recorded: true
}));
break;
}
default:
console.log(JSON.stringify({
error: `Unknown action: ${action}`,
valid_actions: ['spawn', 'sync', 'complete']
}));
}
});
commander_1.program.parse();
//# sourceMappingURL=cli.js.map