@weavelogic/knowledge-graph-agent 0.10.1 → 0.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"doc-generator-agents.js","sources":["../../src/generators/doc-generator-agents.ts"],"sourcesContent":["/**\n * Agent-Driven Document Generator\n *\n * Spawns expert agents from claude-flow to analyze existing code and\n * documentation, then generates appropriate documents for each directory.\n */\n\nimport { existsSync, readFileSync, writeFileSync, readdirSync, statSync, mkdirSync, copyFileSync } from 'fs';\nimport { join, basename, extname, relative, dirname } from 'path';\nimport fg from 'fast-glob';\nimport { spawn } from 'child_process';\n\n/**\n * Service documentation found in src/{service}/docs directories\n */\ninterface ServiceDoc {\n serviceName: string;\n sourcePath: string;\n fileName: string;\n relativePath: string;\n}\n\n/**\n * Document generation context\n */\nexport interface GenerationContext {\n projectRoot: string;\n docsPath: string;\n projectName: string;\n languages: string[];\n frameworks: string[];\n existingDocs: string[];\n sourceFiles: string[];\n serviceDocs: ServiceDoc[];\n}\n\n/**\n * Generation result for a single document\n */\nexport interface GeneratedDoc {\n path: string;\n title: string;\n type: string;\n generated: boolean;\n error?: string;\n}\n\n/**\n * Overall generation result\n */\nexport interface AgentGenerationResult {\n success: boolean;\n documentsGenerated: GeneratedDoc[];\n agentsSpawned: number;\n errors: string[];\n}\n\n/**\n * Agent task definition\n */\ninterface AgentTask {\n directory: string;\n type: 'concept' | 'component' | 'service' | 'feature' | 'integration' | 'standard' | 'guide' | 'reference';\n agentType: 'researcher' | 'coder' | 'analyst';\n prompt: string;\n outputFile: string;\n}\n\n/**\n * Analyze project and generate documents using expert agents\n */\nexport async function generateDocsWithAgents(\n projectRoot: string,\n docsPath: string,\n options: {\n parallel?: boolean;\n dryRun?: boolean;\n verbose?: boolean;\n force?: boolean;\n } = {}\n): Promise<AgentGenerationResult> {\n const result: AgentGenerationResult = {\n success: true,\n documentsGenerated: [],\n agentsSpawned: 0,\n errors: [],\n };\n\n try {\n // Build context by analyzing the project\n const context = await buildGenerationContext(projectRoot, docsPath);\n\n // Determine what documents should be generated\n const tasks = await planDocumentGeneration(context, options.force);\n\n if (options.dryRun) {\n console.log('\\n[Dry Run] Would generate the following documents:');\n for (const task of tasks) {\n console.log(` - ${task.outputFile} (${task.agentType} agent)`);\n }\n if (context.serviceDocs.length > 0) {\n console.log('\\n[Dry Run] Would copy service docs:');\n for (const doc of context.serviceDocs) {\n const targetPath = `services/${doc.serviceName}/${doc.relativePath}`;\n console.log(` - ${doc.sourcePath} → ${targetPath}`);\n }\n }\n return result;\n }\n\n // Copy service docs from src/{service}/docs to main docs directory\n const copiedDocs = copyServiceDocs(context, options.force);\n\n // Execute tasks (parallel or sequential)\n if (options.parallel) {\n const results = await Promise.allSettled(\n tasks.map(task => executeAgentTask(task, context, options.verbose))\n );\n\n for (let i = 0; i < results.length; i++) {\n const r = results[i];\n result.agentsSpawned++;\n\n if (r.status === 'fulfilled') {\n result.documentsGenerated.push(r.value);\n } else {\n result.errors.push(`Failed: ${tasks[i].outputFile} - ${r.reason}`);\n result.documentsGenerated.push({\n path: tasks[i].outputFile,\n title: basename(tasks[i].outputFile, '.md'),\n type: tasks[i].type,\n generated: false,\n error: String(r.reason),\n });\n }\n }\n } else {\n // Sequential execution\n for (const task of tasks) {\n result.agentsSpawned++;\n\n try {\n const doc = await executeAgentTask(task, context, options.verbose);\n result.documentsGenerated.push(doc);\n } catch (error) {\n result.errors.push(`Failed: ${task.outputFile} - ${error}`);\n result.documentsGenerated.push({\n path: task.outputFile,\n title: basename(task.outputFile, '.md'),\n type: task.type,\n generated: false,\n error: String(error),\n });\n }\n }\n }\n\n // Add copied service docs to result\n result.documentsGenerated.push(...copiedDocs);\n\n result.success = result.errors.length === 0;\n } catch (error) {\n result.success = false;\n result.errors.push(`Generation failed: ${error}`);\n }\n\n return result;\n}\n\n/**\n * Copy service docs from src/{service}/docs to main docs directory\n */\nfunction copyServiceDocs(context: GenerationContext, force?: boolean): GeneratedDoc[] {\n const { docsPath, serviceDocs } = context;\n const copied: GeneratedDoc[] = [];\n\n for (const doc of serviceDocs) {\n const targetDir = join(docsPath, 'services', doc.serviceName);\n const targetPath = join(targetDir, doc.relativePath);\n const relativeTarget = `services/${doc.serviceName}/${doc.relativePath}`;\n\n // Skip if target exists and not forcing\n if (!force && existsSync(targetPath)) {\n continue;\n }\n\n try {\n // Create target directory if needed\n const targetFileDir = dirname(targetPath);\n if (!existsSync(targetFileDir)) {\n mkdirSync(targetFileDir, { recursive: true });\n }\n\n // Copy the file\n copyFileSync(doc.sourcePath, targetPath);\n\n copied.push({\n path: relativeTarget,\n title: doc.fileName.replace('.md', ''),\n type: 'service',\n generated: true,\n });\n } catch (error) {\n copied.push({\n path: relativeTarget,\n title: doc.fileName.replace('.md', ''),\n type: 'service',\n generated: false,\n error: String(error),\n });\n }\n }\n\n return copied;\n}\n\n/**\n * Build context by analyzing the project\n */\nasync function buildGenerationContext(\n projectRoot: string,\n docsPath: string\n): Promise<GenerationContext> {\n const context: GenerationContext = {\n projectRoot,\n docsPath,\n projectName: basename(projectRoot),\n languages: [],\n frameworks: [],\n existingDocs: [],\n sourceFiles: [],\n serviceDocs: [],\n };\n\n // Get project name from package.json\n const pkgPath = join(projectRoot, 'package.json');\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));\n context.projectName = pkg.name?.replace(/^@[^/]+\\//, '') || context.projectName;\n\n // Detect frameworks from dependencies\n const deps = { ...pkg.dependencies, ...pkg.devDependencies };\n if (deps.react) context.frameworks.push('React');\n if (deps.next) context.frameworks.push('Next.js');\n if (deps.vue) context.frameworks.push('Vue');\n if (deps.express) context.frameworks.push('Express');\n if (deps.fastify) context.frameworks.push('Fastify');\n if (deps['@prisma/client'] || deps.prisma) context.frameworks.push('Prisma');\n } catch {\n // Ignore parse errors\n }\n }\n\n // Detect languages\n if (existsSync(join(projectRoot, 'tsconfig.json'))) {\n context.languages.push('TypeScript');\n }\n if (existsSync(join(projectRoot, 'package.json'))) {\n context.languages.push('JavaScript');\n }\n\n // Detect Python - check multiple locations for requirements\n const pythonConfigPaths = [\n join(projectRoot, 'requirements.txt'),\n join(projectRoot, 'pyproject.toml'),\n join(projectRoot, 'src/backend/requirements.txt'),\n join(projectRoot, 'backend/requirements.txt'),\n join(projectRoot, 'src/requirements.txt'),\n ];\n const foundPythonConfig = pythonConfigPaths.find(p => existsSync(p));\n\n // Also detect Python if we find .py files later in source scan\n // For now, check if there's a Python config file\n if (foundPythonConfig) {\n context.languages.push('Python');\n\n // Detect Python frameworks from requirements.txt or pyproject.toml\n try {\n let reqContent = readFileSync(foundPythonConfig, 'utf-8').toLowerCase();\n // Also check pyproject.toml if we found requirements.txt\n if (foundPythonConfig.includes('requirements.txt')) {\n const pyprojectPath = join(projectRoot, 'pyproject.toml');\n if (existsSync(pyprojectPath)) {\n reqContent += readFileSync(pyprojectPath, 'utf-8').toLowerCase();\n }\n }\n if (reqContent.includes('fastapi')) context.frameworks.push('FastAPI');\n if (reqContent.includes('flask')) context.frameworks.push('Flask');\n if (reqContent.includes('django')) context.frameworks.push('Django');\n if (reqContent.includes('sqlalchemy')) context.frameworks.push('SQLAlchemy');\n if (reqContent.includes('pydantic')) context.frameworks.push('Pydantic');\n if (reqContent.includes('alembic')) context.frameworks.push('Alembic');\n } catch {\n // Ignore read errors\n }\n }\n if (existsSync(join(projectRoot, 'Cargo.toml'))) {\n context.languages.push('Rust');\n }\n if (existsSync(join(projectRoot, 'go.mod'))) {\n context.languages.push('Go');\n }\n\n // Find existing docs\n const existingDocs = await fg('**/*.md', {\n cwd: docsPath,\n ignore: ['node_modules/**', '.git/**', '_templates/**'],\n });\n context.existingDocs = existingDocs;\n\n // Find source files\n const sourceFiles = await fg('**/*.{ts,tsx,js,jsx,py,rs,go}', {\n cwd: projectRoot,\n ignore: ['node_modules/**', '.git/**', 'dist/**', 'build/**', docsPath + '/**'],\n dot: true,\n });\n context.sourceFiles = sourceFiles;\n\n // Detect Python from .py files if not already detected\n if (!context.languages.includes('Python') && sourceFiles.some(f => f.endsWith('.py'))) {\n context.languages.push('Python');\n }\n\n // Scan for service docs in src/{service}/docs directories\n const serviceDocs: ServiceDoc[] = [];\n const srcDir = join(projectRoot, 'src');\n if (existsSync(srcDir)) {\n try {\n const srcEntries = readdirSync(srcDir, { withFileTypes: true });\n for (const entry of srcEntries) {\n if (entry.isDirectory()) {\n const serviceDocsDir = join(srcDir, entry.name, 'docs');\n if (existsSync(serviceDocsDir)) {\n // Find all markdown files in this service's docs directory\n const docsFiles = await fg('**/*.md', {\n cwd: serviceDocsDir,\n ignore: ['node_modules/**', '.git/**'],\n });\n for (const docFile of docsFiles) {\n serviceDocs.push({\n serviceName: entry.name,\n sourcePath: join(serviceDocsDir, docFile),\n fileName: basename(docFile),\n relativePath: docFile,\n });\n }\n }\n }\n }\n } catch {\n // Ignore errors reading src directory\n }\n }\n context.serviceDocs = serviceDocs;\n\n return context;\n}\n\n/**\n * Plan what documents should be generated based on context\n */\nasync function planDocumentGeneration(context: GenerationContext, force?: boolean): Promise<AgentTask[]> {\n const tasks: AgentTask[] = [];\n const { projectRoot, docsPath, sourceFiles, frameworks } = context;\n\n // Helper to check if doc already exists (returns false if force is true)\n const docExists = (relativePath: string) => {\n if (force) return false; // Force regeneration\n return existsSync(join(docsPath, relativePath));\n };\n\n // Analyze source structure to determine what docs to generate\n const srcDirs = new Set<string>();\n const componentFiles: string[] = [];\n const serviceFiles: string[] = [];\n const utilityFiles: string[] = [];\n const backendFiles: string[] = [];\n const modelFiles: string[] = [];\n const frontendFiles: string[] = [];\n\n for (const file of sourceFiles) {\n const dir = file.split('/')[0];\n srcDirs.add(dir);\n const fileLower = file.toLowerCase();\n\n // Categorize files (improved patterns for Python and TypeScript)\n if (fileLower.includes('component') || fileLower.includes('/ui/') || fileLower.includes('/views/')) {\n componentFiles.push(file);\n }\n if (fileLower.includes('service') || fileLower.includes('/api/') || fileLower.includes('routes') || fileLower.includes('endpoints')) {\n serviceFiles.push(file);\n }\n if (fileLower.includes('util') || fileLower.includes('helper') || fileLower.includes('/lib/') || fileLower.includes('common')) {\n utilityFiles.push(file);\n }\n if (fileLower.includes('backend') || fileLower.includes('server') || fileLower.includes('app/')) {\n backendFiles.push(file);\n }\n if (fileLower.includes('model') || fileLower.includes('schema') || fileLower.includes('entities')) {\n modelFiles.push(file);\n }\n if (fileLower.includes('frontend') || fileLower.includes('client') || fileLower.includes('pages')) {\n frontendFiles.push(file);\n }\n }\n\n // If no service files found but backend files exist, use backend files\n if (serviceFiles.length === 0 && backendFiles.length > 0) {\n serviceFiles.push(...backendFiles);\n }\n\n // Generate architecture overview if source has modules with files\n // Threshold: at least 1 directory with 3+ source files\n if (srcDirs.size >= 1 && sourceFiles.length >= 3 && !docExists('concepts/architecture/overview.md')) {\n tasks.push({\n directory: 'concepts/architecture',\n type: 'concept',\n agentType: 'analyst',\n prompt: buildArchitecturePrompt(context, Array.from(srcDirs)),\n outputFile: 'concepts/architecture/overview.md',\n });\n }\n\n // Generate component docs for detected UI frameworks\n if (frameworks.includes('React') || frameworks.includes('Vue')) {\n if (componentFiles.length > 0 && !docExists('components/ui/overview.md')) {\n tasks.push({\n directory: 'components/ui',\n type: 'component',\n agentType: 'coder',\n prompt: buildComponentPrompt(context, componentFiles.slice(0, 10)),\n outputFile: 'components/ui/overview.md',\n });\n }\n }\n\n // Generate service docs if API files detected\n if (serviceFiles.length > 0 && !docExists('services/api/overview.md')) {\n tasks.push({\n directory: 'services/api',\n type: 'service',\n agentType: 'coder',\n prompt: buildServicePrompt(context, serviceFiles.slice(0, 10)),\n outputFile: 'services/api/overview.md',\n });\n }\n\n // Generate utility docs\n if (utilityFiles.length > 0 && !docExists('components/utilities/overview.md')) {\n tasks.push({\n directory: 'components/utilities',\n type: 'component',\n agentType: 'coder',\n prompt: buildUtilityPrompt(context, utilityFiles.slice(0, 10)),\n outputFile: 'components/utilities/overview.md',\n });\n }\n\n // Generate getting started guide\n if (!docExists('guides/getting-started/quick-start.md')) {\n tasks.push({\n directory: 'guides/getting-started',\n type: 'guide',\n agentType: 'researcher',\n prompt: buildGettingStartedPrompt(context),\n outputFile: 'guides/getting-started/quick-start.md',\n });\n }\n\n // Generate standards/coding guide if tsconfig or eslint exists\n const hasLinting = existsSync(join(projectRoot, '.eslintrc.json')) ||\n existsSync(join(projectRoot, '.eslintrc.js')) ||\n existsSync(join(projectRoot, 'eslint.config.js'));\n const hasTypescript = existsSync(join(projectRoot, 'tsconfig.json'));\n\n if ((hasLinting || hasTypescript) && !docExists('standards/coding-standards/guide.md')) {\n tasks.push({\n directory: 'standards/coding-standards',\n type: 'standard',\n agentType: 'analyst',\n prompt: buildCodingStandardsPrompt(context, hasTypescript, hasLinting),\n outputFile: 'standards/coding-standards/guide.md',\n });\n }\n\n // Generate integration docs for detected databases/services\n if (frameworks.includes('Prisma') && !docExists('integrations/databases/prisma.md')) {\n tasks.push({\n directory: 'integrations/databases',\n type: 'integration',\n agentType: 'coder',\n prompt: buildPrismaPrompt(context),\n outputFile: 'integrations/databases/prisma.md',\n });\n }\n\n // Generate SQLAlchemy docs for Python projects\n if (frameworks.includes('SQLAlchemy') && !docExists('integrations/databases/sqlalchemy.md')) {\n tasks.push({\n directory: 'integrations/databases',\n type: 'integration',\n agentType: 'coder',\n prompt: buildSQLAlchemyPrompt(context, modelFiles),\n outputFile: 'integrations/databases/sqlalchemy.md',\n });\n }\n\n // Generate FastAPI docs\n if (frameworks.includes('FastAPI') && !docExists('services/api/fastapi.md')) {\n tasks.push({\n directory: 'services/api',\n type: 'service',\n agentType: 'coder',\n prompt: buildFastAPIPrompt(context, serviceFiles),\n outputFile: 'services/api/fastapi.md',\n });\n }\n\n // Generate Flask docs\n if (frameworks.includes('Flask') && !docExists('services/api/flask.md')) {\n tasks.push({\n directory: 'services/api',\n type: 'service',\n agentType: 'coder',\n prompt: buildFlaskPrompt(context, serviceFiles),\n outputFile: 'services/api/flask.md',\n });\n }\n\n return tasks;\n}\n\n/**\n * Execute a single agent task\n */\nasync function executeAgentTask(\n task: AgentTask,\n context: GenerationContext,\n verbose?: boolean\n): Promise<GeneratedDoc> {\n const { docsPath } = context;\n const outputPath = join(docsPath, task.outputFile);\n\n // Try to use claude-flow if available, otherwise generate locally\n const hasClaudeFlow = await checkClaudeFlowAvailable();\n\n let content: string;\n\n if (hasClaudeFlow) {\n content = await executeWithClaudeFlow(task, context, verbose);\n } else {\n // Fallback to local template generation\n content = generateLocalTemplate(task, context);\n }\n\n // Write the file\n writeFileSync(outputPath, content, 'utf-8');\n\n return {\n path: task.outputFile,\n title: extractTitle(content) || basename(task.outputFile, '.md'),\n type: task.type,\n generated: true,\n };\n}\n\n/**\n * Check if claude-flow is available\n */\nasync function checkClaudeFlowAvailable(): Promise<boolean> {\n return new Promise((resolve) => {\n const proc = spawn('npx', ['claude-flow@alpha', '--version'], {\n stdio: 'pipe',\n shell: true,\n });\n\n proc.on('close', (code) => {\n resolve(code === 0);\n });\n\n proc.on('error', () => {\n resolve(false);\n });\n\n // Timeout after 5 seconds\n setTimeout(() => {\n proc.kill();\n resolve(false);\n }, 5000);\n });\n}\n\n/**\n * Execute task using claude-flow expert agents\n */\nasync function executeWithClaudeFlow(\n task: AgentTask,\n context: GenerationContext,\n verbose?: boolean\n): Promise<string> {\n return new Promise((resolve, reject) => {\n const agentCmd = `npx claude-flow@alpha sparc run ${task.agentType} \"${task.prompt.replace(/\"/g, '\\\\\"')}\"`;\n\n if (verbose) {\n console.log(`\\n Spawning ${task.agentType} agent for ${task.outputFile}...`);\n }\n\n const proc = spawn(agentCmd, {\n shell: true,\n cwd: context.projectRoot,\n stdio: verbose ? 'inherit' : 'pipe',\n });\n\n let output = '';\n\n if (proc.stdout) {\n proc.stdout.on('data', (data) => {\n output += data.toString();\n });\n }\n\n proc.on('close', (code) => {\n if (code === 0 && output) {\n resolve(output);\n } else {\n // Fallback to local generation\n resolve(generateLocalTemplate(task, context));\n }\n });\n\n proc.on('error', () => {\n resolve(generateLocalTemplate(task, context));\n });\n\n // Timeout after 60 seconds\n setTimeout(() => {\n proc.kill();\n resolve(generateLocalTemplate(task, context));\n }, 60000);\n });\n}\n\n/**\n * Generate document using local templates (fallback)\n */\nfunction generateLocalTemplate(task: AgentTask, context: GenerationContext): string {\n const date = new Date().toISOString().split('T')[0];\n const { projectName } = context;\n\n const templates: Record<string, string> = {\n 'concepts/architecture/overview.md': `---\ntitle: Architecture Overview\ntype: concept\nstatus: active\ntags: [architecture, overview]\ncreated: ${date}\n---\n\n# Architecture Overview\n\nHigh-level architecture documentation for ${projectName}.\n\n## System Overview\n\nThis document describes the overall architecture and design patterns used in ${projectName}.\n\n## Module Structure\n\n${context.sourceFiles.slice(0, 20).map(f => `- \\`${f}\\``).join('\\n')}\n\n## Key Patterns\n\n*Document key architectural patterns here*\n\n## Design Decisions\n\n*Add Architecture Decision Records (ADRs)*\n\n---\n> Auto-generated by kg-agent\n`,\n\n 'components/ui/overview.md': `---\ntitle: UI Components Overview\ntype: technical\nstatus: active\ntags: [components, ui]\ncreated: ${date}\n---\n\n# UI Components\n\nUser interface components for ${projectName}.\n\n## Component Library\n\n${context.frameworks.includes('React') ? 'Built with **React**.' : ''}\n${context.frameworks.includes('Vue') ? 'Built with **Vue**.' : ''}\n\n## Available Components\n\n*Document available UI components*\n\n## Usage Patterns\n\n*Add component usage examples*\n\n---\n> Auto-generated by kg-agent\n`,\n\n 'services/api/overview.md': `---\ntitle: API Services Overview\ntype: service\nstatus: active\ntags: [api, services]\ncreated: ${date}\n---\n\n# API Services\n\nBackend API services for ${projectName}.\n\n## Endpoints\n\n*Document API endpoints*\n\n## Authentication\n\n*Document authentication flow*\n\n## Error Handling\n\n*Document error handling patterns*\n\n---\n> Auto-generated by kg-agent\n`,\n\n 'components/utilities/overview.md': `---\ntitle: Utilities Overview\ntype: technical\nstatus: active\ntags: [utilities, helpers]\ncreated: ${date}\n---\n\n# Utility Functions\n\nReusable utilities and helpers for ${projectName}.\n\n## Available Utilities\n\n*Document available utilities*\n\n## Usage Examples\n\n*Add code examples*\n\n---\n> Auto-generated by kg-agent\n`,\n\n 'guides/getting-started/quick-start.md': `---\ntitle: Quick Start Guide\ntype: guide\nstatus: active\ntags: [guide, getting-started]\ncreated: ${date}\n---\n\n# Quick Start\n\nGet up and running with ${projectName}.\n\n## Prerequisites\n\n${context.languages.map(l => `- ${l}`).join('\\n')}\n\n## Installation\n\n\\`\\`\\`bash\nnpm install\n\\`\\`\\`\n\n## Basic Usage\n\n*Add basic usage instructions*\n\n## Next Steps\n\n- [[concepts/architecture/overview|Architecture Overview]]\n- [[guides/_MOC|More Guides]]\n\n---\n> Auto-generated by kg-agent\n`,\n\n 'standards/coding-standards/guide.md': `---\ntitle: Coding Standards\ntype: standard\nstatus: active\ntags: [standards, coding]\ncreated: ${date}\n---\n\n# Coding Standards\n\nCode style and conventions for ${projectName}.\n\n## Language Standards\n\n${context.languages.map(l => `### ${l}\\n\\n*Add ${l} specific standards*`).join('\\n\\n')}\n\n## Linting Configuration\n\n*Document ESLint/Prettier setup*\n\n## Best Practices\n\n*Add coding best practices*\n\n---\n> Auto-generated by kg-agent\n`,\n\n 'integrations/databases/prisma.md': `---\ntitle: Prisma Integration\ntype: integration\nstatus: active\ntags: [prisma, database, orm]\ncreated: ${date}\n---\n\n# Prisma Integration\n\nDatabase ORM configuration for ${projectName}.\n\n## Schema Location\n\n\\`prisma/schema.prisma\\`\n\n## Models\n\n*Document database models*\n\n## Migrations\n\n\\`\\`\\`bash\nnpx prisma migrate dev\n\\`\\`\\`\n\n## Client Usage\n\n*Add Prisma client usage examples*\n\n---\n> Auto-generated by kg-agent\n`,\n\n 'integrations/databases/sqlalchemy.md': `---\ntitle: SQLAlchemy Integration\ntype: integration\nstatus: active\ntags: [sqlalchemy, database, orm, python]\ncreated: ${date}\n---\n\n# SQLAlchemy Integration\n\nDatabase ORM configuration for ${projectName}.\n\n## Models\n\n*Document your SQLAlchemy models*\n\n## Database Connection\n\n\\`\\`\\`python\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\nengine = create_engine(DATABASE_URL)\nSession = sessionmaker(bind=engine)\n\\`\\`\\`\n\n## Migrations (Alembic)\n\n\\`\\`\\`bash\nalembic upgrade head\n\\`\\`\\`\n\n## Query Examples\n\n*Add common query patterns*\n\n---\n> Auto-generated by kg-agent\n`,\n\n 'services/api/fastapi.md': `---\ntitle: FastAPI Service\ntype: service\nstatus: active\ntags: [fastapi, api, python]\ncreated: ${date}\n---\n\n# FastAPI Service\n\nAPI service documentation for ${projectName}.\n\n## Running the Server\n\n\\`\\`\\`bash\nuvicorn main:app --reload\n\\`\\`\\`\n\n## API Endpoints\n\n*Document your API endpoints*\n\n## Authentication\n\n*Document authentication flow*\n\n## Request/Response Schemas\n\n*Document Pydantic models*\n\n---\n> Auto-generated by kg-agent\n`,\n\n 'services/api/flask.md': `---\ntitle: Flask Service\ntype: service\nstatus: active\ntags: [flask, api, python]\ncreated: ${date}\n---\n\n# Flask Service\n\nAPI service documentation for ${projectName}.\n\n## Running the Server\n\n\\`\\`\\`bash\nflask run\n\\`\\`\\`\n\n## Routes\n\n*Document your Flask routes*\n\n## Blueprints\n\n*Document blueprints structure*\n\n## Error Handling\n\n*Document error handling patterns*\n\n---\n> Auto-generated by kg-agent\n`,\n };\n\n return templates[task.outputFile] || generateGenericTemplate(task, context, date);\n}\n\n/**\n * Generate a generic template for unknown task types\n */\nfunction generateGenericTemplate(\n task: AgentTask,\n context: GenerationContext,\n date: string\n): string {\n const title = basename(task.outputFile, '.md')\n .split('-')\n .map(w => w.charAt(0).toUpperCase() + w.slice(1))\n .join(' ');\n\n return `---\ntitle: ${title}\ntype: ${task.type}\nstatus: draft\ntags: [${task.type}]\ncreated: ${date}\n---\n\n# ${title}\n\nDocumentation for ${context.projectName}.\n\n## Overview\n\n*Add overview content*\n\n## Details\n\n*Add detailed documentation*\n\n---\n> Auto-generated by kg-agent\n`;\n}\n\n/**\n * Extract title from markdown content\n */\nfunction extractTitle(content: string): string | null {\n const match = content.match(/^#\\s+(.+)$/m);\n return match ? match[1] : null;\n}\n\n// Prompt builders\n\nfunction buildArchitecturePrompt(context: GenerationContext, dirs: string[]): string {\n return `Analyze the architecture of ${context.projectName}.\nModules: ${dirs.join(', ')}.\nLanguages: ${context.languages.join(', ')}.\nGenerate an Architecture Overview markdown document with system design, patterns, and key decisions.`;\n}\n\nfunction buildComponentPrompt(context: GenerationContext, files: string[]): string {\n return `Document the UI components in ${context.projectName}.\nFrameworks: ${context.frameworks.join(', ')}.\nComponent files: ${files.join(', ')}.\nGenerate a Components Overview markdown document.`;\n}\n\nfunction buildServicePrompt(context: GenerationContext, files: string[]): string {\n return `Document the API services in ${context.projectName}.\nService files: ${files.join(', ')}.\nGenerate an API Services Overview markdown document with endpoints and patterns.`;\n}\n\nfunction buildUtilityPrompt(context: GenerationContext, files: string[]): string {\n return `Document utility functions in ${context.projectName}.\nUtility files: ${files.join(', ')}.\nGenerate a Utilities Overview markdown document.`;\n}\n\nfunction buildGettingStartedPrompt(context: GenerationContext): string {\n return `Create a Quick Start guide for ${context.projectName}.\nLanguages: ${context.languages.join(', ')}.\nFrameworks: ${context.frameworks.join(', ')}.\nGenerate a Getting Started guide with installation and basic usage.`;\n}\n\nfunction buildCodingStandardsPrompt(\n context: GenerationContext,\n hasTypescript: boolean,\n hasLinting: boolean\n): string {\n return `Document coding standards for ${context.projectName}.\nTypeScript: ${hasTypescript ? 'yes' : 'no'}.\nESLint: ${hasLinting ? 'yes' : 'no'}.\nGenerate a Coding Standards guide with style rules and best practices.`;\n}\n\nfunction buildPrismaPrompt(context: GenerationContext): string {\n return `Document Prisma database integration for ${context.projectName}.\nGenerate integration documentation with schema, models, and usage patterns.`;\n}\n\nfunction buildSQLAlchemyPrompt(context: GenerationContext, modelFiles: string[]): string {\n return `Document SQLAlchemy database integration for ${context.projectName}.\nModel files: ${modelFiles.slice(0, 10).join(', ')}.\nGenerate integration documentation with models, relationships, and query patterns.`;\n}\n\nfunction buildFastAPIPrompt(context: GenerationContext, serviceFiles: string[]): string {\n return `Document FastAPI API service for ${context.projectName}.\nAPI files: ${serviceFiles.slice(0, 10).join(', ')}.\nGenerate API documentation with endpoints, request/response schemas, and authentication.`;\n}\n\nfunction buildFlaskPrompt(context: GenerationContext, serviceFiles: string[]): string {\n return `Document Flask API service for ${context.projectName}.\nRoute files: ${serviceFiles.slice(0, 10).join(', ')}.\nGenerate API documentation with routes, blueprints, and request handling.`;\n}\n"],"names":[],"mappings":";;;;AAuEA,eAAsB,uBACpB,aACA,UACA,UAKI,CAAA,GAC4B;AAChC,QAAM,SAAgC;AAAA,IACpC,SAAS;AAAA,IACT,oBAAoB,CAAA;AAAA,IACpB,eAAe;AAAA,IACf,QAAQ,CAAA;AAAA,EAAC;AAGX,MAAI;AAEF,UAAM,UAAU,MAAM,uBAAuB,aAAa,QAAQ;AAGlE,UAAM,QAAQ,MAAM,uBAAuB,SAAS,QAAQ,KAAK;AAEjE,QAAI,QAAQ,QAAQ;AAClB,cAAQ,IAAI,qDAAqD;AACjE,iBAAW,QAAQ,OAAO;AACxB,gBAAQ,IAAI,OAAO,KAAK,UAAU,KAAK,KAAK,SAAS,SAAS;AAAA,MAChE;AACA,UAAI,QAAQ,YAAY,SAAS,GAAG;AAClC,gBAAQ,IAAI,sCAAsC;AAClD,mBAAW,OAAO,QAAQ,aAAa;AACrC,gBAAM,aAAa,YAAY,IAAI,WAAW,IAAI,IAAI,YAAY;AAClE,kBAAQ,IAAI,OAAO,IAAI,UAAU,MAAM,UAAU,EAAE;AAAA,QACrD;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAGA,UAAM,aAAa,gBAAgB,SAAS,QAAQ,KAAK;AAGzD,QAAI,QAAQ,UAAU;AACpB,YAAM,UAAU,MAAM,QAAQ;AAAA,QAC5B,MAAM,IAAI,CAAA,SAAQ,iBAAiB,MAAM,SAAS,QAAQ,OAAO,CAAC;AAAA,MAAA;AAGpE,eAAS,IAAI,GAAG,IAAI,QAAQ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AgC,QAAQ,WAAW;AAAA,iBAC3C,MAAM,KAAK,IAAI,CAAC;AAAA;AAEjC;AAEA,SAAS,mBAAmB,SAA4B,OAAyB;AAC/E,SAAO,iCAAiC,QAAQ,WAAW;AAAA,iBAC5C,MAAM,KAAK,IAAI,CAAC;AAAA;AAEjC;AAEA,SAAS,0BAA0B,SAAoC;AACrE,SAAO,kCAAkC,QAAQ,WAAW;AAAA,aACjD,QAAQ,UAAU,KAAK,IAAI,CAAC;AAAA,cAC3B,QAAQ,WAAW,KAAK,IAAI,CAAC;AAAA;AAE3C;AAEA,SAAS,2BACP,SACA,eACA,YACQ;AACR,SAAO,iCAAiC,QAAQ,WAAW;AAAA,cAC/C,gBAAgB,QAAQ,IAAI;AAAA,UAChC,aAAa,QAAQ,IAAI;AAAA;AAEnC;AAEA,SAAS,kBAAkB,SAAoC;AAC7D,SAAO,4CAA4C,QAAQ,WAAW;AAAA;AAExE;AAEA,SAAS,sBAAsB,SAA4B,YAA8B;AACvF,SAAO,gDAAgD,QAAQ,WAAW;AAAA,eAC7D,WAAW,MAAM,GAAG,EAAE,EAAE,KAAK,IAAI,CAAC;AAAA;AAEjD;AAEA,SAAS,mBAAmB,SAA4B,cAAgC;AACtF,SAAO,oCAAoC,QAAQ,WAAW;AAAA,aACnD,aAAa,MAAM,GAAG,EAAE,EAAE,KAAK,IAAI,CAAC;AAAA;AAEjD;AAEA,SAAS,iBAAiB,SAA4B,cAAgC;AACpF,SAAO,kCAAkC,QAAQ,WAAW;AAAA,eAC/C,aAAa,MAAM,GAAG,EAAE,EAAE,KAAK,IAAI,CAAC;AAAA;AAEnD;"}
1
+ {"version":3,"file":"doc-generator-agents.js","sources":["../../src/generators/doc-generator-agents.ts"],"sourcesContent":["/**\n * Agent-Driven Document Generator\n *\n * Spawns expert agents from claude-flow to analyze existing code and\n * documentation, then generates appropriate documents for each directory.\n */\n\nimport { existsSync, readFileSync, writeFileSync, readdirSync, statSync, mkdirSync, copyFileSync } from 'fs';\nimport { join, basename, extname, relative, dirname } from 'path';\nimport fg from 'fast-glob';\nimport { spawn } from 'child_process';\n\n/**\n * Service documentation found in src/{service}/docs directories\n */\ninterface ServiceDoc {\n serviceName: string;\n sourcePath: string;\n fileName: string;\n relativePath: string;\n}\n\n/**\n * Document generation context\n */\nexport interface GenerationContext {\n projectRoot: string;\n docsPath: string;\n projectName: string;\n languages: string[];\n frameworks: string[];\n existingDocs: string[];\n sourceFiles: string[];\n serviceDocs: ServiceDoc[];\n}\n\n/**\n * Generation result for a single document\n */\nexport interface GeneratedDoc {\n path: string;\n title: string;\n type: string;\n generated: boolean;\n error?: string;\n}\n\n/**\n * Overall generation result\n */\nexport interface AgentGenerationResult {\n success: boolean;\n documentsGenerated: GeneratedDoc[];\n agentsSpawned: number;\n errors: string[];\n}\n\n/**\n * Agent task definition\n */\ninterface AgentTask {\n directory: string;\n type: 'concept' | 'component' | 'service' | 'feature' | 'integration' | 'standard' | 'guide' | 'reference';\n agentType: 'researcher' | 'coder' | 'analyst';\n prompt: string;\n outputFile: string;\n}\n\n/**\n * Analyze project and generate documents using expert agents\n */\nexport async function generateDocsWithAgents(\n projectRoot: string,\n docsPath: string,\n options: {\n parallel?: boolean;\n dryRun?: boolean;\n verbose?: boolean;\n force?: boolean;\n } = {}\n): Promise<AgentGenerationResult> {\n const result: AgentGenerationResult = {\n success: true,\n documentsGenerated: [],\n agentsSpawned: 0,\n errors: [],\n };\n\n try {\n // Build context by analyzing the project\n const context = await buildGenerationContext(projectRoot, docsPath);\n\n // Determine what documents should be generated\n const tasks = await planDocumentGeneration(context, options.force);\n\n if (options.dryRun) {\n console.log('\\n[Dry Run] Would generate the following documents:');\n for (const task of tasks) {\n console.log(` - ${task.outputFile} (${task.agentType} agent)`);\n }\n if (context.serviceDocs.length > 0) {\n console.log('\\n[Dry Run] Would copy service docs:');\n for (const doc of context.serviceDocs) {\n const targetPath = `services/${doc.serviceName}/${doc.relativePath}`;\n console.log(` - ${doc.sourcePath} → ${targetPath}`);\n }\n }\n return result;\n }\n\n // Copy service docs from src/{service}/docs to main docs directory\n const copiedDocs = copyServiceDocs(context, options.force);\n\n // Execute tasks (parallel or sequential)\n if (options.parallel) {\n const results = await Promise.allSettled(\n tasks.map(task => executeAgentTask(task, context, options.verbose))\n );\n\n for (let i = 0; i < results.length; i++) {\n const r = results[i];\n result.agentsSpawned++;\n\n if (r.status === 'fulfilled') {\n result.documentsGenerated.push(r.value);\n } else {\n result.errors.push(`Failed: ${tasks[i].outputFile} - ${r.reason}`);\n result.documentsGenerated.push({\n path: tasks[i].outputFile,\n title: basename(tasks[i].outputFile, '.md'),\n type: tasks[i].type,\n generated: false,\n error: String(r.reason),\n });\n }\n }\n } else {\n // Sequential execution\n for (const task of tasks) {\n result.agentsSpawned++;\n\n try {\n const doc = await executeAgentTask(task, context, options.verbose);\n result.documentsGenerated.push(doc);\n } catch (error) {\n result.errors.push(`Failed: ${task.outputFile} - ${error}`);\n result.documentsGenerated.push({\n path: task.outputFile,\n title: basename(task.outputFile, '.md'),\n type: task.type,\n generated: false,\n error: String(error),\n });\n }\n }\n }\n\n // Add copied service docs to result\n result.documentsGenerated.push(...copiedDocs);\n\n result.success = result.errors.length === 0;\n } catch (error) {\n result.success = false;\n result.errors.push(`Generation failed: ${error}`);\n }\n\n return result;\n}\n\n/**\n * Copy service docs from src/{service}/docs to main docs directory\n */\nfunction copyServiceDocs(context: GenerationContext, force?: boolean): GeneratedDoc[] {\n const { docsPath, serviceDocs } = context;\n const copied: GeneratedDoc[] = [];\n\n for (const doc of serviceDocs) {\n const targetDir = join(docsPath, 'services', doc.serviceName);\n const targetPath = join(targetDir, doc.relativePath);\n const relativeTarget = `services/${doc.serviceName}/${doc.relativePath}`;\n\n // Skip if target exists and not forcing\n if (!force && existsSync(targetPath)) {\n continue;\n }\n\n try {\n // Create target directory if needed\n const targetFileDir = dirname(targetPath);\n if (!existsSync(targetFileDir)) {\n mkdirSync(targetFileDir, { recursive: true });\n }\n\n // Copy the file\n copyFileSync(doc.sourcePath, targetPath);\n\n copied.push({\n path: relativeTarget,\n title: doc.fileName.replace('.md', ''),\n type: 'service',\n generated: true,\n });\n } catch (error) {\n copied.push({\n path: relativeTarget,\n title: doc.fileName.replace('.md', ''),\n type: 'service',\n generated: false,\n error: String(error),\n });\n }\n }\n\n return copied;\n}\n\n/**\n * Build context by analyzing the project\n */\nasync function buildGenerationContext(\n projectRoot: string,\n docsPath: string\n): Promise<GenerationContext> {\n const context: GenerationContext = {\n projectRoot,\n docsPath,\n projectName: basename(projectRoot),\n languages: [],\n frameworks: [],\n existingDocs: [],\n sourceFiles: [],\n serviceDocs: [],\n };\n\n // Get project name from package.json\n const pkgPath = join(projectRoot, 'package.json');\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));\n context.projectName = pkg.name?.replace(/^@[^/]+\\//, '') || context.projectName;\n\n // Detect frameworks from dependencies\n const deps = { ...pkg.dependencies, ...pkg.devDependencies };\n if (deps.react) context.frameworks.push('React');\n if (deps.next) context.frameworks.push('Next.js');\n if (deps.vue) context.frameworks.push('Vue');\n if (deps.express) context.frameworks.push('Express');\n if (deps.fastify) context.frameworks.push('Fastify');\n if (deps['@prisma/client'] || deps.prisma) context.frameworks.push('Prisma');\n } catch {\n // Ignore parse errors\n }\n }\n\n // Detect languages\n if (existsSync(join(projectRoot, 'tsconfig.json'))) {\n context.languages.push('TypeScript');\n }\n if (existsSync(join(projectRoot, 'package.json'))) {\n context.languages.push('JavaScript');\n }\n\n // Detect Python - check multiple locations for requirements\n const pythonConfigPaths = [\n join(projectRoot, 'requirements.txt'),\n join(projectRoot, 'pyproject.toml'),\n join(projectRoot, 'src/backend/requirements.txt'),\n join(projectRoot, 'backend/requirements.txt'),\n join(projectRoot, 'src/requirements.txt'),\n ];\n const foundPythonConfig = pythonConfigPaths.find(p => existsSync(p));\n\n // Also detect Python if we find .py files later in source scan\n // For now, check if there's a Python config file\n if (foundPythonConfig) {\n context.languages.push('Python');\n\n // Detect Python frameworks from requirements.txt or pyproject.toml\n try {\n let reqContent = readFileSync(foundPythonConfig, 'utf-8').toLowerCase();\n // Also check pyproject.toml if we found requirements.txt\n if (foundPythonConfig.includes('requirements.txt')) {\n const pyprojectPath = join(projectRoot, 'pyproject.toml');\n if (existsSync(pyprojectPath)) {\n reqContent += readFileSync(pyprojectPath, 'utf-8').toLowerCase();\n }\n }\n if (reqContent.includes('fastapi')) context.frameworks.push('FastAPI');\n if (reqContent.includes('flask')) context.frameworks.push('Flask');\n if (reqContent.includes('django')) context.frameworks.push('Django');\n if (reqContent.includes('sqlalchemy')) context.frameworks.push('SQLAlchemy');\n if (reqContent.includes('pydantic')) context.frameworks.push('Pydantic');\n if (reqContent.includes('alembic')) context.frameworks.push('Alembic');\n } catch {\n // Ignore read errors\n }\n }\n if (existsSync(join(projectRoot, 'Cargo.toml'))) {\n context.languages.push('Rust');\n }\n if (existsSync(join(projectRoot, 'go.mod'))) {\n context.languages.push('Go');\n }\n\n // Find existing docs\n const existingDocs = await fg('**/*.md', {\n cwd: docsPath,\n ignore: ['node_modules/**', '.git/**', '_templates/**'],\n });\n context.existingDocs = existingDocs;\n\n // Find source files\n const sourceFiles = await fg('**/*.{ts,tsx,js,jsx,py,rs,go}', {\n cwd: projectRoot,\n ignore: ['node_modules/**', '.git/**', 'dist/**', 'build/**', docsPath + '/**'],\n dot: true,\n });\n context.sourceFiles = sourceFiles;\n\n // Detect Python from .py files if not already detected\n if (!context.languages.includes('Python') && sourceFiles.some(f => f.endsWith('.py'))) {\n context.languages.push('Python');\n }\n\n // Scan for service docs in src/{service}/docs directories\n const serviceDocs: ServiceDoc[] = [];\n const srcDir = join(projectRoot, 'src');\n if (existsSync(srcDir)) {\n try {\n const srcEntries = readdirSync(srcDir, { withFileTypes: true });\n for (const entry of srcEntries) {\n if (entry.isDirectory()) {\n const serviceDocsDir = join(srcDir, entry.name, 'docs');\n if (existsSync(serviceDocsDir)) {\n // Find all markdown files in this service's docs directory\n const docsFiles = await fg('**/*.md', {\n cwd: serviceDocsDir,\n ignore: ['node_modules/**', '.git/**'],\n });\n for (const docFile of docsFiles) {\n serviceDocs.push({\n serviceName: entry.name,\n sourcePath: join(serviceDocsDir, docFile),\n fileName: basename(docFile),\n relativePath: docFile,\n });\n }\n }\n }\n }\n } catch {\n // Ignore errors reading src directory\n }\n }\n context.serviceDocs = serviceDocs;\n\n return context;\n}\n\n/**\n * Plan what documents should be generated based on context\n */\nasync function planDocumentGeneration(context: GenerationContext, force?: boolean): Promise<AgentTask[]> {\n const tasks: AgentTask[] = [];\n const { projectRoot, docsPath, sourceFiles, frameworks } = context;\n\n // Helper to check if doc already exists (returns false if force is true)\n const docExists = (relativePath: string) => {\n if (force) return false; // Force regeneration\n return existsSync(join(docsPath, relativePath));\n };\n\n // Analyze source structure to determine what docs to generate\n const srcDirs = new Set<string>();\n const componentFiles: string[] = [];\n const serviceFiles: string[] = [];\n const utilityFiles: string[] = [];\n const backendFiles: string[] = [];\n const modelFiles: string[] = [];\n const frontendFiles: string[] = [];\n\n for (const file of sourceFiles) {\n const dir = file.split('/')[0];\n srcDirs.add(dir);\n const fileLower = file.toLowerCase();\n\n // Categorize files (improved patterns for Python and TypeScript)\n if (fileLower.includes('component') || fileLower.includes('/ui/') || fileLower.includes('/views/')) {\n componentFiles.push(file);\n }\n if (fileLower.includes('service') || fileLower.includes('/api/') || fileLower.includes('routes') || fileLower.includes('endpoints')) {\n serviceFiles.push(file);\n }\n if (fileLower.includes('util') || fileLower.includes('helper') || fileLower.includes('/lib/') || fileLower.includes('common')) {\n utilityFiles.push(file);\n }\n if (fileLower.includes('backend') || fileLower.includes('server') || fileLower.includes('app/')) {\n backendFiles.push(file);\n }\n if (fileLower.includes('model') || fileLower.includes('schema') || fileLower.includes('entities')) {\n modelFiles.push(file);\n }\n if (fileLower.includes('frontend') || fileLower.includes('client') || fileLower.includes('pages')) {\n frontendFiles.push(file);\n }\n }\n\n // If no service files found but backend files exist, use backend files\n if (serviceFiles.length === 0 && backendFiles.length > 0) {\n serviceFiles.push(...backendFiles);\n }\n\n // Generate architecture overview if source has modules with files\n // Threshold: at least 1 directory with 3+ source files\n if (srcDirs.size >= 1 && sourceFiles.length >= 3 && !docExists('concepts/architecture/overview.md')) {\n tasks.push({\n directory: 'concepts/architecture',\n type: 'concept',\n agentType: 'analyst',\n prompt: buildArchitecturePrompt(context, Array.from(srcDirs)),\n outputFile: 'concepts/architecture/overview.md',\n });\n }\n\n // Generate component docs for detected UI frameworks\n if (frameworks.includes('React') || frameworks.includes('Vue')) {\n if (componentFiles.length > 0 && !docExists('components/ui/overview.md')) {\n tasks.push({\n directory: 'components/ui',\n type: 'component',\n agentType: 'coder',\n prompt: buildComponentPrompt(context, componentFiles.slice(0, 10)),\n outputFile: 'components/ui/overview.md',\n });\n }\n }\n\n // Generate service docs if API files detected\n if (serviceFiles.length > 0 && !docExists('services/api/overview.md')) {\n tasks.push({\n directory: 'services/api',\n type: 'service',\n agentType: 'coder',\n prompt: buildServicePrompt(context, serviceFiles.slice(0, 10)),\n outputFile: 'services/api/overview.md',\n });\n }\n\n // Generate utility docs\n if (utilityFiles.length > 0 && !docExists('components/utilities/overview.md')) {\n tasks.push({\n directory: 'components/utilities',\n type: 'component',\n agentType: 'coder',\n prompt: buildUtilityPrompt(context, utilityFiles.slice(0, 10)),\n outputFile: 'components/utilities/overview.md',\n });\n }\n\n // Generate getting started guide\n if (!docExists('guides/getting-started/quick-start.md')) {\n tasks.push({\n directory: 'guides/getting-started',\n type: 'guide',\n agentType: 'researcher',\n prompt: buildGettingStartedPrompt(context),\n outputFile: 'guides/getting-started/quick-start.md',\n });\n }\n\n // Generate standards/coding guide if tsconfig or eslint exists\n const hasLinting = existsSync(join(projectRoot, '.eslintrc.json')) ||\n existsSync(join(projectRoot, '.eslintrc.js')) ||\n existsSync(join(projectRoot, 'eslint.config.js'));\n const hasTypescript = existsSync(join(projectRoot, 'tsconfig.json'));\n\n if ((hasLinting || hasTypescript) && !docExists('standards/coding-standards/guide.md')) {\n tasks.push({\n directory: 'standards/coding-standards',\n type: 'standard',\n agentType: 'analyst',\n prompt: buildCodingStandardsPrompt(context, hasTypescript, hasLinting),\n outputFile: 'standards/coding-standards/guide.md',\n });\n }\n\n // Generate integration docs for detected databases/services\n if (frameworks.includes('Prisma') && !docExists('integrations/databases/prisma.md')) {\n tasks.push({\n directory: 'integrations/databases',\n type: 'integration',\n agentType: 'coder',\n prompt: buildPrismaPrompt(context),\n outputFile: 'integrations/databases/prisma.md',\n });\n }\n\n // Generate SQLAlchemy docs for Python projects\n if (frameworks.includes('SQLAlchemy') && !docExists('integrations/databases/sqlalchemy.md')) {\n tasks.push({\n directory: 'integrations/databases',\n type: 'integration',\n agentType: 'coder',\n prompt: buildSQLAlchemyPrompt(context, modelFiles),\n outputFile: 'integrations/databases/sqlalchemy.md',\n });\n }\n\n // Generate FastAPI docs\n if (frameworks.includes('FastAPI') && !docExists('services/api/fastapi.md')) {\n tasks.push({\n directory: 'services/api',\n type: 'service',\n agentType: 'coder',\n prompt: buildFastAPIPrompt(context, serviceFiles),\n outputFile: 'services/api/fastapi.md',\n });\n }\n\n // Generate Flask docs\n if (frameworks.includes('Flask') && !docExists('services/api/flask.md')) {\n tasks.push({\n directory: 'services/api',\n type: 'service',\n agentType: 'coder',\n prompt: buildFlaskPrompt(context, serviceFiles),\n outputFile: 'services/api/flask.md',\n });\n }\n\n return tasks;\n}\n\n/**\n * Execute a single agent task\n */\nasync function executeAgentTask(\n task: AgentTask,\n context: GenerationContext,\n verbose?: boolean\n): Promise<GeneratedDoc> {\n const { docsPath } = context;\n const outputPath = join(docsPath, task.outputFile);\n\n // Try to use claude-flow if available, otherwise generate locally\n const hasClaudeFlow = await checkClaudeFlowAvailable();\n\n let content: string;\n\n if (hasClaudeFlow) {\n content = await executeWithClaudeFlow(task, context, verbose);\n } else {\n // Fallback to local template generation\n content = generateLocalTemplate(task, context);\n }\n\n // Write the file\n writeFileSync(outputPath, content, 'utf-8');\n\n return {\n path: task.outputFile,\n title: extractTitle(content) || basename(task.outputFile, '.md'),\n type: task.type,\n generated: true,\n };\n}\n\n/**\n * Check if claude-flow is available\n */\nasync function checkClaudeFlowAvailable(): Promise<boolean> {\n // First try direct command (globally installed claude-flow)\n const tryDirect = new Promise<boolean>((resolve) => {\n const proc = spawn('claude-flow', ['--version'], {\n stdio: 'pipe',\n shell: false,\n });\n\n proc.on('close', (code) => resolve(code === 0));\n proc.on('error', () => resolve(false));\n setTimeout(() => { proc.kill(); resolve(false); }, 5000);\n });\n\n if (await tryDirect) return true;\n\n // Fall back to npx\n return new Promise((resolve) => {\n const proc = spawn('npx', ['claude-flow', '--version'], {\n stdio: 'pipe',\n shell: false,\n });\n\n proc.on('close', (code) => resolve(code === 0));\n proc.on('error', () => resolve(false));\n setTimeout(() => { proc.kill(); resolve(false); }, 30000);\n });\n}\n\n/**\n * Execute task using claude-flow expert agents\n */\nasync function executeWithClaudeFlow(\n task: AgentTask,\n context: GenerationContext,\n verbose?: boolean\n): Promise<string> {\n return new Promise((resolve, reject) => {\n const agentCmd = `claude-flow sparc run ${task.agentType} \"${task.prompt.replace(/\"/g, '\\\\\"')}\"`;\n\n if (verbose) {\n console.log(`\\n Spawning ${task.agentType} agent for ${task.outputFile}...`);\n }\n\n const proc = spawn(agentCmd, {\n shell: true,\n cwd: context.projectRoot,\n stdio: verbose ? 'inherit' : 'pipe',\n });\n\n let output = '';\n\n if (proc.stdout) {\n proc.stdout.on('data', (data) => {\n output += data.toString();\n });\n }\n\n proc.on('close', (code) => {\n if (code === 0 && output) {\n resolve(output);\n } else {\n // Fallback to local generation\n resolve(generateLocalTemplate(task, context));\n }\n });\n\n proc.on('error', () => {\n resolve(generateLocalTemplate(task, context));\n });\n\n // Timeout after 60 seconds\n setTimeout(() => {\n proc.kill();\n resolve(generateLocalTemplate(task, context));\n }, 60000);\n });\n}\n\n/**\n * Generate document using local templates (fallback)\n */\nfunction generateLocalTemplate(task: AgentTask, context: GenerationContext): string {\n const date = new Date().toISOString().split('T')[0];\n const { projectName } = context;\n\n const templates: Record<string, string> = {\n 'concepts/architecture/overview.md': `---\ntitle: Architecture Overview\ntype: concept\nstatus: active\ntags: [architecture, overview]\ncreated: ${date}\n---\n\n# Architecture Overview\n\nHigh-level architecture documentation for ${projectName}.\n\n## System Overview\n\nThis document describes the overall architecture and design patterns used in ${projectName}.\n\n## Module Structure\n\n${context.sourceFiles.slice(0, 20).map(f => `- \\`${f}\\``).join('\\n')}\n\n## Key Patterns\n\n*Document key architectural patterns here*\n\n## Design Decisions\n\n*Add Architecture Decision Records (ADRs)*\n\n---\n> Auto-generated by kg-agent\n`,\n\n 'components/ui/overview.md': `---\ntitle: UI Components Overview\ntype: technical\nstatus: active\ntags: [components, ui]\ncreated: ${date}\n---\n\n# UI Components\n\nUser interface components for ${projectName}.\n\n## Component Library\n\n${context.frameworks.includes('React') ? 'Built with **React**.' : ''}\n${context.frameworks.includes('Vue') ? 'Built with **Vue**.' : ''}\n\n## Available Components\n\n*Document available UI components*\n\n## Usage Patterns\n\n*Add component usage examples*\n\n---\n> Auto-generated by kg-agent\n`,\n\n 'services/api/overview.md': `---\ntitle: API Services Overview\ntype: service\nstatus: active\ntags: [api, services]\ncreated: ${date}\n---\n\n# API Services\n\nBackend API services for ${projectName}.\n\n## Endpoints\n\n*Document API endpoints*\n\n## Authentication\n\n*Document authentication flow*\n\n## Error Handling\n\n*Document error handling patterns*\n\n---\n> Auto-generated by kg-agent\n`,\n\n 'components/utilities/overview.md': `---\ntitle: Utilities Overview\ntype: technical\nstatus: active\ntags: [utilities, helpers]\ncreated: ${date}\n---\n\n# Utility Functions\n\nReusable utilities and helpers for ${projectName}.\n\n## Available Utilities\n\n*Document available utilities*\n\n## Usage Examples\n\n*Add code examples*\n\n---\n> Auto-generated by kg-agent\n`,\n\n 'guides/getting-started/quick-start.md': `---\ntitle: Quick Start Guide\ntype: guide\nstatus: active\ntags: [guide, getting-started]\ncreated: ${date}\n---\n\n# Quick Start\n\nGet up and running with ${projectName}.\n\n## Prerequisites\n\n${context.languages.map(l => `- ${l}`).join('\\n')}\n\n## Installation\n\n\\`\\`\\`bash\nnpm install\n\\`\\`\\`\n\n## Basic Usage\n\n*Add basic usage instructions*\n\n## Next Steps\n\n- [[concepts/architecture/overview|Architecture Overview]]\n- [[guides/_MOC|More Guides]]\n\n---\n> Auto-generated by kg-agent\n`,\n\n 'standards/coding-standards/guide.md': `---\ntitle: Coding Standards\ntype: standard\nstatus: active\ntags: [standards, coding]\ncreated: ${date}\n---\n\n# Coding Standards\n\nCode style and conventions for ${projectName}.\n\n## Language Standards\n\n${context.languages.map(l => `### ${l}\\n\\n*Add ${l} specific standards*`).join('\\n\\n')}\n\n## Linting Configuration\n\n*Document ESLint/Prettier setup*\n\n## Best Practices\n\n*Add coding best practices*\n\n---\n> Auto-generated by kg-agent\n`,\n\n 'integrations/databases/prisma.md': `---\ntitle: Prisma Integration\ntype: integration\nstatus: active\ntags: [prisma, database, orm]\ncreated: ${date}\n---\n\n# Prisma Integration\n\nDatabase ORM configuration for ${projectName}.\n\n## Schema Location\n\n\\`prisma/schema.prisma\\`\n\n## Models\n\n*Document database models*\n\n## Migrations\n\n\\`\\`\\`bash\nnpx prisma migrate dev\n\\`\\`\\`\n\n## Client Usage\n\n*Add Prisma client usage examples*\n\n---\n> Auto-generated by kg-agent\n`,\n\n 'integrations/databases/sqlalchemy.md': `---\ntitle: SQLAlchemy Integration\ntype: integration\nstatus: active\ntags: [sqlalchemy, database, orm, python]\ncreated: ${date}\n---\n\n# SQLAlchemy Integration\n\nDatabase ORM configuration for ${projectName}.\n\n## Models\n\n*Document your SQLAlchemy models*\n\n## Database Connection\n\n\\`\\`\\`python\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\nengine = create_engine(DATABASE_URL)\nSession = sessionmaker(bind=engine)\n\\`\\`\\`\n\n## Migrations (Alembic)\n\n\\`\\`\\`bash\nalembic upgrade head\n\\`\\`\\`\n\n## Query Examples\n\n*Add common query patterns*\n\n---\n> Auto-generated by kg-agent\n`,\n\n 'services/api/fastapi.md': `---\ntitle: FastAPI Service\ntype: service\nstatus: active\ntags: [fastapi, api, python]\ncreated: ${date}\n---\n\n# FastAPI Service\n\nAPI service documentation for ${projectName}.\n\n## Running the Server\n\n\\`\\`\\`bash\nuvicorn main:app --reload\n\\`\\`\\`\n\n## API Endpoints\n\n*Document your API endpoints*\n\n## Authentication\n\n*Document authentication flow*\n\n## Request/Response Schemas\n\n*Document Pydantic models*\n\n---\n> Auto-generated by kg-agent\n`,\n\n 'services/api/flask.md': `---\ntitle: Flask Service\ntype: service\nstatus: active\ntags: [flask, api, python]\ncreated: ${date}\n---\n\n# Flask Service\n\nAPI service documentation for ${projectName}.\n\n## Running the Server\n\n\\`\\`\\`bash\nflask run\n\\`\\`\\`\n\n## Routes\n\n*Document your Flask routes*\n\n## Blueprints\n\n*Document blueprints structure*\n\n## Error Handling\n\n*Document error handling patterns*\n\n---\n> Auto-generated by kg-agent\n`,\n };\n\n return templates[task.outputFile] || generateGenericTemplate(task, context, date);\n}\n\n/**\n * Generate a generic template for unknown task types\n */\nfunction generateGenericTemplate(\n task: AgentTask,\n context: GenerationContext,\n date: string\n): string {\n const title = basename(task.outputFile, '.md')\n .split('-')\n .map(w => w.charAt(0).toUpperCase() + w.slice(1))\n .join(' ');\n\n return `---\ntitle: ${title}\ntype: ${task.type}\nstatus: draft\ntags: [${task.type}]\ncreated: ${date}\n---\n\n# ${title}\n\nDocumentation for ${context.projectName}.\n\n## Overview\n\n*Add overview content*\n\n## Details\n\n*Add detailed documentation*\n\n---\n> Auto-generated by kg-agent\n`;\n}\n\n/**\n * Extract title from markdown content\n */\nfunction extractTitle(content: string): string | null {\n const match = content.match(/^#\\s+(.+)$/m);\n return match ? match[1] : null;\n}\n\n// Prompt builders\n\nfunction buildArchitecturePrompt(context: GenerationContext, dirs: string[]): string {\n return `Analyze the architecture of ${context.projectName}.\nModules: ${dirs.join(', ')}.\nLanguages: ${context.languages.join(', ')}.\nGenerate an Architecture Overview markdown document with system design, patterns, and key decisions.`;\n}\n\nfunction buildComponentPrompt(context: GenerationContext, files: string[]): string {\n return `Document the UI components in ${context.projectName}.\nFrameworks: ${context.frameworks.join(', ')}.\nComponent files: ${files.join(', ')}.\nGenerate a Components Overview markdown document.`;\n}\n\nfunction buildServicePrompt(context: GenerationContext, files: string[]): string {\n return `Document the API services in ${context.projectName}.\nService files: ${files.join(', ')}.\nGenerate an API Services Overview markdown document with endpoints and patterns.`;\n}\n\nfunction buildUtilityPrompt(context: GenerationContext, files: string[]): string {\n return `Document utility functions in ${context.projectName}.\nUtility files: ${files.join(', ')}.\nGenerate a Utilities Overview markdown document.`;\n}\n\nfunction buildGettingStartedPrompt(context: GenerationContext): string {\n return `Create a Quick Start guide for ${context.projectName}.\nLanguages: ${context.languages.join(', ')}.\nFrameworks: ${context.frameworks.join(', ')}.\nGenerate a Getting Started guide with installation and basic usage.`;\n}\n\nfunction buildCodingStandardsPrompt(\n context: GenerationContext,\n hasTypescript: boolean,\n hasLinting: boolean\n): string {\n return `Document coding standards for ${context.projectName}.\nTypeScript: ${hasTypescript ? 'yes' : 'no'}.\nESLint: ${hasLinting ? 'yes' : 'no'}.\nGenerate a Coding Standards guide with style rules and best practices.`;\n}\n\nfunction buildPrismaPrompt(context: GenerationContext): string {\n return `Document Prisma database integration for ${context.projectName}.\nGenerate integration documentation with schema, models, and usage patterns.`;\n}\n\nfunction buildSQLAlchemyPrompt(context: GenerationContext, modelFiles: string[]): string {\n return `Document SQLAlchemy database integration for ${context.projectName}.\nModel files: ${modelFiles.slice(0, 10).join(', ')}.\nGenerate integration documentation with models, relationships, and query patterns.`;\n}\n\nfunction buildFastAPIPrompt(context: GenerationContext, serviceFiles: string[]): string {\n return `Document FastAPI API service for ${context.projectName}.\nAPI files: ${serviceFiles.slice(0, 10).join(', ')}.\nGenerate API documentation with endpoints, request/response schemas, and authentication.`;\n}\n\nfunction buildFlaskPrompt(context: GenerationContext, serviceFiles: string[]): string {\n return `Document Flask API service for ${context.projectName}.\nRoute files: ${serviceFiles.slice(0, 10).join(', ')}.\nGenerate API documentation with routes, blueprints, and request handling.`;\n}\n"],"names":[],"mappings":";;;;AAuEA,eAAsB,uBACpB,aACA,UACA,UAKI,CAAA,GAC4B;AAChC,QAAM,SAAgC;AAAA,IACpC,SAAS;AAAA,IACT,oBAAoB,CAAA;AAAA,IACpB,eAAe;AAAA,IACf,QAAQ,CAAA;AAAA,EAAC;AAGX,MAAI;AAEF,UAAM,UAAU,MAAM,uBAAuB,aAAa,QAAQ;AAGlE,UAAM,QAAQ,MAAM,uBAAuB,SAAS,QAAQ,KAAK;AAEjE,QAAI,QAAQ,QAAQ;AAClB,cAAQ,IAAI,qDAAqD;AACjE,iBAAW,QAAQ,OAAO;AACxB,gBAAQ,IAAI,OAAO,KAAK,UAAU,KAAK,KAAK,SAAS,SAAS;AAAA,MAChE;AACA,UAAI,QAAQ,YAAY,SAAS,GAAG;AAClC,gBAAQ,IAAI,sCAAsC;AAClD,mBAAW,OAAO,QAAQ,aAAa;AACrC,gBAAM,aAAa,YAAY,IAAI,WAAW,IAAI,IAAI,YAAY;AAClE,kBAAQ,IAAI,OAAO,IAAI,UAAU,MAAM,UAAU,EAAE;AAAA,QACrD;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAGA,UAAM,aAAa,gBAAgB,SAAS,QAAQ,KAAK;AAGzD,QAAI,QAAQ,UAAU;AACpB,YAAM,UAAU,MAAM,QAAQ;AAAA,QAC5B,MAAM,IAAI,CAAA,SAAQ,iBAAiB,MAAM,SAAS,QAAQ,OAAO,CAAC;AAAA,MAAA;AAGpE,eAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,cAAM,IAAI,QAAQ,CAAC;AACnB,eAAO;AAEP,YAAI,EAAE,WAAW,aAAa;AAC5B,iBAAO,mBAAmB,KAAK,EAAE,KAAK;AAAA,QACxC,OAAO;AACL,iBAAO,OAAO,KAAK,WAAW,MAAM,C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
123
  return [
124
124
  `# Pre-task hook to restore graph context`,
125
- `npx claude-flow@alpha hooks session-restore --session-id "kg-${this.config.namespace}"`,
125
+ `claude-flow hooks session-restore --session-id "kg-${this.config.namespace}"`,
126
126
  ``,
127
127
  `# Post-edit hook to sync changes`,
128
- `npx claude-flow@alpha hooks post-edit --file "<file>" --memory-key "kg/${this.config.namespace}/changes"`,
128
+ `claude-flow hooks post-edit --file "<file>" --memory-key "kg/${this.config.namespace}/changes"`,
129
129
  ``,
130
130
  `# Session end hook to persist`,
131
- `npx claude-flow@alpha hooks session-end --export-metrics true`
131
+ `claude-flow hooks session-end --export-metrics true`
132
132
  ];
133
133
  }
134
134
  /**
@@ -196,7 +196,7 @@ function generateMcpConfig(namespace) {
196
196
  Add this to your Claude Code configuration:
197
197
 
198
198
  \`\`\`bash
199
- claude mcp add claude-flow npx claude-flow@alpha mcp start
199
+ claude mcp add claude-flow npx claude-flow mcp start
200
200
  \`\`\`
201
201
 
202
202
  ### Memory Namespace
@@ -1 +1 @@
1
- {"version":3,"file":"claude-flow.js","sources":["../../src/integrations/claude-flow.ts"],"sourcesContent":["/**\n * Claude-Flow Integration\n *\n * Integrates knowledge graph with claude-flow memory and coordination.\n */\n\nimport type {\n KnowledgeNode,\n GraphStats,\n MemoryEntry,\n SyncResult,\n} from '../core/types.js';\nimport { KnowledgeGraphDatabase } from '../core/database.js';\n\n/**\n * Claude-Flow client configuration\n */\nexport interface ClaudeFlowConfig {\n namespace: string;\n defaultTTL?: number;\n syncOnChange?: boolean;\n}\n\n/**\n * Memory entry for knowledge graph node\n */\ninterface NodeMemoryEntry {\n id: string;\n title: string;\n type: string;\n status: string;\n path: string;\n tags: string[];\n outgoingLinks: string[];\n incomingLinks: string[];\n summary?: string;\n lastModified: string;\n}\n\n/**\n * Claude-Flow Knowledge Graph Integration\n *\n * Syncs knowledge graph data with claude-flow memory for\n * cross-session persistence and agent coordination.\n */\nexport class ClaudeFlowIntegration {\n private config: Required<ClaudeFlowConfig>;\n\n constructor(config: ClaudeFlowConfig) {\n this.config = {\n namespace: config.namespace,\n defaultTTL: config.defaultTTL || 0,\n syncOnChange: config.syncOnChange ?? true,\n };\n }\n\n /**\n * Sync all nodes to claude-flow memory\n */\n async syncToMemory(db: KnowledgeGraphDatabase): Promise<SyncResult> {\n const result: SyncResult = {\n synced: 0,\n failed: 0,\n errors: [],\n };\n\n const nodes = db.getAllNodes();\n const entries: MemoryEntry[] = [];\n\n // Convert nodes to memory entries\n for (const node of nodes) {\n try {\n const entry = this.nodeToMemoryEntry(node);\n entries.push({\n key: `node/${node.id}`,\n value: entry,\n namespace: this.config.namespace,\n ttl: this.config.defaultTTL,\n });\n } catch (error) {\n result.failed++;\n result.errors.push({\n key: node.id,\n error: String(error),\n });\n }\n }\n\n // Store graph stats\n const stats = db.getStats();\n entries.push({\n key: 'stats',\n value: stats,\n namespace: this.config.namespace,\n });\n\n // Store metadata\n entries.push({\n key: 'metadata',\n value: {\n lastSync: new Date().toISOString(),\n nodeCount: nodes.length,\n version: db.getMetadata('version'),\n },\n namespace: this.config.namespace,\n });\n\n // Store index of all node IDs for quick lookup\n entries.push({\n key: 'index/nodes',\n value: nodes.map(n => ({\n id: n.id,\n title: n.title,\n type: n.type,\n path: n.path,\n })),\n namespace: this.config.namespace,\n });\n\n // Store tag index\n const tagIndex = this.buildTagIndex(nodes);\n entries.push({\n key: 'index/tags',\n value: tagIndex,\n namespace: this.config.namespace,\n });\n\n // Log what would be synced (MCP call would happen here)\n result.synced = entries.length;\n\n // Generate MCP commands for actual sync\n console.log(`\\n[Claude-Flow Sync] Would sync ${entries.length} entries to namespace: ${this.config.namespace}`);\n console.log('\\nTo sync, run these MCP commands:');\n\n for (const entry of entries.slice(0, 5)) {\n console.log(`mcp__claude-flow__memory_usage { action: \"store\", key: \"${entry.key}\", namespace: \"${this.config.namespace}\", value: \"...\" }`);\n }\n\n if (entries.length > 5) {\n console.log(`... and ${entries.length - 5} more entries`);\n }\n\n return result;\n }\n\n /**\n * Sync a single node to memory\n */\n async syncNode(node: KnowledgeNode): Promise<boolean> {\n try {\n const entry = this.nodeToMemoryEntry(node);\n\n // Generate MCP command\n console.log(`\\n[Claude-Flow Sync] Syncing node: ${node.id}`);\n console.log(`mcp__claude-flow__memory_usage {`);\n console.log(` action: \"store\",`);\n console.log(` key: \"node/${node.id}\",`);\n console.log(` namespace: \"${this.config.namespace}\",`);\n console.log(` value: ${JSON.stringify(entry, null, 2)}`);\n console.log(`}`);\n\n return true;\n } catch (error) {\n console.error(`Failed to sync node ${node.id}: ${error}`);\n return false;\n }\n }\n\n /**\n * Generate memory retrieval commands\n */\n generateRetrievalCommands(): string[] {\n return [\n `// Get graph stats`,\n `mcp__claude-flow__memory_usage { action: \"retrieve\", key: \"stats\", namespace: \"${this.config.namespace}\" }`,\n ``,\n `// Get node index`,\n `mcp__claude-flow__memory_usage { action: \"retrieve\", key: \"index/nodes\", namespace: \"${this.config.namespace}\" }`,\n ``,\n `// Get specific node`,\n `mcp__claude-flow__memory_usage { action: \"retrieve\", key: \"node/<node-id>\", namespace: \"${this.config.namespace}\" }`,\n ``,\n `// Search by pattern`,\n `mcp__claude-flow__memory_search { pattern: \"node/*\", namespace: \"${this.config.namespace}\" }`,\n ];\n }\n\n /**\n * Generate hook commands for automatic sync\n */\n generateHookCommands(): string[] {\n return [\n `# Pre-task hook to restore graph context`,\n `npx claude-flow@alpha hooks session-restore --session-id \"kg-${this.config.namespace}\"`,\n ``,\n `# Post-edit hook to sync changes`,\n `npx claude-flow@alpha hooks post-edit --file \"<file>\" --memory-key \"kg/${this.config.namespace}/changes\"`,\n ``,\n `# Session end hook to persist`,\n `npx claude-flow@alpha hooks session-end --export-metrics true`,\n ];\n }\n\n /**\n * Convert node to memory entry format\n */\n private nodeToMemoryEntry(node: KnowledgeNode): NodeMemoryEntry {\n // Extract first paragraph as summary\n const summary = this.extractSummary(node.content);\n\n return {\n id: node.id,\n title: node.title,\n type: node.type,\n status: node.status,\n path: node.path,\n tags: node.tags,\n outgoingLinks: node.outgoingLinks.map(l => l.target),\n incomingLinks: node.incomingLinks.map(l => l.target),\n summary,\n lastModified: node.lastModified.toISOString(),\n };\n }\n\n /**\n * Extract summary from content\n */\n private extractSummary(content: string, maxLength = 200): string {\n // Skip frontmatter and headers\n const lines = content.split('\\n');\n let summary = '';\n\n for (const line of lines) {\n const trimmed = line.trim();\n\n // Skip empty lines, headers, and code blocks\n if (!trimmed || trimmed.startsWith('#') || trimmed.startsWith('```')) {\n continue;\n }\n\n // Skip frontmatter markers\n if (trimmed === '---') {\n continue;\n }\n\n summary = trimmed;\n break;\n }\n\n // Truncate if needed\n if (summary.length > maxLength) {\n summary = summary.slice(0, maxLength - 3) + '...';\n }\n\n return summary;\n }\n\n /**\n * Build tag index from nodes\n */\n private buildTagIndex(nodes: KnowledgeNode[]): Record<string, string[]> {\n const index: Record<string, string[]> = {};\n\n for (const node of nodes) {\n for (const tag of node.tags) {\n if (!index[tag]) {\n index[tag] = [];\n }\n index[tag].push(node.id);\n }\n }\n\n return index;\n }\n}\n\n/**\n * Create claude-flow integration instance\n */\nexport function createClaudeFlowIntegration(\n config: ClaudeFlowConfig\n): ClaudeFlowIntegration {\n return new ClaudeFlowIntegration(config);\n}\n\n/**\n * Generate MCP configuration for CLAUDE.md\n */\nexport function generateMcpConfig(namespace: string): string {\n return `## Claude-Flow MCP Configuration\n\nAdd this to your Claude Code configuration:\n\n\\`\\`\\`bash\nclaude mcp add claude-flow npx claude-flow@alpha mcp start\n\\`\\`\\`\n\n### Memory Namespace\n\nThe knowledge graph uses namespace: \\`${namespace}\\`\n\n### Available Operations\n\n\\`\\`\\`javascript\n// Store knowledge\nmcp__claude-flow__memory_usage {\n action: \"store\",\n key: \"node/<id>\",\n namespace: \"${namespace}\",\n value: { ... }\n}\n\n// Retrieve knowledge\nmcp__claude-flow__memory_usage {\n action: \"retrieve\",\n key: \"node/<id>\",\n namespace: \"${namespace}\"\n}\n\n// Search knowledge\nmcp__claude-flow__memory_search {\n pattern: \"node/*\",\n namespace: \"${namespace}\"\n}\n\n// List all keys\nmcp__claude-flow__memory_usage {\n action: \"list\",\n namespace: \"${namespace}\"\n}\n\\`\\`\\`\n`;\n}\n"],"names":[],"mappings":"AA6CO,MAAM,sBAAsB;AAAA,EACzB;AAAA,EAER,YAAY,QAA0B;AACpC,SAAK,SAAS;AAAA,MACZ,WAAW,OAAO;AAAA,MAClB,YAAY,OAAO,cAAc;AAAA,MACjC,cAAc,OAAO,gBAAgB;AAAA,IAAA;AAAA,EAEzC;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,aAAa,IAAiD;AAClE,UAAM,SAAqB;AAAA,MACzB,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,QAAQ,CAAA;AAAA,IAAC;AAGX,UAAM,QAAQ,GAAG,YAAA;AACjB,UAAM,UAAyB,CAAA;AAG/B,eAAW,QAAQ,OAAO;AACxB,UAAI;AACF,cAAM,QAAQ,KAAK,kBAAkB,IAAI;AACzC,gBAAQ,KAAK;AAAA,UACX,KAAK,QAAQ,KAAK,EAAE;AAAA,UACpB,OAAO;AAAA,UACP,WAAW,KAAK,OAAO;AAAA,UACvB,KAAK,KAAK,OAAO;AAAA,QAAA,CAClB;AAAA,MACH,SAAS,OAAO;AACd,eAAO;AACP,eAAO,OAAO,KAAK;AAAA,UACjB,KAAK,KAAK;AAAA,UACV,OAAO,OAAO,KAAK;AAAA,QAAA,CACpB;AAAA,MACH;AAAA,IACF;AAGA,UAAM,QAAQ,GAAG,SAAA;AACjB,YAAQ,KAAK;AAAA,MACX,KAAK;AAAA,MACL,OAAO;AAAA,MACP,WAAW,KAAK,OAAO;AAAA,IAAA,CACxB;AAGD,YAAQ,KAAK;AAAA,MACX,KAAK;AAAA,MACL,OAAO;AAAA,QACL,WAAU,oBAAI,KAAA,GAAO,YAAA;AAAA,QACrB,WAAW,MAAM;AAAA,QACjB,SAAS,GAAG,YAAY,SAAS;AAAA,MAAA;AAAA,MAEnC,WAAW,KAAK,OAAO;AAAA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AW,GAAG,KAAK,QAAQ,WAAW,KAAK,GAAG;AACpE;AAAA,MACF;AAGA,UAAI,YAAY,OAAO;AACrB;AAAA,MACF;AAEA,gBAAU;AACV;AAAA,IACF;AAGA,QAAI,QAAQ,SAAS,WAAW;AAC9B,gBAAU,QAAQ,MAAM,GAAG,YAAY,CAAC,IAAI;AAAA,IAC9C;AAEA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKQ,cAAc,OAAkD;AACtE,UAAM,QAAkC,CAAA;AAExC,eAAW,QAAQ,OAAO;AACxB,iBAAW,OAAO,KAAK,MAAM;AAC3B,YAAI,CAAC,MAAM,GAAG,GAAG;AACf,gBAAM,GAAG,IAAI,CAAA;AAAA,QACf;AACA,cAAM,GAAG,EAAE,KAAK,KAAK,EAAE;AAAA,MACzB;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AACF;AAKO,SAAS,4BACd,QACuB;AACvB,SAAO,IAAI,sBAAsB,MAAM;AACzC;AAKO,SAAS,kBAAkB,WAA2B;AAC3D,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wCAU+B,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBASjC,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBAQT,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBAMT,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBAMT,SAAS;AAAA;AAAA;AAAA;AAIzB;"}
1
+ {"version":3,"file":"claude-flow.js","sources":["../../src/integrations/claude-flow.ts"],"sourcesContent":["/**\n * Claude-Flow Integration\n *\n * Integrates knowledge graph with claude-flow memory and coordination.\n */\n\nimport type {\n KnowledgeNode,\n GraphStats,\n MemoryEntry,\n SyncResult,\n} from '../core/types.js';\nimport { KnowledgeGraphDatabase } from '../core/database.js';\n\n/**\n * Claude-Flow client configuration\n */\nexport interface ClaudeFlowConfig {\n namespace: string;\n defaultTTL?: number;\n syncOnChange?: boolean;\n}\n\n/**\n * Memory entry for knowledge graph node\n */\ninterface NodeMemoryEntry {\n id: string;\n title: string;\n type: string;\n status: string;\n path: string;\n tags: string[];\n outgoingLinks: string[];\n incomingLinks: string[];\n summary?: string;\n lastModified: string;\n}\n\n/**\n * Claude-Flow Knowledge Graph Integration\n *\n * Syncs knowledge graph data with claude-flow memory for\n * cross-session persistence and agent coordination.\n */\nexport class ClaudeFlowIntegration {\n private config: Required<ClaudeFlowConfig>;\n\n constructor(config: ClaudeFlowConfig) {\n this.config = {\n namespace: config.namespace,\n defaultTTL: config.defaultTTL || 0,\n syncOnChange: config.syncOnChange ?? true,\n };\n }\n\n /**\n * Sync all nodes to claude-flow memory\n */\n async syncToMemory(db: KnowledgeGraphDatabase): Promise<SyncResult> {\n const result: SyncResult = {\n synced: 0,\n failed: 0,\n errors: [],\n };\n\n const nodes = db.getAllNodes();\n const entries: MemoryEntry[] = [];\n\n // Convert nodes to memory entries\n for (const node of nodes) {\n try {\n const entry = this.nodeToMemoryEntry(node);\n entries.push({\n key: `node/${node.id}`,\n value: entry,\n namespace: this.config.namespace,\n ttl: this.config.defaultTTL,\n });\n } catch (error) {\n result.failed++;\n result.errors.push({\n key: node.id,\n error: String(error),\n });\n }\n }\n\n // Store graph stats\n const stats = db.getStats();\n entries.push({\n key: 'stats',\n value: stats,\n namespace: this.config.namespace,\n });\n\n // Store metadata\n entries.push({\n key: 'metadata',\n value: {\n lastSync: new Date().toISOString(),\n nodeCount: nodes.length,\n version: db.getMetadata('version'),\n },\n namespace: this.config.namespace,\n });\n\n // Store index of all node IDs for quick lookup\n entries.push({\n key: 'index/nodes',\n value: nodes.map(n => ({\n id: n.id,\n title: n.title,\n type: n.type,\n path: n.path,\n })),\n namespace: this.config.namespace,\n });\n\n // Store tag index\n const tagIndex = this.buildTagIndex(nodes);\n entries.push({\n key: 'index/tags',\n value: tagIndex,\n namespace: this.config.namespace,\n });\n\n // Log what would be synced (MCP call would happen here)\n result.synced = entries.length;\n\n // Generate MCP commands for actual sync\n console.log(`\\n[Claude-Flow Sync] Would sync ${entries.length} entries to namespace: ${this.config.namespace}`);\n console.log('\\nTo sync, run these MCP commands:');\n\n for (const entry of entries.slice(0, 5)) {\n console.log(`mcp__claude-flow__memory_usage { action: \"store\", key: \"${entry.key}\", namespace: \"${this.config.namespace}\", value: \"...\" }`);\n }\n\n if (entries.length > 5) {\n console.log(`... and ${entries.length - 5} more entries`);\n }\n\n return result;\n }\n\n /**\n * Sync a single node to memory\n */\n async syncNode(node: KnowledgeNode): Promise<boolean> {\n try {\n const entry = this.nodeToMemoryEntry(node);\n\n // Generate MCP command\n console.log(`\\n[Claude-Flow Sync] Syncing node: ${node.id}`);\n console.log(`mcp__claude-flow__memory_usage {`);\n console.log(` action: \"store\",`);\n console.log(` key: \"node/${node.id}\",`);\n console.log(` namespace: \"${this.config.namespace}\",`);\n console.log(` value: ${JSON.stringify(entry, null, 2)}`);\n console.log(`}`);\n\n return true;\n } catch (error) {\n console.error(`Failed to sync node ${node.id}: ${error}`);\n return false;\n }\n }\n\n /**\n * Generate memory retrieval commands\n */\n generateRetrievalCommands(): string[] {\n return [\n `// Get graph stats`,\n `mcp__claude-flow__memory_usage { action: \"retrieve\", key: \"stats\", namespace: \"${this.config.namespace}\" }`,\n ``,\n `// Get node index`,\n `mcp__claude-flow__memory_usage { action: \"retrieve\", key: \"index/nodes\", namespace: \"${this.config.namespace}\" }`,\n ``,\n `// Get specific node`,\n `mcp__claude-flow__memory_usage { action: \"retrieve\", key: \"node/<node-id>\", namespace: \"${this.config.namespace}\" }`,\n ``,\n `// Search by pattern`,\n `mcp__claude-flow__memory_search { pattern: \"node/*\", namespace: \"${this.config.namespace}\" }`,\n ];\n }\n\n /**\n * Generate hook commands for automatic sync\n */\n generateHookCommands(): string[] {\n return [\n `# Pre-task hook to restore graph context`,\n `claude-flow hooks session-restore --session-id \"kg-${this.config.namespace}\"`,\n ``,\n `# Post-edit hook to sync changes`,\n `claude-flow hooks post-edit --file \"<file>\" --memory-key \"kg/${this.config.namespace}/changes\"`,\n ``,\n `# Session end hook to persist`,\n `claude-flow hooks session-end --export-metrics true`,\n ];\n }\n\n /**\n * Convert node to memory entry format\n */\n private nodeToMemoryEntry(node: KnowledgeNode): NodeMemoryEntry {\n // Extract first paragraph as summary\n const summary = this.extractSummary(node.content);\n\n return {\n id: node.id,\n title: node.title,\n type: node.type,\n status: node.status,\n path: node.path,\n tags: node.tags,\n outgoingLinks: node.outgoingLinks.map(l => l.target),\n incomingLinks: node.incomingLinks.map(l => l.target),\n summary,\n lastModified: node.lastModified.toISOString(),\n };\n }\n\n /**\n * Extract summary from content\n */\n private extractSummary(content: string, maxLength = 200): string {\n // Skip frontmatter and headers\n const lines = content.split('\\n');\n let summary = '';\n\n for (const line of lines) {\n const trimmed = line.trim();\n\n // Skip empty lines, headers, and code blocks\n if (!trimmed || trimmed.startsWith('#') || trimmed.startsWith('```')) {\n continue;\n }\n\n // Skip frontmatter markers\n if (trimmed === '---') {\n continue;\n }\n\n summary = trimmed;\n break;\n }\n\n // Truncate if needed\n if (summary.length > maxLength) {\n summary = summary.slice(0, maxLength - 3) + '...';\n }\n\n return summary;\n }\n\n /**\n * Build tag index from nodes\n */\n private buildTagIndex(nodes: KnowledgeNode[]): Record<string, string[]> {\n const index: Record<string, string[]> = {};\n\n for (const node of nodes) {\n for (const tag of node.tags) {\n if (!index[tag]) {\n index[tag] = [];\n }\n index[tag].push(node.id);\n }\n }\n\n return index;\n }\n}\n\n/**\n * Create claude-flow integration instance\n */\nexport function createClaudeFlowIntegration(\n config: ClaudeFlowConfig\n): ClaudeFlowIntegration {\n return new ClaudeFlowIntegration(config);\n}\n\n/**\n * Generate MCP configuration for CLAUDE.md\n */\nexport function generateMcpConfig(namespace: string): string {\n return `## Claude-Flow MCP Configuration\n\nAdd this to your Claude Code configuration:\n\n\\`\\`\\`bash\nclaude mcp add claude-flow npx claude-flow mcp start\n\\`\\`\\`\n\n### Memory Namespace\n\nThe knowledge graph uses namespace: \\`${namespace}\\`\n\n### Available Operations\n\n\\`\\`\\`javascript\n// Store knowledge\nmcp__claude-flow__memory_usage {\n action: \"store\",\n key: \"node/<id>\",\n namespace: \"${namespace}\",\n value: { ... }\n}\n\n// Retrieve knowledge\nmcp__claude-flow__memory_usage {\n action: \"retrieve\",\n key: \"node/<id>\",\n namespace: \"${namespace}\"\n}\n\n// Search knowledge\nmcp__claude-flow__memory_search {\n pattern: \"node/*\",\n namespace: \"${namespace}\"\n}\n\n// List all keys\nmcp__claude-flow__memory_usage {\n action: \"list\",\n namespace: \"${namespace}\"\n}\n\\`\\`\\`\n`;\n}\n"],"names":[],"mappings":"AA6CO,MAAM,sBAAsB;AAAA,EACzB;AAAA,EAER,YAAY,QAA0B;AACpC,SAAK,SAAS;AAAA,MACZ,WAAW,OAAO;AAAA,MAClB,YAAY,OAAO,cAAc;AAAA,MACjC,cAAc,OAAO,gBAAgB;AAAA,IAAA;AAAA,EAEzC;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,aAAa,IAAiD;AAClE,UAAM,SAAqB;AAAA,MACzB,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,QAAQ,CAAA;AAAA,IAAC;AAGX,UAAM,QAAQ,GAAG,YAAA;AACjB,UAAM,UAAyB,CAAA;AAG/B,eAAW,QAAQ,OAAO;AACxB,UAAI;AACF,cAAM,QAAQ,KAAK,kBAAkB,IAAI;AACzC,gBAAQ,KAAK;AAAA,UACX,KAAK,QAAQ,KAAK,EAAE;AAAA,UACpB,OAAO;AAAA,UACP,WAAW,KAAK,OAAO;AAAA,UACvB,KAAK,KAAK,OAAO;AAAA,QAAA,CAClB;AAAA,MACH,SAAS,OAAO;AACd,eAAO;AACP,eAAO,OAAO,KAAK;AAAA,UACjB,KAAK,KAAK;AAAA,UACV,OAAO,OAAO,KAAK;AAAA,QAAA,CACpB;AAAA,MACH;AAAA,IACF;AAGA,UAAM,Q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AAAA;AAAA;AAAA;AAAA,gBAMT,SAAS;AAAA;AAAA;AAAA;AAIzB;"}
@@ -18,7 +18,7 @@ export interface McpClientConfig {
18
18
  timeoutMs: number;
19
19
  /** Whether to fallback to in-memory storage when CLI unavailable (default: true) */
20
20
  fallbackEnabled: boolean;
21
- /** Claude-flow CLI command (default: 'npx claude-flow@alpha') */
21
+ /** Claude-flow CLI command (default: 'claude-flow' or 'npx claude-flow') */
22
22
  cliCommand: string;
23
23
  /** Whether to use JSON output format from CLI when available */
24
24
  useJsonOutput: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-client-adapter.d.ts","sourceRoot":"","sources":["../../../src/mcp/clients/mcp-client-adapter.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAuBH;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,oDAAoD;IACpD,UAAU,EAAE,MAAM,CAAC;IAEnB,oEAAoE;IACpE,YAAY,EAAE,MAAM,CAAC;IAErB,iEAAiE;IACjE,SAAS,EAAE,MAAM,CAAC;IAElB,oFAAoF;IACpF,eAAe,EAAE,OAAO,CAAC;IAEzB,iEAAiE;IACjE,UAAU,EAAE,MAAM,CAAC;IAEnB,gEAAgE;IAChE,aAAa,EAAE,OAAO,CAAC;CACxB;AAED;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC,sCAAsC;IACtC,OAAO,EAAE,OAAO,CAAC;IAEjB,kCAAkC;IAClC,IAAI,CAAC,EAAE,OAAO,CAAC;IAEf,gCAAgC;IAChC,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf,oDAAoD;IACpD,YAAY,EAAE,OAAO,CAAC;IAEtB,8BAA8B;IAC9B,QAAQ,EAAE,MAAM,CAAC;CAClB;AAYD;;;;;;;;;;;;;;;;;;GAkBG;AACH,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,MAAM,CAAkB;IAChC,OAAO,CAAC,aAAa,CAA0C;IAC/D,OAAO,CAAC,YAAY,CAAwB;IAC5C,OAAO,C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AAO,CAAC,gBAAgB;IAgBxB,OAAO,CAAC,cAAc;IA+BtB,OAAO,CAAC,cAAc;IAMtB,OAAO,CAAC,YAAY;CAkBrB;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC,eAAe,CAAC,GAAG,gBAAgB,CAE1F"}
@@ -17,7 +17,7 @@ class McpClientAdapter {
17
17
  retryDelayMs: config.retryDelayMs ?? 1e3,
18
18
  timeoutMs: config.timeoutMs ?? 3e4,
19
19
  fallbackEnabled: config.fallbackEnabled ?? true,
20
- cliCommand: config.cliCommand ?? "npx claude-flow@alpha",
20
+ cliCommand: config.cliCommand ?? "claude-flow",
21
21
  useJsonOutput: config.useJsonOutput ?? true
22
22
  };
23
23
  this.fallbackStore = /* @__PURE__ */ new Map();
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-client-adapter.js","sources":["../../../src/mcp/clients/mcp-client-adapter.ts"],"sourcesContent":["/**\n * MCP Client Adapter\n *\n * Provides real MCP tool execution via the claude-flow CLI with retry logic,\n * timeout handling, and graceful fallback to in-memory storage when CLI is unavailable.\n *\n * @module mcp/clients/mcp-client-adapter\n */\n\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\nimport {\n createLogger,\n withRetry,\n type RetryOptions,\n} from '../../utils/index.js';\n\nconst execAsync = promisify(exec);\n\n/**\n * Extended exec error type with additional properties\n */\ninterface ExecError extends Error {\n code?: string | number;\n killed?: boolean;\n stderr?: string;\n stdout?: string;\n}\nconst logger = createLogger('mcp-client-adapter');\n\n/**\n * MCP Client Configuration\n */\nexport interface McpClientConfig {\n /** Maximum number of retry attempts (default: 3) */\n maxRetries: number;\n\n /** Initial delay in milliseconds between retries (default: 1000) */\n retryDelayMs: number;\n\n /** Command execution timeout in milliseconds (default: 30000) */\n timeoutMs: number;\n\n /** Whether to fallback to in-memory storage when CLI unavailable (default: true) */\n fallbackEnabled: boolean;\n\n /** Claude-flow CLI command (default: 'npx claude-flow@alpha') */\n cliCommand: string;\n\n /** Whether to use JSON output format from CLI when available */\n useJsonOutput: boolean;\n}\n\n/**\n * Result of a memory operation\n */\nexport interface MemoryOperationResult {\n /** Whether the operation succeeded */\n success: boolean;\n\n /** Result data (if successful) */\n data?: unknown;\n\n /** Error message (if failed) */\n error?: string;\n\n /** Whether the result came from fallback storage */\n fromFallback: boolean;\n\n /** Number of attempts made */\n attempts: number;\n}\n\n/**\n * Memory entry stored in fallback\n */\ninterface FallbackEntry {\n value: string;\n ttl?: number;\n createdAt: number;\n expiresAt?: number;\n}\n\n/**\n * MCP Client Adapter\n *\n * Executes real claude-flow CLI commands with robust retry logic and fallback.\n *\n * @example\n * ```typescript\n * const adapter = new McpClientAdapter({\n * maxRetries: 3,\n * timeoutMs: 30000,\n * });\n *\n * // Store value\n * await adapter.memoryStore('myKey', 'myValue', 'myNamespace');\n *\n * // Retrieve value\n * const value = await adapter.memoryRetrieve('myKey', 'myNamespace');\n * ```\n */\nexport class McpClientAdapter {\n private config: McpClientConfig;\n private fallbackStore: Map<string, Map<string, FallbackEntry>>;\n private cliAvailable: boolean | null = null;\n private lastCliCheck: number = 0;\n private readonly CLI_CHECK_INTERVAL = 60000; // Re-check CLI availability every 60s\n\n constructor(config: Partial<McpClientConfig> = {}) {\n this.config = {\n maxRetries: config.maxRetries ?? 3,\n retryDelayMs: config.retryDelayMs ?? 1000,\n timeoutMs: config.timeoutMs ?? 30000,\n fallbackEnabled: config.fallbackEnabled ?? true,\n cliCommand: config.cliCommand ?? 'npx claude-flow@alpha',\n useJsonOutput: config.useJsonOutput ?? true,\n };\n this.fallbackStore = new Map();\n }\n\n /**\n * Store a value in memory\n *\n * @param key - Memory key\n * @param value - Value to store (will be JSON stringified if object)\n * @param namespace - Memory namespace (default: 'default')\n * @param ttl - Time to live in seconds (optional)\n * @returns Whether the operation succeeded\n */\n async memoryStore(\n key: string,\n value: string | object,\n namespace: string = 'default',\n ttl?: number\n ): Promise<boolean> {\n const stringValue = typeof value === 'string' ? value : JSON.stringify(value);\n\n const result = await this.executeWithRetry(async () => {\n const command = this.buildStoreCommand(key, stringValue, namespace, ttl);\n await this.executeCli(command);\n return true;\n });\n\n if (result.success) {\n logger.debug('Memory store succeeded via CLI', { key, namespace });\n return true;\n }\n\n // Fallback to in-memory storage\n if (this.config.fallbackEnabled) {\n this.storeFallback(key, stringValue, namespace, ttl);\n logger.warn('Memory store fell back to in-memory', { key, namespace, error: result.error });\n return true;\n }\n\n logger.error('Memory store failed', undefined, { key, namespace, error: result.error });\n return false;\n }\n\n /**\n * Retrieve a value from memory\n *\n * @param key - Memory key\n * @param namespace - Memory namespace (default: 'default')\n * @returns The stored value or null if not found\n */\n async memoryRetrieve(key: string, namespace: string = 'default'): Promise<string | null> {\n const result = await this.executeWithRetry(async () => {\n const command = this.buildQueryCommand(key, namespace);\n const output = await this.executeCli(command);\n return this.parseQueryOutput(output, key);\n });\n\n if (result.success && result.value !== undefined) {\n logger.debug('Memory retrieve succeeded via CLI', { key, namespace });\n return result.value;\n }\n\n // Fallback to in-memory storage\n if (this.config.fallbackEnabled) {\n const fallbackValue = this.retrieveFallback(key, namespace);\n if (fallbackValue !== null) {\n logger.debug('Memory retrieve fell back to in-memory', { key, namespace });\n return fallbackValue;\n }\n }\n\n logger.debug('Memory retrieve returned null', { key, namespace });\n return null;\n }\n\n /**\n * Search memory by pattern\n *\n * @param pattern - Search pattern (supports glob-like matching)\n * @param namespace - Memory namespace (default: 'default')\n * @param limit - Maximum number of results (default: 10)\n * @returns Array of matching keys\n */\n async memorySearch(\n pattern: string,\n namespace: string = 'default',\n limit: number = 10\n ): Promise<string[]> {\n const result = await this.executeWithRetry(async () => {\n const command = this.buildSearchCommand(pattern, namespace, limit);\n const output = await this.executeCli(command);\n return this.parseSearchOutput(output);\n });\n\n if (result.success && result.value) {\n logger.debug('Memory search succeeded via CLI', { pattern, namespace, count: result.value.length });\n return result.value;\n }\n\n // Fallback to in-memory search\n if (this.config.fallbackEnabled) {\n const fallbackResults = this.searchFallback(pattern, namespace, limit);\n logger.debug('Memory search fell back to in-memory', { pattern, namespace, count: fallbackResults.length });\n return fallbackResults;\n }\n\n logger.debug('Memory search returned empty', { pattern, namespace });\n return [];\n }\n\n /**\n * Delete a value from memory\n *\n * @param key - Memory key\n * @param namespace - Memory namespace (default: 'default')\n * @returns Whether the operation succeeded\n */\n async memoryDelete(key: string, namespace: string = 'default'): Promise<boolean> {\n const result = await this.executeWithRetry(async () => {\n // Use clear command with specific key pattern\n const command = this.buildDeleteCommand(key, namespace);\n await this.executeCli(command);\n return true;\n });\n\n if (result.success) {\n logger.debug('Memory delete succeeded via CLI', { key, namespace });\n }\n\n // Also delete from fallback (regardless of CLI success)\n if (this.config.fallbackEnabled) {\n this.deleteFallback(key, namespace);\n }\n\n return result.success || this.config.fallbackEnabled;\n }\n\n /**\n * List all keys in a namespace\n *\n * @param namespace - Memory namespace (default: 'default')\n * @returns Array of keys\n */\n async memoryList(namespace: string = 'default'): Promise<string[]> {\n const result = await this.executeWithRetry(async () => {\n const command = `${this.config.cliCommand} memory list --namespace \"${namespace}\"`;\n const output = await this.executeCli(command);\n return this.parseListOutput(output);\n });\n\n if (result.success && result.value) {\n logger.debug('Memory list succeeded via CLI', { namespace, count: result.value.length });\n return result.value;\n }\n\n // Fallback\n if (this.config.fallbackEnabled) {\n const fallbackKeys = this.listFallback(namespace);\n logger.debug('Memory list fell back to in-memory', { namespace, count: fallbackKeys.length });\n return fallbackKeys;\n }\n\n return [];\n }\n\n /**\n * Check if CLI is available\n */\n async isCliAvailable(): Promise<boolean> {\n const now = Date.now();\n\n // Use cached result if recent\n if (this.cliAvailable !== null && now - this.lastCliCheck < this.CLI_CHECK_INTERVAL) {\n return this.cliAvailable;\n }\n\n try {\n await this.executeCli(`${this.config.cliCommand} --version`, 5000);\n this.cliAvailable = true;\n this.lastCliCheck = now;\n return true;\n } catch {\n this.cliAvailable = false;\n this.lastCliCheck = now;\n return false;\n }\n }\n\n /**\n * Get current configuration\n */\n getConfig(): Readonly<McpClientConfig> {\n return { ...this.config };\n }\n\n /**\n * Get fallback store size for a namespace\n */\n getFallbackSize(namespace: string = 'default'): number {\n return this.fallbackStore.get(namespace)?.size ?? 0;\n }\n\n /**\n * Clear fallback store\n */\n clearFallback(namespace?: string): void {\n if (namespace) {\n this.fallbackStore.delete(namespace);\n } else {\n this.fallbackStore.clear();\n }\n }\n\n // Private methods\n\n private async executeWithRetry<T>(\n operation: () => Promise<T>\n ): Promise<{ success: boolean; value?: T; error?: string; attempts: number }> {\n const retryOptions: RetryOptions = {\n maxRetries: this.config.maxRetries,\n initialDelay: this.config.retryDelayMs,\n backoffFactor: 2,\n jitter: true,\n onRetry: (error, attempt, delay) => {\n logger.debug('Retrying MCP operation', {\n attempt,\n delay,\n error: error.message,\n });\n },\n };\n\n const result = await withRetry(operation, retryOptions);\n\n return {\n success: result.success,\n value: result.value,\n error: result.error?.message,\n attempts: result.attempts,\n };\n }\n\n private async executeCli(command: string, timeout?: number): Promise<string> {\n const effectiveTimeout = timeout ?? this.config.timeoutMs;\n\n logger.debug('Executing CLI command', { command: command.substring(0, 100) });\n\n try {\n const { stdout, stderr } = await execAsync(command, {\n timeout: effectiveTimeout,\n maxBuffer: 10 * 1024 * 1024, // 10MB buffer\n shell: '/bin/bash',\n });\n\n if (stderr && !stderr.includes('DeprecationWarning')) {\n logger.warn('CLI stderr output', { stderr: stderr.substring(0, 500) });\n }\n\n return stdout.trim();\n } catch (error) {\n const execError = error as ExecError;\n\n if (execError.code === 'ETIMEDOUT' || execError.killed) {\n throw new Error(`CLI command timed out after ${effectiveTimeout}ms`);\n }\n\n // Include any output in the error for debugging\n const message = execError.message || 'CLI execution failed';\n const details = execError.stderr || execError.stdout || '';\n throw new Error(`${message}${details ? `: ${details.substring(0, 200)}` : ''}`);\n }\n }\n\n private buildStoreCommand(\n key: string,\n value: string,\n namespace: string,\n ttl?: number\n ): string {\n const escapedValue = this.escapeShellArg(value);\n let command = `${this.config.cliCommand} memory store \"${key}\" ${escapedValue} --namespace \"${namespace}\"`;\n\n if (ttl !== undefined && ttl > 0) {\n command += ` --ttl ${ttl}`;\n }\n\n return command;\n }\n\n private buildQueryCommand(key: string, namespace: string): string {\n // Use query command to search for exact key\n return `${this.config.cliCommand} memory query \"${key}\" --namespace \"${namespace}\"`;\n }\n\n private buildSearchCommand(pattern: string, namespace: string, limit: number): string {\n return `${this.config.cliCommand} memory query \"${pattern}\" --namespace \"${namespace}\"`;\n }\n\n private buildDeleteCommand(key: string, namespace: string): string {\n // claude-flow uses 'clear' for deletion\n return `${this.config.cliCommand} memory clear --namespace \"${namespace}\"`;\n }\n\n private parseQueryOutput(output: string, key: string): string | null {\n if (!output || output.includes('not found') || output.includes('No results')) {\n return null;\n }\n\n // Try to parse as JSON first\n try {\n const parsed = JSON.parse(output);\n if (typeof parsed === 'object' && parsed !== null) {\n // Look for the key in the result\n if (key in parsed) {\n return typeof parsed[key] === 'string' ? parsed[key] : JSON.stringify(parsed[key]);\n }\n // Return the whole object as JSON string\n return JSON.stringify(parsed);\n }\n return String(parsed);\n } catch {\n // Return raw output\n return output;\n }\n }\n\n private parseSearchOutput(output: string): string[] {\n if (!output || output.includes('No results')) {\n return [];\n }\n\n // Try to parse as JSON array\n try {\n const parsed = JSON.parse(output);\n if (Array.isArray(parsed)) {\n return parsed.map((item) => (typeof item === 'string' ? item : JSON.stringify(item)));\n }\n if (typeof parsed === 'object' && parsed !== null) {\n return Object.keys(parsed);\n }\n } catch {\n // Parse line by line\n return output\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line.length > 0 && !line.startsWith('#'));\n }\n\n return [];\n }\n\n private parseListOutput(output: string): string[] {\n return this.parseSearchOutput(output);\n }\n\n private escapeShellArg(arg: string): string {\n // Escape for shell and wrap in quotes\n const escaped = arg\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\"/g, '\\\\\"')\n .replace(/`/g, '\\\\`')\n .replace(/\\$/g, '\\\\$')\n .replace(/\\n/g, '\\\\n');\n return `\"${escaped}\"`;\n }\n\n // Fallback storage methods\n\n private getOrCreateNamespace(namespace: string): Map<string, FallbackEntry> {\n let ns = this.fallbackStore.get(namespace);\n if (!ns) {\n ns = new Map();\n this.fallbackStore.set(namespace, ns);\n }\n return ns;\n }\n\n private storeFallback(key: string, value: string, namespace: string, ttl?: number): void {\n const ns = this.getOrCreateNamespace(namespace);\n const now = Date.now();\n\n ns.set(key, {\n value,\n ttl,\n createdAt: now,\n expiresAt: ttl ? now + ttl * 1000 : undefined,\n });\n }\n\n private retrieveFallback(key: string, namespace: string): string | null {\n const ns = this.fallbackStore.get(namespace);\n if (!ns) return null;\n\n const entry = ns.get(key);\n if (!entry) return null;\n\n // Check expiration\n if (entry.expiresAt && Date.now() > entry.expiresAt) {\n ns.delete(key);\n return null;\n }\n\n return entry.value;\n }\n\n private searchFallback(pattern: string, namespace: string, limit: number): string[] {\n const ns = this.fallbackStore.get(namespace);\n if (!ns) return [];\n\n const now = Date.now();\n const results: string[] = [];\n\n // Convert glob pattern to regex\n const regexPattern = pattern\n .replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\*/g, '.*')\n .replace(/\\?/g, '.');\n const regex = new RegExp(`^${regexPattern}$`, 'i');\n\n for (const [key, entry] of ns) {\n if (results.length >= limit) break;\n\n // Skip expired entries\n if (entry.expiresAt && now > entry.expiresAt) {\n ns.delete(key);\n continue;\n }\n\n if (regex.test(key)) {\n results.push(key);\n }\n }\n\n return results;\n }\n\n private deleteFallback(key: string, namespace: string): boolean {\n const ns = this.fallbackStore.get(namespace);\n if (!ns) return false;\n return ns.delete(key);\n }\n\n private listFallback(namespace: string): string[] {\n const ns = this.fallbackStore.get(namespace);\n if (!ns) return [];\n\n const now = Date.now();\n const keys: string[] = [];\n\n for (const [key, entry] of ns) {\n // Skip expired entries\n if (entry.expiresAt && now > entry.expiresAt) {\n ns.delete(key);\n continue;\n }\n keys.push(key);\n }\n\n return keys;\n }\n}\n\n/**\n * Create a configured MCP client adapter\n */\nexport function createMcpClientAdapter(config?: Partial<McpClientConfig>): McpClientAdapter {\n return new McpClientAdapter(config);\n}\n"],"names":[],"mappings":";;;;AAiBA,MAAM,YAAY,UAAU,IAAI;AAWhC,MAAM,SAAS,aAAa,oBAAoB;AA0EzC,MAAM,iBAAiB;AAAA,EACpB;AAAA,EACA;AAAA,EACA,eAA+B;AAAA,EAC/B,eAAuB;AAAA,EACd,qBAAqB;AAAA;AAAA,EAEtC,YAAY,SAAmC,IAAI;AACjD,SAAK,SAAS;AAAA,MACZ,YAAY,OAAO,cAAc;AAAA,MACjC,cAAc,OAAO,gBAAgB;AAAA,MACrC,WAAW,OAAO,aAAa;AAAA,MAC/B,iBAAiB,OAAO,mBAAmB;AAAA,MAC3C,YAAY,OAAO,cAAc;AAAA,MACjC,eAAe,OAAO,iBAAiB;AAAA,IAAA;AAEzC,SAAK,oCAAoB,IAAA;AAAA,EAC3B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,MAAM,YACJ,KACA,OACA,YAAoB,WACpB,KACkB;AAClB,UAAM,cAAc,OAAO,UAAU,WAAW,QAAQ,KAAK,UAAU,KAAK;AAE5E,UAAM,SAAS,MAAM,KAAK,iBAAiB,YAAY;AACrD,YAAM,UAAU,KAAK,kBAAkB,KAAK,aAAa,WAAW,GAAG;AACvE,YAAM,KAAK,WAAW,OAAO;AAC7B,aAAO;AAAA,IACT,CAAC;AAED,QAAI,OAAO,SAAS;AAClB,aAAO,MAAM,kCAAkC,EAAE,KAAK,WAAW;AACjE,aAAO;AAAA,IACT;AAGA,QAAI,KAAK,OAAO,iBAAiB;AAC/B,WAAK,cAAc,KAAK,aAAa,WAAW,GAAG;AACnD,aAAO,KAAK,uCAAuC,EAAE,KAAK,WAAW,OAAO,OAAO,OAAO;AAC1F,aAAO;AAAA,IACT;AAEA,WAAO,MAAM,uBAAuB,QAAW,EAAE,KAAK,WAAW,OAAO,OAAO,OAAO;AACtF,WAAO;AAAA,EACT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AAI;AAC7B,UAAI,QAAQ,UAAU,MAAO;AAG7B,UAAI,MAAM,aAAa,MAAM,MAAM,WAAW;AAC5C,WAAG,OAAO,GAAG;AACb;AAAA,MACF;AAEA,UAAI,MAAM,KAAK,GAAG,GAAG;AACnB,gBAAQ,KAAK,GAAG;AAAA,MAClB;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AAAA,EAEQ,eAAe,KAAa,WAA4B;AAC9D,UAAM,KAAK,KAAK,cAAc,IAAI,SAAS;AAC3C,QAAI,CAAC,GAAI,QAAO;AAChB,WAAO,GAAG,OAAO,GAAG;AAAA,EACtB;AAAA,EAEQ,aAAa,WAA6B;AAChD,UAAM,KAAK,KAAK,cAAc,IAAI,SAAS;AAC3C,QAAI,CAAC,GAAI,QAAO,CAAA;AAEhB,UAAM,MAAM,KAAK,IAAA;AACjB,UAAM,OAAiB,CAAA;AAEvB,eAAW,CAAC,KAAK,KAAK,KAAK,IAAI;AAE7B,UAAI,MAAM,aAAa,MAAM,MAAM,WAAW;AAC5C,WAAG,OAAO,GAAG;AACb;AAAA,MACF;AACA,WAAK,KAAK,GAAG;AAAA,IACf;AAEA,WAAO;AAAA,EACT;AACF;AAKO,SAAS,uBAAuB,QAAqD;AAC1F,SAAO,IAAI,iBAAiB,MAAM;AACpC;"}
1
+ {"version":3,"file":"mcp-client-adapter.js","sources":["../../../src/mcp/clients/mcp-client-adapter.ts"],"sourcesContent":["/**\n * MCP Client Adapter\n *\n * Provides real MCP tool execution via the claude-flow CLI with retry logic,\n * timeout handling, and graceful fallback to in-memory storage when CLI is unavailable.\n *\n * @module mcp/clients/mcp-client-adapter\n */\n\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\nimport {\n createLogger,\n withRetry,\n type RetryOptions,\n} from '../../utils/index.js';\n\nconst execAsync = promisify(exec);\n\n/**\n * Extended exec error type with additional properties\n */\ninterface ExecError extends Error {\n code?: string | number;\n killed?: boolean;\n stderr?: string;\n stdout?: string;\n}\nconst logger = createLogger('mcp-client-adapter');\n\n/**\n * MCP Client Configuration\n */\nexport interface McpClientConfig {\n /** Maximum number of retry attempts (default: 3) */\n maxRetries: number;\n\n /** Initial delay in milliseconds between retries (default: 1000) */\n retryDelayMs: number;\n\n /** Command execution timeout in milliseconds (default: 30000) */\n timeoutMs: number;\n\n /** Whether to fallback to in-memory storage when CLI unavailable (default: true) */\n fallbackEnabled: boolean;\n\n /** Claude-flow CLI command (default: 'claude-flow' or 'npx claude-flow') */\n cliCommand: string;\n\n /** Whether to use JSON output format from CLI when available */\n useJsonOutput: boolean;\n}\n\n/**\n * Result of a memory operation\n */\nexport interface MemoryOperationResult {\n /** Whether the operation succeeded */\n success: boolean;\n\n /** Result data (if successful) */\n data?: unknown;\n\n /** Error message (if failed) */\n error?: string;\n\n /** Whether the result came from fallback storage */\n fromFallback: boolean;\n\n /** Number of attempts made */\n attempts: number;\n}\n\n/**\n * Memory entry stored in fallback\n */\ninterface FallbackEntry {\n value: string;\n ttl?: number;\n createdAt: number;\n expiresAt?: number;\n}\n\n/**\n * MCP Client Adapter\n *\n * Executes real claude-flow CLI commands with robust retry logic and fallback.\n *\n * @example\n * ```typescript\n * const adapter = new McpClientAdapter({\n * maxRetries: 3,\n * timeoutMs: 30000,\n * });\n *\n * // Store value\n * await adapter.memoryStore('myKey', 'myValue', 'myNamespace');\n *\n * // Retrieve value\n * const value = await adapter.memoryRetrieve('myKey', 'myNamespace');\n * ```\n */\nexport class McpClientAdapter {\n private config: McpClientConfig;\n private fallbackStore: Map<string, Map<string, FallbackEntry>>;\n private cliAvailable: boolean | null = null;\n private lastCliCheck: number = 0;\n private readonly CLI_CHECK_INTERVAL = 60000; // Re-check CLI availability every 60s\n\n constructor(config: Partial<McpClientConfig> = {}) {\n this.config = {\n maxRetries: config.maxRetries ?? 3,\n retryDelayMs: config.retryDelayMs ?? 1000,\n timeoutMs: config.timeoutMs ?? 30000,\n fallbackEnabled: config.fallbackEnabled ?? true,\n cliCommand: config.cliCommand ?? 'claude-flow',\n useJsonOutput: config.useJsonOutput ?? true,\n };\n this.fallbackStore = new Map();\n }\n\n /**\n * Store a value in memory\n *\n * @param key - Memory key\n * @param value - Value to store (will be JSON stringified if object)\n * @param namespace - Memory namespace (default: 'default')\n * @param ttl - Time to live in seconds (optional)\n * @returns Whether the operation succeeded\n */\n async memoryStore(\n key: string,\n value: string | object,\n namespace: string = 'default',\n ttl?: number\n ): Promise<boolean> {\n const stringValue = typeof value === 'string' ? value : JSON.stringify(value);\n\n const result = await this.executeWithRetry(async () => {\n const command = this.buildStoreCommand(key, stringValue, namespace, ttl);\n await this.executeCli(command);\n return true;\n });\n\n if (result.success) {\n logger.debug('Memory store succeeded via CLI', { key, namespace });\n return true;\n }\n\n // Fallback to in-memory storage\n if (this.config.fallbackEnabled) {\n this.storeFallback(key, stringValue, namespace, ttl);\n logger.warn('Memory store fell back to in-memory', { key, namespace, error: result.error });\n return true;\n }\n\n logger.error('Memory store failed', undefined, { key, namespace, error: result.error });\n return false;\n }\n\n /**\n * Retrieve a value from memory\n *\n * @param key - Memory key\n * @param namespace - Memory namespace (default: 'default')\n * @returns The stored value or null if not found\n */\n async memoryRetrieve(key: string, namespace: string = 'default'): Promise<string | null> {\n const result = await this.executeWithRetry(async () => {\n const command = this.buildQueryCommand(key, namespace);\n const output = await this.executeCli(command);\n return this.parseQueryOutput(output, key);\n });\n\n if (result.success && result.value !== undefined) {\n logger.debug('Memory retrieve succeeded via CLI', { key, namespace });\n return result.value;\n }\n\n // Fallback to in-memory storage\n if (this.config.fallbackEnabled) {\n const fallbackValue = this.retrieveFallback(key, namespace);\n if (fallbackValue !== null) {\n logger.debug('Memory retrieve fell back to in-memory', { key, namespace });\n return fallbackValue;\n }\n }\n\n logger.debug('Memory retrieve returned null', { key, namespace });\n return null;\n }\n\n /**\n * Search memory by pattern\n *\n * @param pattern - Search pattern (supports glob-like matching)\n * @param namespace - Memory namespace (default: 'default')\n * @param limit - Maximum number of results (default: 10)\n * @returns Array of matching keys\n */\n async memorySearch(\n pattern: string,\n namespace: string = 'default',\n limit: number = 10\n ): Promise<string[]> {\n const result = await this.executeWithRetry(async () => {\n const command = this.buildSearchCommand(pattern, namespace, limit);\n const output = await this.executeCli(command);\n return this.parseSearchOutput(output);\n });\n\n if (result.success && result.value) {\n logger.debug('Memory search succeeded via CLI', { pattern, namespace, count: result.value.length });\n return result.value;\n }\n\n // Fallback to in-memory search\n if (this.config.fallbackEnabled) {\n const fallbackResults = this.searchFallback(pattern, namespace, limit);\n logger.debug('Memory search fell back to in-memory', { pattern, namespace, count: fallbackResults.length });\n return fallbackResults;\n }\n\n logger.debug('Memory search returned empty', { pattern, namespace });\n return [];\n }\n\n /**\n * Delete a value from memory\n *\n * @param key - Memory key\n * @param namespace - Memory namespace (default: 'default')\n * @returns Whether the operation succeeded\n */\n async memoryDelete(key: string, namespace: string = 'default'): Promise<boolean> {\n const result = await this.executeWithRetry(async () => {\n // Use clear command with specific key pattern\n const command = this.buildDeleteCommand(key, namespace);\n await this.executeCli(command);\n return true;\n });\n\n if (result.success) {\n logger.debug('Memory delete succeeded via CLI', { key, namespace });\n }\n\n // Also delete from fallback (regardless of CLI success)\n if (this.config.fallbackEnabled) {\n this.deleteFallback(key, namespace);\n }\n\n return result.success || this.config.fallbackEnabled;\n }\n\n /**\n * List all keys in a namespace\n *\n * @param namespace - Memory namespace (default: 'default')\n * @returns Array of keys\n */\n async memoryList(namespace: string = 'default'): Promise<string[]> {\n const result = await this.executeWithRetry(async () => {\n const command = `${this.config.cliCommand} memory list --namespace \"${namespace}\"`;\n const output = await this.executeCli(command);\n return this.parseListOutput(output);\n });\n\n if (result.success && result.value) {\n logger.debug('Memory list succeeded via CLI', { namespace, count: result.value.length });\n return result.value;\n }\n\n // Fallback\n if (this.config.fallbackEnabled) {\n const fallbackKeys = this.listFallback(namespace);\n logger.debug('Memory list fell back to in-memory', { namespace, count: fallbackKeys.length });\n return fallbackKeys;\n }\n\n return [];\n }\n\n /**\n * Check if CLI is available\n */\n async isCliAvailable(): Promise<boolean> {\n const now = Date.now();\n\n // Use cached result if recent\n if (this.cliAvailable !== null && now - this.lastCliCheck < this.CLI_CHECK_INTERVAL) {\n return this.cliAvailable;\n }\n\n try {\n await this.executeCli(`${this.config.cliCommand} --version`, 5000);\n this.cliAvailable = true;\n this.lastCliCheck = now;\n return true;\n } catch {\n this.cliAvailable = false;\n this.lastCliCheck = now;\n return false;\n }\n }\n\n /**\n * Get current configuration\n */\n getConfig(): Readonly<McpClientConfig> {\n return { ...this.config };\n }\n\n /**\n * Get fallback store size for a namespace\n */\n getFallbackSize(namespace: string = 'default'): number {\n return this.fallbackStore.get(namespace)?.size ?? 0;\n }\n\n /**\n * Clear fallback store\n */\n clearFallback(namespace?: string): void {\n if (namespace) {\n this.fallbackStore.delete(namespace);\n } else {\n this.fallbackStore.clear();\n }\n }\n\n // Private methods\n\n private async executeWithRetry<T>(\n operation: () => Promise<T>\n ): Promise<{ success: boolean; value?: T; error?: string; attempts: number }> {\n const retryOptions: RetryOptions = {\n maxRetries: this.config.maxRetries,\n initialDelay: this.config.retryDelayMs,\n backoffFactor: 2,\n jitter: true,\n onRetry: (error, attempt, delay) => {\n logger.debug('Retrying MCP operation', {\n attempt,\n delay,\n error: error.message,\n });\n },\n };\n\n const result = await withRetry(operation, retryOptions);\n\n return {\n success: result.success,\n value: result.value,\n error: result.error?.message,\n attempts: result.attempts,\n };\n }\n\n private async executeCli(command: string, timeout?: number): Promise<string> {\n const effectiveTimeout = timeout ?? this.config.timeoutMs;\n\n logger.debug('Executing CLI command', { command: command.substring(0, 100) });\n\n try {\n const { stdout, stderr } = await execAsync(command, {\n timeout: effectiveTimeout,\n maxBuffer: 10 * 1024 * 1024, // 10MB buffer\n shell: '/bin/bash',\n });\n\n if (stderr && !stderr.includes('DeprecationWarning')) {\n logger.warn('CLI stderr output', { stderr: stderr.substring(0, 500) });\n }\n\n return stdout.trim();\n } catch (error) {\n const execError = error as ExecError;\n\n if (execError.code === 'ETIMEDOUT' || execError.killed) {\n throw new Error(`CLI command timed out after ${effectiveTimeout}ms`);\n }\n\n // Include any output in the error for debugging\n const message = execError.message || 'CLI execution failed';\n const details = execError.stderr || execError.stdout || '';\n throw new Error(`${message}${details ? `: ${details.substring(0, 200)}` : ''}`);\n }\n }\n\n private buildStoreCommand(\n key: string,\n value: string,\n namespace: string,\n ttl?: number\n ): string {\n const escapedValue = this.escapeShellArg(value);\n let command = `${this.config.cliCommand} memory store \"${key}\" ${escapedValue} --namespace \"${namespace}\"`;\n\n if (ttl !== undefined && ttl > 0) {\n command += ` --ttl ${ttl}`;\n }\n\n return command;\n }\n\n private buildQueryCommand(key: string, namespace: string): string {\n // Use query command to search for exact key\n return `${this.config.cliCommand} memory query \"${key}\" --namespace \"${namespace}\"`;\n }\n\n private buildSearchCommand(pattern: string, namespace: string, limit: number): string {\n return `${this.config.cliCommand} memory query \"${pattern}\" --namespace \"${namespace}\"`;\n }\n\n private buildDeleteCommand(key: string, namespace: string): string {\n // claude-flow uses 'clear' for deletion\n return `${this.config.cliCommand} memory clear --namespace \"${namespace}\"`;\n }\n\n private parseQueryOutput(output: string, key: string): string | null {\n if (!output || output.includes('not found') || output.includes('No results')) {\n return null;\n }\n\n // Try to parse as JSON first\n try {\n const parsed = JSON.parse(output);\n if (typeof parsed === 'object' && parsed !== null) {\n // Look for the key in the result\n if (key in parsed) {\n return typeof parsed[key] === 'string' ? parsed[key] : JSON.stringify(parsed[key]);\n }\n // Return the whole object as JSON string\n return JSON.stringify(parsed);\n }\n return String(parsed);\n } catch {\n // Return raw output\n return output;\n }\n }\n\n private parseSearchOutput(output: string): string[] {\n if (!output || output.includes('No results')) {\n return [];\n }\n\n // Try to parse as JSON array\n try {\n const parsed = JSON.parse(output);\n if (Array.isArray(parsed)) {\n return parsed.map((item) => (typeof item === 'string' ? item : JSON.stringify(item)));\n }\n if (typeof parsed === 'object' && parsed !== null) {\n return Object.keys(parsed);\n }\n } catch {\n // Parse line by line\n return output\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line.length > 0 && !line.startsWith('#'));\n }\n\n return [];\n }\n\n private parseListOutput(output: string): string[] {\n return this.parseSearchOutput(output);\n }\n\n private escapeShellArg(arg: string): string {\n // Escape for shell and wrap in quotes\n const escaped = arg\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\"/g, '\\\\\"')\n .replace(/`/g, '\\\\`')\n .replace(/\\$/g, '\\\\$')\n .replace(/\\n/g, '\\\\n');\n return `\"${escaped}\"`;\n }\n\n // Fallback storage methods\n\n private getOrCreateNamespace(namespace: string): Map<string, FallbackEntry> {\n let ns = this.fallbackStore.get(namespace);\n if (!ns) {\n ns = new Map();\n this.fallbackStore.set(namespace, ns);\n }\n return ns;\n }\n\n private storeFallback(key: string, value: string, namespace: string, ttl?: number): void {\n const ns = this.getOrCreateNamespace(namespace);\n const now = Date.now();\n\n ns.set(key, {\n value,\n ttl,\n createdAt: now,\n expiresAt: ttl ? now + ttl * 1000 : undefined,\n });\n }\n\n private retrieveFallback(key: string, namespace: string): string | null {\n const ns = this.fallbackStore.get(namespace);\n if (!ns) return null;\n\n const entry = ns.get(key);\n if (!entry) return null;\n\n // Check expiration\n if (entry.expiresAt && Date.now() > entry.expiresAt) {\n ns.delete(key);\n return null;\n }\n\n return entry.value;\n }\n\n private searchFallback(pattern: string, namespace: string, limit: number): string[] {\n const ns = this.fallbackStore.get(namespace);\n if (!ns) return [];\n\n const now = Date.now();\n const results: string[] = [];\n\n // Convert glob pattern to regex\n const regexPattern = pattern\n .replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\*/g, '.*')\n .replace(/\\?/g, '.');\n const regex = new RegExp(`^${regexPattern}$`, 'i');\n\n for (const [key, entry] of ns) {\n if (results.length >= limit) break;\n\n // Skip expired entries\n if (entry.expiresAt && now > entry.expiresAt) {\n ns.delete(key);\n continue;\n }\n\n if (regex.test(key)) {\n results.push(key);\n }\n }\n\n return results;\n }\n\n private deleteFallback(key: string, namespace: string): boolean {\n const ns = this.fallbackStore.get(namespace);\n if (!ns) return false;\n return ns.delete(key);\n }\n\n private listFallback(namespace: string): string[] {\n const ns = this.fallbackStore.get(namespace);\n if (!ns) return [];\n\n const now = Date.now();\n const keys: string[] = [];\n\n for (const [key, entry] of ns) {\n // Skip expired entries\n if (entry.expiresAt && now > entry.expiresAt) {\n ns.delete(key);\n continue;\n }\n keys.push(key);\n }\n\n return keys;\n }\n}\n\n/**\n * Create a configured MCP client adapter\n */\nexport function createMcpClientAdapter(config?: Partial<McpClientConfig>): McpClientAdapter {\n return new McpClientAdapter(config);\n}\n"],"names":[],"mappings":";;;;AAiBA,MAAM,YAAY,UAAU,IAAI;AAWhC,MAAM,SAAS,aAAa,oBAAoB;AA0EzC,MAAM,iBAAiB;AAAA,EACpB;AAAA,EACA;AAAA,EACA,eAA+B;AAAA,EAC/B,eAAuB;AAAA,EACd,qBAAqB;AAAA;AAAA,EAEtC,YAAY,SAAmC,IAAI;AACjD,SAAK,SAAS;AAAA,MACZ,YAAY,OAAO,cAAc;AAAA,MACjC,cAAc,OAAO,gBAAgB;AAAA,MACrC,WAAW,OAAO,aAAa;AAAA,MAC/B,iBAAiB,OAAO,mBAAmB;AAAA,MAC3C,YAAY,OAAO,cAAc;AAAA,MACjC,eAAe,OAAO,iBAAiB;AAAA,IAAA;AAEzC,SAAK,oCAAoB,IAAA;AAAA,EAC3B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,MAAM,YACJ,KACA,OACA,YAAoB,WACpB,KACkB;AAClB,UAAM,cAAc,OAAO,UAAU,WAAW,QAAQ,KAAK,UAAU,KAAK;AAE5E,UAAM,SAAS,MAAM,KAAK,iBAAiB,YAAY;AACrD,YAAM,UAAU,KAAK,kBAAkB,KAAK,aAAa,WAAW,GAAG;AACvE,YAAM,KAAK,WAAW,OAAO;AAC7B,aAAO;AAAA,IACT,CAAC;AAED,QAAI,OAAO,SAAS;AAClB,aAAO,MAAM,kCAAkC,EAAE,KAA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AC3C,QAAI,CAAC,GAAI,QAAO,CAAA;AAEhB,UAAM,MAAM,KAAK,IAAA;AACjB,UAAM,UAAoB,CAAA;AAG1B,UAAM,eAAe,QAClB,QAAQ,qBAAqB,MAAM,EACnC,QAAQ,OAAO,IAAI,EACnB,QAAQ,OAAO,GAAG;AACrB,UAAM,QAAQ,IAAI,OAAO,IAAI,YAAY,KAAK,GAAG;AAEjD,eAAW,CAAC,KAAK,KAAK,KAAK,IAAI;AAC7B,UAAI,QAAQ,UAAU,MAAO;AAG7B,UAAI,MAAM,aAAa,MAAM,MAAM,WAAW;AAC5C,WAAG,OAAO,GAAG;AACb;AAAA,MACF;AAEA,UAAI,MAAM,KAAK,GAAG,GAAG;AACnB,gBAAQ,KAAK,GAAG;AAAA,MAClB;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AAAA,EAEQ,eAAe,KAAa,WAA4B;AAC9D,UAAM,KAAK,KAAK,cAAc,IAAI,SAAS;AAC3C,QAAI,CAAC,GAAI,QAAO;AAChB,WAAO,GAAG,OAAO,GAAG;AAAA,EACtB;AAAA,EAEQ,aAAa,WAA6B;AAChD,UAAM,KAAK,KAAK,cAAc,IAAI,SAAS;AAC3C,QAAI,CAAC,GAAI,QAAO,CAAA;AAEhB,UAAM,MAAM,KAAK,IAAA;AACjB,UAAM,OAAiB,CAAA;AAEvB,eAAW,CAAC,KAAK,KAAK,KAAK,IAAI;AAE7B,UAAI,MAAM,aAAa,MAAM,MAAM,WAAW;AAC5C,WAAG,OAAO,GAAG;AACb;AAAA,MACF;AACA,WAAK,KAAK,GAAG;AAAA,IACf;AAEA,WAAO;AAAA,EACT;AACF;AAKO,SAAS,uBAAuB,QAAqD;AAC1F,SAAO,IAAI,iBAAiB,MAAM;AACpC;"}
@@ -1,4 +1,4 @@
1
- import { __exports as commonjs } from "../../../../../../../_virtual/index8.js";
1
+ import { __exports as commonjs } from "../../../../../../../_virtual/index9.js";
2
2
  import { __require as requireBraceExpansion } from "../../../../../../brace-expansion/index.js";
3
3
  import { __require as requireAssertValidPattern } from "./assert-valid-pattern.js";
4
4
  import { __require as requireAst } from "./ast.js";
@@ -1,4 +1,4 @@
1
- import { __exports as dist } from "../../../_virtual/index11.js";
1
+ import { __exports as dist } from "../../../_virtual/index10.js";
2
2
  import path__default from "path";
3
3
  import require$$1 from "fs";
4
4
  import { __require as requirePicomatch } from "../../picomatch/index.js";
@@ -1,4 +1,4 @@
1
- import { __exports as dist } from "../../../_virtual/index9.js";
1
+ import { __exports as dist } from "../../../_virtual/index8.js";
2
2
  import require$$1 from "fs";
3
3
  import path__default from "path";
4
4
  import require$$2 from "url";
@@ -1,4 +1,4 @@
1
- import { __exports as lib } from "../../../_virtual/index10.js";
1
+ import { __exports as lib } from "../../../_virtual/index11.js";
2
2
  import { __require as requireTypescript } from "../../typescript/lib/typescript.js";
3
3
  var hasRequiredLib;
4
4
  function requireLib() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@weavelogic/knowledge-graph-agent",
3
- "version": "0.10.1",
3
+ "version": "0.10.2",
4
4
  "description": "Knowledge graph agent for Claude Code - generates knowledge graphs, initializes docs, and integrates with claude-flow",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",