@deimoscloud/coreai 0.1.17 → 0.1.19

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,"sources":["../../src/cli/index.ts","../../src/index.ts","../../src/config/loader.ts","../../src/agents/types.ts","../../src/agents/loader.ts","../../src/agents/resolver.ts","../../src/agents/compiler.ts","../../src/adapters/mcp/types.ts","../../src/adapters/mcp/client.ts","../../src/adapters/mcp/discovery.ts","../../src/adapters/native/github.ts","../../src/cache/types.ts","../../src/cache/provider.ts","../../src/cache/manager.ts","../../src/skills/generator.ts","../../src/knowledge-library/manager.ts","../../src/cli/commands/cache.ts","../../src/cli/commands/sync.ts","../../src/cli/commands/init.ts","../../src/cli/commands/build.ts","../../src/cli/commands/validate.ts","../../src/cli/commands/skills.ts","../../src/cli/commands/status.ts","../../src/cli/commands/agents.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * CoreAI CLI - Entry point\n *\n * A configurable, team-ready AI agent orchestration platform.\n */\n\nimport { join, dirname } from 'path';\nimport { fileURLToPath } from 'url';\nimport { Command } from 'commander';\nimport { VERSION } from '../index.js';\nimport { loadAllAgents, generateAgentMarkdown } from '../agents/index.js';\nimport {\n cacheStatus,\n cacheClear,\n cacheClearExpired,\n formatCacheStatus,\n sync,\n formatSyncResult,\n init,\n formatInitResult,\n build,\n formatBuildResult,\n validate,\n formatValidateResult,\n status,\n formatStatusResult,\n skillsGenerate,\n formatSkillsGenerateResult,\n skillsList,\n formatSkillsListResult,\n agentsAdd,\n agentsRemove,\n formatAgentsAddResult,\n formatAgentsRemoveResult,\n} from './commands/index.js';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\n/**\n * Get the path to built-in core agents\n */\nfunction getCoreAgentsPath(): string {\n // Navigate from dist/cli/index.js to agents/\n return join(__dirname, '..', '..', 'agents');\n}\n\nconst program = new Command();\n\nprogram\n .name('coreai')\n .description('A configurable, team-ready AI agent orchestration platform')\n .version(VERSION, '-v, --version', 'output the current version');\n\n// Init command - initialize a new CoreAI project\nprogram\n .command('init')\n .description('Initialize a new CoreAI project')\n .option('-f, --force', 'overwrite existing configuration')\n .option('-n, --name <name>', 'project name')\n .option('-t, --type <type>', 'project type (software, infrastructure, data, mobile)')\n .option('--skip-dirs', 'skip creating directory structure')\n .action((options: { force?: boolean; name?: string; type?: string; skipDirs?: boolean }) => {\n const result = init({\n projectRoot: process.cwd(),\n force: options.force,\n name: options.name,\n type: options.type as 'software' | 'infrastructure' | 'data' | 'mobile',\n skipDirs: options.skipDirs,\n });\n\n console.log(formatInitResult(result));\n\n if (!result.success) {\n process.exit(1);\n }\n });\n\n// Build command - compile agents to .claude/agents/\nprogram\n .command('build')\n .description('Compile agent definitions to Claude-compatible markdown')\n .option('-w, --watch', 'watch for changes and rebuild')\n .option('-o, --output <dir>', 'output directory (default: .claude/agents)')\n .option('--agents <agents>', 'comma-separated list of agents to build')\n .option('--init-knowledge-library', 'initialize KnowledgeLibrary directories for agents')\n .action(\n (options: {\n watch?: boolean;\n output?: string;\n agents?: string;\n initKnowledgeLibrary?: boolean;\n }) => {\n if (options.watch) {\n console.log('Watch mode is not yet implemented');\n process.exit(1);\n }\n\n console.log('Building agents...\\n');\n\n const result = build({\n projectRoot: process.cwd(),\n coreAgentsDir: getCoreAgentsPath(),\n outputDir: options.output,\n agents: options.agents?.split(',').map((a) => a.trim()),\n initKnowledgeLibrary: options.initKnowledgeLibrary,\n });\n\n console.log(formatBuildResult(result));\n\n if (!result.success) {\n process.exit(1);\n }\n }\n );\n\n// Sync command - sync shared context from remote sources\nprogram\n .command('sync')\n .description('Sync shared context from remote sources')\n .option('--force', 'force refresh all cached content')\n .option('--source <source>', 'filter by source (github, confluence, notion)')\n .option('--concurrency <n>', 'max concurrent fetches', '5')\n .action(async (options: { force?: boolean; source?: string; concurrency?: string }) => {\n try {\n console.log('Syncing shared context...\\n');\n\n const result = await sync({\n projectRoot: process.cwd(),\n force: options.force,\n source: options.source as 'github' | 'confluence' | 'notion' | 'local' | 'custom',\n concurrency: parseInt(options.concurrency ?? '5', 10),\n continueOnError: true,\n onProgress: (completed, total, message) => {\n process.stdout.write(`\\r${message}`);\n },\n });\n\n // Clear the progress line\n process.stdout.write('\\r' + ' '.repeat(60) + '\\r');\n\n console.log(formatSyncResult(result));\n\n if (!result.success) {\n process.exit(1);\n }\n } catch (error) {\n console.error(`Sync failed: ${error instanceof Error ? error.message : error}`);\n process.exit(1);\n }\n });\n\n// Validate command - validate configuration and setup\nprogram\n .command('validate')\n .description('Validate configuration and project setup')\n .option('--skip-agents', 'skip agent validation')\n .option('--skip-dirs', 'skip directory validation')\n .option('--json', 'output as JSON')\n .action((options: { skipAgents?: boolean; skipDirs?: boolean; json?: boolean }) => {\n const result = validate({\n projectRoot: process.cwd(),\n coreAgentsDir: getCoreAgentsPath(),\n checkAgents: !options.skipAgents,\n checkDirs: !options.skipDirs,\n });\n\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log(formatValidateResult(result));\n }\n\n if (!result.valid) {\n process.exit(1);\n }\n });\n\n// Agents subcommand group\nconst agents = program.command('agents').description('Manage agent definitions');\n\nagents\n .command('list')\n .description('List available agents')\n .option('--core', 'show only core agents')\n .option('--custom', 'show only custom agents')\n .action((options: { core?: boolean; custom?: boolean }) => {\n try {\n const customAgentsDir = join(process.cwd(), 'coreai', 'agents');\n\n const allAgents = loadAllAgents({\n coreAgentsDir: getCoreAgentsPath(),\n customAgentsDir,\n });\n\n if (allAgents.size === 0) {\n console.log('No agents found.');\n return;\n }\n\n // Filter by source if requested\n const agents = Array.from(allAgents.entries()).filter(([, meta]) => {\n if (options.core && meta.source !== 'core') return false;\n if (options.custom && meta.source !== 'custom' && meta.source !== 'override') return false;\n return true;\n });\n\n if (agents.length === 0) {\n console.log('No matching agents found.');\n return;\n }\n\n console.log('Available agents:\\n');\n\n // Group by source\n const coreAgents = agents.filter(([, m]) => m.source === 'core');\n const customAgents = agents.filter(([, m]) => m.source === 'custom');\n const overrideAgents = agents.filter(([, m]) => m.source === 'override');\n\n if (coreAgents.length > 0 && !options.custom) {\n console.log('Core agents:');\n for (const [role, meta] of coreAgents) {\n console.log(` ${role} (${meta.definition.type})`);\n console.log(` ${meta.definition.display_name}`);\n }\n console.log();\n }\n\n if (customAgents.length > 0 && !options.core) {\n console.log('Custom agents:');\n for (const [role, meta] of customAgents) {\n console.log(` ${role} (${meta.definition.type})`);\n console.log(` ${meta.definition.display_name}`);\n }\n console.log();\n }\n\n if (overrideAgents.length > 0 && !options.core) {\n console.log('Override agents:');\n for (const [role, meta] of overrideAgents) {\n console.log(` ${role} (${meta.definition.type})`);\n console.log(` ${meta.definition.display_name} [overrides core]`);\n }\n console.log();\n }\n\n console.log(`Total: ${agents.length} agent(s)`);\n } catch (error) {\n console.error(`Failed to list agents: ${error instanceof Error ? error.message : error}`);\n process.exit(1);\n }\n });\n\nagents\n .command('show <name>')\n .description('Show details for a specific agent')\n .option('--markdown', 'output as compiled markdown')\n .option('--json', 'output as JSON')\n .action((name: string, options: { markdown?: boolean; json?: boolean }) => {\n try {\n const customAgentsDir = join(process.cwd(), 'coreai', 'agents');\n\n const allAgents = loadAllAgents({\n coreAgentsDir: getCoreAgentsPath(),\n customAgentsDir,\n });\n\n const agentMeta = allAgents.get(name);\n\n if (!agentMeta) {\n console.error(`Agent not found: ${name}`);\n console.log('\\nAvailable agents:');\n for (const role of allAgents.keys()) {\n console.log(` - ${role}`);\n }\n process.exit(1);\n }\n\n const agent = agentMeta.definition;\n\n if (options.json) {\n console.log(JSON.stringify(agent, null, 2));\n return;\n }\n\n if (options.markdown) {\n console.log(generateAgentMarkdown(agent));\n return;\n }\n\n // Default: human-readable output\n console.log(`\\n${agent.display_name}`);\n console.log('='.repeat(agent.display_name.length));\n console.log();\n console.log(`Role: ${agent.role}`);\n console.log(`Type: ${agent.type}`);\n console.log(`Source: ${agentMeta.source}`);\n console.log();\n console.log('Description:');\n console.log(` ${agent.description}`);\n\n if (agent.responsibilities && agent.responsibilities.length > 0) {\n console.log();\n console.log('Responsibilities:');\n for (const r of agent.responsibilities) {\n console.log(` - ${r}`);\n }\n }\n\n if (agent.expertise?.primary && agent.expertise.primary.length > 0) {\n console.log();\n console.log('Expertise:');\n for (const e of agent.expertise.primary) {\n console.log(` - ${e}`);\n }\n }\n\n if (agent.skills && agent.skills.length > 0) {\n console.log();\n console.log('Skills:');\n for (const s of agent.skills) {\n console.log(` - ${s}`);\n }\n }\n\n if (agent.behaviors?.workflow) {\n console.log();\n console.log(`Workflow: ${agent.behaviors.workflow}`);\n }\n\n console.log();\n console.log(`File: ${agentMeta.filePath}`);\n } catch (error) {\n console.error(`Failed to show agent: ${error instanceof Error ? error.message : error}`);\n process.exit(1);\n }\n });\n\nagents\n .command('add [agents...]')\n .description('Add agents to your project configuration')\n .option('--all', 'add all available core agents')\n .option('--no-build', 'skip rebuilding agents after adding')\n .action(async (agentNames: string[] = [], options: { all?: boolean; build?: boolean }) => {\n try {\n // Parse comma-separated agents if provided as single string\n const parsedAgents = agentNames.flatMap((a) => a.split(',').map((s) => s.trim()));\n\n const result = agentsAdd(parsedAgents, {\n projectRoot: process.cwd(),\n coreAgentsDir: getCoreAgentsPath(),\n all: options.all,\n });\n\n console.log(formatAgentsAddResult(result));\n\n if (!result.success) {\n process.exit(1);\n }\n\n // Run build if agents were added and --no-build wasn't specified\n if (result.added.length > 0 && options.build !== false) {\n console.log('\\nRebuilding agents...\\n');\n const buildResult = build({\n projectRoot: process.cwd(),\n coreAgentsDir: getCoreAgentsPath(),\n });\n console.log(formatBuildResult(buildResult));\n\n if (!buildResult.success) {\n process.exit(1);\n }\n }\n } catch (error) {\n console.error(`Failed to add agents: ${error instanceof Error ? error.message : error}`);\n process.exit(1);\n }\n });\n\nagents\n .command('remove [agents...]')\n .description('Remove agents from your project configuration')\n .option('--all', 'remove all agents from config')\n .option('--no-build', 'skip rebuilding agents after removing')\n .action(async (agentNames: string[] = [], options: { all?: boolean; build?: boolean }) => {\n try {\n // Parse comma-separated agents if provided as single string\n const parsedAgents = agentNames.flatMap((a) => a.split(',').map((s) => s.trim()));\n\n const result = agentsRemove(parsedAgents, {\n projectRoot: process.cwd(),\n all: options.all,\n });\n\n console.log(formatAgentsRemoveResult(result));\n\n if (!result.success) {\n process.exit(1);\n }\n\n // Run build if agents were removed and --no-build wasn't specified\n if (result.removed.length > 0 && options.build !== false) {\n console.log('\\nRebuilding agents...\\n');\n const buildResult = build({\n projectRoot: process.cwd(),\n coreAgentsDir: getCoreAgentsPath(),\n });\n console.log(formatBuildResult(buildResult));\n\n if (!buildResult.success) {\n process.exit(1);\n }\n }\n } catch (error) {\n console.error(`Failed to remove agents: ${error instanceof Error ? error.message : error}`);\n process.exit(1);\n }\n });\n\n// Cache subcommand group\nconst cacheCmd = program.command('cache').description('Manage local cache');\n\ncacheCmd\n .command('clear')\n .description('Clear the local cache')\n .option('--expired', 'only clear expired entries')\n .option('--json', 'output as JSON')\n .action(async (options: { expired?: boolean; json?: boolean }) => {\n try {\n const result = options.expired\n ? await cacheClearExpired({ projectRoot: process.cwd() })\n : await cacheClear({ projectRoot: process.cwd() });\n\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n if (!result.success) {\n console.error(`Failed to clear cache: ${result.error}`);\n process.exit(1);\n }\n\n if (result.cleared === 0) {\n console.log('Cache is already empty.');\n } else {\n const word = result.cleared === 1 ? 'entry' : 'entries';\n console.log(`Cleared ${result.cleared} cache ${word}.`);\n }\n } catch (error) {\n const msg = error instanceof Error ? error.message : error;\n console.error(`Failed to clear cache: ${msg}`);\n process.exit(1);\n }\n });\n\ncacheCmd\n .command('status')\n .description('Show cache status')\n .option('--json', 'output as JSON')\n .action(async (options: { json?: boolean }) => {\n try {\n const result = await cacheStatus({ projectRoot: process.cwd() });\n\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n console.log(formatCacheStatus(result));\n } catch (error) {\n const msg = error instanceof Error ? error.message : error;\n console.error(`Failed to get cache status: ${msg}`);\n process.exit(1);\n }\n });\n\n// Status command - show agent states and pending messages\nprogram\n .command('status')\n .description('Show agent states and pending messages')\n .option('-a, --agent <name>', 'show status for a specific agent')\n .option('-d, --detailed', 'show detailed message information')\n .option('--init', 'initialize KnowledgeLibrary if not exists')\n .option('--json', 'output as JSON')\n .action((options: { agent?: string; detailed?: boolean; init?: boolean; json?: boolean }) => {\n const result = status({\n projectRoot: process.cwd(),\n agent: options.agent,\n detailed: options.detailed,\n init: options.init,\n });\n\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n console.log(formatStatusResult(result));\n\n if (!result.success) {\n process.exit(1);\n }\n });\n\n// Skills subcommand group\nconst skillsCmd = program.command('skills').description('Manage Claude skills');\n\nskillsCmd\n .command('generate')\n .description('Generate Claude skills from source files')\n .option('-o, --output <dir>', 'output directory (default: .claude/skills)')\n .option('--skills <skills>', 'comma-separated list of skills to generate')\n .option('--no-core', 'exclude core skills')\n .option('--no-overwrite', 'do not overwrite existing skill files')\n .option('--json', 'output as JSON')\n .action(\n (options: {\n output?: string;\n skills?: string;\n core?: boolean;\n overwrite?: boolean;\n json?: boolean;\n }) => {\n console.log('Generating skills...\\n');\n\n const result = skillsGenerate({\n projectRoot: process.cwd(),\n outputDir: options.output,\n skills: options.skills?.split(',').map((s) => s.trim()),\n includeCoreSkills: options.core !== false,\n overwrite: options.overwrite !== false,\n });\n\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n console.log(formatSkillsGenerateResult(result));\n\n if (!result.success) {\n process.exit(1);\n }\n }\n );\n\nskillsCmd\n .command('list')\n .description('List available skills')\n .option('--no-core', 'exclude core skills')\n .option('--json', 'output as JSON')\n .action((options: { core?: boolean; json?: boolean }) => {\n const result = skillsList({\n projectRoot: process.cwd(),\n includeCoreSkills: options.core !== false,\n });\n\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n console.log(formatSkillsListResult(result));\n\n if (!result.success) {\n process.exit(1);\n }\n });\n\nprogram.parse();\n","/**\n * CoreAI - A configurable, team-ready AI agent orchestration platform.\n *\n * This is the main library export for programmatic usage.\n */\n\nimport { readFileSync } from 'fs';\nimport { dirname, join } from 'path';\nimport { fileURLToPath } from 'url';\n\n// Find package.json by walking up from the current module\nfunction findPackageJson(): string {\n let dir = dirname(fileURLToPath(import.meta.url));\n while (dir !== dirname(dir)) {\n const pkgPath = join(dir, 'package.json');\n try {\n const content = readFileSync(pkgPath, 'utf-8');\n const pkg = JSON.parse(content);\n if (pkg.name === '@deimoscloud/coreai') {\n return content;\n }\n } catch {\n // Continue searching\n }\n dir = dirname(dir);\n }\n return '{\"version\": \"unknown\"}';\n}\n\nconst packageJson = JSON.parse(findPackageJson());\nexport const VERSION: string = packageJson.version;\n\n// Configuration\nexport {\n loadConfig,\n loadConfigFromFile,\n findConfigFile,\n configExists,\n getConfigPath,\n ConfigError,\n} from './config/index.js';\n\nexport type {\n CoreAIConfig,\n ResolvedCoreAIConfig,\n ProjectConfig,\n TeamConfig,\n IntegrationsConfig,\n QualityGatesConfig,\n TechStackConfig,\n CacheConfig,\n ConfigErrorCode,\n} from './config/index.js';\n\n// Agents\nexport {\n loadAgentFromFile,\n loadAgentsFromDirectory,\n parseAgentYaml,\n validateAgentDefinition,\n getRoleFromFilename,\n AgentError,\n resolveString,\n resolveObject,\n resolveAgentDefinition,\n hasVariables,\n extractVariables,\n ResolutionError,\n generateAgentMarkdown,\n compileAgent,\n compileAgents,\n loadAllAgents,\n filterAgentsByTeam,\n getCoreAgentsDir,\n} from './agents/index.js';\n\nexport type {\n AgentDefinition,\n ResolvedAgentDefinition,\n AgentType,\n WorkflowType,\n AgentMetadata,\n AgentSource,\n AgentErrorCode,\n ResolutionContext,\n ResolutionOptions,\n CompileOptions,\n CompileResult,\n} from './agents/index.js';\n\n// Adapters\nexport {\n AdapterFactory,\n createAdapterFactory,\n createAdapterInfo,\n AdapterError,\n} from './adapters/index.js';\n\nexport type {\n AdapterType,\n AdapterImplementation,\n AdapterInfo,\n AdapterFactoryOptions,\n AdapterErrorCode,\n BaseAdapter,\n IssueTrackerAdapter,\n GitProviderAdapter,\n DocumentationProviderAdapter,\n StateProviderAdapter,\n Adapter,\n Issue,\n IssueQuery,\n IssueStatus,\n CreateIssueData,\n UpdateIssueData,\n PullRequest,\n PullRequestQuery,\n PullRequestStatus,\n CreatePullRequestData,\n Review,\n CreateReviewData,\n ReviewDecision,\n ReviewComment,\n DocumentationPage,\n DocumentationQuery,\n StateEntry,\n StateOptions,\n} from './adapters/index.js';\n\n// Cache\nexport {\n CacheError,\n CACHE_PATHS,\n DEFAULT_CACHE_CONFIG,\n FileCacheProvider,\n createFileCacheProvider,\n FileCacheManager,\n createCacheManager,\n} from './cache/index.js';\n\nexport type {\n CacheSource,\n CacheStatus,\n CacheMetadata,\n CacheEntry,\n CacheOptions,\n CacheListOptions,\n CacheStats,\n SyncResult,\n CacheErrorCode,\n CacheProvider,\n RemoteFetcher,\n FetchOptions,\n CacheManager,\n SyncOptions,\n FileCacheProviderOptions,\n CacheManagerOptions,\n} from './cache/index.js';\n\n// Context\nexport { ContextLoader, createContextLoader } from './context/index.js';\n\nexport type {\n ContextSource,\n ContextLoadResult,\n ContextLoaderOptions,\n LoadOptions,\n} from './context/index.js';\n\n// Commands\nexport {\n CommandRegistry,\n createCommandRegistry,\n getGlobalRegistry,\n resetGlobalRegistry,\n createCommandContext,\n cleanupContext,\n withContext,\n loadCommandFromFile,\n loadCommandsFromDirectory,\n loadCoreAICommands,\n loadAllCommands,\n runCommand,\n executeWithDegradation,\n createDegradingHandler,\n StepTracker,\n} from './commands/index.js';\n\nexport type {\n CommandCategory,\n IntegrationDependency,\n CommandMetadata,\n CommandContext,\n BaseCommandOptions,\n CommandResult,\n CommandHandler,\n CommandDefinition,\n CommandOptionDefinition,\n CommandArgumentDefinition,\n MarkdownCommand,\n RegistryEntry,\n CommandLoaderOptions,\n CommandLoadResult,\n CreateContextOptions,\n RunCommandOptions,\n} from './commands/index.js';\n\n// Skills\nexport {\n getCoreSkillsDir,\n discoverSkills,\n parseSkillFile,\n extractVariables as extractSkillVariables,\n substituteVariables,\n checkDependencies,\n generateSkills,\n formatGenerateResult,\n} from './skills/index.js';\n\nexport type {\n SkillTemplate,\n SkillVariables,\n SkillCategory,\n SkillDependency,\n GenerateSkillsOptions,\n GenerateSkillsResult,\n GeneratedSkill,\n SkillError,\n} from './skills/index.js';\n\n// KnowledgeLibrary\nexport {\n DEFAULT_KNOWLEDGE_LIBRARY_PATH,\n STANDARD_FILES,\n AGENT_DIRECTORIES,\n CONTROL_FILES,\n getAgentDirectories,\n initKnowledgeLibrary,\n initAgentKnowledgeLibrary,\n agentKnowledgeLibraryExists,\n getAgentKnowledgeState,\n generateMessageFilename,\n readInboxMessages,\n writeInboxMessage,\n markMessageProcessed,\n getKnowledgeLibraryState,\n updateAgentContext,\n formatKnowledgeLibraryState,\n formatAgentKnowledgeState,\n} from './knowledge-library/index.js';\n\nexport type {\n MessageType,\n MessagePriority,\n MessageMetadata,\n Message,\n AgentContext,\n Objective,\n Decision,\n Dependency,\n AgentControl,\n AgentDirectories,\n AgentKnowledgeState,\n InitKnowledgeLibraryOptions,\n InitKnowledgeLibraryResult,\n ReadMessagesOptions,\n WriteMessageOptions,\n KnowledgeLibraryState,\n} from './knowledge-library/index.js';\n","/**\n * Configuration Loader\n *\n * Handles config file discovery, parsing, validation, and defaults.\n */\n\nimport { existsSync, readFileSync } from 'fs';\nimport { dirname, join, resolve } from 'path';\nimport { parse as parseYaml } from 'yaml';\nimport Ajv, { type ErrorObject } from 'ajv';\nimport addFormats from 'ajv-formats';\nimport type { CoreAIConfig, ResolvedCoreAIConfig } from './types.js';\n\n// Import schema as JSON\nimport { createRequire } from 'module';\nconst require = createRequire(import.meta.url);\nconst configSchema = require('../../schemas/coreai.config.schema.json') as object;\n\nconst CONFIG_FILE_NAME = 'coreai.config.yaml';\nconst CONFIG_FILE_NAMES = [CONFIG_FILE_NAME, 'coreai.config.yml'];\n\nexport class ConfigError extends Error {\n constructor(\n message: string,\n public readonly code: ConfigErrorCode,\n public readonly details?: unknown\n ) {\n super(message);\n this.name = 'ConfigError';\n }\n}\n\nexport type ConfigErrorCode = 'NOT_FOUND' | 'PARSE_ERROR' | 'VALIDATION_ERROR' | 'READ_ERROR';\n\n/**\n * Default team agents\n */\nconst DEFAULT_AGENTS = [\n 'backend-engineer',\n 'frontend-engineer',\n 'devops-engineer',\n 'engineering-manager',\n];\n\n/**\n * Find the config file by walking up the directory tree\n */\nexport function findConfigFile(startDir: string = process.cwd()): string | null {\n let currentDir = resolve(startDir);\n const root = dirname(currentDir);\n\n while (currentDir !== root) {\n for (const fileName of CONFIG_FILE_NAMES) {\n const configPath = join(currentDir, fileName);\n if (existsSync(configPath)) {\n return configPath;\n }\n }\n\n const parentDir = dirname(currentDir);\n if (parentDir === currentDir) {\n break;\n }\n currentDir = parentDir;\n }\n\n // Check root directory\n for (const fileName of CONFIG_FILE_NAMES) {\n const configPath = join(currentDir, fileName);\n if (existsSync(configPath)) {\n return configPath;\n }\n }\n\n return null;\n}\n\n/**\n * Parse YAML content into an object\n */\nexport function parseConfig(content: string, filePath?: string): unknown {\n try {\n return parseYaml(content);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown parse error';\n throw new ConfigError(\n `Failed to parse YAML${filePath ? ` in ${filePath}` : ''}: ${message}`,\n 'PARSE_ERROR',\n error\n );\n }\n}\n\n/**\n * Validate config against JSON schema\n */\nexport function validateConfig(config: unknown): CoreAIConfig {\n const ajv = new Ajv.default({ allErrors: true, strict: false });\n addFormats.default(ajv);\n\n const validate = ajv.compile<CoreAIConfig>(configSchema);\n const valid = validate(config);\n\n if (!valid) {\n const errors: ErrorObject[] = validate.errors ?? [];\n const errorMessages = errors.map((err: ErrorObject) => {\n const path = err.instancePath || 'root';\n return `${path}: ${err.message ?? 'unknown error'}`;\n });\n\n throw new ConfigError(\n `Configuration validation failed:\\n - ${errorMessages.join('\\n - ')}`,\n 'VALIDATION_ERROR',\n errors\n );\n }\n\n return config as CoreAIConfig;\n}\n\n/**\n * Apply default values to config\n */\nexport function applyDefaults(config: CoreAIConfig): ResolvedCoreAIConfig {\n return {\n ...config,\n project: {\n name: config.project?.name ?? 'unnamed',\n type: config.project?.type ?? 'software',\n root: config.project?.root ?? process.cwd(),\n },\n team: {\n agents: config.team?.agents ?? DEFAULT_AGENTS,\n },\n };\n}\n\n/**\n * Load and validate configuration from a file path\n */\nexport function loadConfigFromFile(filePath: string): ResolvedCoreAIConfig {\n let content: string;\n\n try {\n content = readFileSync(filePath, 'utf-8');\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown read error';\n throw new ConfigError(\n `Failed to read config file ${filePath}: ${message}`,\n 'READ_ERROR',\n error\n );\n }\n\n const parsed = parseConfig(content, filePath);\n const validated = validateConfig(parsed);\n return applyDefaults(validated);\n}\n\n/**\n * Load configuration by searching for config file\n */\nexport function loadConfig(startDir?: string): ResolvedCoreAIConfig {\n const configPath = findConfigFile(startDir);\n\n if (!configPath) {\n throw new ConfigError(\n `Configuration file not found. Create a ${CONFIG_FILE_NAME} file or run 'coreai init'.`,\n 'NOT_FOUND'\n );\n }\n\n return loadConfigFromFile(configPath);\n}\n\n/**\n * Check if a config file exists in the given directory or parent directories\n */\nexport function configExists(startDir?: string): boolean {\n return findConfigFile(startDir) !== null;\n}\n\n/**\n * Get the path to the config file, or null if not found\n */\nexport function getConfigPath(startDir?: string): string | null {\n return findConfigFile(startDir);\n}\n","/**\n * CoreAI Agent Types\n *\n * TypeScript types corresponding to the JSON schema at schemas/agent.schema.json\n */\n\n/** @deprecated Used only for YAML backward compatibility. Will be removed when YAML support is dropped. */\nexport type AgentType = 'ic-engineer' | 'manager' | 'specialist' | 'coordinator';\n\n/** @deprecated Used only for YAML backward compatibility. Will be removed when YAML support is dropped. */\nexport type WorkflowType =\n | 'ticket-implementation'\n | 'bug-investigation'\n | 'code-review'\n | 'planning-estimation'\n | 'product-planning';\n\n/** @deprecated Used only for YAML backward compatibility. Will be removed when YAML support is dropped. */\nexport interface AgentExpertise {\n primary?: string[];\n tech_stack?: string;\n [key: string]: unknown;\n}\n\n/** @deprecated Used only for YAML backward compatibility. Will be removed when YAML support is dropped. */\nexport interface AgentPrinciples {\n code_quality?: string[];\n testing?: string[];\n security?: string[];\n performance?: string[];\n [key: string]: string[] | undefined;\n}\n\n/** @deprecated Used only for YAML backward compatibility. Will be removed when YAML support is dropped. */\nexport interface AgentBehaviors {\n workflow?: WorkflowType;\n quality_gates?: string;\n [key: string]: unknown;\n}\n\n/** @deprecated Used only for YAML backward compatibility. Will be removed when YAML support is dropped. */\nexport interface AgentContextSources {\n shared?: string[];\n personal?: string[];\n}\n\n/** @deprecated Used only for YAML backward compatibility. Will be removed when YAML support is dropped. */\nexport interface AgentKnowledgeLibraryControl {\n objectives?: string;\n decisions?: string;\n dependencies?: string;\n index?: string;\n}\n\n/** @deprecated Used only for YAML backward compatibility. Will be removed when YAML support is dropped. */\nexport interface AgentKnowledgeLibraryShared {\n context?: string;\n architecture?: string;\n prd?: string;\n remote?: string[];\n}\n\n/** @deprecated Used only for YAML backward compatibility. Will be removed when YAML support is dropped. */\nexport interface AgentKnowledgeLibraryPersonal {\n context?: string;\n history?: string;\n inbox?: string;\n outbox?: string;\n tech?: string;\n control?: AgentKnowledgeLibraryControl;\n}\n\n/** @deprecated Used only for YAML backward compatibility. Will be removed when YAML support is dropped. */\nexport interface AgentKnowledgeLibrary {\n shared?: AgentKnowledgeLibraryShared;\n personal?: AgentKnowledgeLibraryPersonal;\n}\n\n/** @deprecated Used only for YAML backward compatibility. Will be removed when YAML support is dropped. */\nexport interface AgentCommunication {\n inbox?: string;\n outbox?: string;\n message_format?: string;\n outbox_format?: string;\n processed_dir?: string;\n}\n\n/** @deprecated Used only for YAML backward compatibility. Will be removed when YAML support is dropped. */\nexport interface AgentStartupProtocol {\n first_session?: string[];\n subsequent?: string[];\n}\n\n/** @deprecated Used only for YAML backward compatibility. Will be removed when YAML support is dropped. */\nexport interface AgentProtocols {\n startup?: AgentStartupProtocol;\n completion?: string[];\n}\n\n/**\n * Default Claude Code tools available to agents\n */\nexport const DEFAULT_AGENT_TOOLS = ['Read', 'Write', 'Edit', 'Bash', 'Glob', 'Grep'] as const;\n\n/**\n * Agent definition.\n * For MD agents: role, type, display_name, description, tools are used.\n * For deprecated YAML agents: all fields may be populated.\n */\nexport interface AgentDefinition {\n role: string;\n type: AgentType;\n display_name: string;\n description: string;\n /** @deprecated YAML-only. In MD agents, responsibilities are in the template body. */\n responsibilities?: string[];\n /** @deprecated YAML-only. In MD agents, expertise is in the template body. */\n expertise?: AgentExpertise;\n /** @deprecated YAML-only. In MD agents, skills are in the template body. */\n skills?: string[];\n /** @deprecated YAML-only. In MD agents, principles are in the template body. */\n principles?: AgentPrinciples;\n /** @deprecated YAML-only. In MD agents, behaviors are in the template body. */\n behaviors?: AgentBehaviors;\n /** @deprecated YAML-only. Use knowledge_library or MD template body instead. */\n context_sources?: AgentContextSources;\n /** @deprecated YAML-only. In MD agents, knowledge library structure is in the template body. */\n knowledge_library?: AgentKnowledgeLibrary;\n /** @deprecated YAML-only. In MD agents, communication details are in the template body. */\n communication?: AgentCommunication;\n /** @deprecated YAML-only. In MD agents, protocols are in the template body. */\n protocols?: AgentProtocols;\n /**\n * Claude Code tools available to this agent.\n * If not specified, defaults to: Read, Write, Edit, Bash, Glob, Grep\n */\n tools?: string[];\n}\n\n/**\n * @deprecated Used only for YAML backward compatibility.\n */\nexport interface ResolvedAgentDefinition extends AgentDefinition {\n expertise?: AgentExpertise & {\n tech_stack?: Record<string, unknown>;\n };\n behaviors?: AgentBehaviors & {\n quality_gates?: Record<string, unknown>;\n };\n}\n\n/**\n * Agent source location\n */\nexport type AgentSource = 'core' | 'custom' | 'override';\n\n/**\n * Agent metadata including source information\n */\nexport interface AgentMetadata {\n definition: AgentDefinition;\n source: AgentSource;\n filePath: string;\n}\n","/**\n * Agent Loader\n *\n * Handles loading agent definitions from Markdown templates (primary)\n * and YAML files (deprecated, backward compatible).\n */\n\nimport { existsSync, readdirSync, readFileSync } from 'fs';\nimport { basename, extname, join } from 'path';\nimport { parse as parseYaml } from 'yaml';\nimport Ajv, { type ErrorObject } from 'ajv';\nimport type { AgentDefinition, AgentMetadata, AgentSource } from './types.js';\n\n// Import schema as JSON (for deprecated YAML validation)\nimport { createRequire } from 'module';\nconst require = createRequire(import.meta.url);\nconst agentSchema = require('../../schemas/agent.schema.json') as object;\n\nexport class AgentError extends Error {\n constructor(\n message: string,\n public readonly code: AgentErrorCode,\n public readonly details?: unknown\n ) {\n super(message);\n this.name = 'AgentError';\n }\n}\n\nexport type AgentErrorCode = 'NOT_FOUND' | 'PARSE_ERROR' | 'VALIDATION_ERROR' | 'READ_ERROR';\n\n/**\n * Extract YAML frontmatter from a Markdown file.\n * Returns the parsed frontmatter object and the body content.\n */\nexport function extractFrontmatter(content: string): { frontmatter: Record<string, unknown>; body: string } {\n const match = content.match(/^---\\n([\\s\\S]*?)\\n---\\n?([\\s\\S]*)$/);\n if (!match) {\n throw new AgentError(\n 'No YAML frontmatter found. Agent MD files must start with YAML frontmatter (---)',\n 'PARSE_ERROR'\n );\n }\n\n const frontmatterYaml = match[1]!;\n const body = match[2] ?? '';\n let frontmatter: unknown;\n try {\n frontmatter = parseYaml(frontmatterYaml);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown parse error';\n throw new AgentError(`Failed to parse YAML frontmatter: ${message}`, 'PARSE_ERROR', error);\n }\n\n if (!frontmatter || typeof frontmatter !== 'object') {\n throw new AgentError('Invalid frontmatter: expected an object', 'PARSE_ERROR');\n }\n\n return { frontmatter: frontmatter as Record<string, unknown>, body };\n}\n\n/**\n * Load an agent definition from a Markdown template file.\n *\n * Extracts metadata from YAML frontmatter (name, description, tools).\n * The full MD content is the agent's identity - processed at compile time.\n */\nexport function loadAgentFromMdFile(filePath: string): AgentDefinition {\n if (!existsSync(filePath)) {\n throw new AgentError(`Agent file not found: ${filePath}`, 'NOT_FOUND');\n }\n\n let content: string;\n try {\n content = readFileSync(filePath, 'utf-8');\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown read error';\n throw new AgentError(`Failed to read agent file ${filePath}: ${message}`, 'READ_ERROR', error);\n }\n\n const { frontmatter } = extractFrontmatter(content);\n\n // Extract role from frontmatter 'name' field or filename\n const role = (frontmatter.name as string) || getRoleFromFilename(filePath);\n if (!role) {\n throw new AgentError(\n `Agent MD file must have a 'name' field in frontmatter or a valid filename: ${filePath}`,\n 'VALIDATION_ERROR'\n );\n }\n\n // Extract description\n const description = (frontmatter.description as string) || '';\n\n // Extract tools\n const tools: string[] | undefined = typeof frontmatter.tools === 'string'\n ? frontmatter.tools.split(',').map((t: string) => t.trim()).filter(Boolean)\n : undefined;\n\n const definition: AgentDefinition = {\n role,\n type: 'ic-engineer', // Default, actual identity is in the MD content\n display_name: role.split('-').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' '),\n description,\n };\n\n if (tools) {\n definition.tools = tools;\n }\n\n return definition;\n}\n\n// --- Deprecated YAML support (backward compatibility) ---\n\n/**\n * Parse YAML content into an agent definition\n * @deprecated Use Markdown agent files instead\n */\nexport function parseAgentYaml(content: string, filePath?: string): unknown {\n try {\n return parseYaml(content);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown parse error';\n throw new AgentError(\n `Failed to parse agent YAML${filePath ? ` in ${filePath}` : ''}: ${message}`,\n 'PARSE_ERROR',\n error\n );\n }\n}\n\n/**\n * Validate parsed YAML against agent schema\n * @deprecated Use Markdown agent files instead\n */\nexport function validateAgentDefinition(agent: unknown): AgentDefinition {\n const ajv = new Ajv.default({ allErrors: true, strict: false });\n const validate = ajv.compile<AgentDefinition>(agentSchema);\n const valid = validate(agent);\n\n if (!valid) {\n const errors: ErrorObject[] = validate.errors ?? [];\n const errorMessages = errors.map((err: ErrorObject) => {\n const path = err.instancePath || 'root';\n return `${path}: ${err.message ?? 'unknown error'}`;\n });\n\n throw new AgentError(\n `Agent validation failed:\\n - ${errorMessages.join('\\n - ')}`,\n 'VALIDATION_ERROR',\n errors\n );\n }\n\n return agent as AgentDefinition;\n}\n\n/**\n * Load and validate an agent definition from a YAML file\n * @deprecated Use Markdown agent files instead\n */\nexport function loadAgentFromYamlFile(filePath: string): AgentDefinition {\n if (!existsSync(filePath)) {\n throw new AgentError(`Agent file not found: ${filePath}`, 'NOT_FOUND');\n }\n\n let content: string;\n try {\n content = readFileSync(filePath, 'utf-8');\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown read error';\n throw new AgentError(`Failed to read agent file ${filePath}: ${message}`, 'READ_ERROR', error);\n }\n\n const parsed = parseAgentYaml(content, filePath);\n return validateAgentDefinition(parsed);\n}\n\n// --- Unified loading (supports both MD and YAML) ---\n\n/**\n * Load an agent definition from a file (MD or YAML).\n * MD files are the primary format. YAML files are deprecated but supported.\n */\nexport function loadAgentFromFile(filePath: string): AgentDefinition {\n const ext = extname(filePath).toLowerCase();\n\n if (ext === '.md') {\n return loadAgentFromMdFile(filePath);\n }\n\n if (ext === '.yaml' || ext === '.yml') {\n console.warn(\n `Warning: YAML agent definitions are deprecated and will be removed in a future version.\\n` +\n ` Please migrate ${basename(filePath)} to Markdown format.`\n );\n return loadAgentFromYamlFile(filePath);\n }\n\n throw new AgentError(\n `Unsupported agent file format: ${ext}. Use .md (recommended) or .yaml/.yml (deprecated)`,\n 'PARSE_ERROR'\n );\n}\n\n/**\n * List all agent files in a directory (MD and YAML).\n * Excludes files/directories starting with underscore (e.g., _templates/).\n */\nfunction listAgentFiles(dir: string): string[] {\n if (!existsSync(dir)) {\n return [];\n }\n\n return readdirSync(dir)\n .filter((file) => {\n // Skip underscore-prefixed files/dirs (templates, etc.)\n if (file.startsWith('_')) return false;\n const ext = extname(file).toLowerCase();\n return ext === '.md' || ext === '.yaml' || ext === '.yml';\n })\n .map((file) => join(dir, file));\n}\n\n/**\n * Load all agents from a directory\n */\nexport function loadAgentsFromDirectory(\n dir: string,\n source: AgentSource\n): Map<string, AgentMetadata> {\n const agents = new Map<string, AgentMetadata>();\n const files = listAgentFiles(dir);\n\n for (const filePath of files) {\n try {\n const definition = loadAgentFromFile(filePath);\n agents.set(definition.role, {\n definition,\n source,\n filePath,\n });\n } catch (error) {\n // Log warning but continue loading other agents\n const fileName = basename(filePath);\n console.warn(`Warning: Failed to load agent from ${fileName}: ${(error as Error).message}`);\n }\n }\n\n return agents;\n}\n\n/**\n * Get the agent role name from a filename\n */\nexport function getRoleFromFilename(filePath: string): string {\n const fileName = basename(filePath);\n const ext = extname(fileName);\n return fileName.slice(0, -ext.length);\n}\n","/**\n * Variable Resolution System\n *\n * Resolves variable placeholders in agent definitions.\n * Supports: ${config.*}, ${agent.*}, ${remote.*}\n */\n\nimport type { CoreAIConfig } from '../config/types.js';\nimport type { AgentDefinition } from './types.js';\n\n/**\n * Context for variable resolution\n */\nexport interface ResolutionContext {\n config?: CoreAIConfig;\n agent?: AgentDefinition;\n}\n\n/**\n * Options for variable resolution\n */\nexport interface ResolutionOptions {\n /**\n * If true, throw an error for unresolved variables.\n * If false, leave unresolved variables as-is.\n * Default: false\n */\n strict?: boolean;\n}\n\n/**\n * Error thrown when variable resolution fails\n */\nexport class ResolutionError extends Error {\n constructor(\n message: string,\n public readonly variable: string,\n public readonly path?: string\n ) {\n super(message);\n this.name = 'ResolutionError';\n }\n}\n\n/**\n * Pattern to match variable placeholders: ${namespace.path.to.value}\n */\nconst VARIABLE_PATTERN = /\\$\\{([a-z_][a-z0-9_]*(?:\\.[a-z_][a-z0-9_]*)*)\\}/gi;\n\n/**\n * Get a nested value from an object using dot notation\n */\nfunction getNestedValue(obj: unknown, path: string): unknown {\n const parts = path.split('.');\n let current: unknown = obj;\n\n for (const part of parts) {\n if (current === null || current === undefined) {\n return undefined;\n }\n if (typeof current !== 'object') {\n return undefined;\n }\n current = (current as Record<string, unknown>)[part];\n }\n\n return current;\n}\n\n/**\n * Resolve a single variable reference\n */\nfunction resolveVariable(\n variable: string,\n context: ResolutionContext,\n options: ResolutionOptions\n): string | undefined {\n const parts = variable.split('.');\n const namespace = parts[0];\n const path = parts.slice(1).join('.');\n\n let value: unknown;\n\n switch (namespace) {\n case 'config':\n if (!context.config) {\n if (options.strict) {\n throw new ResolutionError(\n `Cannot resolve \\${${variable}}: no config context provided`,\n variable\n );\n }\n return undefined;\n }\n value = getNestedValue(context.config, path);\n break;\n\n case 'agent':\n if (!context.agent) {\n if (options.strict) {\n throw new ResolutionError(\n `Cannot resolve \\${${variable}}: no agent context provided`,\n variable\n );\n }\n return undefined;\n }\n value = getNestedValue(context.agent, path);\n break;\n\n case 'remote':\n // Remote is a shortcut for integration URLs\n value = resolveRemoteVariable(path, context, options);\n break;\n\n default:\n if (options.strict) {\n throw new ResolutionError(`Unknown variable namespace: ${namespace}`, variable);\n }\n return undefined;\n }\n\n if (value === undefined) {\n if (options.strict) {\n throw new ResolutionError(`Cannot resolve \\${${variable}}: path not found`, variable, path);\n }\n return undefined;\n }\n\n // Convert value to string representation\n if (typeof value === 'string') {\n return value;\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n // For objects/arrays, return JSON representation\n return JSON.stringify(value);\n}\n\n/**\n * Resolve remote.* variables (shortcuts to integration URLs)\n */\nfunction resolveRemoteVariable(\n path: string,\n context: ResolutionContext,\n options: ResolutionOptions\n): string | undefined {\n if (!context.config?.integrations) {\n if (options.strict) {\n throw new ResolutionError(\n `Cannot resolve \\${remote.${path}}: no integrations configured`,\n `remote.${path}`\n );\n }\n return undefined;\n }\n\n const integrations = context.config.integrations;\n\n // Map remote shortcuts to integration paths\n switch (path) {\n case 'documentation':\n return (\n integrations.documentation?.config?.base_url ??\n integrations.documentation?.config?.base_path\n );\n\n case 'issues':\n return integrations.issue_tracker?.config?.base_url;\n\n case 'git':\n return integrations.git?.config?.repo;\n\n case 'state':\n return integrations.state?.config?.base_path ?? integrations.state?.config?.bucket;\n\n default:\n // Try to resolve as nested path under integrations\n return getNestedValue(integrations, path) as string | undefined;\n }\n}\n\n/**\n * Resolve all variables in a string\n */\nexport function resolveString(\n input: string,\n context: ResolutionContext,\n options: ResolutionOptions = {}\n): string {\n return input.replace(VARIABLE_PATTERN, (match, variable: string) => {\n const resolved = resolveVariable(variable, context, options);\n return resolved !== undefined ? resolved : match;\n });\n}\n\n/**\n * Check if a string contains variable placeholders\n */\nexport function hasVariables(input: string): boolean {\n // Create new regex to avoid state issues with global flag\n const pattern = /\\$\\{([a-z_][a-z0-9_]*(?:\\.[a-z_][a-z0-9_]*)*)\\}/i;\n return pattern.test(input);\n}\n\n/**\n * Extract all variable references from a string\n */\nexport function extractVariables(input: string): string[] {\n const matches = input.matchAll(VARIABLE_PATTERN);\n return Array.from(matches, (m) => m[1]).filter((v): v is string => v !== undefined);\n}\n\n/**\n * Recursively resolve all variables in an object\n */\nexport function resolveObject<T>(\n obj: T,\n context: ResolutionContext,\n options: ResolutionOptions = {}\n): T {\n if (obj === null || obj === undefined) {\n return obj;\n }\n\n if (typeof obj === 'string') {\n return resolveString(obj, context, options) as T;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => resolveObject(item, context, options)) as T;\n }\n\n if (typeof obj === 'object') {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n result[key] = resolveObject(value, context, options);\n }\n return result as T;\n }\n\n return obj;\n}\n\n/**\n * Resolve all variables in an agent definition\n */\nexport function resolveAgentDefinition(\n agent: AgentDefinition,\n config?: CoreAIConfig,\n options: ResolutionOptions = {}\n): AgentDefinition {\n const context: ResolutionContext = {\n agent,\n };\n if (config) {\n context.config = config;\n }\n\n return resolveObject(agent, context, options);\n}\n","/**\n * Agent Compiler\n *\n * Processes agent Markdown templates with variable substitution and include directives.\n * For deprecated YAML agents, falls back to structural transformation.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';\nimport { join, dirname, extname, isAbsolute } from 'path';\nimport { parse as parseYaml, stringify as stringifyYaml } from 'yaml';\nimport type { CoreAIConfig } from '../config/types.js';\nimport type { AgentDefinition, AgentMetadata, AgentSource } from './types.js';\nimport { DEFAULT_AGENT_TOOLS } from './types.js';\nimport { loadAgentsFromDirectory } from './loader.js';\nimport { resolveString, resolveAgentDefinition, type ResolutionContext } from './resolver.js';\n\n/**\n * Options for compiling agents\n */\nexport interface CompileOptions {\n outputDir?: string;\n coreAgentsDir?: string;\n customAgentsDir?: string;\n projectRoot?: string;\n filter?: (agent: AgentDefinition) => boolean;\n mcpServers?: string[];\n}\n\n/**\n * Result of compiling agents\n */\nexport interface CompileResult {\n compiled: {\n role: string;\n source: AgentSource;\n outputPath: string;\n }[];\n errors: {\n role: string;\n source: AgentSource;\n error: string;\n }[];\n}\n\n/**\n * Build the tools string for agent frontmatter\n */\nexport function buildAgentTools(agent: AgentDefinition, mcpServers?: string[]): string {\n const tools: string[] = agent.tools\n ? [...agent.tools]\n : [...DEFAULT_AGENT_TOOLS];\n\n if (mcpServers && mcpServers.length > 0) {\n for (const server of mcpServers) {\n const mcpTool = `mcp__${server}`;\n if (!tools.includes(mcpTool)) {\n tools.push(mcpTool);\n }\n }\n }\n\n return tools.join(', ');\n}\n\n/**\n * Process include directives in a template.\n *\n * Replaces `<!-- include: path -->` with the contents of the referenced file.\n * Paths are resolved relative to the template's directory.\n * Supports recursive includes up to a configurable depth limit.\n */\nexport function processIncludes(\n template: string,\n templateDir: string,\n depth: number = 0,\n maxDepth: number = 3\n): string {\n if (depth > maxDepth) {\n throw new Error(`Include depth exceeded maximum of ${maxDepth}`);\n }\n\n const includePattern = /<!--\\s*include:\\s*(\\S+)\\s*-->/g;\n\n return template.replace(includePattern, (_match, includePath: string) => {\n const resolvedPath = isAbsolute(includePath)\n ? includePath\n : join(templateDir, includePath);\n\n if (!existsSync(resolvedPath)) {\n throw new Error(`Include file not found: ${includePath} (resolved to ${resolvedPath})`);\n }\n\n const includedContent = readFileSync(resolvedPath, 'utf-8');\n return processIncludes(includedContent, dirname(resolvedPath), depth + 1, maxDepth);\n });\n}\n\n/**\n * Process a Markdown agent template: expand includes, resolve variables, and update frontmatter tools.\n *\n * This is the primary compilation path for .md agent files.\n * Pipeline: read → expand includes → extract custom frontmatter → resolve variables → inject tools → rebuild.\n */\nexport function processAgentTemplate(\n templatePath: string,\n agent: AgentDefinition,\n config?: CoreAIConfig,\n mcpServers?: string[]\n): string {\n const template = readFileSync(templatePath, 'utf-8');\n\n // Step 1: Expand include directives before variable resolution\n const templateDir = dirname(templatePath);\n const expandedTemplate = processIncludes(template, templateDir);\n\n // Step 2: Parse frontmatter early to extract custom agent fields (e.g. tech_artifacts)\n const earlyMatch = expandedTemplate.match(/^---\\n([\\s\\S]*?)\\n---\\n?([\\s\\S]*)$/);\n if (!earlyMatch) {\n throw new Error(`Invalid markdown format in ${templatePath}: no frontmatter found`);\n }\n\n const earlyFrontmatter = parseYaml(earlyMatch[1]!) as Record<string, unknown>;\n const reservedKeys = new Set(['name', 'description', 'tools']);\n const extendedAgent: Record<string, unknown> = { ...agent };\n for (const [key, value] of Object.entries(earlyFrontmatter)) {\n if (!reservedKeys.has(key) && !(key in extendedAgent)) {\n extendedAgent[key] = value;\n }\n }\n\n // Step 3: Build resolution context with extended agent\n const context: ResolutionContext = { agent: extendedAgent as unknown as AgentDefinition };\n if (config) {\n context.config = config;\n }\n\n // Step 4: Resolve variables in the expanded template\n const resolved = resolveString(expandedTemplate, context);\n\n // Step 5: Parse frontmatter from resolved template to update tools\n const frontmatterMatch = resolved.match(/^---\\n([\\s\\S]*?)\\n---\\n?([\\s\\S]*)$/);\n if (!frontmatterMatch) {\n throw new Error(`Invalid markdown format after resolution in ${templatePath}`);\n }\n\n const frontmatterYaml = frontmatterMatch[1]!;\n const body = frontmatterMatch[2] ?? '';\n const frontmatter = parseYaml(frontmatterYaml) as Record<string, unknown>;\n\n // Update tools line with MCP servers\n const tools = buildAgentTools(agent, mcpServers);\n frontmatter.tools = tools;\n\n // Flatten description for frontmatter (single line)\n if (typeof frontmatter.description === 'string') {\n frontmatter.description = frontmatter.description.replace(/\\n/g, ' ').trim();\n }\n\n // Rebuild with updated frontmatter\n const updatedFrontmatter = stringifyYaml(frontmatter, { lineWidth: 0 }).trim();\n return `---\\n${updatedFrontmatter}\\n---\\n${body}`;\n}\n\n// --- Deprecated YAML compilation (backward compatibility) ---\n\n/**\n * Generate markdown content from a resolved YAML agent definition.\n * @deprecated Use MD templates instead. This exists for backward compatibility with YAML agents.\n */\nexport function generateAgentMarkdown(agent: AgentDefinition, mcpServers?: string[]): string {\n const lines: string[] = [];\n const tools = buildAgentTools(agent, mcpServers);\n\n // YAML frontmatter\n lines.push('---');\n lines.push(`name: ${agent.role}`);\n lines.push(`description: ${agent.description.replace(/\\n/g, ' ').trim()}`);\n lines.push(`tools: ${tools}`);\n lines.push('---');\n lines.push('');\n\n // Header\n lines.push(`# ${agent.display_name}`);\n lines.push('');\n lines.push(`**Role:** ${agent.role}`);\n lines.push(`**Type:** ${agent.type}`);\n lines.push('');\n\n // Description\n lines.push('## Description');\n lines.push('');\n lines.push(agent.description.trim());\n lines.push('');\n\n // Responsibilities\n if (agent.responsibilities && agent.responsibilities.length > 0) {\n lines.push('## Responsibilities');\n lines.push('');\n for (const r of agent.responsibilities) {\n lines.push(`- ${r}`);\n }\n lines.push('');\n }\n\n // Expertise\n if (agent.expertise) {\n lines.push('## Expertise');\n lines.push('');\n if (agent.expertise.primary && agent.expertise.primary.length > 0) {\n lines.push('### Primary Areas');\n lines.push('');\n for (const area of agent.expertise.primary) {\n lines.push(`- ${area}`);\n }\n lines.push('');\n }\n if (agent.expertise.tech_stack) {\n lines.push('### Tech Stack');\n lines.push('');\n const ts = agent.expertise.tech_stack;\n if (typeof ts === 'string') {\n lines.push(ts);\n } else if (typeof ts === 'object') {\n lines.push('```json');\n lines.push(JSON.stringify(ts, null, 2));\n lines.push('```');\n }\n lines.push('');\n }\n }\n\n // Skills\n if (agent.skills && agent.skills.length > 0) {\n lines.push('## Skills');\n lines.push('');\n for (const skill of agent.skills) {\n lines.push(`- ${skill}`);\n }\n lines.push('');\n }\n\n // Principles\n if (agent.principles) {\n lines.push('## Principles');\n lines.push('');\n for (const [category, items] of Object.entries(agent.principles)) {\n if (items && Array.isArray(items) && items.length > 0) {\n const title = category.replace(/[_-]/g, ' ').replace(/\\b\\w/g, (c) => c.toUpperCase());\n lines.push(`### ${title}`);\n lines.push('');\n for (const item of items) {\n lines.push(`- ${item}`);\n }\n lines.push('');\n }\n }\n }\n\n // Behaviors\n if (agent.behaviors) {\n lines.push('## Behaviors');\n lines.push('');\n if (agent.behaviors.workflow) {\n lines.push(`**Workflow:** ${agent.behaviors.workflow}`);\n lines.push('');\n }\n if (agent.behaviors.quality_gates) {\n lines.push('### Quality Gates');\n lines.push('');\n const gates = agent.behaviors.quality_gates;\n if (typeof gates === 'string') {\n lines.push(gates);\n } else if (typeof gates === 'object') {\n lines.push('```json');\n lines.push(JSON.stringify(gates, null, 2));\n lines.push('```');\n }\n lines.push('');\n }\n }\n\n // Knowledge Library\n if (agent.knowledge_library) {\n generateKnowledgeLibrarySection(agent, lines);\n }\n\n // Communication\n if (agent.communication) {\n generateCommunicationSection(agent, lines);\n }\n\n // Protocols\n if (agent.protocols?.startup) {\n generateStartupProtocolSection(agent, lines);\n }\n if (agent.protocols?.completion) {\n generateCompletionProtocolSection(agent, lines);\n }\n\n // Legacy context sources\n if (agent.context_sources && !agent.knowledge_library) {\n lines.push('## Context Sources');\n lines.push('');\n if (agent.context_sources.shared?.length) {\n lines.push('### Shared');\n lines.push('');\n for (const s of agent.context_sources.shared) lines.push(`- ${s}`);\n lines.push('');\n }\n if (agent.context_sources.personal?.length) {\n lines.push('### Personal');\n lines.push('');\n for (const p of agent.context_sources.personal) lines.push(`- ${p}`);\n lines.push('');\n }\n }\n\n lines.push('---');\n lines.push('');\n lines.push('*Generated by CoreAI*');\n lines.push('');\n\n return lines.join('\\n');\n}\n\nfunction generateKnowledgeLibrarySection(agent: AgentDefinition, lines: string[]): void {\n const kl = agent.knowledge_library;\n if (!kl) return;\n lines.push('## Knowledge Library Structure');\n lines.push('');\n if (kl.shared) {\n lines.push('### Shared Context (Root - All Agents)');\n lines.push('```');\n lines.push('/KnowledgeLibrary/');\n if (kl.shared.context) lines.push(`├── ${kl.shared.context.split('/').pop()}`);\n if (kl.shared.architecture) lines.push(`├── ${kl.shared.architecture.split('/').pop()}`);\n if (kl.shared.prd) lines.push(`└── ${kl.shared.prd.split('/').pop()}`);\n lines.push('```');\n if (kl.shared.remote?.length) {\n lines.push('');\n lines.push('**Remote Documentation:**');\n for (const r of kl.shared.remote) lines.push(`- ${r}`);\n }\n lines.push('');\n }\n if (kl.personal) {\n lines.push(`### Personal Context (${agent.role})`);\n lines.push('```');\n lines.push(`/KnowledgeLibrary/${agent.role}/`);\n if (kl.personal.context) { lines.push('├── context/'); lines.push('│ └── current.txt'); }\n if (kl.personal.history) { lines.push('├── history/'); }\n if (kl.personal.inbox) { lines.push('├── inbox/'); }\n if (kl.personal.outbox) { lines.push('├── outbox/'); }\n if (kl.personal.tech) { lines.push('├── tech/'); }\n if (kl.personal.control) {\n lines.push('└── control/');\n if (kl.personal.control.objectives) lines.push(' ├── objectives.txt');\n if (kl.personal.control.decisions) lines.push(' ├── decisions.txt');\n if (kl.personal.control.dependencies) lines.push(' ├── dependencies.txt');\n if (kl.personal.control.index) lines.push(' └── index.txt');\n }\n lines.push('```');\n lines.push('');\n }\n lines.push('---');\n lines.push('');\n}\n\nfunction generateCommunicationSection(agent: AgentDefinition, lines: string[]): void {\n const comm = agent.communication;\n if (!comm) return;\n lines.push('## Communication');\n lines.push('');\n if (comm.inbox) lines.push(`**Inbox:** \\`${comm.inbox}\\``);\n if (comm.outbox) lines.push(`**Outbox:** \\`${comm.outbox}\\``);\n lines.push('');\n if (comm.message_format || comm.outbox_format || comm.processed_dir) {\n lines.push('### Message Conventions');\n lines.push('');\n if (comm.message_format) lines.push(`- **Inbox message naming:** \\`${comm.message_format}\\``);\n if (comm.outbox_format) lines.push(`- **Outbox message naming:** \\`${comm.outbox_format}\\``);\n if (comm.processed_dir) lines.push(`- **Processed messages:** Move handled inbox messages to \\`${comm.processed_dir}\\``);\n lines.push('');\n }\n}\n\nfunction generateStartupProtocolSection(agent: AgentDefinition, lines: string[]): void {\n const p = agent.protocols;\n if (!p?.startup) return;\n lines.push('## When Invoked');\n lines.push('');\n lines.push('> **MANDATORY STARTUP PROTOCOL** - Execute before proceeding with any task.');\n lines.push('');\n lines.push('### Session Context Check');\n lines.push('');\n if (p.startup.first_session?.length) {\n lines.push('**If this is your FIRST invocation in this session:**');\n lines.push('');\n for (const s of p.startup.first_session) lines.push(`- [ ] ${s}`);\n lines.push('');\n lines.push('Acknowledge: \"Startup protocol complete. Full context loaded.\"');\n lines.push('');\n }\n if (p.startup.subsequent?.length) {\n lines.push('**If you have ALREADY loaded context in this session:**');\n lines.push('');\n for (const s of p.startup.subsequent) lines.push(`- [ ] ${s}`);\n lines.push('');\n lines.push('Acknowledge: \"Context already loaded. Checked inbox for new messages.\"');\n lines.push('');\n }\n lines.push('Then proceed with the task.');\n lines.push('');\n lines.push('---');\n lines.push('');\n}\n\nfunction generateCompletionProtocolSection(agent: AgentDefinition, lines: string[]): void {\n const p = agent.protocols;\n if (!p?.completion?.length) return;\n lines.push('## Before Finishing');\n lines.push('');\n lines.push('> **MANDATORY COMPLETION PROTOCOL** - Execute ALL steps before ending any task.');\n lines.push('');\n for (let i = 0; i < p.completion.length; i++) {\n lines.push(`### ${i + 1}. ${p.completion[i]}`);\n lines.push('');\n }\n lines.push('Acknowledge: \"Completion protocol finished. Context updated.\"');\n lines.push('');\n lines.push('---');\n lines.push('');\n}\n\n// --- Unified compilation ---\n\n/**\n * Compile a single agent.\n * MD templates use simple variable substitution.\n * YAML files use the deprecated structural transformation.\n */\nexport function compileAgent(\n agent: AgentDefinition,\n filePath: string,\n config?: CoreAIConfig,\n mcpServers?: string[]\n): string {\n const ext = extname(filePath).toLowerCase();\n\n if (ext === '.md') {\n return processAgentTemplate(filePath, agent, config, mcpServers);\n }\n\n // Deprecated YAML path\n const resolved = resolveAgentDefinition(agent, config);\n return generateAgentMarkdown(resolved, mcpServers);\n}\n\n/**\n * Load all agents from core and custom directories\n */\nexport function loadAllAgents(options: CompileOptions = {}): Map<string, AgentMetadata> {\n const agents = new Map<string, AgentMetadata>();\n\n if (options.coreAgentsDir && existsSync(options.coreAgentsDir)) {\n const coreAgents = loadAgentsFromDirectory(options.coreAgentsDir, 'core');\n for (const [role, metadata] of coreAgents) {\n agents.set(role, metadata);\n }\n }\n\n if (options.customAgentsDir && existsSync(options.customAgentsDir)) {\n const customAgents = loadAgentsFromDirectory(options.customAgentsDir, 'custom');\n for (const [role, metadata] of customAgents) {\n if (agents.has(role)) {\n metadata.source = 'override';\n }\n agents.set(role, metadata);\n }\n }\n\n return agents;\n}\n\n/**\n * Filter agents based on team configuration\n */\nexport function filterAgentsByTeam(\n agents: Map<string, AgentMetadata>,\n config?: CoreAIConfig\n): Map<string, AgentMetadata> {\n if (!config?.team?.agents || config.team.agents.length === 0) {\n return agents;\n }\n\n const filtered = new Map<string, AgentMetadata>();\n for (const [role, metadata] of agents) {\n if (metadata.source === 'custom' || metadata.source === 'override') {\n filtered.set(role, metadata);\n } else if (config.team.agents.includes(role)) {\n filtered.set(role, metadata);\n }\n }\n\n return filtered;\n}\n\n/**\n * Compile all agents and write to output directory\n */\nexport function compileAgents(config?: CoreAIConfig, options: CompileOptions = {}): CompileResult {\n const projectRoot = options.projectRoot ?? process.cwd();\n const outputDir = options.outputDir ?? join(projectRoot, '.claude', 'agents');\n const coreAgentsDir = options.coreAgentsDir ?? getCoreAgentsDir();\n const customAgentsDir = options.customAgentsDir ?? join(projectRoot, 'coreai', 'agents');\n\n const result: CompileResult = {\n compiled: [],\n errors: [],\n };\n\n const allAgents = loadAllAgents({\n ...options,\n coreAgentsDir,\n customAgentsDir,\n });\n\n const agents = filterAgentsByTeam(allAgents, config);\n\n if (!existsSync(outputDir)) {\n mkdirSync(outputDir, { recursive: true });\n }\n\n for (const [role, metadata] of agents) {\n if (options.filter && !options.filter(metadata.definition)) {\n continue;\n }\n\n try {\n const markdown = compileAgent(\n metadata.definition,\n metadata.filePath,\n config,\n options.mcpServers\n );\n const outputPath = join(outputDir, `${role}.md`);\n writeFileSync(outputPath, markdown, 'utf-8');\n\n result.compiled.push({\n role,\n source: metadata.source,\n outputPath,\n });\n } catch (error) {\n result.errors.push({\n role,\n source: metadata.source,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n return result;\n}\n\n/**\n * Get the default core agents directory\n */\nexport function getCoreAgentsDir(): string {\n let currentDir = dirname(import.meta.url.replace('file://', ''));\n for (let i = 0; i < 5; i++) {\n if (existsSync(join(currentDir, 'package.json'))) {\n return join(currentDir, 'agents');\n }\n currentDir = dirname(currentDir);\n }\n return join(dirname(dirname(dirname(import.meta.url.replace('file://', '')))), 'agents');\n}\n","/**\n * MCP Integration Types\n *\n * Types for MCP server configuration and integration.\n */\n\n/**\n * Transport type for MCP servers\n */\nexport type McpTransportType = 'stdio' | 'http' | 'sse';\n\n/**\n * Configuration for a stdio-based MCP server\n */\nexport interface StdioServerConfig {\n transport: 'stdio';\n command: string;\n args?: string[];\n env?: Record<string, string>;\n cwd?: string;\n}\n\n/**\n * Configuration for an HTTP-based MCP server\n */\nexport interface HttpServerConfig {\n transport: 'http' | 'sse';\n url: string;\n headers?: Record<string, string>;\n}\n\n/**\n * Union type for all MCP server configurations\n */\nexport type McpServerConfig = StdioServerConfig | HttpServerConfig;\n\n/**\n * MCP server definition from config\n */\nexport interface McpServerDefinition {\n /**\n * Unique name for this server\n */\n name: string;\n\n /**\n * Server configuration\n */\n config: McpServerConfig;\n\n /**\n * Whether this server is enabled\n */\n enabled?: boolean;\n\n /**\n * Description of what this server provides\n */\n description?: string;\n}\n\n/**\n * MCP config file structure (e.g., mcp.json)\n */\nexport interface McpConfigFile {\n /**\n * MCP servers to connect to\n */\n mcpServers?: Record<string, McpServerConfig>;\n}\n\n/**\n * Information about a connected MCP server\n */\nexport interface McpServerInfo {\n /**\n * Server name\n */\n name: string;\n\n /**\n * Server version (if available)\n */\n version?: string;\n\n /**\n * Protocol version\n */\n protocolVersion?: string;\n\n /**\n * Server capabilities\n */\n capabilities?: McpCapabilities;\n\n /**\n * Server instructions (if any)\n */\n instructions?: string;\n\n /**\n * Whether the server is connected\n */\n connected: boolean;\n}\n\n/**\n * MCP server capabilities\n */\nexport interface McpCapabilities {\n tools?: boolean;\n resources?: boolean;\n prompts?: boolean;\n logging?: boolean;\n}\n\n/**\n * MCP tool definition\n */\nexport interface McpTool {\n /**\n * Tool name\n */\n name: string;\n\n /**\n * Tool description\n */\n description?: string;\n\n /**\n * Input schema for the tool\n */\n inputSchema: {\n type: 'object';\n properties?: Record<string, unknown>;\n required?: string[];\n };\n\n /**\n * Tool annotations\n */\n annotations?: {\n title?: string;\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n };\n}\n\n/**\n * MCP resource definition\n */\nexport interface McpResource {\n /**\n * Resource URI\n */\n uri: string;\n\n /**\n * Resource name\n */\n name: string;\n\n /**\n * Resource description\n */\n description?: string;\n\n /**\n * MIME type\n */\n mimeType?: string;\n}\n\n/**\n * Result of calling an MCP tool\n */\nexport interface McpToolResult {\n /**\n * Tool output content\n */\n content: McpContent[];\n\n /**\n * Whether the tool call resulted in an error\n */\n isError?: boolean;\n\n /**\n * Structured content (if tool has outputSchema)\n */\n structuredContent?: Record<string, unknown>;\n}\n\n/**\n * Content returned by MCP tools and resources\n */\nexport type McpContent = McpTextContent | McpImageContent | McpResourceContent;\n\n/**\n * Text content\n */\nexport interface McpTextContent {\n type: 'text';\n text: string;\n}\n\n/**\n * Image content\n */\nexport interface McpImageContent {\n type: 'image';\n data: string;\n mimeType: string;\n}\n\n/**\n * Embedded resource content\n */\nexport interface McpResourceContent {\n type: 'resource';\n resource: {\n uri: string;\n text?: string;\n blob?: string;\n mimeType?: string;\n };\n}\n\n/**\n * Error from MCP operations\n */\nexport class McpError extends Error {\n constructor(\n message: string,\n public readonly code: McpErrorCode,\n public readonly server?: string,\n cause?: Error\n ) {\n super(message, { cause });\n this.name = 'McpError';\n }\n}\n\n/**\n * MCP error codes\n */\nexport type McpErrorCode =\n | 'connection_failed'\n | 'connection_closed'\n | 'server_not_found'\n | 'tool_not_found'\n | 'resource_not_found'\n | 'invalid_config'\n | 'transport_error'\n | 'protocol_error'\n | 'timeout';\n","/**\n * MCP Client Wrapper\n *\n * Provides a simplified interface for connecting to and communicating with MCP servers.\n */\n\nimport { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';\nimport type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';\nimport type {\n McpServerConfig,\n McpServerInfo,\n McpTool,\n McpResource,\n McpToolResult,\n McpCapabilities,\n McpContent,\n StdioServerConfig,\n} from './types.js';\nimport { McpError } from './types.js';\n\n/**\n * Options for creating an MCP client\n */\nexport interface McpClientOptions {\n /**\n * Client name to report to servers\n */\n clientName?: string;\n\n /**\n * Client version to report to servers\n */\n clientVersion?: string;\n\n /**\n * Timeout for operations in milliseconds\n */\n timeout?: number;\n}\n\nconst DEFAULT_OPTIONS: Required<McpClientOptions> = {\n clientName: 'coreai',\n clientVersion: '0.1.0',\n timeout: 30000,\n};\n\n/**\n * MCP Client Wrapper\n *\n * Manages a connection to a single MCP server and provides\n * a simplified API for tool calls, resource access, etc.\n */\nexport class McpClient {\n private client: Client | null = null;\n private transport: Transport | null = null;\n private _serverInfo: McpServerInfo | null = null;\n private options: Required<McpClientOptions>;\n private serverName: string;\n private config: McpServerConfig;\n\n constructor(serverName: string, config: McpServerConfig, options?: McpClientOptions) {\n this.serverName = serverName;\n this.config = config;\n this.options = { ...DEFAULT_OPTIONS, ...options };\n }\n\n /**\n * Connect to the MCP server\n */\n async connect(): Promise<void> {\n if (this.client && this.isConnected()) {\n return;\n }\n\n try {\n // Create the appropriate transport\n this.transport = await this.createTransport();\n\n // Create the MCP client\n this.client = new Client(\n {\n name: this.options.clientName,\n version: this.options.clientVersion,\n },\n {\n capabilities: {\n roots: { listChanged: true },\n },\n }\n );\n\n // Connect to the server\n await this.client.connect(this.transport);\n\n // Store server info\n const serverVersion = this.client.getServerVersion();\n const serverCapabilities = this.client.getServerCapabilities();\n\n const info: McpServerInfo = {\n name: this.serverName,\n connected: true,\n };\n\n if (serverVersion?.version) {\n info.version = serverVersion.version;\n }\n\n const caps = this.parseCapabilities(serverCapabilities);\n if (caps) {\n info.capabilities = caps;\n }\n\n const instructions = this.client.getInstructions();\n if (instructions) {\n info.instructions = instructions;\n }\n\n this._serverInfo = info;\n } catch (error) {\n throw new McpError(\n `Failed to connect to MCP server \"${this.serverName}\": ${error instanceof Error ? error.message : String(error)}`,\n 'connection_failed',\n this.serverName,\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /**\n * Disconnect from the MCP server\n */\n async disconnect(): Promise<void> {\n if (this.transport) {\n await this.transport.close();\n this.transport = null;\n }\n\n this.client = null;\n\n if (this._serverInfo) {\n this._serverInfo.connected = false;\n }\n }\n\n /**\n * Check if connected to the server\n */\n isConnected(): boolean {\n return this._serverInfo?.connected ?? false;\n }\n\n /**\n * Get server information\n */\n getServerInfo(): McpServerInfo | null {\n return this._serverInfo;\n }\n\n /**\n * List available tools from the server\n */\n async listTools(): Promise<McpTool[]> {\n const client = this.ensureConnected();\n\n const result = await client.listTools();\n\n return result.tools.map((tool) => {\n // Build inputSchema with only defined properties\n const inputSchema: McpTool['inputSchema'] = { type: 'object' };\n if (tool.inputSchema.properties) {\n inputSchema.properties = tool.inputSchema.properties as Record<string, unknown>;\n }\n if (tool.inputSchema.required) {\n inputSchema.required = tool.inputSchema.required;\n }\n\n const mapped: McpTool = {\n name: tool.name,\n inputSchema,\n };\n\n if (tool.description) {\n mapped.description = tool.description;\n }\n\n if (tool.annotations) {\n const annotations: McpTool['annotations'] = {};\n if (tool.annotations.title) annotations.title = tool.annotations.title;\n if (tool.annotations.readOnlyHint !== undefined)\n annotations.readOnlyHint = tool.annotations.readOnlyHint;\n if (tool.annotations.destructiveHint !== undefined)\n annotations.destructiveHint = tool.annotations.destructiveHint;\n if (tool.annotations.idempotentHint !== undefined)\n annotations.idempotentHint = tool.annotations.idempotentHint;\n if (Object.keys(annotations).length > 0) {\n mapped.annotations = annotations;\n }\n }\n\n return mapped;\n });\n }\n\n /**\n * Call a tool on the server\n */\n async callTool(name: string, args?: Record<string, unknown>): Promise<McpToolResult> {\n const client = this.ensureConnected();\n\n try {\n const result = await client.callTool({\n name,\n arguments: args,\n });\n\n // Handle the different result formats\n if ('content' in result && Array.isArray(result.content)) {\n const content: McpContent[] = [];\n\n for (const c of result.content) {\n if (typeof c === 'object' && c !== null && 'type' in c) {\n const item = c as { type: string; [key: string]: unknown };\n if (item.type === 'text' && typeof item.text === 'string') {\n content.push({ type: 'text', text: item.text });\n } else if (\n item.type === 'image' &&\n typeof item.data === 'string' &&\n typeof item.mimeType === 'string'\n ) {\n content.push({ type: 'image', data: item.data, mimeType: item.mimeType });\n } else if (item.type === 'resource' && typeof item.resource === 'object') {\n const res = item.resource as {\n uri: string;\n text?: string;\n blob?: string;\n mimeType?: string;\n };\n const resourceContent: {\n uri: string;\n text?: string;\n blob?: string;\n mimeType?: string;\n } = {\n uri: res.uri,\n };\n if (res.text) resourceContent.text = res.text;\n if (res.blob) resourceContent.blob = res.blob;\n if (res.mimeType) resourceContent.mimeType = res.mimeType;\n content.push({\n type: 'resource',\n resource: resourceContent,\n });\n } else {\n // Default to text for unknown types\n content.push({ type: 'text', text: JSON.stringify(c) });\n }\n }\n }\n\n const toolResult: McpToolResult = { content };\n\n if (typeof result.isError === 'boolean') {\n toolResult.isError = result.isError;\n }\n\n if (typeof result.structuredContent === 'object' && result.structuredContent !== null) {\n toolResult.structuredContent = result.structuredContent as Record<string, unknown>;\n }\n\n return toolResult;\n }\n\n // Handle legacy toolResult format\n if ('toolResult' in result) {\n return {\n content: [{ type: 'text', text: JSON.stringify(result.toolResult) }],\n };\n }\n\n return {\n content: [],\n };\n } catch (error) {\n throw new McpError(\n `Failed to call tool \"${name}\": ${error instanceof Error ? error.message : String(error)}`,\n 'protocol_error',\n this.serverName,\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /**\n * List available resources from the server\n */\n async listResources(): Promise<McpResource[]> {\n const client = this.ensureConnected();\n\n const result = await client.listResources();\n\n return result.resources.map((resource) => {\n const mapped: McpResource = {\n uri: resource.uri,\n name: resource.name,\n };\n if (resource.description) {\n mapped.description = resource.description;\n }\n if (resource.mimeType) {\n mapped.mimeType = resource.mimeType;\n }\n return mapped;\n });\n }\n\n /**\n * Read a resource from the server\n */\n async readResource(uri: string): Promise<string> {\n const client = this.ensureConnected();\n\n const result = await client.readResource({ uri });\n\n // Return the first text content, or blob as base64\n for (const content of result.contents) {\n if ('text' in content) {\n return content.text;\n }\n if ('blob' in content) {\n return content.blob;\n }\n }\n\n return '';\n }\n\n /**\n * Create the appropriate transport for the server config\n */\n private async createTransport(): Promise<Transport> {\n if (this.config.transport === 'stdio') {\n return this.createStdioTransport(this.config);\n }\n\n // HTTP/SSE transports would be added here\n throw new McpError(\n `Unsupported transport type: ${this.config.transport}`,\n 'invalid_config',\n this.serverName\n );\n }\n\n /**\n * Create a stdio transport for local MCP servers\n */\n private createStdioTransport(config: StdioServerConfig): Transport {\n const params: {\n command: string;\n args?: string[];\n env?: Record<string, string>;\n cwd?: string;\n } = {\n command: config.command,\n };\n\n if (config.args) {\n params.args = config.args;\n }\n if (config.env) {\n params.env = config.env;\n }\n if (config.cwd) {\n params.cwd = config.cwd;\n }\n\n return new StdioClientTransport(params);\n }\n\n /**\n * Parse server capabilities into our format\n */\n private parseCapabilities(capabilities?: Record<string, unknown>): McpCapabilities | undefined {\n if (!capabilities) return undefined;\n\n return {\n tools: !!capabilities.tools,\n resources: !!capabilities.resources,\n prompts: !!capabilities.prompts,\n logging: !!capabilities.logging,\n };\n }\n\n /**\n * Ensure the client is connected and return the client instance\n */\n private ensureConnected(): Client {\n if (!this.client || !this.isConnected()) {\n throw new McpError(\n `Not connected to MCP server \"${this.serverName}\"`,\n 'connection_closed',\n this.serverName\n );\n }\n return this.client;\n }\n\n /**\n * Set server info (for mock/testing purposes)\n */\n protected setServerInfo(info: McpServerInfo): void {\n this._serverInfo = info;\n }\n}\n\n/**\n * Create a mock MCP client for testing\n */\nexport function createMockMcpClient(\n serverName: string,\n tools: McpTool[] = [],\n resources: McpResource[] = []\n): McpClient {\n // Create a client with in-memory transport for testing\n const client = new McpClient(serverName, { transport: 'stdio', command: 'mock' });\n\n // Store mock data\n const mockTools = tools;\n const mockResources = resources;\n\n // Override connect to set up mock state\n client.connect = async function (this: McpClient) {\n const info: McpServerInfo = {\n name: serverName,\n version: '1.0.0',\n connected: true,\n capabilities: { tools: true, resources: true },\n };\n (this as McpClient & { setServerInfo(info: McpServerInfo): void }).setServerInfo(info);\n };\n\n client.listTools = async function () {\n return mockTools;\n };\n\n client.listResources = async function () {\n return mockResources;\n };\n\n return client;\n}\n","/**\n * MCP Server Discovery\n *\n * Discovers and loads MCP server configurations from various sources.\n */\n\nimport { existsSync, readFileSync } from 'fs';\nimport { join, dirname } from 'path';\nimport { homedir } from 'os';\nimport type {\n McpConfigFile,\n McpServerConfig,\n McpServerDefinition,\n StdioServerConfig,\n HttpServerConfig,\n} from './types.js';\nimport { McpError } from './types.js';\n\n/**\n * Options for discovering MCP servers\n */\nexport interface DiscoveryOptions {\n /**\n * Project root directory to search from\n */\n projectRoot?: string;\n\n /**\n * Whether to include global config from home directory\n */\n includeGlobal?: boolean;\n\n /**\n * Additional config file paths to check\n */\n additionalPaths?: string[];\n}\n\n/**\n * Known config file locations\n */\nconst CONFIG_FILENAMES = ['mcp.json', '.mcp.json', 'claude_desktop_config.json'];\n\nconst PROJECT_CONFIG_DIRS = ['.claude', '.config', ''];\n\n/**\n * Discover MCP servers from configuration files\n */\nexport function discoverMcpServers(options: DiscoveryOptions = {}): McpServerDefinition[] {\n const projectRoot = options.projectRoot ?? process.cwd();\n const includeGlobal = options.includeGlobal ?? true;\n const additionalPaths = options.additionalPaths ?? [];\n\n const servers: McpServerDefinition[] = [];\n const seenServers = new Set<string>();\n\n // Build list of config file paths to check\n const configPaths: string[] = [];\n\n // Project-level configs (highest priority)\n for (const dir of PROJECT_CONFIG_DIRS) {\n for (const filename of CONFIG_FILENAMES) {\n const path = dir ? join(projectRoot, dir, filename) : join(projectRoot, filename);\n configPaths.push(path);\n }\n }\n\n // Additional paths\n configPaths.push(...additionalPaths);\n\n // Global config (lowest priority)\n if (includeGlobal) {\n const homeDir = homedir();\n const globalPaths = [\n join(homeDir, '.config', 'claude', 'mcp.json'),\n join(homeDir, '.claude', 'mcp.json'),\n join(homeDir, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json'),\n ];\n configPaths.push(...globalPaths);\n }\n\n // Load servers from each config file (earlier files take precedence)\n for (const configPath of configPaths) {\n if (!existsSync(configPath)) continue;\n\n try {\n const fileServers = loadServersFromFile(configPath);\n\n for (const server of fileServers) {\n // Skip if we already have a server with this name\n if (seenServers.has(server.name)) continue;\n\n seenServers.add(server.name);\n servers.push(server);\n }\n } catch (error) {\n // Log warning but continue with other files\n console.warn(\n `Warning: Failed to load MCP config from ${configPath}: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n return servers;\n}\n\n/**\n * Load MCP servers from a config file\n */\nexport function loadServersFromFile(filePath: string): McpServerDefinition[] {\n if (!existsSync(filePath)) {\n throw new McpError(`Config file not found: ${filePath}`, 'invalid_config');\n }\n\n const content = readFileSync(filePath, 'utf-8');\n let config: McpConfigFile;\n\n try {\n config = JSON.parse(content);\n } catch (error) {\n throw new McpError(\n `Invalid JSON in config file ${filePath}: ${error instanceof Error ? error.message : String(error)}`,\n 'invalid_config',\n undefined,\n error instanceof Error ? error : undefined\n );\n }\n\n return parseServersFromConfig(config, filePath);\n}\n\n/**\n * Parse server definitions from config object\n */\nexport function parseServersFromConfig(\n config: McpConfigFile,\n sourcePath?: string\n): McpServerDefinition[] {\n const servers: McpServerDefinition[] = [];\n\n if (!config.mcpServers) {\n return servers;\n }\n\n for (const [name, serverConfig] of Object.entries(config.mcpServers)) {\n try {\n const validConfig = validateServerConfig(serverConfig, name);\n\n // Resolve relative paths for stdio commands\n if (validConfig.transport === 'stdio' && sourcePath) {\n validConfig.cwd = validConfig.cwd ?? dirname(sourcePath);\n }\n\n servers.push({\n name,\n config: validConfig,\n enabled: true,\n });\n } catch (error) {\n console.warn(\n `Warning: Invalid server config for \"${name}\": ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n return servers;\n}\n\n/**\n * Validate and normalize a server configuration\n */\nexport function validateServerConfig(config: unknown, serverName: string): McpServerConfig {\n if (!config || typeof config !== 'object') {\n throw new McpError(\n `Server config for \"${serverName}\" must be an object`,\n 'invalid_config',\n serverName\n );\n }\n\n const cfg = config as Record<string, unknown>;\n\n // Determine transport type\n // If 'command' exists, it's stdio\n // If 'url' exists, it's http/sse\n // Otherwise check explicit 'transport' field\n\n if ('command' in cfg && typeof cfg.command === 'string') {\n return validateStdioConfig(cfg, serverName);\n }\n\n if ('url' in cfg && typeof cfg.url === 'string') {\n return validateHttpConfig(cfg, serverName);\n }\n\n // Check explicit transport\n if ('transport' in cfg) {\n const transport = cfg.transport;\n if (transport === 'stdio') {\n return validateStdioConfig(cfg, serverName);\n }\n if (transport === 'http' || transport === 'sse') {\n return validateHttpConfig(cfg, serverName);\n }\n throw new McpError(\n `Unknown transport type \"${transport}\" for server \"${serverName}\"`,\n 'invalid_config',\n serverName\n );\n }\n\n throw new McpError(\n `Server config for \"${serverName}\" must have either 'command' (stdio) or 'url' (http)`,\n 'invalid_config',\n serverName\n );\n}\n\n/**\n * Validate stdio server configuration\n */\nfunction validateStdioConfig(cfg: Record<string, unknown>, serverName: string): StdioServerConfig {\n if (!cfg.command || typeof cfg.command !== 'string') {\n throw new McpError(\n `Server \"${serverName}\" requires a 'command' string`,\n 'invalid_config',\n serverName\n );\n }\n\n const config: StdioServerConfig = {\n transport: 'stdio',\n command: cfg.command,\n };\n\n if (cfg.args !== undefined) {\n if (!Array.isArray(cfg.args) || !cfg.args.every((a) => typeof a === 'string')) {\n throw new McpError(\n `Server \"${serverName}\" 'args' must be an array of strings`,\n 'invalid_config',\n serverName\n );\n }\n config.args = cfg.args;\n }\n\n if (cfg.env !== undefined) {\n if (typeof cfg.env !== 'object' || cfg.env === null) {\n throw new McpError(\n `Server \"${serverName}\" 'env' must be an object`,\n 'invalid_config',\n serverName\n );\n }\n config.env = cfg.env as Record<string, string>;\n }\n\n if (cfg.cwd !== undefined) {\n if (typeof cfg.cwd !== 'string') {\n throw new McpError(\n `Server \"${serverName}\" 'cwd' must be a string`,\n 'invalid_config',\n serverName\n );\n }\n config.cwd = cfg.cwd;\n }\n\n return config;\n}\n\n/**\n * Validate HTTP/SSE server configuration\n */\nfunction validateHttpConfig(cfg: Record<string, unknown>, serverName: string): HttpServerConfig {\n if (!cfg.url || typeof cfg.url !== 'string') {\n throw new McpError(\n `Server \"${serverName}\" requires a 'url' string`,\n 'invalid_config',\n serverName\n );\n }\n\n // Validate URL\n try {\n new URL(cfg.url);\n } catch {\n throw new McpError(\n `Server \"${serverName}\" has invalid URL: ${cfg.url}`,\n 'invalid_config',\n serverName\n );\n }\n\n const transport = cfg.transport === 'sse' ? 'sse' : 'http';\n\n const config: HttpServerConfig = {\n transport,\n url: cfg.url,\n };\n\n if (cfg.headers !== undefined) {\n if (typeof cfg.headers !== 'object' || cfg.headers === null) {\n throw new McpError(\n `Server \"${serverName}\" 'headers' must be an object`,\n 'invalid_config',\n serverName\n );\n }\n config.headers = cfg.headers as Record<string, string>;\n }\n\n return config;\n}\n\n/**\n * Find an MCP config file in the project\n */\nexport function findMcpConfigFile(projectRoot?: string): string | null {\n const root = projectRoot ?? process.cwd();\n\n for (const dir of PROJECT_CONFIG_DIRS) {\n for (const filename of CONFIG_FILENAMES) {\n const path = dir ? join(root, dir, filename) : join(root, filename);\n if (existsSync(path)) {\n return path;\n }\n }\n }\n\n return null;\n}\n\n/**\n * Get the default MCP config path for a project\n */\nexport function getDefaultMcpConfigPath(projectRoot?: string): string {\n const root = projectRoot ?? process.cwd();\n return join(root, '.claude', 'mcp.json');\n}\n","/**\n * Native GitHub Adapter\n *\n * Implements GitProviderAdapter using the GitHub CLI (gh).\n * Requires the gh CLI to be installed and authenticated.\n */\n\nimport { execFile } from 'child_process';\nimport { promisify } from 'util';\nimport type { GitProviderAdapter } from '../interfaces.js';\nimport type {\n AdapterInfo,\n PullRequest,\n PullRequestQuery,\n CreatePullRequestData,\n Review,\n CreateReviewData,\n PullRequestStatus,\n ReviewDecision,\n} from '../types.js';\nimport { AdapterError } from '../types.js';\n\nconst execFileAsync = promisify(execFile);\n\n/**\n * Options for creating a GitHub adapter\n */\nexport interface GitHubAdapterOptions {\n /**\n * Repository in owner/repo format\n */\n repository: string;\n\n /**\n * Path to gh CLI (default: 'gh')\n */\n ghPath?: string;\n}\n\n/**\n * Native GitHub adapter using gh CLI\n */\nexport class GitHubAdapter implements GitProviderAdapter {\n private repository: string;\n private ghPath: string;\n private connected = false;\n private owner: string;\n private repo: string;\n\n constructor(options: GitHubAdapterOptions) {\n this.repository = options.repository;\n this.ghPath = options.ghPath ?? 'gh';\n\n const [owner, repo] = this.repository.split('/');\n if (!owner || !repo) {\n throw new AdapterError(\n `Invalid repository format: ${this.repository}. Expected owner/repo`,\n 'invalid_config',\n this.getInfo()\n );\n }\n this.owner = owner;\n this.repo = repo;\n }\n\n /**\n * Get adapter info\n */\n getInfo(): AdapterInfo {\n return {\n type: 'git',\n provider: 'github',\n implementation: 'native',\n connected: this.connected,\n };\n }\n\n /**\n * Check if connected\n */\n isConnected(): boolean {\n return this.connected;\n }\n\n /**\n * Connect (verify gh CLI is available and authenticated)\n */\n async connect(): Promise<void> {\n try {\n // Check gh is installed and authenticated\n await this.gh(['auth', 'status']);\n\n // Verify we can access the repository\n await this.gh(['repo', 'view', this.repository, '--json', 'name']);\n\n this.connected = true;\n } catch (error) {\n throw new AdapterError(\n `Failed to connect to GitHub: ${error instanceof Error ? error.message : String(error)}`,\n 'connection_failed',\n this.getInfo(),\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /**\n * Disconnect\n */\n async disconnect(): Promise<void> {\n this.connected = false;\n }\n\n /**\n * Get a pull request by number\n */\n async getPullRequest(idOrNumber: string | number): Promise<PullRequest> {\n this.ensureConnected();\n\n try {\n const result = await this.gh([\n 'pr',\n 'view',\n String(idOrNumber),\n '-R',\n this.repository,\n '--json',\n 'number,title,body,state,author,headRefName,baseRefName,createdAt,updatedAt,mergedAt,url,reviewRequests',\n ]);\n\n const data = JSON.parse(result);\n return this.mapPullRequest(data);\n } catch (error) {\n if (this.isNotFoundError(error)) {\n throw new AdapterError(\n `Pull request #${idOrNumber} not found`,\n 'not_found',\n this.getInfo()\n );\n }\n throw this.wrapError(error, `Failed to get pull request #${idOrNumber}`);\n }\n }\n\n /**\n * List pull requests\n */\n async listPullRequests(query?: PullRequestQuery): Promise<PullRequest[]> {\n this.ensureConnected();\n\n try {\n const args = [\n 'pr',\n 'list',\n '-R',\n this.repository,\n '--json',\n 'number,title,body,state,author,headRefName,baseRefName,createdAt,updatedAt,url',\n ];\n\n // Map status to gh CLI state\n if (query?.status) {\n const states = Array.isArray(query.status) ? query.status : [query.status];\n const ghStates = states\n .map((s) => this.mapStatusToGh(s))\n .filter((s): s is string => s !== undefined);\n if (ghStates.length > 0 && ghStates[0]) {\n args.push('--state', ghStates[0]);\n }\n }\n\n if (query?.author) {\n args.push('--author', query.author);\n }\n\n if (query?.limit) {\n args.push('--limit', String(query.limit));\n }\n\n const result = await this.gh(args);\n const data = JSON.parse(result) as unknown[];\n\n return data.map((pr) => this.mapPullRequest(pr as Record<string, unknown>));\n } catch (error) {\n throw this.wrapError(error, 'Failed to list pull requests');\n }\n }\n\n /**\n * Create a pull request\n */\n async createPullRequest(data: CreatePullRequestData): Promise<PullRequest> {\n this.ensureConnected();\n\n try {\n const args = [\n 'pr',\n 'create',\n '-R',\n this.repository,\n '--head',\n data.source_branch,\n '--base',\n data.target_branch,\n '--title',\n data.title,\n ];\n\n if (data.description) {\n args.push('--body', data.description);\n }\n\n if (data.draft) {\n args.push('--draft');\n }\n\n if (data.reviewers && data.reviewers.length > 0) {\n args.push('--reviewer', data.reviewers.join(','));\n }\n\n // Create and get the PR details\n const createResult = await this.gh(args);\n\n // Parse the URL from the output to get the PR number\n const urlMatch = createResult.match(/https:\\/\\/github\\.com\\/[^/]+\\/[^/]+\\/pull\\/(\\d+)/);\n if (urlMatch?.[1]) {\n return this.getPullRequest(parseInt(urlMatch[1], 10));\n }\n\n // Fallback: list to find the just-created PR\n const prs = await this.listPullRequests({ limit: 1 });\n const firstPr = prs[0];\n if (firstPr) {\n return firstPr;\n }\n\n throw new Error('Failed to retrieve created pull request');\n } catch (error) {\n throw this.wrapError(error, 'Failed to create pull request');\n }\n }\n\n /**\n * Update a pull request\n */\n async updatePullRequest(\n idOrNumber: string | number,\n data: Partial<CreatePullRequestData>\n ): Promise<PullRequest> {\n this.ensureConnected();\n\n try {\n const args = ['pr', 'edit', String(idOrNumber), '-R', this.repository];\n\n if (data.title) {\n args.push('--title', data.title);\n }\n\n if (data.description !== undefined) {\n args.push('--body', data.description);\n }\n\n if (data.target_branch) {\n args.push('--base', data.target_branch);\n }\n\n if (data.reviewers && data.reviewers.length > 0) {\n args.push('--add-reviewer', data.reviewers.join(','));\n }\n\n await this.gh(args);\n\n return this.getPullRequest(idOrNumber);\n } catch (error) {\n throw this.wrapError(error, `Failed to update pull request #${idOrNumber}`);\n }\n }\n\n /**\n * Merge a pull request\n */\n async mergePullRequest(\n idOrNumber: string | number,\n options?: { method?: 'merge' | 'squash' | 'rebase'; message?: string }\n ): Promise<void> {\n this.ensureConnected();\n\n try {\n const args = ['pr', 'merge', String(idOrNumber), '-R', this.repository];\n\n const method = options?.method ?? 'merge';\n args.push(`--${method}`);\n\n if (options?.message) {\n args.push('--body', options.message);\n }\n\n // Auto-confirm the merge\n args.push('--delete-branch=false');\n\n await this.gh(args);\n } catch (error) {\n throw this.wrapError(error, `Failed to merge pull request #${idOrNumber}`);\n }\n }\n\n /**\n * Close a pull request\n */\n async closePullRequest(idOrNumber: string | number): Promise<void> {\n this.ensureConnected();\n\n try {\n await this.gh(['pr', 'close', String(idOrNumber), '-R', this.repository]);\n } catch (error) {\n throw this.wrapError(error, `Failed to close pull request #${idOrNumber}`);\n }\n }\n\n /**\n * Add a review to a pull request\n */\n async addReview(idOrNumber: string | number, review: CreateReviewData): Promise<Review> {\n this.ensureConnected();\n\n try {\n const args = ['pr', 'review', String(idOrNumber), '-R', this.repository];\n\n // Map decision to gh CLI flag\n switch (review.decision) {\n case 'approve':\n args.push('--approve');\n break;\n case 'request_changes':\n args.push('--request-changes');\n break;\n case 'comment':\n args.push('--comment');\n break;\n }\n\n if (review.body) {\n args.push('--body', review.body);\n }\n\n await this.gh(args);\n\n // Return the review data (gh doesn't return review ID)\n const reviewResult: Review = {\n id: `review-${Date.now()}`,\n pull_request_id: String(idOrNumber),\n author: 'current-user',\n decision: review.decision,\n body: review.body ?? '',\n created_at: new Date().toISOString(),\n };\n return reviewResult;\n } catch (error) {\n throw this.wrapError(error, `Failed to add review to pull request #${idOrNumber}`);\n }\n }\n\n /**\n * Get reviews for a pull request\n */\n async getReviews(idOrNumber: string | number): Promise<Review[]> {\n this.ensureConnected();\n\n try {\n const result = await this.gh([\n 'pr',\n 'view',\n String(idOrNumber),\n '-R',\n this.repository,\n '--json',\n 'reviews',\n ]);\n\n const data = JSON.parse(result);\n const reviews = data.reviews || [];\n\n return reviews.map((r: Record<string, unknown>) => ({\n id: String(r.id || `review-${Date.now()}`),\n pull_request_id: String(idOrNumber),\n author: (r.author as { login?: string })?.login || 'unknown',\n decision: this.mapGhStateToDecision(String(r.state || 'COMMENTED')),\n body: String(r.body || ''),\n created_at: String(r.submittedAt || new Date().toISOString()),\n }));\n } catch (error) {\n throw this.wrapError(error, `Failed to get reviews for pull request #${idOrNumber}`);\n }\n }\n\n /**\n * Request reviewers for a pull request\n */\n async requestReviewers(idOrNumber: string | number, reviewers: string[]): Promise<void> {\n this.ensureConnected();\n\n try {\n await this.gh([\n 'pr',\n 'edit',\n String(idOrNumber),\n '-R',\n this.repository,\n '--add-reviewer',\n reviewers.join(','),\n ]);\n } catch (error) {\n throw this.wrapError(error, `Failed to request reviewers for pull request #${idOrNumber}`);\n }\n }\n\n /**\n * Add a comment to a pull request\n */\n async addPullRequestComment(idOrNumber: string | number, comment: string): Promise<void> {\n this.ensureConnected();\n\n try {\n await this.gh([\n 'pr',\n 'comment',\n String(idOrNumber),\n '-R',\n this.repository,\n '--body',\n comment,\n ]);\n } catch (error) {\n throw this.wrapError(error, `Failed to add comment to pull request #${idOrNumber}`);\n }\n }\n\n /**\n * Get the diff for a pull request\n */\n async getPullRequestDiff(idOrNumber: string | number): Promise<string> {\n this.ensureConnected();\n\n try {\n return await this.gh(['pr', 'diff', String(idOrNumber), '-R', this.repository]);\n } catch (error) {\n throw this.wrapError(error, `Failed to get diff for pull request #${idOrNumber}`);\n }\n }\n\n /**\n * Get files changed in a pull request\n */\n async getPullRequestFiles(idOrNumber: string | number): Promise<string[]> {\n this.ensureConnected();\n\n try {\n const result = await this.gh([\n 'pr',\n 'view',\n String(idOrNumber),\n '-R',\n this.repository,\n '--json',\n 'files',\n ]);\n\n const data = JSON.parse(result);\n const files = data.files || [];\n\n return files.map((f: { path?: string }) => f.path || '');\n } catch (error) {\n throw this.wrapError(error, `Failed to get files for pull request #${idOrNumber}`);\n }\n }\n\n /**\n * Execute gh CLI command\n */\n private async gh(args: string[]): Promise<string> {\n try {\n const { stdout } = await execFileAsync(this.ghPath, args, {\n maxBuffer: 10 * 1024 * 1024, // 10MB\n });\n return stdout;\n } catch (error) {\n const execError = error as { stderr?: string; message?: string };\n throw new Error(execError.stderr || execError.message || 'Unknown gh error');\n }\n }\n\n /**\n * Ensure adapter is connected\n */\n private ensureConnected(): void {\n if (!this.connected) {\n throw new AdapterError(\n 'GitHub adapter is not connected. Call connect() first.',\n 'not_connected',\n this.getInfo()\n );\n }\n }\n\n /**\n * Map gh PR data to PullRequest type\n */\n private mapPullRequest(data: Record<string, unknown>): PullRequest {\n const pr: PullRequest = {\n id: String(data.number),\n number: Number(data.number),\n title: String(data.title || ''),\n source_branch: String(data.headRefName || ''),\n target_branch: String(data.baseRefName || ''),\n status: this.mapGhStateToPrStatus(String(data.state || 'OPEN')),\n };\n\n if (data.body) {\n pr.description = String(data.body);\n }\n\n if (data.author && typeof data.author === 'object') {\n const login = (data.author as { login?: string }).login;\n if (login) {\n pr.author = login;\n }\n }\n\n if (data.createdAt) {\n pr.created_at = String(data.createdAt);\n }\n\n if (data.updatedAt) {\n pr.updated_at = String(data.updatedAt);\n }\n\n if (data.mergedAt) {\n pr.merged_at = String(data.mergedAt);\n }\n\n if (data.url) {\n pr.url = String(data.url);\n }\n\n if (data.reviewRequests && Array.isArray(data.reviewRequests)) {\n pr.reviewers = data.reviewRequests\n .map((r: { login?: string }) => r.login || '')\n .filter(Boolean);\n }\n\n return pr;\n }\n\n /**\n * Map gh state to PullRequestStatus\n */\n private mapGhStateToPrStatus(state: string): PullRequestStatus {\n switch (state.toUpperCase()) {\n case 'OPEN':\n return 'open';\n case 'CLOSED':\n return 'closed';\n case 'MERGED':\n return 'merged';\n default:\n return 'open';\n }\n }\n\n /**\n * Map PullRequestStatus to gh CLI state\n */\n private mapStatusToGh(status: PullRequestStatus): string | undefined {\n switch (status) {\n case 'open':\n return 'open';\n case 'closed':\n return 'closed';\n case 'merged':\n return 'merged';\n default:\n return undefined;\n }\n }\n\n /**\n * Map gh review state to ReviewDecision\n */\n private mapGhStateToDecision(state: string): ReviewDecision {\n switch (state.toUpperCase()) {\n case 'APPROVED':\n return 'approve';\n case 'CHANGES_REQUESTED':\n return 'request_changes';\n case 'COMMENTED':\n default:\n return 'comment';\n }\n }\n\n /**\n * Check if error is a not found error\n */\n private isNotFoundError(error: unknown): boolean {\n const message = error instanceof Error ? error.message : String(error);\n return message.includes('Could not resolve') || message.includes('not found');\n }\n\n /**\n * Wrap error in AdapterError\n */\n private wrapError(error: unknown, message: string): AdapterError {\n return new AdapterError(\n `${message}: ${error instanceof Error ? error.message : String(error)}`,\n 'operation_failed',\n this.getInfo(),\n error instanceof Error ? error : undefined\n );\n }\n}\n\n/**\n * Create a GitHub adapter\n */\nexport function createGitHubAdapter(options: GitHubAdapterOptions): GitHubAdapter {\n return new GitHubAdapter(options);\n}\n","/**\n * Cache Types\n *\n * Type definitions for the shared context cache system.\n */\n\n/**\n * Source type for cached content\n */\nexport type CacheSource = 'confluence' | 'github' | 'notion' | 'local' | 'custom';\n\n/**\n * Cache entry status\n */\nexport type CacheStatus = 'valid' | 'stale' | 'expired' | 'error';\n\n/**\n * Metadata for a cached entry\n */\nexport interface CacheMetadata {\n /**\n * Unique key for this cache entry\n */\n key: string;\n\n /**\n * Source provider (e.g., 'confluence', 'github')\n */\n source: CacheSource;\n\n /**\n * Original source URL or identifier\n */\n sourceUrl: string;\n\n /**\n * When the content was cached\n */\n cachedAt: string;\n\n /**\n * When the content expires (ISO date string)\n */\n expiresAt: string;\n\n /**\n * ETag or version hash from source (for conditional fetching)\n */\n etag?: string;\n\n /**\n * Content hash for integrity checking\n */\n contentHash: string;\n\n /**\n * Size in bytes\n */\n size: number;\n\n /**\n * Content type (e.g., 'text/markdown', 'application/json')\n */\n contentType: string;\n\n /**\n * Original title or name\n */\n title?: string;\n\n /**\n * Last modified timestamp from source\n */\n lastModified?: string;\n\n /**\n * Custom tags for categorization\n */\n tags?: string[];\n}\n\n/**\n * A cached content entry\n */\nexport interface CacheEntry<T = string> {\n /**\n * Entry metadata\n */\n metadata: CacheMetadata;\n\n /**\n * The cached content\n */\n content: T;\n}\n\n/**\n * Options for cache operations\n */\nexport interface CacheOptions {\n /**\n * Time-to-live in seconds (default: 3600 = 1 hour)\n */\n ttl?: number;\n\n /**\n * Force refresh even if cached\n */\n forceRefresh?: boolean;\n\n /**\n * Skip cache and fetch directly\n */\n skipCache?: boolean;\n\n /**\n * Custom tags to apply\n */\n tags?: string[];\n}\n\n/**\n * Options for listing cache entries\n */\nexport interface CacheListOptions {\n /**\n * Filter by source\n */\n source?: CacheSource;\n\n /**\n * Filter by tag\n */\n tag?: string;\n\n /**\n * Filter by status\n */\n status?: CacheStatus;\n\n /**\n * Maximum entries to return\n */\n limit?: number;\n}\n\n/**\n * Cache statistics\n */\nexport interface CacheStats {\n /**\n * Total number of entries\n */\n totalEntries: number;\n\n /**\n * Total size in bytes\n */\n totalSize: number;\n\n /**\n * Number of valid entries\n */\n validEntries: number;\n\n /**\n * Number of stale entries\n */\n staleEntries: number;\n\n /**\n * Number of expired entries\n */\n expiredEntries: number;\n\n /**\n * Entries by source\n */\n bySource: Record<CacheSource, number>;\n\n /**\n * Oldest entry timestamp\n */\n oldestEntry?: string;\n\n /**\n * Newest entry timestamp\n */\n newestEntry?: string;\n}\n\n/**\n * Result of a sync operation\n */\nexport interface SyncResult {\n /**\n * Number of entries added\n */\n added: number;\n\n /**\n * Number of entries updated\n */\n updated: number;\n\n /**\n * Number of entries removed\n */\n removed: number;\n\n /**\n * Number of entries that failed to sync\n */\n failed: number;\n\n /**\n * Error messages for failed entries\n */\n errors: { key: string; error: string }[];\n\n /**\n * Duration of sync in milliseconds\n */\n duration: number;\n}\n\n/**\n * Cache error codes\n */\nexport type CacheErrorCode =\n | 'not_found'\n | 'expired'\n | 'invalid_key'\n | 'write_failed'\n | 'read_failed'\n | 'fetch_failed'\n | 'invalid_config'\n | 'storage_full';\n\n/**\n * Cache-specific error\n */\nexport class CacheError extends Error {\n constructor(\n message: string,\n public readonly code: CacheErrorCode,\n public readonly key?: string,\n public override readonly cause?: Error\n ) {\n super(message);\n this.name = 'CacheError';\n }\n}\n\n/**\n * Default cache directory paths\n */\nexport const CACHE_PATHS = {\n /**\n * Root cache directory (relative to project root)\n */\n ROOT: '.coreai/cache',\n\n /**\n * Content storage directory\n */\n CONTENT: '.coreai/cache/content',\n\n /**\n * Metadata storage directory\n */\n METADATA: '.coreai/cache/metadata',\n\n /**\n * Index file for fast lookups\n */\n INDEX: '.coreai/cache/index.json',\n\n /**\n * Lock file for concurrent access\n */\n LOCK: '.coreai/cache/.lock',\n} as const;\n\n/**\n * Default cache configuration\n */\nexport const DEFAULT_CACHE_CONFIG = {\n /**\n * Default TTL in seconds (1 hour)\n */\n ttl: 3600,\n\n /**\n * Maximum cache size in bytes (100MB)\n */\n maxSize: 100 * 1024 * 1024,\n\n /**\n * Maximum number of entries\n */\n maxEntries: 1000,\n\n /**\n * Enable automatic cleanup of expired entries\n */\n autoCleanup: true,\n\n /**\n * Cleanup interval in seconds (1 hour)\n */\n cleanupInterval: 3600,\n} as const;\n","/**\n * File-based Cache Provider\n *\n * Implements CacheProvider using the local filesystem.\n * Stores content in files with separate metadata JSON files.\n */\n\nimport { promises as fs } from 'fs';\nimport { join, dirname } from 'path';\nimport { createHash } from 'crypto';\nimport type {\n CacheEntry,\n CacheMetadata,\n CacheOptions,\n CacheListOptions,\n CacheStats,\n CacheStatus,\n CacheSource,\n} from './types.js';\nimport { CacheError, CACHE_PATHS, DEFAULT_CACHE_CONFIG } from './types.js';\nimport type { CacheProvider } from './interfaces.js';\n\n/**\n * No-op function for ignoring errors\n */\nfunction noop(): void {\n // Intentionally empty\n}\n\n/**\n * Options for creating a file cache provider\n */\nexport interface FileCacheProviderOptions {\n /**\n * Base path for cache storage (project root)\n */\n basePath: string;\n\n /**\n * Default TTL in seconds\n */\n ttl?: number;\n\n /**\n * Maximum cache size in bytes\n */\n maxSize?: number;\n\n /**\n * Maximum number of entries\n */\n maxEntries?: number;\n}\n\n/**\n * Cache index structure for fast lookups\n */\ninterface CacheIndex {\n version: number;\n entries: Record<string, CacheIndexEntry>;\n stats: {\n totalSize: number;\n entryCount: number;\n lastCleanup: string | null;\n };\n}\n\n/**\n * Index entry for quick access\n */\ninterface CacheIndexEntry {\n key: string;\n source: CacheSource;\n cachedAt: string;\n expiresAt: string;\n size: number;\n contentFile: string;\n metadataFile: string;\n}\n\nconst INDEX_VERSION = 1;\n\n/**\n * File-based cache provider implementation\n */\nexport class FileCacheProvider implements CacheProvider {\n private basePath: string;\n private cachePath: string;\n private contentPath: string;\n private metadataPath: string;\n private indexPath: string;\n private ttl: number;\n private maxSize: number;\n private maxEntries: number;\n private initialized = false;\n private index: CacheIndex | null = null;\n\n constructor(options: FileCacheProviderOptions) {\n this.basePath = options.basePath;\n this.cachePath = join(this.basePath, CACHE_PATHS.ROOT);\n this.contentPath = join(this.basePath, CACHE_PATHS.CONTENT);\n this.metadataPath = join(this.basePath, CACHE_PATHS.METADATA);\n this.indexPath = join(this.basePath, CACHE_PATHS.INDEX);\n this.ttl = options.ttl ?? DEFAULT_CACHE_CONFIG.ttl;\n this.maxSize = options.maxSize ?? DEFAULT_CACHE_CONFIG.maxSize;\n this.maxEntries = options.maxEntries ?? DEFAULT_CACHE_CONFIG.maxEntries;\n }\n\n /**\n * Initialize the cache (create directories, load index)\n */\n async initialize(): Promise<void> {\n if (this.initialized) return;\n\n try {\n // Create cache directories\n await fs.mkdir(this.contentPath, { recursive: true });\n await fs.mkdir(this.metadataPath, { recursive: true });\n\n // Load or create index\n this.index = await this.loadIndex();\n\n // Save index to ensure file exists\n await this.saveIndex();\n\n this.initialized = true;\n } catch (error) {\n throw new CacheError(\n `Failed to initialize cache: ${error instanceof Error ? error.message : String(error)}`,\n 'write_failed',\n undefined,\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /**\n * Check if the cache is initialized\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n\n /**\n * Get a cached entry by key\n */\n async get<T = string>(key: string, options?: CacheOptions): Promise<CacheEntry<T> | null> {\n this.ensureInitialized();\n\n if (options?.skipCache) {\n return null;\n }\n\n const indexEntry = this.index?.entries[key];\n if (!indexEntry) {\n return null;\n }\n\n // Check expiration (unless force refresh)\n if (!options?.forceRefresh) {\n const status = this.getEntryStatus(indexEntry);\n if (status === 'expired') {\n return null;\n }\n }\n\n try {\n // Read metadata\n const metadataContent = await fs.readFile(indexEntry.metadataFile, 'utf-8');\n const metadata: CacheMetadata = JSON.parse(metadataContent);\n\n // Read content\n const contentRaw = await fs.readFile(indexEntry.contentFile, 'utf-8');\n let content: T;\n\n // Try to parse as JSON if content type indicates it\n if (metadata.contentType.includes('json')) {\n content = JSON.parse(contentRaw) as T;\n } else {\n content = contentRaw as T;\n }\n\n return { metadata, content };\n } catch {\n // Entry exists in index but files are missing - clean up\n await this.delete(key);\n return null;\n }\n }\n\n /**\n * Get the content only (convenience method)\n */\n async getContent<T = string>(key: string, options?: CacheOptions): Promise<T | null> {\n const entry = await this.get<T>(key, options);\n return entry?.content ?? null;\n }\n\n /**\n * Set a cache entry\n */\n async set<T = string>(\n key: string,\n content: T,\n metadata: Partial<CacheMetadata>,\n options?: CacheOptions\n ): Promise<void> {\n this.ensureInitialized();\n\n const now = new Date();\n const ttl = options?.ttl ?? this.ttl;\n const expiresAt = new Date(now.getTime() + ttl * 1000);\n\n // Serialize content\n const contentStr = typeof content === 'string' ? content : JSON.stringify(content, null, 2);\n const contentHash = this.hashContent(contentStr);\n const size = Buffer.byteLength(contentStr, 'utf-8');\n\n // Generate file paths\n const safeKey = this.sanitizeKey(key);\n const contentFile = join(this.contentPath, `${safeKey}.cache`);\n const metadataFile = join(this.metadataPath, `${safeKey}.json`);\n\n // Build full metadata\n const fullMetadata: CacheMetadata = {\n key,\n source: metadata.source ?? 'custom',\n sourceUrl: metadata.sourceUrl ?? '',\n cachedAt: now.toISOString(),\n expiresAt: expiresAt.toISOString(),\n contentHash,\n size,\n contentType:\n metadata.contentType ?? (typeof content === 'string' ? 'text/plain' : 'application/json'),\n };\n // Conditionally add optional properties\n if (metadata.etag) {\n fullMetadata.etag = metadata.etag;\n }\n if (metadata.title) {\n fullMetadata.title = metadata.title;\n }\n if (metadata.lastModified) {\n fullMetadata.lastModified = metadata.lastModified;\n }\n const tags = options?.tags ?? metadata.tags;\n if (tags) {\n fullMetadata.tags = tags;\n }\n\n try {\n // Ensure directories exist\n await fs.mkdir(dirname(contentFile), { recursive: true });\n await fs.mkdir(dirname(metadataFile), { recursive: true });\n\n // Write files\n await fs.writeFile(contentFile, contentStr, 'utf-8');\n await fs.writeFile(metadataFile, JSON.stringify(fullMetadata, null, 2), 'utf-8');\n\n // Update index\n if (this.index) {\n // Remove old size from stats if updating\n const oldEntry = this.index.entries[key];\n if (oldEntry) {\n this.index.stats.totalSize -= oldEntry.size;\n } else {\n this.index.stats.entryCount++;\n }\n\n this.index.entries[key] = {\n key,\n source: fullMetadata.source,\n cachedAt: fullMetadata.cachedAt,\n expiresAt: fullMetadata.expiresAt,\n size,\n contentFile,\n metadataFile,\n };\n this.index.stats.totalSize += size;\n\n await this.saveIndex();\n }\n } catch (error) {\n throw new CacheError(\n `Failed to write cache entry: ${error instanceof Error ? error.message : String(error)}`,\n 'write_failed',\n key,\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /**\n * Check if a key exists in the cache\n */\n async has(key: string): Promise<boolean> {\n this.ensureInitialized();\n return key in (this.index?.entries ?? {});\n }\n\n /**\n * Delete a cache entry\n */\n async delete(key: string): Promise<boolean> {\n this.ensureInitialized();\n\n const indexEntry = this.index?.entries[key];\n if (!indexEntry) {\n return false;\n }\n\n try {\n // Delete files (ignore if already missing)\n await fs.unlink(indexEntry.contentFile).catch(noop);\n await fs.unlink(indexEntry.metadataFile).catch(noop);\n\n // Update index\n if (this.index) {\n this.index.stats.totalSize -= indexEntry.size;\n this.index.stats.entryCount--;\n // Remove entry from index using destructuring\n const { [key]: _removed, ...remaining } = this.index.entries;\n this.index.entries = remaining;\n await this.saveIndex();\n }\n\n return true;\n } catch (error) {\n throw new CacheError(\n `Failed to delete cache entry: ${error instanceof Error ? error.message : String(error)}`,\n 'write_failed',\n key,\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /**\n * Get the status of a cache entry\n */\n async getStatus(key: string): Promise<CacheStatus | null> {\n this.ensureInitialized();\n\n const indexEntry = this.index?.entries[key];\n if (!indexEntry) {\n return null;\n }\n\n return this.getEntryStatus(indexEntry);\n }\n\n /**\n * Get metadata for a cache entry\n */\n async getMetadata(key: string): Promise<CacheMetadata | null> {\n this.ensureInitialized();\n\n const indexEntry = this.index?.entries[key];\n if (!indexEntry) {\n return null;\n }\n\n try {\n const content = await fs.readFile(indexEntry.metadataFile, 'utf-8');\n return JSON.parse(content);\n } catch {\n return null;\n }\n }\n\n /**\n * Update metadata for a cache entry\n */\n async updateMetadata(key: string, metadata: Partial<CacheMetadata>): Promise<void> {\n this.ensureInitialized();\n\n const existing = await this.getMetadata(key);\n if (!existing) {\n throw new CacheError(`Cache entry not found: ${key}`, 'not_found', key);\n }\n\n const indexEntry = this.index?.entries[key];\n if (!indexEntry) {\n throw new CacheError(`Cache entry not found: ${key}`, 'not_found', key);\n }\n\n const updated: CacheMetadata = {\n ...existing,\n ...metadata,\n key: existing.key, // Can't change key\n };\n\n try {\n await fs.writeFile(indexEntry.metadataFile, JSON.stringify(updated, null, 2), 'utf-8');\n\n // Update index if relevant fields changed\n if (this.index && indexEntry) {\n if (metadata.source) indexEntry.source = metadata.source;\n if (metadata.expiresAt) indexEntry.expiresAt = metadata.expiresAt;\n await this.saveIndex();\n }\n } catch (error) {\n throw new CacheError(\n `Failed to update metadata: ${error instanceof Error ? error.message : String(error)}`,\n 'write_failed',\n key,\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /**\n * List cache entries\n */\n async list(options?: CacheListOptions): Promise<CacheMetadata[]> {\n this.ensureInitialized();\n\n if (!this.index) return [];\n\n let entries = Object.values(this.index.entries);\n\n // Apply filters\n if (options?.source) {\n entries = entries.filter((e) => e.source === options.source);\n }\n\n if (options?.status) {\n entries = entries.filter((e) => this.getEntryStatus(e) === options.status);\n }\n\n // Load full metadata for tag filtering and return\n const metadataPromises = entries.map(async (e) => {\n const metadata = await this.getMetadata(e.key);\n return metadata;\n });\n\n let results = (await Promise.all(metadataPromises)).filter(\n (m): m is CacheMetadata => m !== null\n );\n\n // Filter by tag if specified\n if (options?.tag) {\n const tag = options.tag;\n results = results.filter((m) => m.tags?.includes(tag));\n }\n\n // Apply limit\n if (options?.limit && results.length > options.limit) {\n results = results.slice(0, options.limit);\n }\n\n return results;\n }\n\n /**\n * Get cache statistics\n */\n async getStats(): Promise<CacheStats> {\n this.ensureInitialized();\n\n if (!this.index) {\n return {\n totalEntries: 0,\n totalSize: 0,\n validEntries: 0,\n staleEntries: 0,\n expiredEntries: 0,\n bySource: {\n confluence: 0,\n github: 0,\n notion: 0,\n local: 0,\n custom: 0,\n },\n };\n }\n\n const entries = Object.values(this.index.entries);\n const bySource: Record<CacheSource, number> = {\n confluence: 0,\n github: 0,\n notion: 0,\n local: 0,\n custom: 0,\n };\n\n let validEntries = 0;\n let staleEntries = 0;\n let expiredEntries = 0;\n let oldestEntry: string | undefined;\n let newestEntry: string | undefined;\n\n for (const entry of entries) {\n bySource[entry.source]++;\n\n const status = this.getEntryStatus(entry);\n if (status === 'valid') validEntries++;\n else if (status === 'stale') staleEntries++;\n else if (status === 'expired') expiredEntries++;\n\n if (!oldestEntry || entry.cachedAt < oldestEntry) {\n oldestEntry = entry.cachedAt;\n }\n if (!newestEntry || entry.cachedAt > newestEntry) {\n newestEntry = entry.cachedAt;\n }\n }\n\n const stats: CacheStats = {\n totalEntries: this.index.stats.entryCount,\n totalSize: this.index.stats.totalSize,\n validEntries,\n staleEntries,\n expiredEntries,\n bySource,\n };\n\n if (oldestEntry) stats.oldestEntry = oldestEntry;\n if (newestEntry) stats.newestEntry = newestEntry;\n\n return stats;\n }\n\n /**\n * Clear all cache entries\n */\n async clear(): Promise<number> {\n this.ensureInitialized();\n\n if (!this.index) return 0;\n\n const count = this.index.stats.entryCount;\n\n try {\n // Delete all content and metadata files\n await fs.rm(this.contentPath, { recursive: true, force: true });\n await fs.rm(this.metadataPath, { recursive: true, force: true });\n\n // Recreate directories\n await fs.mkdir(this.contentPath, { recursive: true });\n await fs.mkdir(this.metadataPath, { recursive: true });\n\n // Reset index\n this.index = this.createEmptyIndex();\n await this.saveIndex();\n\n return count;\n } catch (error) {\n throw new CacheError(\n `Failed to clear cache: ${error instanceof Error ? error.message : String(error)}`,\n 'write_failed',\n undefined,\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /**\n * Clear expired entries only\n */\n async clearExpired(): Promise<number> {\n this.ensureInitialized();\n\n if (!this.index) return 0;\n\n const expiredKeys = Object.entries(this.index.entries)\n .filter(([, entry]) => this.getEntryStatus(entry) === 'expired')\n .map(([key]) => key);\n\n for (const key of expiredKeys) {\n await this.delete(key);\n }\n\n if (this.index) {\n this.index.stats.lastCleanup = new Date().toISOString();\n await this.saveIndex();\n }\n\n return expiredKeys.length;\n }\n\n /**\n * Clear entries by source\n */\n async clearBySource(source: string): Promise<number> {\n this.ensureInitialized();\n\n if (!this.index) return 0;\n\n const keys = Object.entries(this.index.entries)\n .filter(([, entry]) => entry.source === source)\n .map(([key]) => key);\n\n for (const key of keys) {\n await this.delete(key);\n }\n\n return keys.length;\n }\n\n /**\n * Clear entries by tag\n */\n async clearByTag(tag: string): Promise<number> {\n this.ensureInitialized();\n\n const entries = await this.list({ tag });\n for (const entry of entries) {\n await this.delete(entry.key);\n }\n\n return entries.length;\n }\n\n // Private helpers\n\n private ensureInitialized(): void {\n if (!this.initialized) {\n throw new CacheError('Cache not initialized. Call initialize() first.', 'invalid_config');\n }\n }\n\n private async loadIndex(): Promise<CacheIndex> {\n try {\n const content = await fs.readFile(this.indexPath, 'utf-8');\n const index = JSON.parse(content) as CacheIndex;\n\n // Validate version\n if (index.version !== INDEX_VERSION) {\n // Index version mismatch - rebuild\n return this.rebuildIndex();\n }\n\n return index;\n } catch {\n // Index doesn't exist or is invalid - create new one\n return this.createEmptyIndex();\n }\n }\n\n private async saveIndex(): Promise<void> {\n if (!this.index) return;\n\n try {\n await fs.writeFile(this.indexPath, JSON.stringify(this.index, null, 2), 'utf-8');\n } catch (error) {\n throw new CacheError(\n `Failed to save cache index: ${error instanceof Error ? error.message : String(error)}`,\n 'write_failed',\n undefined,\n error instanceof Error ? error : undefined\n );\n }\n }\n\n private createEmptyIndex(): CacheIndex {\n return {\n version: INDEX_VERSION,\n entries: {},\n stats: {\n totalSize: 0,\n entryCount: 0,\n lastCleanup: null,\n },\n };\n }\n\n private async rebuildIndex(): Promise<CacheIndex> {\n const index = this.createEmptyIndex();\n\n try {\n const metadataFiles = await fs.readdir(this.metadataPath);\n\n for (const file of metadataFiles) {\n if (!file.endsWith('.json')) continue;\n\n try {\n const metadataPath = join(this.metadataPath, file);\n const content = await fs.readFile(metadataPath, 'utf-8');\n const metadata: CacheMetadata = JSON.parse(content);\n\n const safeKey = this.sanitizeKey(metadata.key);\n const contentFile = join(this.contentPath, `${safeKey}.cache`);\n\n // Verify content file exists\n await fs.access(contentFile);\n\n index.entries[metadata.key] = {\n key: metadata.key,\n source: metadata.source,\n cachedAt: metadata.cachedAt,\n expiresAt: metadata.expiresAt,\n size: metadata.size,\n contentFile,\n metadataFile: metadataPath,\n };\n\n index.stats.totalSize += metadata.size;\n index.stats.entryCount++;\n } catch {\n // Skip invalid entries\n }\n }\n } catch {\n // Metadata directory doesn't exist or is empty\n }\n\n return index;\n }\n\n private getEntryStatus(entry: CacheIndexEntry): CacheStatus {\n const now = new Date();\n const expiresAt = new Date(entry.expiresAt);\n const cachedAt = new Date(entry.cachedAt);\n\n if (now > expiresAt) {\n return 'expired';\n }\n\n // Consider stale if more than 80% of TTL has passed\n const totalTtl = expiresAt.getTime() - cachedAt.getTime();\n const elapsed = now.getTime() - cachedAt.getTime();\n if (elapsed > totalTtl * 0.8) {\n return 'stale';\n }\n\n return 'valid';\n }\n\n private sanitizeKey(key: string): string {\n // Create a safe filename from the key\n return createHash('sha256').update(key).digest('hex').substring(0, 32);\n }\n\n private hashContent(content: string): string {\n return createHash('sha256').update(content).digest('hex');\n }\n}\n\n/**\n * Create a file cache provider\n */\nexport function createFileCacheProvider(options: FileCacheProviderOptions): FileCacheProvider {\n return new FileCacheProvider(options);\n}\n","/**\n * Cache Manager\n *\n * Higher-level cache management that combines caching with remote fetching.\n * Implements cache-first resolution with remote fallback strategy.\n */\n\nimport type { CacheEntry, CacheMetadata, CacheOptions, CacheSource, SyncResult } from './types.js';\nimport { CacheError } from './types.js';\nimport type {\n CacheProvider,\n CacheManager as ICacheManager,\n RemoteFetcher,\n FetchOptions,\n SyncOptions,\n} from './interfaces.js';\n\n/**\n * Options for creating a cache manager\n */\nexport interface CacheManagerOptions {\n /**\n * The underlying cache provider\n */\n cache: CacheProvider;\n\n /**\n * Default TTL in seconds\n */\n defaultTtl?: number;\n\n /**\n * Default source for new entries\n */\n defaultSource?: CacheSource;\n}\n\n/**\n * Cache manager implementation\n *\n * Provides cache-first resolution strategy:\n * 1. Check cache for valid entry\n * 2. If cached and valid, return cached content\n * 3. If stale or missing, fetch from remote\n * 4. Cache the fetched content\n * 5. Return the content\n */\nexport class CacheManager implements ICacheManager {\n private cache: CacheProvider;\n private fetchers = new Map<string, RemoteFetcher>();\n private defaultTtl: number;\n private defaultSource: CacheSource;\n\n constructor(options: CacheManagerOptions) {\n this.cache = options.cache;\n this.defaultTtl = options.defaultTtl ?? 3600;\n this.defaultSource = options.defaultSource ?? 'custom';\n }\n\n /**\n * Get content with cache-first strategy\n */\n async getWithFallback<T = string>(\n key: string,\n url: string,\n options?: CacheOptions & FetchOptions\n ): Promise<CacheEntry<T>> {\n // Try cache first (unless skipCache is set)\n if (!options?.skipCache && !options?.forceRefresh) {\n const cached = await this.cache.get<T>(key);\n if (cached) {\n const status = await this.cache.getStatus(key);\n // Return if valid (not stale or expired)\n if (status === 'valid') {\n return cached;\n }\n // If stale, try to refresh but fall back to stale if fetch fails\n if (status === 'stale') {\n try {\n return await this.fetchAndCache<T>(key, url, options);\n } catch {\n // Return stale content on fetch failure\n return cached;\n }\n }\n }\n }\n\n // Cache miss or forceRefresh - fetch from remote\n return this.fetchAndCache<T>(key, url, options);\n }\n\n /**\n * Sync all entries from a source\n */\n async syncSource(source: string, options?: SyncOptions): Promise<SyncResult> {\n const startTime = Date.now();\n const result: SyncResult = {\n added: 0,\n updated: 0,\n removed: 0,\n failed: 0,\n errors: [],\n duration: 0,\n };\n\n // Get all entries from this source\n const entries = await this.cache.list({ source: source as CacheSource });\n\n // Sync each entry\n const concurrency = options?.concurrency ?? 5;\n const chunks = this.chunkArray(entries, concurrency);\n\n for (const chunk of chunks) {\n const promises = chunk.map(async (entry) => {\n try {\n const fetcher = this.fetchers.get(source);\n if (!fetcher) {\n throw new Error(`No fetcher registered for source: ${source}`);\n }\n\n // Check if content has changed\n const hasChanged = await fetcher.hasChanged(entry.sourceUrl, entry.etag);\n\n if (hasChanged || options?.force) {\n // Fetch and update\n const fetchOptions: FetchOptions = {};\n if (entry.etag) {\n fetchOptions.etag = entry.etag;\n }\n const { content, metadata } = await fetcher.fetch(entry.sourceUrl, fetchOptions);\n\n await this.cache.set(entry.key, content, {\n ...entry,\n ...metadata,\n });\n\n result.updated++;\n }\n } catch (error) {\n result.failed++;\n result.errors.push({\n key: entry.key,\n error: error instanceof Error ? error.message : String(error),\n });\n\n if (!options?.continueOnError) {\n throw error;\n }\n }\n });\n\n await Promise.all(promises);\n }\n\n // Report final progress\n if (options?.onProgress) {\n options.onProgress(entries.length, entries.length);\n }\n\n result.duration = Date.now() - startTime;\n return result;\n }\n\n /**\n * Sync specific entries\n */\n async syncEntries(keys: string[], options?: SyncOptions): Promise<SyncResult> {\n const startTime = Date.now();\n const result: SyncResult = {\n added: 0,\n updated: 0,\n removed: 0,\n failed: 0,\n errors: [],\n duration: 0,\n };\n\n const concurrency = options?.concurrency ?? 5;\n const chunks = this.chunkArray(keys, concurrency);\n\n for (const chunk of chunks) {\n const promises = chunk.map(async (key) => {\n try {\n const metadata = await this.cache.getMetadata(key);\n if (!metadata) {\n result.failed++;\n result.errors.push({ key, error: 'Entry not found in cache' });\n return;\n }\n\n const fetcher = this.fetchers.get(metadata.source);\n if (!fetcher) {\n result.failed++;\n result.errors.push({ key, error: `No fetcher for source: ${metadata.source}` });\n return;\n }\n\n // Check if content has changed\n const hasChanged = await fetcher.hasChanged(metadata.sourceUrl, metadata.etag);\n\n if (hasChanged || options?.force) {\n const fetchOpts: FetchOptions = {};\n if (metadata.etag) {\n fetchOpts.etag = metadata.etag;\n }\n const { content, metadata: newMeta } = await fetcher.fetch(\n metadata.sourceUrl,\n fetchOpts\n );\n\n await this.cache.set(key, content, {\n ...metadata,\n ...newMeta,\n });\n\n result.updated++;\n }\n } catch (error) {\n result.failed++;\n result.errors.push({\n key,\n error: error instanceof Error ? error.message : String(error),\n });\n\n if (!options?.continueOnError) {\n throw error;\n }\n }\n });\n\n await Promise.all(promises);\n }\n\n // Report final progress\n if (options?.onProgress) {\n options.onProgress(keys.length, keys.length);\n }\n\n result.duration = Date.now() - startTime;\n return result;\n }\n\n /**\n * Register a fetcher for a source\n */\n registerFetcher(source: string, fetcher: RemoteFetcher): void {\n this.fetchers.set(source, fetcher);\n }\n\n /**\n * Get the underlying cache provider\n */\n getCache(): CacheProvider {\n return this.cache;\n }\n\n /**\n * Check if a fetcher is registered for a source\n */\n hasFetcher(source: string): boolean {\n return this.fetchers.has(source);\n }\n\n /**\n * Get all registered sources\n */\n getRegisteredSources(): string[] {\n return Array.from(this.fetchers.keys());\n }\n\n // Private helpers\n\n private async fetchAndCache<T>(\n key: string,\n url: string,\n options?: CacheOptions & FetchOptions\n ): Promise<CacheEntry<T>> {\n // Determine source from URL\n const source = this.getSourceFromUrl(url);\n const fetcher = this.fetchers.get(source);\n\n if (!fetcher) {\n throw new CacheError(\n `No fetcher registered for source: ${source}. Register one with registerFetcher().`,\n 'fetch_failed',\n key\n );\n }\n\n try {\n // Fetch from remote\n const fetchOpts: FetchOptions = {};\n if (options?.timeout) {\n fetchOpts.timeout = options.timeout;\n }\n if (options?.headers) {\n fetchOpts.headers = options.headers;\n }\n const { content, metadata } = await fetcher.fetch(url, fetchOpts);\n\n // Build full metadata\n const fullMetadata: Partial<CacheMetadata> = {\n source: source as CacheSource,\n sourceUrl: url,\n contentType: metadata.contentType ?? 'text/plain',\n };\n if (metadata.etag) {\n fullMetadata.etag = metadata.etag;\n }\n if (metadata.title) {\n fullMetadata.title = metadata.title;\n }\n if (metadata.lastModified) {\n fullMetadata.lastModified = metadata.lastModified;\n }\n if (options?.tags) {\n fullMetadata.tags = options.tags;\n }\n\n // Cache the content\n const cacheOpts: CacheOptions = {\n ttl: options?.ttl ?? this.defaultTtl,\n };\n if (options?.tags) {\n cacheOpts.tags = options.tags;\n }\n await this.cache.set(key, content, fullMetadata, cacheOpts);\n\n // Return the entry\n const entry = await this.cache.get<T>(key);\n if (!entry) {\n throw new CacheError('Failed to retrieve cached entry after write', 'read_failed', key);\n }\n\n return entry;\n } catch (error) {\n if (error instanceof CacheError) {\n throw error;\n }\n throw new CacheError(\n `Failed to fetch content: ${error instanceof Error ? error.message : String(error)}`,\n 'fetch_failed',\n key,\n error instanceof Error ? error : undefined\n );\n }\n }\n\n private getSourceFromUrl(url: string): string {\n try {\n const parsed = new URL(url);\n const hostname = parsed.hostname.toLowerCase();\n\n // Map common hostnames to sources\n if (hostname.includes('confluence') || hostname.includes('atlassian.net')) {\n return 'confluence';\n }\n if (hostname.includes('github.com') || hostname.includes('github')) {\n return 'github';\n }\n if (hostname.includes('notion.so') || hostname.includes('notion')) {\n return 'notion';\n }\n\n // Default to custom\n return this.defaultSource;\n } catch {\n // Invalid URL, might be a file path\n return 'local';\n }\n }\n\n private chunkArray<T>(array: T[], size: number): T[][] {\n const chunks: T[][] = [];\n for (let i = 0; i < array.length; i += size) {\n chunks.push(array.slice(i, i + size));\n }\n return chunks;\n }\n}\n\n/**\n * Create a cache manager\n */\nexport function createCacheManager(options: CacheManagerOptions): CacheManager {\n return new CacheManager(options);\n}\n","/**\n * Skill Generator\n *\n * Discovers skill source files from skills/ directory and compiles them\n * to .claude/skills/<name>/SKILL.md format for Claude Code.\n *\n * Source: skills/<category>/<name>/SKILL.md (grouped by category)\n * Output: .claude/skills/<name>/SKILL.md (flat, one level deep)\n */\n\nimport { existsSync, mkdirSync, writeFileSync, readFileSync, readdirSync, statSync } from 'fs';\nimport { join, dirname } from 'path';\nimport type { ResolvedCoreAIConfig } from '../config/types.js';\nimport type {\n SkillTemplate,\n SkillVariables,\n GenerateSkillsOptions,\n GenerateSkillsResult,\n GeneratedSkill,\n SkillDependency,\n SkillCategory,\n} from './types.js';\n\n/**\n * Get the default core skills directory (bundled with CoreAI package)\n */\nexport function getCoreSkillsDir(): string {\n let currentDir = dirname(import.meta.url.replace('file://', ''));\n for (let i = 0; i < 5; i++) {\n if (existsSync(join(currentDir, 'package.json'))) {\n return join(currentDir, 'skills');\n }\n currentDir = dirname(currentDir);\n }\n return join(dirname(dirname(dirname(import.meta.url.replace('file://', '')))), 'skills');\n}\n\n/**\n * Discover skill source files from a skills directory.\n *\n * Scans skills/<category>/<name>/SKILL.md structure.\n * Each category directory (core, git, etc.) contains skill directories.\n */\nexport function discoverSkills(skillsDir: string): SkillTemplate[] {\n const templates: SkillTemplate[] = [];\n\n if (!existsSync(skillsDir)) {\n return templates;\n }\n\n // Scan category directories (core/, git/, etc.)\n const categories = readdirSync(skillsDir);\n\n for (const category of categories) {\n const categoryPath = join(skillsDir, category);\n const stat = statSync(categoryPath);\n if (!stat.isDirectory()) continue;\n\n // Skip hidden/underscore directories\n if (category.startsWith('.') || category.startsWith('_')) continue;\n\n // Scan skill directories within this category\n const skillDirs = readdirSync(categoryPath);\n\n for (const skillName of skillDirs) {\n const skillDir = join(categoryPath, skillName);\n const skillStat = statSync(skillDir);\n if (!skillStat.isDirectory()) continue;\n\n const skillFile = join(skillDir, 'SKILL.md');\n if (!existsSync(skillFile)) continue;\n\n try {\n const content = readFileSync(skillFile, 'utf-8');\n const template = parseSkillFile(skillName, category as SkillCategory, content);\n templates.push(template);\n } catch {\n // Skip invalid skill files\n }\n }\n }\n\n return templates;\n}\n\n/**\n * Parse a SKILL.md file into a SkillTemplate\n */\nexport function parseSkillFile(\n name: string,\n category: SkillCategory,\n content: string\n): SkillTemplate {\n const template: SkillTemplate = {\n name,\n description: name,\n category,\n content,\n };\n\n // Parse frontmatter\n const frontmatterMatch = content.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n/);\n if (!frontmatterMatch) {\n return template;\n }\n\n const frontmatter = frontmatterMatch[1]!;\n const lines = frontmatter.split(/\\r?\\n/);\n const dependencies: SkillDependency[] = [];\n\n for (const line of lines) {\n const colonIndex = line.indexOf(':');\n if (colonIndex === -1) continue;\n\n const key = line.slice(0, colonIndex).trim();\n let value = line.slice(colonIndex + 1).trim();\n\n // Remove quotes\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n\n switch (key) {\n case 'name':\n template.name = value;\n break;\n case 'description':\n template.description = value;\n break;\n case 'argument-hint':\n template.argumentHint = value;\n break;\n case 'requires':\n if (value.startsWith('[') && value.endsWith(']')) {\n const items = value\n .slice(1, -1)\n .split(',')\n .map((s) => s.trim().replace(/['\"]/g, ''));\n for (const item of items) {\n if (item) {\n dependencies.push({\n type: mapIntegrationName(item),\n required: true,\n });\n }\n }\n }\n break;\n case 'optional':\n if (value.startsWith('[') && value.endsWith(']')) {\n const items = value\n .slice(1, -1)\n .split(',')\n .map((s) => s.trim().replace(/['\"]/g, ''));\n for (const item of items) {\n if (item) {\n dependencies.push({\n type: mapIntegrationName(item),\n required: false,\n });\n }\n }\n }\n break;\n }\n }\n\n if (dependencies.length > 0) {\n template.dependencies = dependencies;\n }\n\n return template;\n}\n\n/**\n * Map integration name to adapter type\n */\nfunction mapIntegrationName(name: string): 'issue_tracker' | 'git' | 'documentation' | 'state' {\n const lower = name.toLowerCase();\n\n if (['jira', 'linear', 'issue_tracker', 'issues', 'github-issues'].includes(lower)) {\n return 'issue_tracker';\n }\n if (['git', 'github', 'gitlab', 'bitbucket'].includes(lower)) {\n return 'git';\n }\n if (['docs', 'documentation', 'confluence', 'notion', 'wiki'].includes(lower)) {\n return 'documentation';\n }\n\n return 'state';\n}\n\n/**\n * Extract variables from config for template substitution\n */\nexport function extractVariables(config?: ResolvedCoreAIConfig | null): SkillVariables {\n const vars: SkillVariables = {};\n\n if (!config) {\n return vars;\n }\n\n // Project variables\n vars.PROJECT_NAME = config.project.name;\n vars.PROJECT_ROOT = config.project.root;\n if (config.project.type) {\n vars.PROJECT_TYPE = config.project.type;\n }\n\n // Issue tracker variables\n if (config.integrations?.issue_tracker) {\n const tracker = config.integrations.issue_tracker;\n if (tracker.config?.project_key) {\n vars.JIRA_PROJECT = tracker.config.project_key;\n }\n if (tracker.config?.base_url) {\n vars.JIRA_URL = tracker.config.base_url;\n }\n }\n\n // Git variables\n if (config.integrations?.git) {\n const git = config.integrations.git;\n if (git.config?.repo) {\n vars.GITHUB_REPO = git.config.repo;\n }\n if (git.config?.owner) {\n vars.GITHUB_OWNER = git.config.owner;\n }\n if (git.config?.default_branch) {\n vars.DEFAULT_BRANCH = git.config.default_branch;\n }\n }\n\n // Documentation variables\n if (config.integrations?.documentation) {\n const docs = config.integrations.documentation;\n if (docs.config?.space_key) {\n vars.CONFLUENCE_SPACE = docs.config.space_key;\n }\n if (docs.config?.base_url) {\n vars.CONFLUENCE_URL = docs.config.base_url;\n }\n if (docs.config?.base_path) {\n vars.DOCS_PATH = docs.config.base_path;\n }\n }\n\n // Quality gate commands\n if (config.quality_gates) {\n const gates = config.quality_gates;\n // Map common gate names to variables\n const gateMappings: Record<string, keyof SkillVariables> = {\n lint: 'LINT_CMD',\n test: 'TEST_CMD',\n build: 'BUILD_CMD',\n static_analysis: 'STATIC_ANALYSIS_CMD',\n staticAnalysis: 'STATIC_ANALYSIS_CMD',\n };\n\n for (const [gateName, gate] of Object.entries(gates)) {\n const varName = gateMappings[gateName];\n if (varName) {\n vars[varName] = gate.command;\n }\n }\n }\n\n // Tech stack\n if (config.tech_stack?.primary_language) {\n vars.PRIMARY_LANGUAGE = config.tech_stack.primary_language;\n }\n\n return vars;\n}\n\n/**\n * Substitute variables in template content\n */\nexport function substituteVariables(content: string, variables: SkillVariables): string {\n let result = content;\n\n for (const [key, value] of Object.entries(variables)) {\n if (value !== undefined) {\n // Replace {{VARIABLE}} pattern\n const pattern = new RegExp(`\\\\{\\\\{${key}\\\\}\\\\}`, 'g');\n result = result.replace(pattern, value);\n }\n }\n\n return result;\n}\n\n/**\n * Check if a skill's dependencies are satisfied\n */\nexport function checkDependencies(\n skill: SkillTemplate,\n config?: ResolvedCoreAIConfig | null\n): { satisfied: boolean; missing: SkillDependency[] } {\n if (!skill.dependencies || skill.dependencies.length === 0) {\n return { satisfied: true, missing: [] };\n }\n\n const missing: SkillDependency[] = [];\n\n for (const dep of skill.dependencies) {\n if (!dep.required) {\n // Optional dependencies don't block skill generation\n continue;\n }\n\n // Check if the integration is configured\n let hasIntegration = false;\n\n if (config?.integrations) {\n switch (dep.type) {\n case 'issue_tracker':\n hasIntegration = !!config.integrations.issue_tracker;\n break;\n case 'git':\n hasIntegration = !!config.integrations.git;\n break;\n case 'documentation':\n hasIntegration = !!config.integrations.documentation;\n break;\n case 'state':\n hasIntegration = !!config.integrations.state;\n break;\n }\n }\n\n if (!hasIntegration) {\n missing.push(dep);\n }\n }\n\n return {\n satisfied: missing.length === 0,\n missing,\n };\n}\n\n/**\n * Generate skills from source files to Claude Code output format.\n *\n * Discovers skills from skills/<category>/<name>/SKILL.md and writes\n * compiled output to .claude/skills/<name>/SKILL.md (flattened).\n */\nexport function generateSkills(\n config: ResolvedCoreAIConfig | undefined,\n options: GenerateSkillsOptions = {}\n): GenerateSkillsResult {\n const projectRoot = options.projectRoot ?? process.cwd();\n const coreSkillsDir = options.coreSkillsDir ?? getCoreSkillsDir();\n const outputDir = options.outputDir ?? join(projectRoot, '.claude', 'skills');\n const includeCoreSkills = options.includeCoreSkills ?? true;\n const overwrite = options.overwrite ?? true;\n\n const result: GenerateSkillsResult = {\n generated: [],\n errors: [],\n variables: {},\n };\n\n // Extract variables from config\n const variables = extractVariables(config);\n\n // Merge custom variables\n if (options.variables) {\n Object.assign(variables, options.variables);\n }\n\n result.variables = variables;\n\n // Discover skill templates from source directory\n let templates: SkillTemplate[] = [];\n\n if (includeCoreSkills) {\n const discovered = discoverSkills(coreSkillsDir);\n templates.push(...discovered);\n }\n\n // Add custom templates if provided\n if (options.customTemplatesDir && existsSync(options.customTemplatesDir)) {\n const custom = discoverSkills(options.customTemplatesDir);\n templates.push(...custom);\n }\n\n // Filter to specific skills if requested\n if (options.skills && options.skills.length > 0) {\n const skillsToInclude = options.skills;\n templates = templates.filter((t) => skillsToInclude.includes(t.name));\n }\n\n // Generate each skill\n for (const template of templates) {\n try {\n const generated = generateSkill(template, variables, config, outputDir, overwrite);\n result.generated.push(generated);\n } catch (error) {\n result.errors.push({\n name: template.name,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n return result;\n}\n\n/**\n * Generate a single skill to .claude/skills/<name>/SKILL.md\n */\nfunction generateSkill(\n template: SkillTemplate,\n variables: SkillVariables,\n config: ResolvedCoreAIConfig | undefined,\n outputDir: string,\n overwrite: boolean\n): GeneratedSkill {\n // Output is directory-per-skill: .claude/skills/<name>/SKILL.md\n const skillDir = join(outputDir, template.name);\n const outputPath = join(skillDir, 'SKILL.md');\n\n // Check if file exists and we shouldn't overwrite\n if (existsSync(outputPath) && !overwrite) {\n return {\n name: template.name,\n category: template.category,\n outputPath,\n action: 'skipped',\n skipReason: 'File already exists',\n };\n }\n\n // Check dependencies\n const { satisfied, missing } = checkDependencies(template, config);\n\n if (!satisfied) {\n const missingTypes = missing.map((d) => d.type).join(', ');\n return {\n name: template.name,\n category: template.category,\n outputPath,\n action: 'skipped',\n skipReason: `Missing required integrations: ${missingTypes}`,\n };\n }\n\n // Substitute variables in content\n const content = substituteVariables(template.content, variables);\n\n // Check if content changed (for update vs create)\n const isUpdate = existsSync(outputPath);\n\n // Ensure skill directory exists\n if (!existsSync(skillDir)) {\n mkdirSync(skillDir, { recursive: true });\n }\n\n // Write the skill file\n writeFileSync(outputPath, content, 'utf-8');\n\n return {\n name: template.name,\n category: template.category,\n outputPath,\n action: isUpdate ? 'updated' : 'created',\n };\n}\n\n/**\n * Format skill generation result for display\n */\nexport function formatGenerateResult(result: GenerateSkillsResult): string {\n const lines: string[] = [];\n\n const created = result.generated.filter((g) => g.action === 'created');\n const updated = result.generated.filter((g) => g.action === 'updated');\n const skipped = result.generated.filter((g) => g.action === 'skipped');\n\n if (created.length > 0) {\n lines.push(`Created ${created.length} skill(s):`);\n for (const skill of created) {\n lines.push(` \\u2713 ${skill.name}`);\n }\n lines.push('');\n }\n\n if (updated.length > 0) {\n lines.push(`Updated ${updated.length} skill(s):`);\n for (const skill of updated) {\n lines.push(` \\u2713 ${skill.name}`);\n }\n lines.push('');\n }\n\n if (skipped.length > 0) {\n lines.push(`Skipped ${skipped.length} skill(s):`);\n for (const skill of skipped) {\n lines.push(` - ${skill.name}: ${skill.skipReason}`);\n }\n lines.push('');\n }\n\n if (result.errors.length > 0) {\n lines.push(`Failed to generate ${result.errors.length} skill(s):`);\n for (const error of result.errors) {\n lines.push(` \\u2717 ${error.name}: ${error.error}`);\n }\n lines.push('');\n }\n\n const total = created.length + updated.length;\n if (total > 0) {\n lines.push(`Generated ${total} skill(s) to .claude/skills/`);\n } else if (result.generated.length === 0 && result.errors.length === 0) {\n lines.push('No skills to generate.');\n }\n\n return lines.join('\\n');\n}\n","/**\n * KnowledgeLibrary Manager\n *\n * Manages the KnowledgeLibrary directory structure and agent state.\n */\n\nimport {\n existsSync,\n mkdirSync,\n writeFileSync,\n readFileSync,\n readdirSync,\n renameSync,\n statSync,\n} from 'fs';\nimport { join, basename } from 'path';\nimport type {\n AgentDirectories,\n AgentKnowledgeState,\n InitKnowledgeLibraryOptions,\n InitKnowledgeLibraryResult,\n KnowledgeLibraryState,\n Message,\n MessageMetadata,\n ReadMessagesOptions,\n WriteMessageOptions,\n AgentContext,\n} from './types.js';\n\n/**\n * Default KnowledgeLibrary base path\n */\nexport const DEFAULT_KNOWLEDGE_LIBRARY_PATH = 'KnowledgeLibrary';\n\n/**\n * Standard files in a KnowledgeLibrary\n */\nexport const STANDARD_FILES = {\n context: 'context.txt',\n architecture: 'architecture.txt',\n prd: 'prd.txt',\n} as const;\n\n/**\n * Standard directories for each agent\n */\nexport const AGENT_DIRECTORIES = [\n 'inbox',\n 'inbox/processed',\n 'outbox',\n 'context',\n 'control',\n 'history',\n 'tech',\n] as const;\n\n/**\n * Standard files in an agent's control directory\n */\nexport const CONTROL_FILES = {\n objectives: 'objectives.txt',\n decisions: 'decisions.txt',\n dependencies: 'dependencies.txt',\n} as const;\n\n/**\n * Get the path to an agent's directories\n */\nexport function getAgentDirectories(basePath: string, agentName: string): AgentDirectories {\n const root = join(basePath, agentName);\n return {\n root,\n inbox: join(root, 'inbox'),\n inboxProcessed: join(root, 'inbox', 'processed'),\n outbox: join(root, 'outbox'),\n context: join(root, 'context'),\n control: join(root, 'control'),\n history: join(root, 'history'),\n tech: join(root, 'tech'),\n };\n}\n\n/**\n * Initialize the KnowledgeLibrary base structure\n */\nexport function initKnowledgeLibrary(\n options: InitKnowledgeLibraryOptions = {}\n): InitKnowledgeLibraryResult {\n const projectRoot = options.projectRoot ?? process.cwd();\n const basePath = join(projectRoot, options.basePath ?? DEFAULT_KNOWLEDGE_LIBRARY_PATH);\n const createDefaults = options.createDefaults ?? true;\n\n const createdDirs: string[] = [];\n const createdFiles: string[] = [];\n\n try {\n // Create base directory\n if (!existsSync(basePath)) {\n mkdirSync(basePath, { recursive: true });\n createdDirs.push(basePath);\n }\n\n // Create default global files if requested\n if (createDefaults) {\n // context.txt\n const contextPath = join(basePath, STANDARD_FILES.context);\n if (!existsSync(contextPath)) {\n writeFileSync(\n contextPath,\n `# Project Context\n\n## Current Sprint\n- Sprint: [Sprint name/number]\n- Goals: [Sprint goals]\n- Deadline: [Sprint deadline]\n\n## Priorities\n1. [Priority 1]\n2. [Priority 2]\n3. [Priority 3]\n\n## Notes\n[Project-wide notes and context]\n`,\n 'utf-8'\n );\n createdFiles.push(contextPath);\n }\n\n // architecture.txt\n const architecturePath = join(basePath, STANDARD_FILES.architecture);\n if (!existsSync(architecturePath)) {\n writeFileSync(\n architecturePath,\n `# Architecture Notes\n\n## Technical Decisions\n[Record major technical decisions here]\n\n## System Overview\n[High-level system architecture]\n\n## Key Components\n[Important system components]\n`,\n 'utf-8'\n );\n createdFiles.push(architecturePath);\n }\n\n // prd.txt\n const prdPath = join(basePath, STANDARD_FILES.prd);\n if (!existsSync(prdPath)) {\n writeFileSync(\n prdPath,\n `# Product Requirements Document\n\n## Overview\n[Product overview]\n\n## Goals\n[Product goals]\n\n## Features\n[Feature list]\n\n## Requirements\n[Detailed requirements]\n`,\n 'utf-8'\n );\n createdFiles.push(prdPath);\n }\n }\n\n return {\n success: true,\n createdDirs,\n createdFiles,\n };\n } catch (error) {\n return {\n success: false,\n createdDirs,\n createdFiles,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n/**\n * Initialize an agent's KnowledgeLibrary directories\n */\nexport function initAgentKnowledgeLibrary(\n agentName: string,\n options: InitKnowledgeLibraryOptions = {}\n): InitKnowledgeLibraryResult {\n const projectRoot = options.projectRoot ?? process.cwd();\n const basePath = join(projectRoot, options.basePath ?? DEFAULT_KNOWLEDGE_LIBRARY_PATH);\n const createDefaults = options.createDefaults ?? true;\n\n const createdDirs: string[] = [];\n const createdFiles: string[] = [];\n\n try {\n // Ensure base KnowledgeLibrary exists\n if (!existsSync(basePath)) {\n const baseResult = initKnowledgeLibrary(options);\n if (!baseResult.success) {\n return baseResult;\n }\n createdDirs.push(...baseResult.createdDirs);\n createdFiles.push(...baseResult.createdFiles);\n }\n\n // Get agent directories\n const dirs = getAgentDirectories(basePath, agentName);\n\n // Create all agent directories\n for (const dir of AGENT_DIRECTORIES) {\n const dirPath = join(dirs.root, dir);\n if (!existsSync(dirPath)) {\n mkdirSync(dirPath, { recursive: true });\n createdDirs.push(dirPath);\n }\n }\n\n // Create default files if requested\n if (createDefaults) {\n // context/current.txt\n const currentContextPath = join(dirs.context, 'current.txt');\n if (!existsSync(currentContextPath)) {\n writeFileSync(\n currentContextPath,\n `# ${agentName} Current Context\n\n## Status\n- State: idle\n- Current Task: None\n- Last Updated: ${new Date().toISOString()}\n\n## Notes\n[Agent-specific context notes]\n`,\n 'utf-8'\n );\n createdFiles.push(currentContextPath);\n }\n\n // control/objectives.txt\n const objectivesPath = join(dirs.control, CONTROL_FILES.objectives);\n if (!existsSync(objectivesPath)) {\n writeFileSync(\n objectivesPath,\n `# ${agentName} Objectives\n\n## Current Objectives\n[None]\n\n## Success Criteria\n[Define success criteria for objectives]\n`,\n 'utf-8'\n );\n createdFiles.push(objectivesPath);\n }\n\n // control/decisions.txt\n const decisionsPath = join(dirs.control, CONTROL_FILES.decisions);\n if (!existsSync(decisionsPath)) {\n writeFileSync(\n decisionsPath,\n `# ${agentName} Decision Log\n\n## Decisions\n[Record important decisions here]\n\nFormat:\n- Date: YYYY-MM-DD\n- Decision: [What was decided]\n- Reasoning: [Why]\n- Related: [Ticket or task reference]\n`,\n 'utf-8'\n );\n createdFiles.push(decisionsPath);\n }\n\n // control/dependencies.txt\n const dependenciesPath = join(dirs.control, CONTROL_FILES.dependencies);\n if (!existsSync(dependenciesPath)) {\n writeFileSync(\n dependenciesPath,\n `# ${agentName} Dependencies\n\n## Blocked By\n[Tasks/agents blocking this agent]\n\n## Blocking\n[Tasks/agents this agent is blocking]\n\nLast Updated: ${new Date().toISOString()}\n`,\n 'utf-8'\n );\n createdFiles.push(dependenciesPath);\n }\n }\n\n return {\n success: true,\n createdDirs,\n createdFiles,\n };\n } catch (error) {\n return {\n success: false,\n createdDirs,\n createdFiles,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n/**\n * Check if a KnowledgeLibrary exists for an agent\n */\nexport function agentKnowledgeLibraryExists(\n agentName: string,\n options: { projectRoot?: string; basePath?: string } = {}\n): boolean {\n const projectRoot = options.projectRoot ?? process.cwd();\n const basePath = join(projectRoot, options.basePath ?? DEFAULT_KNOWLEDGE_LIBRARY_PATH);\n const agentRoot = join(basePath, agentName);\n\n return existsSync(agentRoot) && existsSync(join(agentRoot, 'inbox'));\n}\n\n/**\n * Get the KnowledgeLibrary state for an agent\n */\nexport function getAgentKnowledgeState(\n agentName: string,\n options: { projectRoot?: string; basePath?: string } = {}\n): AgentKnowledgeState {\n const projectRoot = options.projectRoot ?? process.cwd();\n const basePath = join(projectRoot, options.basePath ?? DEFAULT_KNOWLEDGE_LIBRARY_PATH);\n const dirs = getAgentDirectories(basePath, agentName);\n\n const initialized = agentKnowledgeLibraryExists(agentName, options);\n\n // Get pending messages\n const pendingMessages = initialized ? readInboxMessages(agentName, options) : [];\n\n // Get context\n let context: AgentContext | undefined;\n const currentContextPath = join(dirs.context, 'current.txt');\n if (existsSync(currentContextPath)) {\n const content = readFileSync(currentContextPath, 'utf-8');\n context = parseContextFile(content);\n }\n\n const state: AgentKnowledgeState = {\n agentName,\n directories: dirs,\n pendingMessages,\n initialized,\n };\n\n if (context) {\n state.context = context;\n }\n\n return state;\n}\n\n/**\n * Parse a context file into AgentContext\n */\nfunction parseContextFile(content: string): AgentContext {\n const context: AgentContext = {\n lastUpdated: new Date(),\n };\n\n // Simple parsing - look for key patterns\n const statusMatch = content.match(/State:\\s*(.+)/i);\n if (statusMatch && statusMatch[1]) {\n context.status = statusMatch[1].trim();\n }\n\n const taskMatch = content.match(/Current Task:\\s*(.+)/i);\n if (taskMatch && taskMatch[1] && taskMatch[1].trim() !== 'None') {\n context.currentTask = taskMatch[1].trim();\n }\n\n const ticketMatch = content.match(/Current Ticket:\\s*([A-Z]+-\\d+)/i);\n if (ticketMatch && ticketMatch[1]) {\n context.currentTicket = ticketMatch[1];\n }\n\n const updatedMatch = content.match(/Last Updated:\\s*(.+)/i);\n if (updatedMatch) {\n const dateStr = updatedMatch[1]?.trim();\n if (dateStr) {\n const parsed = new Date(dateStr);\n if (!isNaN(parsed.getTime())) {\n context.lastUpdated = parsed;\n }\n }\n }\n\n return context;\n}\n\n/**\n * Generate a message filename\n */\nexport function generateMessageFilename(from: string, subject: string): string {\n const now = new Date();\n const timestamp = now.toISOString().replace(/[-:T]/g, '').slice(0, 12); // YYYYMMDDHHMM\n const sanitizedSubject = subject\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .slice(0, 30);\n return `${timestamp}-${from}-${sanitizedSubject}.md`;\n}\n\n/**\n * Parse message frontmatter\n */\nfunction parseMessageFrontmatter(content: string): {\n metadata: Partial<MessageMetadata>;\n body: string;\n} {\n const match = content.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n([\\s\\S]*)$/);\n\n if (!match) {\n return { metadata: {}, body: content };\n }\n\n const frontmatter = match[1] ?? '';\n const body = match[2] ?? '';\n const metadata: Partial<MessageMetadata> = {};\n\n for (const line of frontmatter.split(/\\r?\\n/)) {\n const colonIndex = line.indexOf(':');\n if (colonIndex === -1) continue;\n\n const key = line.slice(0, colonIndex).trim();\n const value = line.slice(colonIndex + 1).trim();\n\n switch (key) {\n case 'type':\n metadata.type = value as MessageMetadata['type'];\n break;\n case 'from':\n metadata.from = value;\n break;\n case 'to':\n metadata.to = value;\n break;\n case 'date':\n metadata.date = new Date(value);\n break;\n case 'ticket':\n metadata.ticket = value;\n break;\n case 'priority':\n if (value === 'P0' || value === 'P1' || value === 'P2' || value === 'P3') {\n metadata.priority = value;\n }\n break;\n case 'subject':\n metadata.subject = value;\n break;\n }\n }\n\n return { metadata, body };\n}\n\n/**\n * Read inbox messages for an agent\n */\nexport function readInboxMessages(\n agentName: string,\n options: { projectRoot?: string; basePath?: string } & ReadMessagesOptions = {}\n): Message[] {\n const projectRoot = options.projectRoot ?? process.cwd();\n const basePath = join(projectRoot, options.basePath ?? DEFAULT_KNOWLEDGE_LIBRARY_PATH);\n const dirs = getAgentDirectories(basePath, agentName);\n\n const messages: Message[] = [];\n\n // Read inbox\n if (existsSync(dirs.inbox)) {\n const files = readdirSync(dirs.inbox).filter(\n (f) => f.endsWith('.md') && statSync(join(dirs.inbox, f)).isFile()\n );\n\n for (const file of files) {\n const filePath = join(dirs.inbox, file);\n const rawContent = readFileSync(filePath, 'utf-8');\n const { metadata, body } = parseMessageFrontmatter(rawContent);\n\n // Apply filters\n if (options.type && metadata.type !== options.type) continue;\n if (options.from && metadata.from !== options.from) continue;\n if (options.priority && metadata.priority !== options.priority) continue;\n\n messages.push({\n filename: file,\n path: filePath,\n metadata: metadata as MessageMetadata,\n rawContent,\n body,\n });\n }\n }\n\n // Include processed if requested\n if (options.includeProcessed && existsSync(dirs.inboxProcessed)) {\n const files = readdirSync(dirs.inboxProcessed).filter(\n (f) => f.endsWith('.md') && statSync(join(dirs.inboxProcessed, f)).isFile()\n );\n\n for (const file of files) {\n const filePath = join(dirs.inboxProcessed, file);\n const rawContent = readFileSync(filePath, 'utf-8');\n const { metadata, body } = parseMessageFrontmatter(rawContent);\n\n // Apply filters\n if (options.type && metadata.type !== options.type) continue;\n if (options.from && metadata.from !== options.from) continue;\n if (options.priority && metadata.priority !== options.priority) continue;\n\n messages.push({\n filename: file,\n path: filePath,\n metadata: metadata as MessageMetadata,\n rawContent,\n body,\n });\n }\n }\n\n // Sort by date (newest first)\n messages.sort((a, b) => {\n const dateA = a.metadata.date?.getTime() ?? 0;\n const dateB = b.metadata.date?.getTime() ?? 0;\n return dateB - dateA;\n });\n\n // Apply limit\n if (options.limit && messages.length > options.limit) {\n return messages.slice(0, options.limit);\n }\n\n return messages;\n}\n\n/**\n * Write a message to an agent's inbox\n */\nexport function writeInboxMessage(\n options: WriteMessageOptions & { projectRoot?: string; basePath?: string }\n): { success: boolean; path?: string; error?: string } {\n const projectRoot = options.projectRoot ?? process.cwd();\n const basePath = join(projectRoot, options.basePath ?? DEFAULT_KNOWLEDGE_LIBRARY_PATH);\n const dirs = getAgentDirectories(basePath, options.to);\n\n try {\n // Ensure agent inbox exists\n if (!existsSync(dirs.inbox)) {\n mkdirSync(dirs.inbox, { recursive: true });\n }\n\n // Generate filename\n const filename = generateMessageFilename(options.from, options.subject);\n const filePath = join(dirs.inbox, filename);\n\n // Format message\n const now = new Date();\n const content = formatMessage(options, now);\n\n // Write file\n writeFileSync(filePath, content, 'utf-8');\n\n // Also copy to sender's outbox\n const senderDirs = getAgentDirectories(basePath, options.from);\n if (existsSync(senderDirs.outbox)) {\n writeFileSync(join(senderDirs.outbox, filename), content, 'utf-8');\n }\n\n return { success: true, path: filePath };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n/**\n * Format a message with frontmatter\n */\nfunction formatMessage(options: WriteMessageOptions, date: Date): string {\n let frontmatter = `---\ntype: ${options.type}\nfrom: ${options.from}\nto: ${options.to}\ndate: ${date.toISOString().slice(0, 16).replace('T', ' ')}`;\n\n if (options.ticket) {\n frontmatter += `\\nticket: ${options.ticket}`;\n }\n\n if (options.priority) {\n frontmatter += `\\npriority: ${options.priority}`;\n }\n\n frontmatter += `\\nsubject: ${options.subject}`;\n\n frontmatter += `\\n---\n\n## ${options.subject}\n\n${options.body}`;\n\n return frontmatter;\n}\n\n/**\n * Mark a message as processed (move to processed folder)\n */\nexport function markMessageProcessed(\n agentName: string,\n messageFilename: string,\n options: { projectRoot?: string; basePath?: string } = {}\n): { success: boolean; error?: string } {\n const projectRoot = options.projectRoot ?? process.cwd();\n const basePath = join(projectRoot, options.basePath ?? DEFAULT_KNOWLEDGE_LIBRARY_PATH);\n const dirs = getAgentDirectories(basePath, agentName);\n\n const sourcePath = join(dirs.inbox, messageFilename);\n const destPath = join(dirs.inboxProcessed, messageFilename);\n\n try {\n if (!existsSync(sourcePath)) {\n return { success: false, error: `Message not found: ${messageFilename}` };\n }\n\n if (!existsSync(dirs.inboxProcessed)) {\n mkdirSync(dirs.inboxProcessed, { recursive: true });\n }\n\n renameSync(sourcePath, destPath);\n return { success: true };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n/**\n * Get global KnowledgeLibrary state\n */\nexport function getKnowledgeLibraryState(\n options: { projectRoot?: string; basePath?: string } = {}\n): KnowledgeLibraryState | null {\n const projectRoot = options.projectRoot ?? process.cwd();\n const basePath = join(projectRoot, options.basePath ?? DEFAULT_KNOWLEDGE_LIBRARY_PATH);\n\n if (!existsSync(basePath)) {\n return null;\n }\n\n // Get list of agents\n const agents: string[] = [];\n const entries = readdirSync(basePath);\n for (const entry of entries) {\n const entryPath = join(basePath, entry);\n if (statSync(entryPath).isDirectory() && existsSync(join(entryPath, 'inbox'))) {\n agents.push(entry);\n }\n }\n\n return {\n basePath,\n contextPath: join(basePath, STANDARD_FILES.context),\n architecturePath: join(basePath, STANDARD_FILES.architecture),\n prdPath: join(basePath, STANDARD_FILES.prd),\n agents,\n };\n}\n\n/**\n * Update agent context\n */\nexport function updateAgentContext(\n agentName: string,\n context: Partial<AgentContext>,\n options: { projectRoot?: string; basePath?: string } = {}\n): { success: boolean; error?: string } {\n const projectRoot = options.projectRoot ?? process.cwd();\n const basePath = join(projectRoot, options.basePath ?? DEFAULT_KNOWLEDGE_LIBRARY_PATH);\n const dirs = getAgentDirectories(basePath, agentName);\n const contextPath = join(dirs.context, 'current.txt');\n\n try {\n const now = new Date();\n const content = `# ${agentName} Current Context\n\n## Status\n- State: ${context.status ?? 'idle'}\n- Current Task: ${context.currentTask ?? 'None'}\n${context.currentTicket ? `- Current Ticket: ${context.currentTicket}` : ''}- Last Updated: ${now.toISOString()}\n\n## Notes\n${context.notes ?? '[Agent-specific context notes]'}\n`;\n\n if (!existsSync(dirs.context)) {\n mkdirSync(dirs.context, { recursive: true });\n }\n\n writeFileSync(contextPath, content, 'utf-8');\n return { success: true };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n/**\n * Format KnowledgeLibrary state for display\n */\nexport function formatKnowledgeLibraryState(state: KnowledgeLibraryState | null): string {\n if (!state) {\n return 'KnowledgeLibrary not initialized.';\n }\n\n const lines: string[] = [];\n lines.push(`KnowledgeLibrary: ${state.basePath}\\n`);\n\n lines.push('Global files:');\n lines.push(` - ${basename(state.contextPath)}`);\n lines.push(` - ${basename(state.architecturePath)}`);\n lines.push(` - ${basename(state.prdPath)}`);\n lines.push('');\n\n if (state.agents.length > 0) {\n lines.push(`Agents (${state.agents.length}):`);\n for (const agent of state.agents) {\n lines.push(` - ${agent}`);\n }\n } else {\n lines.push('No agents initialized.');\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Format agent knowledge state for display\n */\nexport function formatAgentKnowledgeState(state: AgentKnowledgeState): string {\n const lines: string[] = [];\n\n lines.push(`Agent: ${state.agentName}`);\n lines.push(`Status: ${state.initialized ? 'Initialized' : 'Not initialized'}`);\n lines.push('');\n\n if (state.context) {\n lines.push('Context:');\n lines.push(` State: ${state.context.status ?? 'unknown'}`);\n if (state.context.currentTask) {\n lines.push(` Current Task: ${state.context.currentTask}`);\n }\n if (state.context.currentTicket) {\n lines.push(` Current Ticket: ${state.context.currentTicket}`);\n }\n lines.push(` Last Updated: ${state.context.lastUpdated.toISOString()}`);\n lines.push('');\n }\n\n if (state.pendingMessages.length > 0) {\n lines.push(`Pending Messages (${state.pendingMessages.length}):`);\n for (const msg of state.pendingMessages) {\n const type = msg.metadata.type ?? 'unknown';\n const from = msg.metadata.from ?? 'unknown';\n const subject = msg.metadata.subject ?? msg.filename;\n lines.push(` - [${type}] from ${from}: ${subject}`);\n }\n } else {\n lines.push('No pending messages.');\n }\n\n return lines.join('\\n');\n}\n","/**\n * Cache Commands\n *\n * Commands for managing the local cache.\n */\n\nimport { join } from 'path';\nimport { FileCacheProvider, CACHE_PATHS, type CacheStats } from '../../cache/index.js';\n\n/**\n * Options for cache commands\n */\nexport interface CacheCommandOptions {\n /**\n * Project root directory\n */\n projectRoot?: string;\n\n /**\n * Custom cache path (overrides default)\n */\n cachePath?: string;\n\n /**\n * Output format\n */\n format?: 'text' | 'json';\n}\n\n/**\n * Result of cache status command\n */\nexport interface CacheStatusResult {\n initialized: boolean;\n path: string;\n stats: CacheStats | null;\n entries: {\n key: string;\n source: string;\n status: string;\n size: number;\n cachedAt: string;\n expiresAt: string;\n }[];\n}\n\n/**\n * Result of cache clear command\n */\nexport interface CacheClearResult {\n cleared: number;\n success: boolean;\n error?: string;\n}\n\n/**\n * Get the cache path for a project\n */\nfunction getCachePath(options: CacheCommandOptions): string {\n if (options.cachePath) {\n return options.cachePath;\n }\n const root = options.projectRoot ?? process.cwd();\n return join(root, CACHE_PATHS.ROOT);\n}\n\n/**\n * Get cache status\n */\nexport async function cacheStatus(options: CacheCommandOptions = {}): Promise<CacheStatusResult> {\n const cachePath = getCachePath(options);\n\n const provider = new FileCacheProvider({ basePath: cachePath });\n\n try {\n await provider.initialize();\n } catch {\n return {\n initialized: false,\n path: cachePath,\n stats: null,\n entries: [],\n };\n }\n\n const stats = await provider.getStats();\n const metadataList = await provider.list();\n\n const entries = await Promise.all(\n metadataList.map(async (metadata) => {\n const status = await provider.getStatus(metadata.key);\n return {\n key: metadata.key,\n source: metadata.source,\n status: status ?? 'unknown',\n size: metadata.size,\n cachedAt: metadata.cachedAt,\n expiresAt: metadata.expiresAt,\n };\n })\n );\n\n return {\n initialized: true,\n path: cachePath,\n stats,\n entries,\n };\n}\n\n/**\n * Clear all cache entries\n */\nexport async function cacheClear(options: CacheCommandOptions = {}): Promise<CacheClearResult> {\n const cachePath = getCachePath(options);\n\n const provider = new FileCacheProvider({ basePath: cachePath });\n\n try {\n await provider.initialize();\n const cleared = await provider.clear();\n return { cleared, success: true };\n } catch (error) {\n return {\n cleared: 0,\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n/**\n * Clear expired cache entries\n */\nexport async function cacheClearExpired(\n options: CacheCommandOptions = {}\n): Promise<CacheClearResult> {\n const cachePath = getCachePath(options);\n\n const provider = new FileCacheProvider({ basePath: cachePath });\n\n try {\n await provider.initialize();\n const cleared = await provider.clearExpired();\n return { cleared, success: true };\n } catch (error) {\n return {\n cleared: 0,\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n/**\n * Format bytes to human-readable string\n */\nexport function formatBytes(bytes: number): string {\n if (bytes === 0) return '0 B';\n const k = 1024;\n const sizes = ['B', 'KB', 'MB', 'GB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\n}\n\n/**\n * Format cache status for terminal output\n */\nexport function formatCacheStatus(result: CacheStatusResult): string {\n const lines: string[] = [];\n\n lines.push('Cache Status');\n lines.push('============');\n lines.push('');\n\n if (!result.initialized) {\n lines.push(`Path: ${result.path}`);\n lines.push('Status: Not initialized (no cache found)');\n return lines.join('\\n');\n }\n\n lines.push(`Path: ${result.path}`);\n lines.push('Status: Initialized');\n lines.push('');\n\n if (result.stats) {\n lines.push('Statistics:');\n lines.push(` Entries: ${result.stats.totalEntries}`);\n lines.push(` Total size: ${formatBytes(result.stats.totalSize)}`);\n lines.push(\n ` Valid: ${result.stats.validEntries}, Stale: ${result.stats.staleEntries}, Expired: ${result.stats.expiredEntries}`\n );\n if (result.stats.newestEntry) {\n lines.push(` Last updated: ${result.stats.newestEntry}`);\n }\n }\n\n if (result.entries.length > 0) {\n lines.push('');\n lines.push('Entries:');\n lines.push('');\n\n // Group by source\n const bySource = new Map<string, typeof result.entries>();\n for (const entry of result.entries) {\n const source = entry.source;\n if (!bySource.has(source)) {\n bySource.set(source, []);\n }\n const entries = bySource.get(source);\n if (entries) {\n entries.push(entry);\n }\n }\n\n for (const [source, entries] of bySource) {\n lines.push(` ${source}:`);\n for (const entry of entries) {\n const statusIcon = entry.status === 'valid' ? '✓' : entry.status === 'stale' ? '○' : '✗';\n lines.push(` ${statusIcon} ${entry.key} (${formatBytes(entry.size)})`);\n }\n }\n } else {\n lines.push('');\n lines.push('No entries in cache.');\n }\n\n return lines.join('\\n');\n}\n","/**\n * Sync Command\n *\n * Syncs shared context from remote sources.\n */\n\nimport { join } from 'path';\nimport {\n FileCacheProvider,\n CACHE_PATHS,\n type SyncResult,\n type CacheSource,\n} from '../../cache/index.js';\nimport { CacheManager } from '../../cache/manager.js';\nimport type { RemoteFetcher } from '../../cache/interfaces.js';\n\n/**\n * Options for sync command\n */\nexport interface SyncCommandOptions {\n /**\n * Project root directory\n */\n projectRoot?: string;\n\n /**\n * Custom cache path\n */\n cachePath?: string;\n\n /**\n * Force refresh all entries\n */\n force?: boolean;\n\n /**\n * Filter by source type\n */\n source?: CacheSource;\n\n /**\n * Continue on error\n */\n continueOnError?: boolean;\n\n /**\n * Maximum concurrent fetches\n */\n concurrency?: number;\n\n /**\n * Progress callback\n */\n onProgress?: (completed: number, total: number, message: string) => void;\n}\n\n/**\n * Result of sync command\n */\nexport interface SyncCommandResult {\n success: boolean;\n result: SyncResult | null;\n error?: string;\n sources: string[];\n}\n\n/**\n * Create a mock fetcher for a source (placeholder until real fetchers are implemented)\n *\n * In a real implementation, these would be replaced with actual fetchers\n * that use the documentation adapter interfaces.\n */\nfunction createPlaceholderFetcher(source: string): RemoteFetcher {\n return {\n async fetch(url: string) {\n // This is a placeholder - real implementation would use adapters\n throw new Error(\n `No fetcher implementation for source \"${source}\". ` +\n `URL: ${url}. Configure a documentation provider in coreai.config.yaml.`\n );\n },\n async hasChanged(_url: string, _etag?: string) {\n // Always return true for placeholder\n return true;\n },\n };\n}\n\n/**\n * Get the cache path for a project\n */\nfunction getCachePath(options: SyncCommandOptions): string {\n if (options.cachePath) {\n return options.cachePath;\n }\n const root = options.projectRoot ?? process.cwd();\n return join(root, CACHE_PATHS.base);\n}\n\n/**\n * Sync cached entries from remote sources\n *\n * This command refreshes cached content by re-fetching from remote sources.\n * If --force is specified, it clears stale/expired status and fetches fresh content.\n */\nexport async function sync(options: SyncCommandOptions = {}): Promise<SyncCommandResult> {\n const cachePath = getCachePath(options);\n\n const provider = new FileCacheProvider({ basePath: cachePath });\n\n try {\n await provider.initialize();\n } catch (error) {\n return {\n success: false,\n result: null,\n error: `Failed to initialize cache: ${error instanceof Error ? error.message : String(error)}`,\n sources: [],\n };\n }\n\n // Get all cached entries\n const entries = await provider.list({ source: options.source });\n\n if (entries.length === 0) {\n return {\n success: true,\n result: {\n added: 0,\n updated: 0,\n removed: 0,\n failed: 0,\n errors: [],\n duration: 0,\n },\n sources: [],\n };\n }\n\n // Create cache manager\n const manager = new CacheManager({\n cache: provider,\n defaultTtl: 3600,\n });\n\n // Collect unique sources and register placeholder fetchers\n const sources = new Set<string>();\n for (const entry of entries) {\n sources.add(entry.source);\n }\n\n // Register fetchers for each source\n // In a real implementation, these would be actual fetcher implementations\n for (const source of sources) {\n if (!manager.hasFetcher(source)) {\n manager.registerFetcher(source, createPlaceholderFetcher(source));\n }\n }\n\n // Get keys to sync\n const keys = entries.map((e) => e.key);\n\n // Report progress\n if (options.onProgress) {\n options.onProgress(0, keys.length, 'Starting sync...');\n }\n\n // Sync entries\n try {\n const result = await manager.syncEntries(keys, {\n force: options.force,\n continueOnError: options.continueOnError ?? true,\n concurrency: options.concurrency ?? 5,\n onProgress: (completed, total) => {\n if (options.onProgress) {\n options.onProgress(completed, total, `Syncing ${completed}/${total} entries...`);\n }\n },\n });\n\n return {\n success: result.failed === 0 || options.continueOnError === true,\n result,\n sources: Array.from(sources),\n };\n } catch (error) {\n return {\n success: false,\n result: null,\n error: error instanceof Error ? error.message : String(error),\n sources: Array.from(sources),\n };\n }\n}\n\n/**\n * Format sync result for terminal output\n */\nexport function formatSyncResult(result: SyncCommandResult): string {\n const lines: string[] = [];\n\n lines.push('Sync Results');\n lines.push('============');\n lines.push('');\n\n if (!result.success && result.error) {\n lines.push(`Error: ${result.error}`);\n return lines.join('\\n');\n }\n\n if (!result.result) {\n lines.push('No sync operation performed.');\n return lines.join('\\n');\n }\n\n const r = result.result;\n\n if (r.added === 0 && r.updated === 0 && r.removed === 0 && r.failed === 0) {\n lines.push('Cache is empty. Nothing to sync.');\n lines.push('');\n lines.push('Tip: Add context sources to your coreai.config.yaml to fetch remote content.');\n return lines.join('\\n');\n }\n\n lines.push(`Duration: ${r.duration}ms`);\n lines.push('');\n\n if (result.sources.length > 0) {\n lines.push(`Sources: ${result.sources.join(', ')}`);\n lines.push('');\n }\n\n lines.push('Summary:');\n if (r.added > 0) lines.push(` ✓ Added: ${r.added}`);\n if (r.updated > 0) lines.push(` ✓ Updated: ${r.updated}`);\n if (r.removed > 0) lines.push(` ○ Removed: ${r.removed}`);\n if (r.failed > 0) lines.push(` ✗ Failed: ${r.failed}`);\n\n if (r.errors.length > 0) {\n lines.push('');\n lines.push('Errors:');\n for (const err of r.errors.slice(0, 10)) {\n lines.push(` - ${err.key}: ${err.error}`);\n }\n if (r.errors.length > 10) {\n lines.push(` ... and ${r.errors.length - 10} more errors`);\n }\n }\n\n return lines.join('\\n');\n}\n","/**\n * Init Command\n *\n * Initializes a new CoreAI project with configuration file and directory structure.\n */\n\nimport { existsSync, writeFileSync, mkdirSync, readFileSync } from 'fs';\nimport { join, basename } from 'path';\nimport { execSync } from 'child_process';\nimport type { ProjectType, GitProvider } from '../../config/types.js';\nimport { configExists } from '../../config/loader.js';\n\n/**\n * Options for init command\n */\nexport interface InitCommandOptions {\n /**\n * Project root directory\n */\n projectRoot?: string;\n\n /**\n * Overwrite existing configuration\n */\n force?: boolean;\n\n /**\n * Skip interactive prompts\n */\n nonInteractive?: boolean;\n\n /**\n * Project name (for non-interactive mode)\n */\n name?: string;\n\n /**\n * Project type (for non-interactive mode)\n */\n type?: ProjectType;\n\n /**\n * Skip creating directory structure\n */\n skipDirs?: boolean;\n}\n\n/**\n * Result of init command\n */\nexport interface InitCommandResult {\n success: boolean;\n configPath?: string;\n createdDirs?: string[];\n error?: string;\n gitInfo?: {\n provider?: GitProvider;\n owner?: string;\n repo?: string;\n };\n}\n\n/**\n * Detect git remote information\n */\nfunction detectGitInfo(): { provider?: GitProvider; owner?: string; repo?: string } | null {\n try {\n const remoteUrl = execSync('git remote get-url origin', { encoding: 'utf-8' }).trim();\n\n // GitHub HTTPS: https://github.com/owner/repo.git\n const httpsMatch = remoteUrl.match(/https:\\/\\/github\\.com\\/([^/]+)\\/([^/.]+)/);\n if (httpsMatch) {\n return { provider: 'github', owner: httpsMatch[1], repo: httpsMatch[2] };\n }\n\n // GitHub SSH: git@github.com:owner/repo.git\n const sshMatch = remoteUrl.match(/git@github\\.com:([^/]+)\\/([^/.]+)/);\n if (sshMatch) {\n return { provider: 'github', owner: sshMatch[1], repo: sshMatch[2] };\n }\n\n // GitLab HTTPS\n const gitlabHttps = remoteUrl.match(/https:\\/\\/gitlab\\.com\\/([^/]+)\\/([^/.]+)/);\n if (gitlabHttps) {\n return { provider: 'gitlab', owner: gitlabHttps[1], repo: gitlabHttps[2] };\n }\n\n // GitLab SSH\n const gitlabSsh = remoteUrl.match(/git@gitlab\\.com:([^/]+)\\/([^/.]+)/);\n if (gitlabSsh) {\n return { provider: 'gitlab', owner: gitlabSsh[1], repo: gitlabSsh[2] };\n }\n\n return null;\n } catch {\n // Not a git repo or no remote\n return null;\n }\n}\n\n/**\n * Detect project name from directory or package.json\n */\nfunction detectProjectName(projectRoot: string): string {\n // Try package.json first\n const packageJsonPath = join(projectRoot, 'package.json');\n if (existsSync(packageJsonPath)) {\n try {\n const content = JSON.parse(readFileSync(packageJsonPath, 'utf-8')) as { name?: string };\n if (content.name) {\n return content.name;\n }\n } catch {\n // Ignore parse errors\n }\n }\n\n // Fall back to directory name\n return basename(projectRoot);\n}\n\n/**\n * Generate config file content\n */\nfunction generateConfigYaml(options: {\n name: string;\n type: ProjectType;\n gitInfo?: { provider?: GitProvider; owner?: string; repo?: string } | null;\n}): string {\n let yaml = `# CoreAI Configuration\n# See https://coreai.dev/docs/config for full schema\n\nversion: \"1.0\"\n\nproject:\n name: \"${options.name}\"\n type: ${options.type}\n\nteam:\n agents:\n - backend-engineer\n - frontend-engineer\n - devops-engineer\n - engineering-manager\n`;\n\n if (options.gitInfo?.provider) {\n yaml += `\nintegrations:\n git:\n provider: ${options.gitInfo.provider}\n config:\n owner: \"${options.gitInfo.owner}\"\n repo: \"${options.gitInfo.repo}\"\n`;\n }\n\n yaml += `\n# quality_gates:\n# lint:\n# command: npm run lint\n# required: true\n# test:\n# command: npm test\n# required: true\n# build:\n# command: npm run build\n# required: true\n\n# tech_stack:\n# primary_language: typescript\n# frameworks:\n# - node.js\n# - express\n`;\n\n return yaml;\n}\n\n/**\n * Create directory structure for CoreAI\n */\nfunction createDirectories(projectRoot: string): string[] {\n const dirs = [\n join(projectRoot, 'coreai', 'agents'),\n join(projectRoot, 'coreai', 'commands'),\n join(projectRoot, '.coreai', 'cache'),\n ];\n\n const created: string[] = [];\n\n for (const dir of dirs) {\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n created.push(dir);\n }\n }\n\n return created;\n}\n\n/**\n * Initialize a new CoreAI project\n */\nexport function init(options: InitCommandOptions = {}): InitCommandResult {\n const projectRoot = options.projectRoot ?? process.cwd();\n\n // Check if config already exists\n if (configExists(projectRoot) && !options.force) {\n return {\n success: false,\n error: 'CoreAI configuration already exists. Use --force to overwrite.',\n };\n }\n\n // Detect git info\n const gitInfo = detectGitInfo();\n\n // Determine project name\n const name = options.name ?? detectProjectName(projectRoot);\n\n // Determine project type\n const type = options.type ?? 'software';\n\n // Generate config\n const configContent = generateConfigYaml({ name, type, gitInfo });\n\n // Write config file\n const configPath = join(projectRoot, 'coreai.config.yaml');\n try {\n writeFileSync(configPath, configContent, 'utf-8');\n } catch (error) {\n return {\n success: false,\n error: `Failed to write config file: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n\n // Create directories unless skipped\n let createdDirs: string[] = [];\n if (!options.skipDirs) {\n try {\n createdDirs = createDirectories(projectRoot);\n } catch (error) {\n return {\n success: false,\n configPath,\n error: `Failed to create directories: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n\n return {\n success: true,\n configPath,\n createdDirs,\n gitInfo: gitInfo ?? undefined,\n };\n}\n\n/**\n * Format init result for display\n */\nexport function formatInitResult(result: InitCommandResult): string {\n if (!result.success) {\n return `Error: ${result.error}`;\n }\n\n const lines: string[] = [];\n\n lines.push('CoreAI project initialized successfully!\\n');\n\n if (result.configPath) {\n lines.push(`Created: ${result.configPath}`);\n }\n\n if (result.createdDirs && result.createdDirs.length > 0) {\n lines.push('\\nCreated directories:');\n for (const dir of result.createdDirs) {\n lines.push(` - ${dir}`);\n }\n }\n\n if (result.gitInfo?.provider) {\n lines.push(\n `\\nDetected ${result.gitInfo.provider} repository: ${result.gitInfo.owner}/${result.gitInfo.repo}`\n );\n }\n\n lines.push('\\nNext steps:');\n lines.push(' 1. Edit coreai.config.yaml to configure your project');\n lines.push(' 2. Run `coreai build` to compile agents');\n lines.push(' 3. Run `coreai validate` to check your setup');\n\n return lines.join('\\n');\n}\n","/**\n * Build Command\n *\n * Compiles agent definitions and skills to Claude-compatible format.\n */\n\nimport { configExists, loadConfig, ConfigError } from '../../config/loader.js';\nimport type { ResolvedCoreAIConfig } from '../../config/types.js';\nimport { compileAgents, type CompileOptions, type CompileResult } from '../../agents/index.js';\nimport { generateSkills, type GenerateSkillsResult } from '../../skills/index.js';\nimport { initAgentKnowledgeLibrary } from '../../knowledge-library/index.js';\nimport { discoverMcpServers } from '../../adapters/mcp/index.js';\n\n/**\n * Options for build command\n */\nexport interface BuildCommandOptions {\n /**\n * Project root directory\n */\n projectRoot?: string;\n\n /**\n * Path to core agents directory\n */\n coreAgentsDir?: string;\n\n /**\n * Output directory for compiled agents\n */\n outputDir?: string;\n\n /**\n * Watch for changes (not yet implemented)\n */\n watch?: boolean;\n\n /**\n * Only compile specific agents\n */\n agents?: string[];\n\n /**\n * Skip validation before build\n */\n skipValidation?: boolean;\n\n /**\n * Initialize KnowledgeLibrary directories for agents\n */\n initKnowledgeLibrary?: boolean;\n\n /**\n * Include MCP servers as agent tools.\n * If true, discovers MCP servers from config files.\n * If an array, uses the specified server names.\n * Default: true (auto-discover)\n */\n mcpServers?: boolean | string[];\n\n /**\n * Skip skill generation\n */\n skipSkills?: boolean;\n\n /**\n * Only generate specific skills\n */\n skills?: string[];\n}\n\n/**\n * Result of build command\n */\nexport interface BuildCommandResult {\n success: boolean;\n result?: CompileResult;\n skillsResult?: GenerateSkillsResult;\n config?: ResolvedCoreAIConfig;\n error?: string;\n warnings?: string[];\n knowledgeLibraryInitialized?: string[];\n mcpServers?: string[];\n}\n\n/**\n * Build agents\n */\nexport function build(options: BuildCommandOptions = {}): BuildCommandResult {\n const projectRoot = options.projectRoot ?? process.cwd();\n const warnings: string[] = [];\n\n // Load config if available\n let config: ResolvedCoreAIConfig | undefined;\n if (configExists(projectRoot)) {\n try {\n config = loadConfig(projectRoot);\n } catch (error) {\n if (error instanceof ConfigError) {\n return {\n success: false,\n error: `Configuration error: ${error.message}`,\n };\n }\n return {\n success: false,\n error: `Failed to load config: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n } else {\n warnings.push('No configuration file found. Building with defaults.');\n }\n\n // Set up compile options\n const compileOptions: CompileOptions = {\n projectRoot,\n };\n\n if (options.coreAgentsDir) {\n compileOptions.coreAgentsDir = options.coreAgentsDir;\n }\n\n if (options.outputDir) {\n compileOptions.outputDir = options.outputDir;\n }\n\n // Filter to specific agents if requested\n if (options.agents && options.agents.length > 0) {\n const agentsList = options.agents;\n compileOptions.filter = (agent) => agentsList.includes(agent.role);\n }\n\n // Discover MCP servers for tools\n const includeMcpServers = options.mcpServers ?? true;\n if (includeMcpServers !== false) {\n try {\n if (Array.isArray(includeMcpServers)) {\n // Use explicitly provided server names\n compileOptions.mcpServers = includeMcpServers;\n } else {\n // Auto-discover from config files\n const discoveredServers = discoverMcpServers({\n projectRoot,\n includeGlobal: false, // Only use project-level MCP config\n });\n if (discoveredServers.length > 0) {\n compileOptions.mcpServers = discoveredServers.map((s) => s.name);\n }\n }\n } catch {\n // MCP discovery failed, continue without MCP tools\n // This is non-fatal - agents will just use default tools\n }\n }\n\n // Compile agents\n try {\n const result = compileAgents(config, compileOptions);\n\n // Check for errors\n if (result.errors.length > 0) {\n return {\n success: false,\n result,\n config,\n error: `Failed to compile ${result.errors.length} agent(s)`,\n warnings,\n };\n }\n\n // Generate skills\n let skillsResult: GenerateSkillsResult | undefined;\n if (!options.skipSkills) {\n skillsResult = generateSkills(config, {\n projectRoot,\n skills: options.skills,\n overwrite: true,\n });\n }\n\n // Initialize KnowledgeLibrary for agents if requested\n let knowledgeLibraryInitialized: string[] | undefined;\n if (options.initKnowledgeLibrary) {\n knowledgeLibraryInitialized = [];\n for (const compiled of result.compiled) {\n const initResult = initAgentKnowledgeLibrary(compiled.role, {\n projectRoot,\n createDefaults: true,\n });\n if (initResult.success && initResult.createdDirs.length > 0) {\n knowledgeLibraryInitialized.push(compiled.role);\n }\n }\n }\n\n return {\n success: true,\n result,\n skillsResult,\n config,\n warnings: warnings.length > 0 ? warnings : undefined,\n knowledgeLibraryInitialized,\n mcpServers: compileOptions.mcpServers,\n };\n } catch (error) {\n return {\n success: false,\n error: `Build failed: ${error instanceof Error ? error.message : String(error)}`,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n }\n}\n\n/**\n * Format build result for display\n */\nexport function formatBuildResult(result: BuildCommandResult): string {\n const lines: string[] = [];\n\n // Warnings\n if (result.warnings && result.warnings.length > 0) {\n for (const warning of result.warnings) {\n lines.push(`⚠ ${warning}`);\n }\n lines.push('');\n }\n\n if (!result.success) {\n lines.push(`Build failed: ${result.error}`);\n\n // Show individual errors\n if (result.result?.errors && result.result.errors.length > 0) {\n lines.push('');\n for (const error of result.result.errors) {\n lines.push(` ✗ ${error.role}: ${error.error}`);\n }\n }\n\n return lines.join('\\n');\n }\n\n const compileResult = result.result;\n if (!compileResult) {\n lines.push('No agents to compile.');\n return lines.join('\\n');\n }\n\n if (compileResult.compiled.length === 0) {\n lines.push('No agents to compile.');\n return lines.join('\\n');\n }\n\n lines.push(`Compiled ${compileResult.compiled.length} agent(s):\\n`);\n\n // Group by source\n const coreAgents = compileResult.compiled.filter((a) => a.source === 'core');\n const customAgents = compileResult.compiled.filter((a) => a.source === 'custom');\n const overrideAgents = compileResult.compiled.filter((a) => a.source === 'override');\n\n if (coreAgents.length > 0) {\n lines.push('Core agents:');\n for (const agent of coreAgents) {\n lines.push(` ✓ ${agent.role}`);\n lines.push(` → ${agent.outputPath}`);\n }\n lines.push('');\n }\n\n if (customAgents.length > 0) {\n lines.push('Custom agents:');\n for (const agent of customAgents) {\n lines.push(` ✓ ${agent.role}`);\n lines.push(` → ${agent.outputPath}`);\n }\n lines.push('');\n }\n\n if (overrideAgents.length > 0) {\n lines.push('Override agents:');\n for (const agent of overrideAgents) {\n lines.push(` ✓ ${agent.role} (overrides core)`);\n lines.push(` → ${agent.outputPath}`);\n }\n lines.push('');\n }\n\n // Skills generated\n if (result.skillsResult) {\n const created = result.skillsResult.generated.filter((g) => g.action === 'created');\n const updated = result.skillsResult.generated.filter((g) => g.action === 'updated');\n const total = created.length + updated.length;\n if (total > 0) {\n lines.push(`Generated ${total} skill(s):`);\n for (const skill of [...created, ...updated]) {\n lines.push(` \\u2713 ${skill.name} \\u2192 ${skill.outputPath}`);\n }\n lines.push('');\n }\n if (result.skillsResult.errors.length > 0) {\n for (const error of result.skillsResult.errors) {\n lines.push(` \\u2717 skill ${error.name}: ${error.error}`);\n }\n lines.push('');\n }\n }\n\n // MCP servers included\n if (result.mcpServers && result.mcpServers.length > 0) {\n lines.push(`MCP tools included: ${result.mcpServers.map((s) => `mcp__${s}`).join(', ')}`);\n lines.push('');\n }\n\n // KnowledgeLibrary initialization\n if (result.knowledgeLibraryInitialized && result.knowledgeLibraryInitialized.length > 0) {\n lines.push(\n `KnowledgeLibrary initialized for ${result.knowledgeLibraryInitialized.length} agent(s):`\n );\n for (const agent of result.knowledgeLibraryInitialized) {\n lines.push(` ✓ ${agent}`);\n }\n lines.push('');\n }\n\n lines.push('Build complete!');\n\n return lines.join('\\n');\n}\n","/**\n * Validate Command\n *\n * Validates CoreAI configuration and project setup.\n */\n\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport { configExists, loadConfig, ConfigError } from '../../config/loader.js';\nimport type { ResolvedCoreAIConfig } from '../../config/types.js';\nimport { loadAllAgents } from '../../agents/index.js';\n\n/**\n * Options for validate command\n */\nexport interface ValidateCommandOptions {\n /**\n * Project root directory\n */\n projectRoot?: string;\n\n /**\n * Path to core agents directory\n */\n coreAgentsDir?: string;\n\n /**\n * Check if configured agents exist\n */\n checkAgents?: boolean;\n\n /**\n * Check directory structure\n */\n checkDirs?: boolean;\n\n /**\n * Check quality gates commands exist\n */\n checkQualityGates?: boolean;\n}\n\n/**\n * Single validation issue\n */\nexport interface ValidationIssue {\n level: 'error' | 'warning' | 'info';\n category: 'config' | 'agents' | 'directories' | 'quality_gates' | 'integrations';\n message: string;\n fix?: string;\n}\n\n/**\n * Result of validate command\n */\nexport interface ValidateCommandResult {\n success: boolean;\n valid: boolean;\n config?: ResolvedCoreAIConfig;\n issues: ValidationIssue[];\n summary: {\n errors: number;\n warnings: number;\n info: number;\n };\n}\n\n/**\n * Validate configuration file\n */\nfunction validateConfig(projectRoot: string): {\n config?: ResolvedCoreAIConfig;\n issues: ValidationIssue[];\n} {\n const issues: ValidationIssue[] = [];\n\n if (!configExists(projectRoot)) {\n issues.push({\n level: 'error',\n category: 'config',\n message: 'No CoreAI configuration file found',\n fix: 'Run `coreai init` to create a configuration file',\n });\n return { issues };\n }\n\n try {\n const config = loadConfig(projectRoot);\n return { config, issues };\n } catch (error) {\n if (error instanceof ConfigError) {\n issues.push({\n level: 'error',\n category: 'config',\n message: `Configuration error: ${error.message}`,\n fix: 'Check coreai.config.yaml for syntax errors',\n });\n } else {\n issues.push({\n level: 'error',\n category: 'config',\n message: `Failed to load config: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n return { issues };\n }\n}\n\n/**\n * Validate configured agents exist\n */\nfunction validateAgents(\n config: ResolvedCoreAIConfig,\n coreAgentsDir: string,\n projectRoot: string\n): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n const customAgentsDir = join(projectRoot, 'coreai', 'agents');\n\n // Load available agents\n let availableAgents: Map<string, unknown>;\n try {\n availableAgents = loadAllAgents({\n coreAgentsDir,\n customAgentsDir,\n });\n } catch (error) {\n issues.push({\n level: 'warning',\n category: 'agents',\n message: `Could not load agents: ${error instanceof Error ? error.message : String(error)}`,\n });\n return issues;\n }\n\n // Check each configured agent\n const configuredAgents = config.team.agents;\n for (const agentRole of configuredAgents) {\n if (!availableAgents.has(agentRole)) {\n issues.push({\n level: 'error',\n category: 'agents',\n message: `Configured agent '${agentRole}' not found`,\n fix: `Add agent definition to coreai/agents/${agentRole}.yaml or remove from config`,\n });\n }\n }\n\n // Info about available but not configured agents\n const unconfigured = Array.from(availableAgents.keys()).filter(\n (role) => !configuredAgents.includes(role)\n );\n if (unconfigured.length > 0) {\n issues.push({\n level: 'info',\n category: 'agents',\n message: `${unconfigured.length} available agent(s) not configured: ${unconfigured.join(', ')}`,\n });\n }\n\n return issues;\n}\n\n/**\n * Validate directory structure\n */\nfunction validateDirectories(projectRoot: string): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n\n const requiredDirs = [{ path: 'coreai', description: 'CoreAI configuration directory' }];\n\n const optionalDirs = [\n { path: 'coreai/agents', description: 'Custom agent definitions' },\n { path: 'coreai/commands', description: 'Custom command definitions' },\n { path: '.coreai', description: 'CoreAI runtime directory' },\n { path: '.coreai/cache', description: 'Cache directory' },\n { path: '.claude/agents', description: 'Compiled agents output' },\n ];\n\n // Check required directories\n for (const dir of requiredDirs) {\n const fullPath = join(projectRoot, dir.path);\n if (!existsSync(fullPath)) {\n issues.push({\n level: 'warning',\n category: 'directories',\n message: `Missing directory: ${dir.path} (${dir.description})`,\n fix: `Run mkdir -p ${dir.path}`,\n });\n }\n }\n\n // Check optional directories (info only)\n for (const dir of optionalDirs) {\n const fullPath = join(projectRoot, dir.path);\n if (!existsSync(fullPath)) {\n issues.push({\n level: 'info',\n category: 'directories',\n message: `Optional directory not found: ${dir.path} (${dir.description})`,\n });\n }\n }\n\n return issues;\n}\n\n/**\n * Validate integrations configuration\n */\nfunction validateIntegrations(config: ResolvedCoreAIConfig): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n\n if (!config.integrations) {\n issues.push({\n level: 'info',\n category: 'integrations',\n message: 'No integrations configured',\n });\n return issues;\n }\n\n // Check git integration\n if (config.integrations.git) {\n const git = config.integrations.git;\n if (!git.config?.owner || !git.config?.repo) {\n issues.push({\n level: 'warning',\n category: 'integrations',\n message: 'Git integration configured but owner/repo not specified',\n fix: 'Add integrations.git.config.owner and integrations.git.config.repo to config',\n });\n }\n }\n\n // Check issue tracker\n if (config.integrations.issue_tracker) {\n const tracker = config.integrations.issue_tracker;\n if (tracker.provider === 'jira' && !tracker.config?.base_url) {\n issues.push({\n level: 'warning',\n category: 'integrations',\n message: 'Jira integration configured but base_url not specified',\n fix: 'Add integrations.issue_tracker.config.base_url to config',\n });\n }\n }\n\n return issues;\n}\n\n/**\n * Validate the CoreAI project\n */\nexport function validate(options: ValidateCommandOptions = {}): ValidateCommandResult {\n const projectRoot = options.projectRoot ?? process.cwd();\n const coreAgentsDir =\n options.coreAgentsDir ?? join(projectRoot, 'node_modules', '@coreai', 'cli', 'agents');\n const checkAgents = options.checkAgents ?? true;\n const checkDirs = options.checkDirs ?? true;\n\n const allIssues: ValidationIssue[] = [];\n\n // Validate config\n const { config, issues: configIssues } = validateConfig(projectRoot);\n allIssues.push(...configIssues);\n\n // If config loaded successfully, validate other aspects\n if (config) {\n // Validate agents\n if (checkAgents) {\n allIssues.push(...validateAgents(config, coreAgentsDir, projectRoot));\n }\n\n // Validate integrations\n allIssues.push(...validateIntegrations(config));\n }\n\n // Validate directories (independent of config)\n if (checkDirs) {\n allIssues.push(...validateDirectories(projectRoot));\n }\n\n // Calculate summary\n const summary = {\n errors: allIssues.filter((i) => i.level === 'error').length,\n warnings: allIssues.filter((i) => i.level === 'warning').length,\n info: allIssues.filter((i) => i.level === 'info').length,\n };\n\n return {\n success: true,\n valid: summary.errors === 0,\n config,\n issues: allIssues,\n summary,\n };\n}\n\n/**\n * Format validate result for display\n */\nexport function formatValidateResult(result: ValidateCommandResult): string {\n const lines: string[] = [];\n\n // Header\n if (result.valid) {\n lines.push('✓ Configuration is valid\\n');\n } else {\n lines.push('✗ Configuration has errors\\n');\n }\n\n // Group issues by category\n const categories = ['config', 'agents', 'integrations', 'directories', 'quality_gates'] as const;\n\n for (const category of categories) {\n const categoryIssues = result.issues.filter((i) => i.category === category);\n if (categoryIssues.length === 0) continue;\n\n const categoryLabel = category.charAt(0).toUpperCase() + category.slice(1).replace('_', ' ');\n lines.push(`${categoryLabel}:`);\n\n for (const issue of categoryIssues) {\n const prefix = issue.level === 'error' ? ' ✗' : issue.level === 'warning' ? ' ⚠' : ' ℹ';\n lines.push(`${prefix} ${issue.message}`);\n if (issue.fix) {\n lines.push(` → ${issue.fix}`);\n }\n }\n lines.push('');\n }\n\n // Summary\n lines.push('Summary:');\n lines.push(` Errors: ${result.summary.errors}`);\n lines.push(` Warnings: ${result.summary.warnings}`);\n lines.push(` Info: ${result.summary.info}`);\n\n return lines.join('\\n');\n}\n","/**\n * Skills Command\n *\n * Generates Claude skills from templates based on project configuration.\n */\n\nimport { configExists, loadConfig, ConfigError } from '../../config/loader.js';\nimport type { ResolvedCoreAIConfig } from '../../config/types.js';\nimport {\n generateSkills,\n formatGenerateResult,\n discoverSkills,\n getCoreSkillsDir,\n type GenerateSkillsOptions,\n type GenerateSkillsResult,\n} from '../../skills/index.js';\n\n/**\n * Options for skills generate command\n */\nexport interface SkillsGenerateOptions {\n /**\n * Project root directory\n */\n projectRoot?: string;\n\n /**\n * Output directory for generated skills\n */\n outputDir?: string;\n\n /**\n * Directory containing custom skill templates\n */\n customTemplatesDir?: string;\n\n /**\n * Only generate specific skills\n */\n skills?: string[];\n\n /**\n * Include core skills (default: true)\n */\n includeCoreSkills?: boolean;\n\n /**\n * Overwrite existing skill files\n */\n overwrite?: boolean;\n\n /**\n * Additional variables for template substitution\n */\n variables?: Record<string, string>;\n}\n\n/**\n * Result of skills generate command\n */\nexport interface SkillsGenerateResult {\n success: boolean;\n result?: GenerateSkillsResult;\n config?: ResolvedCoreAIConfig;\n error?: string;\n warnings?: string[];\n}\n\n/**\n * Generate skills from templates\n */\nexport function skillsGenerate(options: SkillsGenerateOptions = {}): SkillsGenerateResult {\n const projectRoot = options.projectRoot ?? process.cwd();\n const warnings: string[] = [];\n\n // Load config if available\n let config: ResolvedCoreAIConfig | undefined;\n if (configExists(projectRoot)) {\n try {\n config = loadConfig(projectRoot);\n } catch (error) {\n if (error instanceof ConfigError) {\n return {\n success: false,\n error: `Configuration error: ${error.message}`,\n };\n }\n return {\n success: false,\n error: `Failed to load config: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n } else {\n warnings.push('No configuration file found. Generating skills with defaults.');\n }\n\n // Set up generate options\n const generateOptions: GenerateSkillsOptions = {\n projectRoot,\n includeCoreSkills: options.includeCoreSkills ?? true,\n overwrite: options.overwrite ?? true,\n };\n\n if (options.outputDir) {\n generateOptions.outputDir = options.outputDir;\n }\n\n if (options.customTemplatesDir) {\n generateOptions.customTemplatesDir = options.customTemplatesDir;\n }\n\n if (options.skills && options.skills.length > 0) {\n generateOptions.skills = options.skills;\n }\n\n if (options.variables) {\n generateOptions.variables = options.variables;\n }\n\n // Generate skills\n try {\n const result = generateSkills(config, generateOptions);\n\n // Check for errors\n if (result.errors.length > 0) {\n return {\n success: false,\n result,\n config,\n error: `Failed to generate ${result.errors.length} skill(s)`,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n }\n\n return {\n success: true,\n result,\n config,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n } catch (error) {\n return {\n success: false,\n error: `Skill generation failed: ${error instanceof Error ? error.message : String(error)}`,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n }\n}\n\n/**\n * Format skills generate result for display\n */\nexport function formatSkillsGenerateResult(result: SkillsGenerateResult): string {\n const lines: string[] = [];\n\n // Warnings\n if (result.warnings && result.warnings.length > 0) {\n for (const warning of result.warnings) {\n lines.push(`⚠ ${warning}`);\n }\n lines.push('');\n }\n\n if (!result.success) {\n lines.push(`Skill generation failed: ${result.error}`);\n\n // Show individual errors\n if (result.result?.errors && result.result.errors.length > 0) {\n lines.push('');\n for (const error of result.result.errors) {\n lines.push(` ✗ ${error.name}: ${error.error}`);\n }\n }\n\n return lines.join('\\n');\n }\n\n // Use the generator's format function for the detailed output\n if (result.result) {\n return formatGenerateResult(result.result);\n }\n\n lines.push('No skills to generate.');\n return lines.join('\\n');\n}\n\n/**\n * List available skills\n */\nexport interface SkillsListOptions {\n /**\n * Project root directory\n */\n projectRoot?: string;\n\n /**\n * Directory containing custom skill templates\n */\n customTemplatesDir?: string;\n\n /**\n * Include core skills\n */\n includeCoreSkills?: boolean;\n}\n\n/**\n * Information about an available skill\n */\nexport interface SkillInfo {\n name: string;\n description: string;\n category: string;\n dependencies?: string[];\n argumentHint?: string;\n}\n\n/**\n * Result of skills list command\n */\nexport interface SkillsListResult {\n success: boolean;\n skills?: SkillInfo[];\n error?: string;\n}\n\n/**\n * List available skills\n */\nexport function skillsList(options: SkillsListOptions = {}): SkillsListResult {\n try {\n const skills: SkillInfo[] = [];\n\n // Discover skills from source directory\n const coreSkillsDir = getCoreSkillsDir();\n const discovered = discoverSkills(coreSkillsDir);\n\n const includeCoreSkills = options.includeCoreSkills ?? true;\n\n for (const skill of discovered) {\n if (skill.category === 'core' && !includeCoreSkills) continue;\n\n skills.push({\n name: skill.name,\n description: skill.description,\n category: skill.category,\n dependencies: skill.dependencies?.filter((d) => d.required).map((d) => d.type),\n argumentHint: skill.argumentHint,\n });\n }\n\n // Add custom skills if directory specified\n if (options.customTemplatesDir) {\n const customSkills = discoverSkills(options.customTemplatesDir);\n for (const skill of customSkills) {\n skills.push({\n name: skill.name,\n description: skill.description,\n category: skill.category,\n dependencies: skill.dependencies?.filter((d) => d.required).map((d) => d.type),\n argumentHint: skill.argumentHint,\n });\n }\n }\n\n return {\n success: true,\n skills,\n };\n } catch (error) {\n return {\n success: false,\n error: `Failed to list skills: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n}\n\n/**\n * Format skills list result for display\n */\nexport function formatSkillsListResult(result: SkillsListResult): string {\n if (!result.success) {\n return `Error: ${result.error}`;\n }\n\n if (!result.skills || result.skills.length === 0) {\n return 'No skills available.';\n }\n\n const lines: string[] = [];\n lines.push('Available skills:\\n');\n\n // Group by category\n const coreSkills = result.skills.filter((s) => s.category === 'core');\n const customSkills = result.skills.filter((s) => s.category === 'custom');\n\n if (coreSkills.length > 0) {\n lines.push('Core skills:');\n for (const skill of coreSkills) {\n lines.push(` ${skill.name}`);\n lines.push(` ${skill.description}`);\n if (skill.argumentHint) {\n lines.push(` Argument: ${skill.argumentHint}`);\n }\n }\n lines.push('');\n }\n\n if (customSkills.length > 0) {\n lines.push('Custom skills:');\n for (const skill of customSkills) {\n lines.push(` ${skill.name}`);\n lines.push(` ${skill.description}`);\n if (skill.argumentHint) {\n lines.push(` Argument: ${skill.argumentHint}`);\n }\n }\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n","/**\n * Status Command\n *\n * Shows agent states and pending messages.\n */\n\nimport { configExists, loadConfig, ConfigError } from '../../config/loader.js';\nimport type { ResolvedCoreAIConfig } from '../../config/types.js';\nimport {\n getKnowledgeLibraryState,\n getAgentKnowledgeState,\n initKnowledgeLibrary,\n type KnowledgeLibraryState,\n} from '../../knowledge-library/index.js';\n\n/**\n * Options for status command\n */\nexport interface StatusCommandOptions {\n /**\n * Project root directory\n */\n projectRoot?: string;\n\n /**\n * Show status for specific agent only\n */\n agent?: string;\n\n /**\n * Show detailed status including message subjects\n */\n detailed?: boolean;\n\n /**\n * Initialize KnowledgeLibrary if not exists\n */\n init?: boolean;\n}\n\n/**\n * Agent status info\n */\nexport interface AgentStatus {\n /**\n * Agent name/role\n */\n name: string;\n\n /**\n * Whether the agent's KnowledgeLibrary is initialized\n */\n initialized: boolean;\n\n /**\n * Current status (e.g., \"idle\", \"working\")\n */\n status?: string;\n\n /**\n * Current task\n */\n currentTask?: string;\n\n /**\n * Current ticket\n */\n currentTicket?: string;\n\n /**\n * Number of pending inbox messages\n */\n pendingMessages: number;\n\n /**\n * Last activity timestamp\n */\n lastActivity?: Date;\n\n /**\n * Message details (if detailed mode)\n */\n messageDetails?: {\n type: string;\n from: string;\n subject: string;\n date?: Date;\n }[];\n}\n\n/**\n * Result of status command\n */\nexport interface StatusCommandResult {\n success: boolean;\n knowledgeLibrary?: KnowledgeLibraryState;\n agents: AgentStatus[];\n error?: string;\n warnings?: string[];\n}\n\n/**\n * Get status of agents and KnowledgeLibrary\n */\nexport function status(options: StatusCommandOptions = {}): StatusCommandResult {\n const projectRoot = options.projectRoot ?? process.cwd();\n const warnings: string[] = [];\n\n // Load config if available to get team agents\n let config: ResolvedCoreAIConfig | undefined;\n let configuredAgents: string[] = [];\n\n if (configExists(projectRoot)) {\n try {\n config = loadConfig(projectRoot);\n if (config.team?.agents) {\n configuredAgents = config.team.agents;\n }\n } catch (error) {\n if (error instanceof ConfigError) {\n warnings.push(`Configuration error: ${error.message}`);\n } else {\n warnings.push(\n `Failed to load config: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n } else {\n warnings.push('No configuration file found.');\n }\n\n // Get KnowledgeLibrary state\n let klState = getKnowledgeLibraryState({ projectRoot });\n\n // Initialize if requested and doesn't exist\n if (!klState && options.init) {\n const initResult = initKnowledgeLibrary({ projectRoot, createDefaults: true });\n if (initResult.success) {\n klState = getKnowledgeLibraryState({ projectRoot });\n } else {\n return {\n success: false,\n agents: [],\n error: `Failed to initialize KnowledgeLibrary: ${initResult.error}`,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n }\n }\n\n if (!klState) {\n return {\n success: true,\n agents: [],\n warnings: [\n ...warnings,\n 'KnowledgeLibrary not initialized. Run `coreai status --init` to create it.',\n ],\n };\n }\n\n // Determine which agents to show status for\n let agentsToCheck: string[];\n if (options.agent) {\n agentsToCheck = [options.agent];\n } else {\n // Combine configured agents and discovered agents\n agentsToCheck = [...new Set([...configuredAgents, ...klState.agents])];\n }\n\n // Get status for each agent\n const agentStatuses: AgentStatus[] = [];\n\n for (const agentName of agentsToCheck) {\n const agentState = getAgentKnowledgeState(agentName, { projectRoot });\n\n const agentStatus: AgentStatus = {\n name: agentName,\n initialized: agentState.initialized,\n pendingMessages: agentState.pendingMessages.length,\n };\n\n if (agentState.context) {\n agentStatus.status = agentState.context.status;\n agentStatus.currentTask = agentState.context.currentTask;\n agentStatus.currentTicket = agentState.context.currentTicket;\n agentStatus.lastActivity = agentState.context.lastUpdated;\n }\n\n // Add message details if detailed mode\n if (options.detailed && agentState.pendingMessages.length > 0) {\n agentStatus.messageDetails = agentState.pendingMessages.map((msg) => ({\n type: msg.metadata.type ?? 'unknown',\n from: msg.metadata.from ?? 'unknown',\n subject: msg.metadata.subject ?? msg.filename,\n date: msg.metadata.date,\n }));\n }\n\n agentStatuses.push(agentStatus);\n }\n\n // Sort by pending messages (most first), then by name\n agentStatuses.sort((a, b) => {\n if (b.pendingMessages !== a.pendingMessages) {\n return b.pendingMessages - a.pendingMessages;\n }\n return a.name.localeCompare(b.name);\n });\n\n return {\n success: true,\n knowledgeLibrary: klState,\n agents: agentStatuses,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n}\n\n/**\n * Format status result for display\n */\nexport function formatStatusResult(result: StatusCommandResult): string {\n const lines: string[] = [];\n\n // Warnings\n if (result.warnings && result.warnings.length > 0) {\n for (const warning of result.warnings) {\n lines.push(`⚠ ${warning}`);\n }\n lines.push('');\n }\n\n if (!result.success) {\n lines.push(`Error: ${result.error}`);\n return lines.join('\\n');\n }\n\n if (result.agents.length === 0) {\n lines.push('No agents found.');\n return lines.join('\\n');\n }\n\n lines.push('Agent Status\\n');\n\n // Summary table header\n const activeAgents = result.agents.filter((a) => a.status === 'working');\n const idleAgents = result.agents.filter(\n (a) => a.initialized && (!a.status || a.status === 'idle')\n );\n const uninitializedAgents = result.agents.filter((a) => !a.initialized);\n const totalPending = result.agents.reduce((sum, a) => sum + a.pendingMessages, 0);\n\n lines.push(`Total agents: ${result.agents.length}`);\n if (activeAgents.length > 0) {\n lines.push(` Active: ${activeAgents.length}`);\n }\n if (idleAgents.length > 0) {\n lines.push(` Idle: ${idleAgents.length}`);\n }\n if (uninitializedAgents.length > 0) {\n lines.push(` Not initialized: ${uninitializedAgents.length}`);\n }\n if (totalPending > 0) {\n lines.push(` Total pending messages: ${totalPending}`);\n }\n lines.push('');\n\n // Detailed agent list\n for (const agent of result.agents) {\n const statusIcon = !agent.initialized ? '○' : agent.pendingMessages > 0 ? '●' : '◎';\n const statusText = !agent.initialized ? 'not initialized' : (agent.status ?? 'idle');\n\n lines.push(`${statusIcon} ${agent.name}`);\n lines.push(` Status: ${statusText}`);\n\n if (agent.currentTask) {\n lines.push(` Task: ${agent.currentTask}`);\n }\n\n if (agent.currentTicket) {\n lines.push(` Ticket: ${agent.currentTicket}`);\n }\n\n if (agent.pendingMessages > 0) {\n lines.push(` Pending messages: ${agent.pendingMessages}`);\n\n // Show message details if available\n if (agent.messageDetails && agent.messageDetails.length > 0) {\n for (const msg of agent.messageDetails) {\n const dateStr = msg.date ? msg.date.toISOString().slice(0, 16).replace('T', ' ') : '';\n lines.push(` - [${msg.type}] from ${msg.from}: ${msg.subject}`);\n if (dateStr) {\n lines.push(` ${dateStr}`);\n }\n }\n }\n }\n\n if (agent.lastActivity) {\n const activityStr = agent.lastActivity.toISOString().slice(0, 16).replace('T', ' ');\n lines.push(` Last activity: ${activityStr}`);\n }\n\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Format a compact status summary\n */\nexport function formatStatusSummary(result: StatusCommandResult): string {\n if (!result.success) {\n return `Error: ${result.error}`;\n }\n\n const activeCount = result.agents.filter((a) => a.status === 'working').length;\n const pendingCount = result.agents.reduce((sum, a) => sum + a.pendingMessages, 0);\n\n const parts: string[] = [];\n parts.push(`${result.agents.length} agents`);\n\n if (activeCount > 0) {\n parts.push(`${activeCount} active`);\n }\n\n if (pendingCount > 0) {\n parts.push(`${pendingCount} pending messages`);\n }\n\n return parts.join(', ');\n}\n","/**\n * Agents Commands\n *\n * Commands to manage agents in the CoreAI configuration.\n */\n\nimport { readFileSync, writeFileSync } from 'fs';\nimport { join, dirname } from 'path';\nimport { parse as parseYaml, stringify as stringifyYaml } from 'yaml';\nimport { loadAllAgents } from '../../agents/index.js';\nimport { findConfigFile } from '../../config/loader.js';\nimport type { CoreAIConfig } from '../../config/types.js';\n\n/**\n * Options for agents add command\n */\nexport interface AgentsAddOptions {\n /**\n * Project root directory\n */\n projectRoot?: string | undefined;\n\n /**\n * Core agents directory\n */\n coreAgentsDir?: string | undefined;\n\n /**\n * Skip rebuilding agents after adding\n */\n skipBuild?: boolean | undefined;\n\n /**\n * Add all available core agents\n */\n all?: boolean | undefined;\n}\n\n/**\n * Result of agents add command\n */\nexport interface AgentsAddResult {\n success: boolean;\n added: string[];\n alreadyExists: string[];\n notFound: string[];\n configPath?: string;\n error?: string;\n}\n\n/**\n * Options for agents remove command\n */\nexport interface AgentsRemoveOptions {\n /**\n * Project root directory\n */\n projectRoot?: string | undefined;\n\n /**\n * Core agents directory\n */\n coreAgentsDir?: string | undefined;\n\n /**\n * Skip rebuilding agents after removing\n */\n skipBuild?: boolean | undefined;\n\n /**\n * Remove all agents from config\n */\n all?: boolean | undefined;\n}\n\n/**\n * Result of agents remove command\n */\nexport interface AgentsRemoveResult {\n success: boolean;\n removed: string[];\n notInConfig: string[];\n configPath?: string;\n error?: string;\n}\n\n/**\n * Read and parse the config file preserving structure\n */\nfunction readConfigFile(configPath: string): { content: string; parsed: CoreAIConfig } {\n const content = readFileSync(configPath, 'utf-8');\n const parsed = parseYaml(content) as CoreAIConfig;\n return { content, parsed };\n}\n\n/**\n * Update the team.agents array in the config file\n * Preserves comments and formatting as much as possible\n */\nfunction updateConfigAgents(configPath: string, agents: string[]): void {\n const content = readFileSync(configPath, 'utf-8');\n const parsed = parseYaml(content) as CoreAIConfig;\n\n // Initialize team if not exists\n if (!parsed.team) {\n parsed.team = {};\n }\n\n // Update agents list\n parsed.team.agents = agents;\n\n // Write back to file\n const newContent = stringifyYaml(parsed, {\n indent: 2,\n lineWidth: 0,\n singleQuote: false,\n });\n\n writeFileSync(configPath, newContent, 'utf-8');\n}\n\n/**\n * Get list of available agent roles\n */\nfunction getAvailableAgents(\n coreAgentsDir: string,\n customAgentsDir: string\n): Map<string, 'core' | 'custom'> {\n const available = new Map<string, 'core' | 'custom'>();\n\n const allAgents = loadAllAgents({\n coreAgentsDir,\n customAgentsDir,\n });\n\n for (const [role, meta] of allAgents) {\n available.set(role, meta.source === 'core' ? 'core' : 'custom');\n }\n\n return available;\n}\n\n/**\n * Add agents to the CoreAI configuration\n */\nexport function agentsAdd(agents: string[], options: AgentsAddOptions = {}): AgentsAddResult {\n const projectRoot = options.projectRoot ?? process.cwd();\n const coreAgentsDir = options.coreAgentsDir ?? join(dirname(dirname(dirname(__dirname))), 'agents');\n const customAgentsDir = join(projectRoot, 'coreai', 'agents');\n\n // Find config file\n const configPath = findConfigFile(projectRoot);\n if (!configPath) {\n return {\n success: false,\n added: [],\n alreadyExists: [],\n notFound: [],\n error: 'No coreai.config.yaml found. Run `coreai init` first.',\n };\n }\n\n // Get available agents\n const availableAgents = getAvailableAgents(coreAgentsDir, customAgentsDir);\n\n // If --all flag, use all available agents\n const agentsToAdd = options.all ? Array.from(availableAgents.keys()) : agents;\n\n if (agentsToAdd.length === 0) {\n return {\n success: false,\n added: [],\n alreadyExists: [],\n notFound: [],\n configPath,\n error: 'No agents specified. Use --all to add all agents or provide a comma-separated list.',\n };\n }\n\n // Read current config\n const { parsed } = readConfigFile(configPath);\n const currentAgents = parsed.team?.agents ?? [];\n\n const added: string[] = [];\n const alreadyExists: string[] = [];\n const notFound: string[] = [];\n\n for (const agent of agentsToAdd) {\n const trimmedAgent = agent.trim();\n\n if (!availableAgents.has(trimmedAgent)) {\n notFound.push(trimmedAgent);\n continue;\n }\n\n if (currentAgents.includes(trimmedAgent)) {\n alreadyExists.push(trimmedAgent);\n continue;\n }\n\n added.push(trimmedAgent);\n }\n\n // Update config if there are agents to add\n if (added.length > 0) {\n const newAgents = [...currentAgents, ...added].sort();\n try {\n updateConfigAgents(configPath, newAgents);\n } catch (error) {\n return {\n success: false,\n added: [],\n alreadyExists,\n notFound,\n configPath,\n error: `Failed to update config: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n\n return {\n success: notFound.length === 0,\n added,\n alreadyExists,\n notFound,\n configPath,\n };\n}\n\n/**\n * Remove agents from the CoreAI configuration\n */\nexport function agentsRemove(agents: string[], options: AgentsRemoveOptions = {}): AgentsRemoveResult {\n const projectRoot = options.projectRoot ?? process.cwd();\n\n // Find config file\n const configPath = findConfigFile(projectRoot);\n if (!configPath) {\n return {\n success: false,\n removed: [],\n notInConfig: [],\n error: 'No coreai.config.yaml found. Run `coreai init` first.',\n };\n }\n\n // Read current config\n const { parsed } = readConfigFile(configPath);\n const currentAgents = parsed.team?.agents ?? [];\n\n // If --all flag, remove all agents\n const agentsToRemove = options.all ? [...currentAgents] : agents;\n\n if (agentsToRemove.length === 0) {\n return {\n success: false,\n removed: [],\n notInConfig: [],\n configPath,\n error: 'No agents specified. Use --all to remove all agents or provide a comma-separated list.',\n };\n }\n\n const removed: string[] = [];\n const notInConfig: string[] = [];\n\n for (const agent of agentsToRemove) {\n const trimmedAgent = agent.trim();\n\n if (!currentAgents.includes(trimmedAgent)) {\n notInConfig.push(trimmedAgent);\n continue;\n }\n\n removed.push(trimmedAgent);\n }\n\n // Update config if there are agents to remove\n if (removed.length > 0) {\n const newAgents = currentAgents.filter((a) => !removed.includes(a));\n try {\n updateConfigAgents(configPath, newAgents);\n } catch (error) {\n return {\n success: false,\n removed: [],\n notInConfig,\n configPath,\n error: `Failed to update config: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n\n return {\n success: true,\n removed,\n notInConfig,\n configPath,\n };\n}\n\n/**\n * Format agents add result for display\n */\nexport function formatAgentsAddResult(result: AgentsAddResult): string {\n const lines: string[] = [];\n\n if (!result.success && result.error) {\n return `Error: ${result.error}`;\n }\n\n if (result.added.length > 0) {\n lines.push('Added agents:');\n for (const agent of result.added) {\n lines.push(` + ${agent}`);\n }\n }\n\n if (result.alreadyExists.length > 0) {\n if (lines.length > 0) lines.push('');\n lines.push('Already in config:');\n for (const agent of result.alreadyExists) {\n lines.push(` = ${agent}`);\n }\n }\n\n if (result.notFound.length > 0) {\n if (lines.length > 0) lines.push('');\n lines.push('Not found (run `coreai agents list` to see available):');\n for (const agent of result.notFound) {\n lines.push(` ! ${agent}`);\n }\n }\n\n if (result.added.length === 0 && result.alreadyExists.length === 0 && result.notFound.length === 0) {\n lines.push('No changes made.');\n }\n\n if (result.added.length > 0) {\n lines.push('');\n lines.push('Run `coreai build` to compile the updated agent list.');\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Format agents remove result for display\n */\nexport function formatAgentsRemoveResult(result: AgentsRemoveResult): string {\n const lines: string[] = [];\n\n if (!result.success && result.error) {\n return `Error: ${result.error}`;\n }\n\n if (result.removed.length > 0) {\n lines.push('Removed agents:');\n for (const agent of result.removed) {\n lines.push(` - ${agent}`);\n }\n }\n\n if (result.notInConfig.length > 0) {\n if (lines.length > 0) lines.push('');\n lines.push('Not in config:');\n for (const agent of result.notInConfig) {\n lines.push(` ? ${agent}`);\n }\n }\n\n if (result.removed.length === 0 && result.notInConfig.length === 0) {\n lines.push('No changes made.');\n }\n\n if (result.removed.length > 0) {\n lines.push('');\n lines.push('Run `coreai build` to compile the updated agent list.');\n }\n\n return lines.join('\\n');\n}\n"],"mappings":";;;AAQA,SAAS,QAAAA,QAAM,WAAAC,gBAAe;AAC9B,SAAS,iBAAAC,sBAAqB;AAC9B,SAAS,e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AAa,QAAQ,IAAI;AAAA,IACzB,mBAAmB,QAAQ,SAAS;AAAA,EACtC,CAAC;AAED,MAAI,QAAQ,MAAM;AAChB,YAAQ,IAAI,KAAK,UAAU,QAAQ,MAAM,CAAC,CAAC;AAC3C;AAAA,EACF;AAEA,UAAQ,IAAI,uBAAuB,MAAM,CAAC;AAE1C,MAAI,CAAC,OAAO,SAAS;AACnB,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF,CAAC;AAEH,QAAQ,MAAM;","names":["join","dirname","fileURLToPath","readFileSync","dirname","join","require","validate","existsSync","readFileSync","join","parseYaml","Ajv","createRequire","require","validate","agents","existsSync","readFileSync","join","dirname","extname","parseYaml","join","existsSync","readFileSync","dirname","parseYaml","extname","agents","existsSync","readFileSync","join","dirname","join","existsSync","readFileSync","dirname","join","dirname","join","status","dirname","status","existsSync","mkdirSync","writeFileSync","readFileSync","readdirSync","join","dirname","extractVariables","existsSync","mkdirSync","writeFileSync","readFileSync","readdirSync","statSync","join","basename","join","existsSync","readdirSync","statSync","readFileSync","join","existsSync","agents","readdirSync","statSync","dirname","join","readFileSync","join","join","status","join","getCachePath","join","existsSync","writeFileSync","mkdirSync","readFileSync","join","basename","join","existsSync","readFileSync","basename","mkdirSync","writeFileSync","existsSync","join","validateConfig","join","existsSync","readFileSync","writeFileSync","join","dirname","parseYaml","stringifyYaml","readFileSync","parseYaml","agents","stringifyYaml","writeFileSync","join","dirname","fileURLToPath","__dirname","dirname","join","agents"]}
1
+ {"version":3,"sources":["../../src/cli/index.ts","../../src/index.ts","../../src/config/loader.ts","../../src/agents/types.ts","../../src/agents/loader.ts","../../src/agents/resolver.ts","../../src/agents/compiler.ts","../../src/adapters/mcp/types.ts","../../src/adapters/mcp/client.ts","../../src/adapters/mcp/discovery.ts","../../src/adapters/native/github.ts","../../src/cache/types.ts","../../src/cache/provider.ts","../../src/cache/manager.ts","../../src/skills/generator.ts","../../src/knowledge-library/manager.ts","../../src/cli/commands/cache.ts","../../src/cli/commands/sync.ts","../../src/cli/commands/init.ts","../../src/cli/commands/build.ts","../../src/cli/commands/validate.ts","../../src/cli/commands/skills.ts","../../src/cli/commands/status.ts","../../src/cli/commands/agents.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * CoreAI CLI - Entry point\n *\n * A configurable, team-ready AI agent orchestration platform.\n */\n\nimport { join, dirname } from 'path';\nimport { fileURLToPath } from 'url';\nimport { Command } from 'commander';\nimport { VERSION } from '../index.js';\nimport { loadAllAgents, generateAgentMarkdown } from '../agents/index.js';\nimport {\n cacheStatus,\n cacheClear,\n cacheClearExpired,\n formatCacheStatus,\n sync,\n formatSyncResult,\n init,\n formatInitResult,\n build,\n formatBuildResult,\n validate,\n formatValidateResult,\n status,\n formatStatusResult,\n skillsGenerate,\n formatSkillsGenerateResult,\n skillsList,\n formatSkillsListResult,\n agentsAdd,\n agentsRemove,\n formatAgentsAddResult,\n formatAgentsRemoveResult,\n} from './commands/index.js';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\n/**\n * Get the path to built-in core agents\n */\nfunction getCoreAgentsPath(): string {\n // Navigate from dist/cli/index.js to agents/\n return join(__dirname, '..', '..', 'agents');\n}\n\nconst program = new Command();\n\nprogram\n .name('coreai')\n .description('A configurable, team-ready AI agent orchestration platform')\n .version(VERSION, '-v, --version', 'output the current version');\n\n// Init command - initialize a new CoreAI project\nprogram\n .command('init')\n .description('Initialize a new CoreAI project')\n .option('-f, --force', 'overwrite existing configuration')\n .option('-n, --name <name>', 'project name')\n .option('-t, --type <type>', 'project type (software, infrastructure, data, mobile)')\n .option('--skip-dirs', 'skip creating directory structure')\n .action((options: { force?: boolean; name?: string; type?: string; skipDirs?: boolean }) => {\n const result = init({\n projectRoot: process.cwd(),\n force: options.force,\n name: options.name,\n type: options.type as 'software' | 'infrastructure' | 'data' | 'mobile',\n skipDirs: options.skipDirs,\n });\n\n console.log(formatInitResult(result));\n\n if (!result.success) {\n process.exit(1);\n }\n });\n\n// Build command - compile agents to .claude/agents/\nprogram\n .command('build')\n .description('Compile agent definitions to Claude-compatible markdown')\n .option('-w, --watch', 'watch for changes and rebuild')\n .option('-o, --output <dir>', 'output directory (default: .claude/agents)')\n .option('--agents <agents>', 'comma-separated list of agents to build')\n .option('--init-knowledge-library', 'initialize KnowledgeLibrary directories for agents')\n .action(\n (options: {\n watch?: boolean;\n output?: string;\n agents?: string;\n initKnowledgeLibrary?: boolean;\n }) => {\n if (options.watch) {\n console.log('Watch mode is not yet implemented');\n process.exit(1);\n }\n\n console.log('Building agents...\\n');\n\n const result = build({\n projectRoot: process.cwd(),\n coreAgentsDir: getCoreAgentsPath(),\n outputDir: options.output,\n agents: options.agents?.split(',').map((a) => a.trim()),\n initKnowledgeLibrary: options.initKnowledgeLibrary,\n });\n\n console.log(formatBuildResult(result));\n\n if (!result.success) {\n process.exit(1);\n }\n }\n );\n\n// Sync command - sync shared context from remote sources\nprogram\n .command('sync')\n .description('Sync shared context from remote sources')\n .option('--force', 'force refresh all cached content')\n .option('--source <source>', 'filter by source (github, confluence, notion)')\n .option('--concurrency <n>', 'max concurrent fetches', '5')\n .action(async (options: { force?: boolean; source?: string; concurrency?: string }) => {\n try {\n console.log('Syncing shared context...\\n');\n\n const result = await sync({\n projectRoot: process.cwd(),\n force: options.force,\n source: options.source as 'github' | 'confluence' | 'notion' | 'local' | 'custom',\n concurrency: parseInt(options.concurrency ?? '5', 10),\n continueOnError: true,\n onProgress: (completed, total, message) => {\n process.stdout.write(`\\r${message}`);\n },\n });\n\n // Clear the progress line\n process.stdout.write('\\r' + ' '.repeat(60) + '\\r');\n\n console.log(formatSyncResult(result));\n\n if (!result.success) {\n process.exit(1);\n }\n } catch (error) {\n console.error(`Sync failed: ${error instanceof Error ? error.message : error}`);\n process.exit(1);\n }\n });\n\n// Validate command - validate configuration and setup\nprogram\n .command('validate')\n .description('Validate configuration and project setup')\n .option('--skip-agents', 'skip agent validation')\n .option('--skip-dirs', 'skip directory validation')\n .option('--json', 'output as JSON')\n .action((options: { skipAgents?: boolean; skipDirs?: boolean; json?: boolean }) => {\n const result = validate({\n projectRoot: process.cwd(),\n coreAgentsDir: getCoreAgentsPath(),\n checkAgents: !options.skipAgents,\n checkDirs: !options.skipDirs,\n });\n\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log(formatValidateResult(result));\n }\n\n if (!result.valid) {\n process.exit(1);\n }\n });\n\n// Agents subcommand group\nconst agents = program.command('agents').description('Manage agent definitions');\n\nagents\n .command('list')\n .description('List available agents')\n .option('--core', 'show only core agents')\n .option('--custom', 'show only custom agents')\n .action((options: { core?: boolean; custom?: boolean }) => {\n try {\n const customAgentsDir = join(process.cwd(), 'coreai', 'agents');\n\n const allAgents = loadAllAgents({\n coreAgentsDir: getCoreAgentsPath(),\n customAgentsDir,\n });\n\n if (allAgents.size === 0) {\n console.log('No agents found.');\n return;\n }\n\n // Filter by source if requested\n const agents = Array.from(allAgents.entries()).filter(([, meta]) => {\n if (options.core && meta.source !== 'core') return false;\n if (options.custom && meta.source !== 'custom' && meta.source !== 'override') return false;\n return true;\n });\n\n if (agents.length === 0) {\n console.log('No matching agents found.');\n return;\n }\n\n console.log('Available agents:\\n');\n\n // Group by source\n const coreAgents = agents.filter(([, m]) => m.source === 'core');\n const customAgents = agents.filter(([, m]) => m.source === 'custom');\n const overrideAgents = agents.filter(([, m]) => m.source === 'override');\n\n if (coreAgents.length > 0 && !options.custom) {\n console.log('Core agents:');\n for (const [role, meta] of coreAgents) {\n console.log(` ${role} (${meta.definition.type})`);\n console.log(` ${meta.definition.display_name}`);\n }\n console.log();\n }\n\n if (customAgents.length > 0 && !options.core) {\n console.log('Custom agents:');\n for (const [role, meta] of customAgents) {\n console.log(` ${role} (${meta.definition.type})`);\n console.log(` ${meta.definition.display_name}`);\n }\n console.log();\n }\n\n if (overrideAgents.length > 0 && !options.core) {\n console.log('Override agents:');\n for (const [role, meta] of overrideAgents) {\n console.log(` ${role} (${meta.definition.type})`);\n console.log(` ${meta.definition.display_name} [overrides core]`);\n }\n console.log();\n }\n\n console.log(`Total: ${agents.length} agent(s)`);\n } catch (error) {\n console.error(`Failed to list agents: ${error instanceof Error ? error.message : error}`);\n process.exit(1);\n }\n });\n\nagents\n .command('show <name>')\n .description('Show details for a specific agent')\n .option('--markdown', 'output as compiled markdown')\n .option('--json', 'output as JSON')\n .action((name: string, options: { markdown?: boolean; json?: boolean }) => {\n try {\n const customAgentsDir = join(process.cwd(), 'coreai', 'agents');\n\n const allAgents = loadAllAgents({\n coreAgentsDir: getCoreAgentsPath(),\n customAgentsDir,\n });\n\n const agentMeta = allAgents.get(name);\n\n if (!agentMeta) {\n console.error(`Agent not found: ${name}`);\n console.log('\\nAvailable agents:');\n for (const role of allAgents.keys()) {\n console.log(` - ${role}`);\n }\n process.exit(1);\n }\n\n const agent = agentMeta.definition;\n\n if (options.json) {\n console.log(JSON.stringify(agent, null, 2));\n return;\n }\n\n if (options.markdown) {\n console.log(generateAgentMarkdown(agent));\n return;\n }\n\n // Default: human-readable output\n console.log(`\\n${agent.display_name}`);\n console.log('='.repeat(agent.display_name.length));\n console.log();\n console.log(`Role: ${agent.role}`);\n console.log(`Type: ${agent.type}`);\n console.log(`Source: ${agentMeta.source}`);\n console.log();\n console.log('Description:');\n console.log(` ${agent.description}`);\n\n if (agent.responsibilities && agent.responsibilities.length > 0) {\n console.log();\n console.log('Responsibilities:');\n for (const r of agent.responsibilities) {\n console.log(` - ${r}`);\n }\n }\n\n if (agent.expertise?.primary && agent.expertise.primary.length > 0) {\n console.log();\n console.log('Expertise:');\n for (const e of agent.expertise.primary) {\n console.log(` - ${e}`);\n }\n }\n\n if (agent.skills && agent.skills.length > 0) {\n console.log();\n console.log('Skills:');\n for (const s of agent.skills) {\n console.log(` - ${s}`);\n }\n }\n\n if (agent.behaviors?.workflow) {\n console.log();\n console.log(`Workflow: ${agent.behaviors.workflow}`);\n }\n\n console.log();\n console.log(`File: ${agentMeta.filePath}`);\n } catch (error) {\n console.error(`Failed to show agent: ${error instanceof Error ? error.message : error}`);\n process.exit(1);\n }\n });\n\nagents\n .command('add [agents...]')\n .description('Add agents to your project configuration')\n .option('--all', 'add all available core agents')\n .option('--no-build', 'skip rebuilding agents after adding')\n .action(async (agentNames: string[] = [], options: { all?: boolean; build?: boolean }) => {\n try {\n // Parse comma-separated agents if provided as single string\n const parsedAgents = agentNames.flatMap((a) => a.split(',').map((s) => s.trim()));\n\n const result = agentsAdd(parsedAgents, {\n projectRoot: process.cwd(),\n coreAgentsDir: getCoreAgentsPath(),\n all: options.all,\n });\n\n console.log(formatAgentsAddResult(result));\n\n if (!result.success) {\n process.exit(1);\n }\n\n // Run build if agents were added and --no-build wasn't specified\n if (result.added.length > 0 && options.build !== false) {\n console.log('\\nRebuilding agents...\\n');\n const buildResult = build({\n projectRoot: process.cwd(),\n coreAgentsDir: getCoreAgentsPath(),\n });\n console.log(formatBuildResult(buildResult));\n\n if (!buildResult.success) {\n process.exit(1);\n }\n }\n } catch (error) {\n console.error(`Failed to add agents: ${error instanceof Error ? error.message : error}`);\n process.exit(1);\n }\n });\n\nagents\n .command('remove [agents...]')\n .description('Remove agents from your project configuration')\n .option('--all', 'remove all agents from config')\n .option('--no-build', 'skip rebuilding agents after removing')\n .action(async (agentNames: string[] = [], options: { all?: boolean; build?: boolean }) => {\n try {\n // Parse comma-separated agents if provided as single string\n const parsedAgents = agentNames.flatMap((a) => a.split(',').map((s) => s.trim()));\n\n const result = agentsRemove(parsedAgents, {\n projectRoot: process.cwd(),\n all: options.all,\n });\n\n console.log(formatAgentsRemoveResult(result));\n\n if (!result.success) {\n process.exit(1);\n }\n\n // Run build if agents were removed and --no-build wasn't specified\n if (result.removed.length > 0 && options.build !== false) {\n console.log('\\nRebuilding agents...\\n');\n const buildResult = build({\n projectRoot: process.cwd(),\n coreAgentsDir: getCoreAgentsPath(),\n });\n console.log(formatBuildResult(buildResult));\n\n if (!buildResult.success) {\n process.exit(1);\n }\n }\n } catch (error) {\n console.error(`Failed to remove agents: ${error instanceof Error ? error.message : error}`);\n process.exit(1);\n }\n });\n\n// Cache subcommand group\nconst cacheCmd = program.command('cache').description('Manage local cache');\n\ncacheCmd\n .command('clear')\n .description('Clear the local cache')\n .option('--expired', 'only clear expired entries')\n .option('--json', 'output as JSON')\n .action(async (options: { expired?: boolean; json?: boolean }) => {\n try {\n const result = options.expired\n ? await cacheClearExpired({ projectRoot: process.cwd() })\n : await cacheClear({ projectRoot: process.cwd() });\n\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n if (!result.success) {\n console.error(`Failed to clear cache: ${result.error}`);\n process.exit(1);\n }\n\n if (result.cleared === 0) {\n console.log('Cache is already empty.');\n } else {\n const word = result.cleared === 1 ? 'entry' : 'entries';\n console.log(`Cleared ${result.cleared} cache ${word}.`);\n }\n } catch (error) {\n const msg = error instanceof Error ? error.message : error;\n console.error(`Failed to clear cache: ${msg}`);\n process.exit(1);\n }\n });\n\ncacheCmd\n .command('status')\n .description('Show cache status')\n .option('--json', 'output as JSON')\n .action(async (options: { json?: boolean }) => {\n try {\n const result = await cacheStatus({ projectRoot: process.cwd() });\n\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n console.log(formatCacheStatus(result));\n } catch (error) {\n const msg = error instanceof Error ? error.message : error;\n console.error(`Failed to get cache status: ${msg}`);\n process.exit(1);\n }\n });\n\n// Status command - show agent states and pending messages\nprogram\n .command('status')\n .description('Show agent states and pending messages')\n .option('-a, --agent <name>', 'show status for a specific agent')\n .option('-d, --detailed', 'show detailed message information')\n .option('--init', 'initialize KnowledgeLibrary if not exists')\n .option('--json', 'output as JSON')\n .action((options: { agent?: string; detailed?: boolean; init?: boolean; json?: boolean }) => {\n const result = status({\n projectRoot: process.cwd(),\n agent: options.agent,\n detailed: options.detailed,\n init: options.init,\n });\n\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n console.log(formatStatusResult(result));\n\n if (!result.success) {\n process.exit(1);\n }\n });\n\n// Skills subcommand group\nconst skillsCmd = program.command('skills').description('Manage Claude skills');\n\nskillsCmd\n .command('generate')\n .description('Generate Claude skills from source files')\n .option('-o, --output <dir>', 'output directory (default: .claude/skills)')\n .option('--skills <skills>', 'comma-separated list of skills to generate')\n .option('--no-core', 'exclude core skills')\n .option('--no-overwrite', 'do not overwrite existing skill files')\n .option('--json', 'output as JSON')\n .action(\n (options: {\n output?: string;\n skills?: string;\n core?: boolean;\n overwrite?: boolean;\n json?: boolean;\n }) => {\n console.log('Generating skills...\\n');\n\n const result = skillsGenerate({\n projectRoot: process.cwd(),\n outputDir: options.output,\n skills: options.skills?.split(',').map((s) => s.trim()),\n includeCoreSkills: options.core !== false,\n overwrite: options.overwrite !== false,\n });\n\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n console.log(formatSkillsGenerateResult(result));\n\n if (!result.success) {\n process.exit(1);\n }\n }\n );\n\nskillsCmd\n .command('list')\n .description('List available skills')\n .option('--no-core', 'exclude core skills')\n .option('--json', 'output as JSON')\n .action((options: { core?: boolean; json?: boolean }) => {\n const result = skillsList({\n projectRoot: process.cwd(),\n includeCoreSkills: options.core !== false,\n });\n\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n console.log(formatSkillsListResult(result));\n\n if (!result.success) {\n process.exit(1);\n }\n });\n\nprogram.parse();\n","/**\n * CoreAI - A configurable, team-ready AI agent orchestration platform.\n *\n * This is the main library export for programmatic usage.\n */\n\nimport { readFileSync } from 'fs';\nimport { dirname, join } from 'path';\nimport { fileURLToPath } from 'url';\n\n// Find package.json by walking up from the current module\nfunction findPackageJson(): string {\n let dir = dirname(fileURLToPath(import.meta.url));\n while (dir !== dirname(dir)) {\n const pkgPath = join(dir, 'package.json');\n try {\n const content = readFileSync(pkgPath, 'utf-8');\n const pkg = JSON.parse(content);\n if (pkg.name === '@deimoscloud/coreai') {\n return content;\n }\n } catch {\n // Continue searching\n }\n dir = dirname(dir);\n }\n return '{\"version\": \"unknown\"}';\n}\n\nconst packageJson = JSON.parse(findPackageJson());\nexport const VERSION: string = packageJson.version;\n\n// Configuration\nexport {\n loadConfig,\n loadConfigFromFile,\n findConfigFile,\n configExists,\n getConfigPath,\n ConfigError,\n} from './config/index.js';\n\nexport type {\n CoreAIConfig,\n ResolvedCoreAIConfig,\n ProjectConfig,\n TeamConfig,\n IntegrationsConfig,\n QualityGatesConfig,\n CacheConfig,\n ConfigErrorCode,\n} from './config/index.js';\n\n// Agents\nexport {\n loadAgentFromFile,\n loadAgentsFromDirectory,\n parseAgentYaml,\n validateAgentDefinition,\n getRoleFromFilename,\n AgentError,\n resolveString,\n resolveObject,\n resolveAgentDefinition,\n hasVariables,\n extractVariables,\n ResolutionError,\n generateAgentMarkdown,\n compileAgent,\n compileAgents,\n loadAllAgents,\n filterAgentsByTeam,\n getCoreAgentsDir,\n} from './agents/index.js';\n\nexport type {\n AgentDefinition,\n ResolvedAgentDefinition,\n AgentType,\n WorkflowType,\n AgentMetadata,\n AgentSource,\n AgentErrorCode,\n ResolutionContext,\n ResolutionOptions,\n CompileOptions,\n CompileResult,\n} from './agents/index.js';\n\n// Adapters\nexport {\n AdapterFactory,\n createAdapterFactory,\n createAdapterInfo,\n AdapterError,\n} from './adapters/index.js';\n\nexport type {\n AdapterType,\n AdapterImplementation,\n AdapterInfo,\n AdapterFactoryOptions,\n AdapterErrorCode,\n BaseAdapter,\n IssueTrackerAdapter,\n GitProviderAdapter,\n DocumentationProviderAdapter,\n StateProviderAdapter,\n Adapter,\n Issue,\n IssueQuery,\n IssueStatus,\n CreateIssueData,\n UpdateIssueData,\n PullRequest,\n PullRequestQuery,\n PullRequestStatus,\n CreatePullRequestData,\n Review,\n CreateReviewData,\n ReviewDecision,\n ReviewComment,\n DocumentationPage,\n DocumentationQuery,\n StateEntry,\n StateOptions,\n} from './adapters/index.js';\n\n// Cache\nexport {\n CacheError,\n CACHE_PATHS,\n DEFAULT_CACHE_CONFIG,\n FileCacheProvider,\n createFileCacheProvider,\n FileCacheManager,\n createCacheManager,\n} from './cache/index.js';\n\nexport type {\n CacheSource,\n CacheStatus,\n CacheMetadata,\n CacheEntry,\n CacheOptions,\n CacheListOptions,\n CacheStats,\n SyncResult,\n CacheErrorCode,\n CacheProvider,\n RemoteFetcher,\n FetchOptions,\n CacheManager,\n SyncOptions,\n FileCacheProviderOptions,\n CacheManagerOptions,\n} from './cache/index.js';\n\n// Context\nexport { ContextLoader, createContextLoader } from './context/index.js';\n\nexport type {\n ContextSource,\n ContextLoadResult,\n ContextLoaderOptions,\n LoadOptions,\n} from './context/index.js';\n\n// Commands\nexport {\n CommandRegistry,\n createCommandRegistry,\n getGlobalRegistry,\n resetGlobalRegistry,\n createCommandContext,\n cleanupContext,\n withContext,\n loadCommandFromFile,\n loadCommandsFromDirectory,\n loadCoreAICommands,\n loadAllCommands,\n runCommand,\n executeWithDegradation,\n createDegradingHandler,\n StepTracker,\n} from './commands/index.js';\n\nexport type {\n CommandCategory,\n IntegrationDependency,\n CommandMetadata,\n CommandContext,\n BaseCommandOptions,\n CommandResult,\n CommandHandler,\n CommandDefinition,\n CommandOptionDefinition,\n CommandArgumentDefinition,\n MarkdownCommand,\n RegistryEntry,\n CommandLoaderOptions,\n CommandLoadResult,\n CreateContextOptions,\n RunCommandOptions,\n} from './commands/index.js';\n\n// Skills\nexport {\n getCoreSkillsDir,\n discoverSkills,\n parseSkillFile,\n extractVariables as extractSkillVariables,\n substituteVariables,\n checkDependencies,\n generateSkills,\n formatGenerateResult,\n} from './skills/index.js';\n\nexport type {\n SkillTemplate,\n SkillVariables,\n SkillCategory,\n SkillDependency,\n GenerateSkillsOptions,\n GenerateSkillsResult,\n GeneratedSkill,\n SkillError,\n} from './skills/index.js';\n\n// KnowledgeLibrary\nexport {\n DEFAULT_KNOWLEDGE_LIBRARY_PATH,\n STANDARD_FILES,\n AGENT_DIRECTORIES,\n CONTROL_FILES,\n getAgentDirectories,\n initKnowledgeLibrary,\n initAgentKnowledgeLibrary,\n agentKnowledgeLibraryExists,\n getAgentKnowledgeState,\n generateMessageFilename,\n readInboxMessages,\n writeInboxMessage,\n markMessageProcessed,\n getKnowledgeLibraryState,\n updateAgentContext,\n formatKnowledgeLibraryState,\n formatAgentKnowledgeState,\n} from './knowledge-library/index.js';\n\nexport type {\n MessageType,\n MessagePriority,\n MessageMetadata,\n Message,\n AgentContext,\n Objective,\n Decision,\n Dependency,\n AgentControl,\n AgentDirectories,\n AgentKnowledgeState,\n InitKnowledgeLibraryOptions,\n InitKnowledgeLibraryResult,\n ReadMessagesOptions,\n WriteMessageOptions,\n KnowledgeLibraryState,\n} from './knowledge-library/index.js';\n","/**\n * Configuration Loader\n *\n * Handles config file discovery, parsing, validation, and defaults.\n */\n\nimport { existsSync, readFileSync } from 'fs';\nimport { dirname, join, resolve } from 'path';\nimport { parse as parseYaml } from 'yaml';\nimport Ajv, { type ErrorObject } from 'ajv';\nimport addFormats from 'ajv-formats';\nimport type { CoreAIConfig, ResolvedCoreAIConfig } from './types.js';\n\n// Import schema as JSON\nimport { createRequire } from 'module';\nconst require = createRequire(import.meta.url);\nconst configSchema = require('../../schemas/coreai.config.schema.json') as object;\n\nconst CONFIG_FILE_NAME = 'coreai.config.yaml';\nconst CONFIG_FILE_NAMES = [CONFIG_FILE_NAME, 'coreai.config.yml'];\n\nexport class ConfigError extends Error {\n constructor(\n message: string,\n public readonly code: ConfigErrorCode,\n public readonly details?: unknown\n ) {\n super(message);\n this.name = 'ConfigError';\n }\n}\n\nexport type ConfigErrorCode = 'NOT_FOUND' | 'PARSE_ERROR' | 'VALIDATION_ERROR' | 'READ_ERROR';\n\n/**\n * Default team agents\n */\nconst DEFAULT_AGENTS = [\n 'engineering-manager',\n];\n\n/**\n * Find the config file by walking up the directory tree\n */\nexport function findConfigFile(startDir: string = process.cwd()): string | null {\n let currentDir = resolve(startDir);\n const root = dirname(currentDir);\n\n while (currentDir !== root) {\n for (const fileName of CONFIG_FILE_NAMES) {\n const configPath = join(currentDir, fileName);\n if (existsSync(configPath)) {\n return configPath;\n }\n }\n\n const parentDir = dirname(currentDir);\n if (parentDir === currentDir) {\n break;\n }\n currentDir = parentDir;\n }\n\n // Check root directory\n for (const fileName of CONFIG_FILE_NAMES) {\n const configPath = join(currentDir, fileName);\n if (existsSync(configPath)) {\n return configPath;\n }\n }\n\n return null;\n}\n\n/**\n * Parse YAML content into an object\n */\nexport function parseConfig(content: string, filePath?: string): unknown {\n try {\n return parseYaml(content);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown parse error';\n throw new ConfigError(\n `Failed to parse YAML${filePath ? ` in ${filePath}` : ''}: ${message}`,\n 'PARSE_ERROR',\n error\n );\n }\n}\n\n/**\n * Validate config against JSON schema\n */\nexport function validateConfig(config: unknown): CoreAIConfig {\n const ajv = new Ajv.default({ allErrors: true, strict: false });\n addFormats.default(ajv);\n\n const validate = ajv.compile<CoreAIConfig>(configSchema);\n const valid = validate(config);\n\n if (!valid) {\n const errors: ErrorObject[] = validate.errors ?? [];\n const errorMessages = errors.map((err: ErrorObject) => {\n const path = err.instancePath || 'root';\n return `${path}: ${err.message ?? 'unknown error'}`;\n });\n\n throw new ConfigError(\n `Configuration validation failed:\\n - ${errorMessages.join('\\n - ')}`,\n 'VALIDATION_ERROR',\n errors\n );\n }\n\n return config as CoreAIConfig;\n}\n\n/**\n * Apply default values to config\n */\nexport function applyDefaults(config: CoreAIConfig): ResolvedCoreAIConfig {\n const project: ResolvedCoreAIConfig['project'] = {\n name: config.project?.name ?? 'unnamed',\n root: config.project?.root ?? process.cwd(),\n };\n if (config.project?.description) {\n project.description = config.project.description;\n }\n return {\n ...config,\n project,\n team: {\n agents: config.team?.agents ?? DEFAULT_AGENTS,\n },\n };\n}\n\n/**\n * Load and validate configuration from a file path\n */\nexport function loadConfigFromFile(filePath: string): ResolvedCoreAIConfig {\n let content: string;\n\n try {\n content = readFileSync(filePath, 'utf-8');\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown read error';\n throw new ConfigError(\n `Failed to read config file ${filePath}: ${message}`,\n 'READ_ERROR',\n error\n );\n }\n\n const parsed = parseConfig(content, filePath);\n const validated = validateConfig(parsed);\n return applyDefaults(validated);\n}\n\n/**\n * Load configuration by searching for config file\n */\nexport function loadConfig(startDir?: string): ResolvedCoreAIConfig {\n const configPath = findConfigFile(startDir);\n\n if (!configPath) {\n throw new ConfigError(\n `Configuration file not found. Create a ${CONFIG_FILE_NAME} file or run 'coreai init'.`,\n 'NOT_FOUND'\n );\n }\n\n return loadConfigFromFile(configPath);\n}\n\n/**\n * Check if a config file exists in the given directory or parent directories\n */\nexport function configExists(startDir?: string): boolean {\n return findConfigFile(startDir) !== null;\n}\n\n/**\n * Get the path to the config file, or null if not found\n */\nexport function getConfigPath(startDir?: string): string | null {\n return findConfigFile(startDir);\n}\n","/**\n * CoreAI Agent Types\n *\n * TypeScript types corresponding to the JSON schema at schemas/agent.schema.json\n */\n\n/** @deprecated Used only for YAML backward compatibility. Will be removed when YAML support is dropped. */\nexport type AgentType = 'ic-engineer' | 'manager' | 'specialist' | 'coordinator';\n\n/** @deprecated Used only for YAML backward compatibility. Will be removed when YAML support is dropped. */\nexport type WorkflowType =\n | 'ticket-implementation'\n | 'bug-investigation'\n | 'code-review'\n | 'planning-estimation'\n | 'product-planning';\n\n/** @deprecated Used only for YAML backward compatibility. Will be removed when YAML support is dropped. */\nexport interface AgentExpertise {\n primary?: string[];\n tech_stack?: string;\n [key: string]: unknown;\n}\n\n/** @deprecated Used only for YAML backward compatibility. Will be removed when YAML support is dropped. */\nexport interface AgentPrinciples {\n code_quality?: string[];\n testing?: string[];\n security?: string[];\n performance?: string[];\n [key: string]: string[] | undefined;\n}\n\n/** @deprecated Used only for YAML backward compatibility. Will be removed when YAML support is dropped. */\nexport interface AgentBehaviors {\n workflow?: WorkflowType;\n quality_gates?: string;\n [key: string]: unknown;\n}\n\n/** @deprecated Used only for YAML backward compatibility. Will be removed when YAML support is dropped. */\nexport interface AgentContextSources {\n shared?: string[];\n personal?: string[];\n}\n\n/** @deprecated Used only for YAML backward compatibility. Will be removed when YAML support is dropped. */\nexport interface AgentKnowledgeLibraryControl {\n objectives?: string;\n decisions?: string;\n dependencies?: string;\n index?: string;\n}\n\n/** @deprecated Used only for YAML backward compatibility. Will be removed when YAML support is dropped. */\nexport interface AgentKnowledgeLibraryShared {\n context?: string;\n architecture?: string;\n prd?: string;\n remote?: string[];\n}\n\n/** @deprecated Used only for YAML backward compatibility. Will be removed when YAML support is dropped. */\nexport interface AgentKnowledgeLibraryPersonal {\n context?: string;\n history?: string;\n inbox?: string;\n outbox?: string;\n tech?: string;\n control?: AgentKnowledgeLibraryControl;\n}\n\n/** @deprecated Used only for YAML backward compatibility. Will be removed when YAML support is dropped. */\nexport interface AgentKnowledgeLibrary {\n shared?: AgentKnowledgeLibraryShared;\n personal?: AgentKnowledgeLibraryPersonal;\n}\n\n/** @deprecated Used only for YAML backward compatibility. Will be removed when YAML support is dropped. */\nexport interface AgentCommunication {\n inbox?: string;\n outbox?: string;\n message_format?: string;\n outbox_format?: string;\n processed_dir?: string;\n}\n\n/** @deprecated Used only for YAML backward compatibility. Will be removed when YAML support is dropped. */\nexport interface AgentStartupProtocol {\n first_session?: string[];\n subsequent?: string[];\n}\n\n/** @deprecated Used only for YAML backward compatibility. Will be removed when YAML support is dropped. */\nexport interface AgentProtocols {\n startup?: AgentStartupProtocol;\n completion?: string[];\n}\n\n/**\n * Default Claude Code tools available to agents\n */\nexport const DEFAULT_AGENT_TOOLS = ['Read', 'Write', 'Edit', 'Bash', 'Glob', 'Grep'] as const;\n\n/**\n * Agent definition.\n * For MD agents: role, type, display_name, description, tools are used.\n * For deprecated YAML agents: all fields may be populated.\n */\nexport interface AgentDefinition {\n role: string;\n type: AgentType;\n display_name: string;\n description: string;\n /** @deprecated YAML-only. In MD agents, responsibilities are in the template body. */\n responsibilities?: string[];\n /** @deprecated YAML-only. In MD agents, expertise is in the template body. */\n expertise?: AgentExpertise;\n /** @deprecated YAML-only. In MD agents, skills are in the template body. */\n skills?: string[];\n /** @deprecated YAML-only. In MD agents, principles are in the template body. */\n principles?: AgentPrinciples;\n /** @deprecated YAML-only. In MD agents, behaviors are in the template body. */\n behaviors?: AgentBehaviors;\n /** @deprecated YAML-only. Use knowledge_library or MD template body instead. */\n context_sources?: AgentContextSources;\n /** @deprecated YAML-only. In MD agents, knowledge library structure is in the template body. */\n knowledge_library?: AgentKnowledgeLibrary;\n /** @deprecated YAML-only. In MD agents, communication details are in the template body. */\n communication?: AgentCommunication;\n /** @deprecated YAML-only. In MD agents, protocols are in the template body. */\n protocols?: AgentProtocols;\n /**\n * Claude Code tools available to this agent.\n * If not specified, defaults to: Read, Write, Edit, Bash, Glob, Grep\n */\n tools?: string[];\n}\n\n/**\n * @deprecated Used only for YAML backward compatibility.\n */\nexport interface ResolvedAgentDefinition extends AgentDefinition {\n expertise?: AgentExpertise & {\n tech_stack?: Record<string, unknown>;\n };\n behaviors?: AgentBehaviors & {\n quality_gates?: Record<string, unknown>;\n };\n}\n\n/**\n * Agent source location\n */\nexport type AgentSource = 'core' | 'custom' | 'override';\n\n/**\n * Agent metadata including source information\n */\nexport interface AgentMetadata {\n definition: AgentDefinition;\n source: AgentSource;\n filePath: string;\n}\n","/**\n * Agent Loader\n *\n * Handles loading agent definitions from Markdown templates (primary)\n * and YAML files (deprecated, backward compatible).\n */\n\nimport { existsSync, readdirSync, readFileSync } from 'fs';\nimport { basename, extname, join } from 'path';\nimport { parse as parseYaml } from 'yaml';\nimport Ajv, { type ErrorObject } from 'ajv';\nimport type { AgentDefinition, AgentMetadata, AgentSource } from './types.js';\n\n// Import schema as JSON (for deprecated YAML validation)\nimport { createRequire } from 'module';\nconst require = createRequire(import.meta.url);\nconst agentSchema = require('../../schemas/agent.schema.json') as object;\n\nexport class AgentError extends Error {\n constructor(\n message: string,\n public readonly code: AgentErrorCode,\n public readonly details?: unknown\n ) {\n super(message);\n this.name = 'AgentError';\n }\n}\n\nexport type AgentErrorCode = 'NOT_FOUND' | 'PARSE_ERROR' | 'VALIDATION_ERROR' | 'READ_ERROR';\n\n/**\n * Extract YAML frontmatter from a Markdown file.\n * Returns the parsed frontmatter object and the body content.\n */\nexport function extractFrontmatter(content: string): { frontmatter: Record<string, unknown>; body: string } {\n const match = content.match(/^---\\n([\\s\\S]*?)\\n---\\n?([\\s\\S]*)$/);\n if (!match) {\n throw new AgentError(\n 'No YAML frontmatter found. Agent MD files must start with YAML frontmatter (---)',\n 'PARSE_ERROR'\n );\n }\n\n const frontmatterYaml = match[1]!;\n const body = match[2] ?? '';\n let frontmatter: unknown;\n try {\n frontmatter = parseYaml(frontmatterYaml);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown parse error';\n throw new AgentError(`Failed to parse YAML frontmatter: ${message}`, 'PARSE_ERROR', error);\n }\n\n if (!frontmatter || typeof frontmatter !== 'object') {\n throw new AgentError('Invalid frontmatter: expected an object', 'PARSE_ERROR');\n }\n\n return { frontmatter: frontmatter as Record<string, unknown>, body };\n}\n\n/**\n * Load an agent definition from a Markdown template file.\n *\n * Extracts metadata from YAML frontmatter (name, description, tools).\n * The full MD content is the agent's identity - processed at compile time.\n */\nexport function loadAgentFromMdFile(filePath: string): AgentDefinition {\n if (!existsSync(filePath)) {\n throw new AgentError(`Agent file not found: ${filePath}`, 'NOT_FOUND');\n }\n\n let content: string;\n try {\n content = readFileSync(filePath, 'utf-8');\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown read error';\n throw new AgentError(`Failed to read agent file ${filePath}: ${message}`, 'READ_ERROR', error);\n }\n\n const { frontmatter } = extractFrontmatter(content);\n\n // Extract role from frontmatter 'name' field or filename\n const role = (frontmatter.name as string) || getRoleFromFilename(filePath);\n if (!role) {\n throw new AgentError(\n `Agent MD file must have a 'name' field in frontmatter or a valid filename: ${filePath}`,\n 'VALIDATION_ERROR'\n );\n }\n\n // Extract description\n const description = (frontmatter.description as string) || '';\n\n // Extract tools\n const tools: string[] | undefined = typeof frontmatter.tools === 'string'\n ? frontmatter.tools.split(',').map((t: string) => t.trim()).filter(Boolean)\n : undefined;\n\n const definition: AgentDefinition = {\n role,\n type: 'ic-engineer', // Default, actual identity is in the MD content\n display_name: role.split('-').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' '),\n description,\n };\n\n if (tools) {\n definition.tools = tools;\n }\n\n return definition;\n}\n\n// --- Deprecated YAML support (backward compatibility) ---\n\n/**\n * Parse YAML content into an agent definition\n * @deprecated Use Markdown agent files instead\n */\nexport function parseAgentYaml(content: string, filePath?: string): unknown {\n try {\n return parseYaml(content);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown parse error';\n throw new AgentError(\n `Failed to parse agent YAML${filePath ? ` in ${filePath}` : ''}: ${message}`,\n 'PARSE_ERROR',\n error\n );\n }\n}\n\n/**\n * Validate parsed YAML against agent schema\n * @deprecated Use Markdown agent files instead\n */\nexport function validateAgentDefinition(agent: unknown): AgentDefinition {\n const ajv = new Ajv.default({ allErrors: true, strict: false });\n const validate = ajv.compile<AgentDefinition>(agentSchema);\n const valid = validate(agent);\n\n if (!valid) {\n const errors: ErrorObject[] = validate.errors ?? [];\n const errorMessages = errors.map((err: ErrorObject) => {\n const path = err.instancePath || 'root';\n return `${path}: ${err.message ?? 'unknown error'}`;\n });\n\n throw new AgentError(\n `Agent validation failed:\\n - ${errorMessages.join('\\n - ')}`,\n 'VALIDATION_ERROR',\n errors\n );\n }\n\n return agent as AgentDefinition;\n}\n\n/**\n * Load and validate an agent definition from a YAML file\n * @deprecated Use Markdown agent files instead\n */\nexport function loadAgentFromYamlFile(filePath: string): AgentDefinition {\n if (!existsSync(filePath)) {\n throw new AgentError(`Agent file not found: ${filePath}`, 'NOT_FOUND');\n }\n\n let content: string;\n try {\n content = readFileSync(filePath, 'utf-8');\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown read error';\n throw new AgentError(`Failed to read agent file ${filePath}: ${message}`, 'READ_ERROR', error);\n }\n\n const parsed = parseAgentYaml(content, filePath);\n return validateAgentDefinition(parsed);\n}\n\n// --- Unified loading (supports both MD and YAML) ---\n\n/**\n * Load an agent definition from a file (MD or YAML).\n * MD files are the primary format. YAML files are deprecated but supported.\n */\nexport function loadAgentFromFile(filePath: string): AgentDefinition {\n const ext = extname(filePath).toLowerCase();\n\n if (ext === '.md') {\n return loadAgentFromMdFile(filePath);\n }\n\n if (ext === '.yaml' || ext === '.yml') {\n console.warn(\n `Warning: YAML agent definitions are deprecated and will be removed in a future version.\\n` +\n ` Please migrate ${basename(filePath)} to Markdown format.`\n );\n return loadAgentFromYamlFile(filePath);\n }\n\n throw new AgentError(\n `Unsupported agent file format: ${ext}. Use .md (recommended) or .yaml/.yml (deprecated)`,\n 'PARSE_ERROR'\n );\n}\n\n/**\n * List all agent files in a directory (MD and YAML).\n * Excludes files/directories starting with underscore (e.g., _templates/).\n */\nfunction listAgentFiles(dir: string): string[] {\n if (!existsSync(dir)) {\n return [];\n }\n\n return readdirSync(dir)\n .filter((file) => {\n // Skip underscore-prefixed files/dirs (templates, etc.)\n if (file.startsWith('_')) return false;\n const ext = extname(file).toLowerCase();\n return ext === '.md' || ext === '.yaml' || ext === '.yml';\n })\n .map((file) => join(dir, file));\n}\n\n/**\n * Load all agents from a directory\n */\nexport function loadAgentsFromDirectory(\n dir: string,\n source: AgentSource\n): Map<string, AgentMetadata> {\n const agents = new Map<string, AgentMetadata>();\n const files = listAgentFiles(dir);\n\n for (const filePath of files) {\n try {\n const definition = loadAgentFromFile(filePath);\n agents.set(definition.role, {\n definition,\n source,\n filePath,\n });\n } catch (error) {\n // Log warning but continue loading other agents\n const fileName = basename(filePath);\n console.warn(`Warning: Failed to load agent from ${fileName}: ${(error as Error).message}`);\n }\n }\n\n return agents;\n}\n\n/**\n * Get the agent role name from a filename\n */\nexport function getRoleFromFilename(filePath: string): string {\n const fileName = basename(filePath);\n const ext = extname(fileName);\n return fileName.slice(0, -ext.length);\n}\n","/**\n * Variable Resolution System\n *\n * Resolves variable placeholders in agent definitions.\n * Supports: ${config.*}, ${agent.*}, ${remote.*}\n */\n\nimport type { CoreAIConfig } from '../config/types.js';\nimport type { AgentDefinition } from './types.js';\n\n/**\n * Context for variable resolution\n */\nexport interface ResolutionContext {\n config?: CoreAIConfig;\n agent?: AgentDefinition;\n}\n\n/**\n * Options for variable resolution\n */\nexport interface ResolutionOptions {\n /**\n * If true, throw an error for unresolved variables.\n * If false, leave unresolved variables as-is.\n * Default: false\n */\n strict?: boolean;\n}\n\n/**\n * Error thrown when variable resolution fails\n */\nexport class ResolutionError extends Error {\n constructor(\n message: string,\n public readonly variable: string,\n public readonly path?: string\n ) {\n super(message);\n this.name = 'ResolutionError';\n }\n}\n\n/**\n * Pattern to match variable placeholders: ${namespace.path.to.value}\n */\nconst VARIABLE_PATTERN = /\\$\\{([a-z_][a-z0-9_]*(?:\\.[a-z_][a-z0-9_]*)*)\\}/gi;\n\n/**\n * Get a nested value from an object using dot notation\n */\nfunction getNestedValue(obj: unknown, path: string): unknown {\n const parts = path.split('.');\n let current: unknown = obj;\n\n for (const part of parts) {\n if (current === null || current === undefined) {\n return undefined;\n }\n if (typeof current !== 'object') {\n return undefined;\n }\n current = (current as Record<string, unknown>)[part];\n }\n\n return current;\n}\n\n/**\n * Resolve a single variable reference\n */\nfunction resolveVariable(\n variable: string,\n context: ResolutionContext,\n options: ResolutionOptions\n): string | undefined {\n const parts = variable.split('.');\n const namespace = parts[0];\n const path = parts.slice(1).join('.');\n\n let value: unknown;\n\n switch (namespace) {\n case 'config':\n if (!context.config) {\n if (options.strict) {\n throw new ResolutionError(\n `Cannot resolve \\${${variable}}: no config context provided`,\n variable\n );\n }\n return undefined;\n }\n value = getNestedValue(context.config, path);\n break;\n\n case 'agent':\n if (!context.agent) {\n if (options.strict) {\n throw new ResolutionError(\n `Cannot resolve \\${${variable}}: no agent context provided`,\n variable\n );\n }\n return undefined;\n }\n value = getNestedValue(context.agent, path);\n break;\n\n case 'remote':\n // Remote is a shortcut for integration URLs\n value = resolveRemoteVariable(path, context, options);\n break;\n\n default:\n if (options.strict) {\n throw new ResolutionError(`Unknown variable namespace: ${namespace}`, variable);\n }\n return undefined;\n }\n\n if (value === undefined) {\n if (options.strict) {\n throw new ResolutionError(`Cannot resolve \\${${variable}}: path not found`, variable, path);\n }\n return undefined;\n }\n\n // Convert value to string representation\n if (typeof value === 'string') {\n return value;\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n // For objects/arrays, return JSON representation\n return JSON.stringify(value);\n}\n\n/**\n * Resolve remote.* variables (shortcuts to integration URLs)\n */\nfunction resolveRemoteVariable(\n path: string,\n context: ResolutionContext,\n options: ResolutionOptions\n): string | undefined {\n if (!context.config?.integrations) {\n if (options.strict) {\n throw new ResolutionError(\n `Cannot resolve \\${remote.${path}}: no integrations configured`,\n `remote.${path}`\n );\n }\n return undefined;\n }\n\n const integrations = context.config.integrations;\n\n // Map remote shortcuts to integration paths\n switch (path) {\n case 'documentation':\n return (\n integrations.documentation?.config?.base_url ??\n integrations.documentation?.config?.base_path\n );\n\n case 'issues':\n return integrations.issue_tracker?.config?.base_url;\n\n case 'git':\n return integrations.git?.config?.repo;\n\n case 'state':\n return integrations.state?.config?.base_path ?? integrations.state?.config?.bucket;\n\n default:\n // Try to resolve as nested path under integrations\n return getNestedValue(integrations, path) as string | undefined;\n }\n}\n\n/**\n * Resolve all variables in a string\n */\nexport function resolveString(\n input: string,\n context: ResolutionContext,\n options: ResolutionOptions = {}\n): string {\n return input.replace(VARIABLE_PATTERN, (match, variable: string) => {\n const resolved = resolveVariable(variable, context, options);\n return resolved !== undefined ? resolved : match;\n });\n}\n\n/**\n * Check if a string contains variable placeholders\n */\nexport function hasVariables(input: string): boolean {\n // Create new regex to avoid state issues with global flag\n const pattern = /\\$\\{([a-z_][a-z0-9_]*(?:\\.[a-z_][a-z0-9_]*)*)\\}/i;\n return pattern.test(input);\n}\n\n/**\n * Extract all variable references from a string\n */\nexport function extractVariables(input: string): string[] {\n const matches = input.matchAll(VARIABLE_PATTERN);\n return Array.from(matches, (m) => m[1]).filter((v): v is string => v !== undefined);\n}\n\n/**\n * Recursively resolve all variables in an object\n */\nexport function resolveObject<T>(\n obj: T,\n context: ResolutionContext,\n options: ResolutionOptions = {}\n): T {\n if (obj === null || obj === undefined) {\n return obj;\n }\n\n if (typeof obj === 'string') {\n return resolveString(obj, context, options) as T;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => resolveObject(item, context, options)) as T;\n }\n\n if (typeof obj === 'object') {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n result[key] = resolveObject(value, context, options);\n }\n return result as T;\n }\n\n return obj;\n}\n\n/**\n * Resolve all variables in an agent definition\n */\nexport function resolveAgentDefinition(\n agent: AgentDefinition,\n config?: CoreAIConfig,\n options: ResolutionOptions = {}\n): AgentDefinition {\n const context: ResolutionContext = {\n agent,\n };\n if (config) {\n context.config = config;\n }\n\n return resolveObject(agent, context, options);\n}\n","/**\n * Agent Compiler\n *\n * Processes agent Markdown templates with variable substitution and include directives.\n * For deprecated YAML agents, falls back to structural transformation.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';\nimport { join, dirname, extname, isAbsolute } from 'path';\nimport { parse as parseYaml, stringify as stringifyYaml } from 'yaml';\nimport type { CoreAIConfig } from '../config/types.js';\nimport type { AgentDefinition, AgentMetadata, AgentSource } from './types.js';\nimport { DEFAULT_AGENT_TOOLS } from './types.js';\nimport { loadAgentsFromDirectory } from './loader.js';\nimport { resolveString, resolveAgentDefinition, type ResolutionContext } from './resolver.js';\n\n/**\n * Options for compiling agents\n */\nexport interface CompileOptions {\n outputDir?: string;\n coreAgentsDir?: string;\n customAgentsDir?: string;\n projectRoot?: string;\n filter?: (agent: AgentDefinition) => boolean;\n mcpServers?: string[];\n}\n\n/**\n * Result of compiling agents\n */\nexport interface CompileResult {\n compiled: {\n role: string;\n source: AgentSource;\n outputPath: string;\n }[];\n errors: {\n role: string;\n source: AgentSource;\n error: string;\n }[];\n}\n\n/**\n * Build the tools string for agent frontmatter\n */\nexport function buildAgentTools(agent: AgentDefinition, mcpServers?: string[]): string {\n const tools: string[] = agent.tools\n ? [...agent.tools]\n : [...DEFAULT_AGENT_TOOLS];\n\n if (mcpServers && mcpServers.length > 0) {\n for (const server of mcpServers) {\n const mcpTool = `mcp__${server}`;\n if (!tools.includes(mcpTool)) {\n tools.push(mcpTool);\n }\n }\n }\n\n return tools.join(', ');\n}\n\n/**\n * Process include directives in a template.\n *\n * Replaces `<!-- include: path -->` with the contents of the referenced file.\n * Paths are resolved relative to the template's directory.\n * Supports recursive includes up to a configurable depth limit.\n */\nexport function processIncludes(\n template: string,\n templateDir: string,\n depth: number = 0,\n maxDepth: number = 3\n): string {\n if (depth > maxDepth) {\n throw new Error(`Include depth exceeded maximum of ${maxDepth}`);\n }\n\n const includePattern = /<!--\\s*include:\\s*(\\S+)\\s*-->/g;\n\n return template.replace(includePattern, (_match, includePath: string) => {\n const resolvedPath = isAbsolute(includePath)\n ? includePath\n : join(templateDir, includePath);\n\n if (!existsSync(resolvedPath)) {\n throw new Error(`Include file not found: ${includePath} (resolved to ${resolvedPath})`);\n }\n\n const includedContent = readFileSync(resolvedPath, 'utf-8');\n return processIncludes(includedContent, dirname(resolvedPath), depth + 1, maxDepth);\n });\n}\n\n/**\n * Process a Markdown agent template: expand includes, resolve variables, and update frontmatter tools.\n *\n * This is the primary compilation path for .md agent files.\n * Pipeline: read → expand includes → extract custom frontmatter → resolve variables → inject tools → rebuild.\n */\nexport function processAgentTemplate(\n templatePath: string,\n agent: AgentDefinition,\n config?: CoreAIConfig,\n mcpServers?: string[]\n): string {\n const template = readFileSync(templatePath, 'utf-8');\n\n // Step 1: Expand include directives before variable resolution\n const templateDir = dirname(templatePath);\n const expandedTemplate = processIncludes(template, templateDir);\n\n // Step 2: Parse frontmatter early to extract custom agent fields (e.g. tech_artifacts)\n const earlyMatch = expandedTemplate.match(/^---\\n([\\s\\S]*?)\\n---\\n?([\\s\\S]*)$/);\n if (!earlyMatch) {\n throw new Error(`Invalid markdown format in ${templatePath}: no frontmatter found`);\n }\n\n const earlyFrontmatter = parseYaml(earlyMatch[1]!) as Record<string, unknown>;\n const reservedKeys = new Set(['name', 'description', 'tools']);\n const extendedAgent: Record<string, unknown> = { ...agent };\n for (const [key, value] of Object.entries(earlyFrontmatter)) {\n if (!reservedKeys.has(key) && !(key in extendedAgent)) {\n extendedAgent[key] = value;\n }\n }\n\n // Step 3: Build resolution context with extended agent\n const context: ResolutionContext = { agent: extendedAgent as unknown as AgentDefinition };\n if (config) {\n context.config = config;\n }\n\n // Step 4: Resolve variables in the expanded template\n const resolved = resolveString(expandedTemplate, context);\n\n // Step 5: Parse frontmatter from resolved template to update tools\n const frontmatterMatch = resolved.match(/^---\\n([\\s\\S]*?)\\n---\\n?([\\s\\S]*)$/);\n if (!frontmatterMatch) {\n throw new Error(`Invalid markdown format after resolution in ${templatePath}`);\n }\n\n const frontmatterYaml = frontmatterMatch[1]!;\n const body = frontmatterMatch[2] ?? '';\n const frontmatter = parseYaml(frontmatterYaml) as Record<string, unknown>;\n\n // Update tools line with MCP servers\n const tools = buildAgentTools(agent, mcpServers);\n frontmatter.tools = tools;\n\n // Flatten description for frontmatter (single line)\n if (typeof frontmatter.description === 'string') {\n frontmatter.description = frontmatter.description.replace(/\\n/g, ' ').trim();\n }\n\n // Rebuild with updated frontmatter\n const updatedFrontmatter = stringifyYaml(frontmatter, { lineWidth: 0 }).trim();\n return `---\\n${updatedFrontmatter}\\n---\\n${body}`;\n}\n\n// --- Deprecated YAML compilation (backward compatibility) ---\n\n/**\n * Generate markdown content from a resolved YAML agent definition.\n * @deprecated Use MD templates instead. This exists for backward compatibility with YAML agents.\n */\nexport function generateAgentMarkdown(agent: AgentDefinition, mcpServers?: string[]): string {\n const lines: string[] = [];\n const tools = buildAgentTools(agent, mcpServers);\n\n // YAML frontmatter\n lines.push('---');\n lines.push(`name: ${agent.role}`);\n lines.push(`description: ${agent.description.replace(/\\n/g, ' ').trim()}`);\n lines.push(`tools: ${tools}`);\n lines.push('---');\n lines.push('');\n\n // Header\n lines.push(`# ${agent.display_name}`);\n lines.push('');\n lines.push(`**Role:** ${agent.role}`);\n lines.push(`**Type:** ${agent.type}`);\n lines.push('');\n\n // Description\n lines.push('## Description');\n lines.push('');\n lines.push(agent.description.trim());\n lines.push('');\n\n // Responsibilities\n if (agent.responsibilities && agent.responsibilities.length > 0) {\n lines.push('## Responsibilities');\n lines.push('');\n for (const r of agent.responsibilities) {\n lines.push(`- ${r}`);\n }\n lines.push('');\n }\n\n // Expertise\n if (agent.expertise) {\n lines.push('## Expertise');\n lines.push('');\n if (agent.expertise.primary && agent.expertise.primary.length > 0) {\n lines.push('### Primary Areas');\n lines.push('');\n for (const area of agent.expertise.primary) {\n lines.push(`- ${area}`);\n }\n lines.push('');\n }\n if (agent.expertise.tech_stack) {\n lines.push('### Tech Stack');\n lines.push('');\n const ts = agent.expertise.tech_stack;\n if (typeof ts === 'string') {\n lines.push(ts);\n } else if (typeof ts === 'object') {\n lines.push('```json');\n lines.push(JSON.stringify(ts, null, 2));\n lines.push('```');\n }\n lines.push('');\n }\n }\n\n // Skills\n if (agent.skills && agent.skills.length > 0) {\n lines.push('## Skills');\n lines.push('');\n for (const skill of agent.skills) {\n lines.push(`- ${skill}`);\n }\n lines.push('');\n }\n\n // Principles\n if (agent.principles) {\n lines.push('## Principles');\n lines.push('');\n for (const [category, items] of Object.entries(agent.principles)) {\n if (items && Array.isArray(items) && items.length > 0) {\n const title = category.replace(/[_-]/g, ' ').replace(/\\b\\w/g, (c) => c.toUpperCase());\n lines.push(`### ${title}`);\n lines.push('');\n for (const item of items) {\n lines.push(`- ${item}`);\n }\n lines.push('');\n }\n }\n }\n\n // Behaviors\n if (agent.behaviors) {\n lines.push('## Behaviors');\n lines.push('');\n if (agent.behaviors.workflow) {\n lines.push(`**Workflow:** ${agent.behaviors.workflow}`);\n lines.push('');\n }\n if (agent.behaviors.quality_gates) {\n lines.push('### Quality Gates');\n lines.push('');\n const gates = agent.behaviors.quality_gates;\n if (typeof gates === 'string') {\n lines.push(gates);\n } else if (typeof gates === 'object') {\n lines.push('```json');\n lines.push(JSON.stringify(gates, null, 2));\n lines.push('```');\n }\n lines.push('');\n }\n }\n\n // Knowledge Library\n if (agent.knowledge_library) {\n generateKnowledgeLibrarySection(agent, lines);\n }\n\n // Communication\n if (agent.communication) {\n generateCommunicationSection(agent, lines);\n }\n\n // Protocols\n if (agent.protocols?.startup) {\n generateStartupProtocolSection(agent, lines);\n }\n if (agent.protocols?.completion) {\n generateCompletionProtocolSection(agent, lines);\n }\n\n // Legacy context sources\n if (agent.context_sources && !agent.knowledge_library) {\n lines.push('## Context Sources');\n lines.push('');\n if (agent.context_sources.shared?.length) {\n lines.push('### Shared');\n lines.push('');\n for (const s of agent.context_sources.shared) lines.push(`- ${s}`);\n lines.push('');\n }\n if (agent.context_sources.personal?.length) {\n lines.push('### Personal');\n lines.push('');\n for (const p of agent.context_sources.personal) lines.push(`- ${p}`);\n lines.push('');\n }\n }\n\n lines.push('---');\n lines.push('');\n lines.push('*Generated by CoreAI*');\n lines.push('');\n\n return lines.join('\\n');\n}\n\nfunction generateKnowledgeLibrarySection(agent: AgentDefinition, lines: string[]): void {\n const kl = agent.knowledge_library;\n if (!kl) return;\n lines.push('## Knowledge Library Structure');\n lines.push('');\n if (kl.shared) {\n lines.push('### Shared Context (Root - All Agents)');\n lines.push('```');\n lines.push('/KnowledgeLibrary/');\n if (kl.shared.context) lines.push(`├── ${kl.shared.context.split('/').pop()}`);\n if (kl.shared.architecture) lines.push(`├── ${kl.shared.architecture.split('/').pop()}`);\n if (kl.shared.prd) lines.push(`└── ${kl.shared.prd.split('/').pop()}`);\n lines.push('```');\n if (kl.shared.remote?.length) {\n lines.push('');\n lines.push('**Remote Documentation:**');\n for (const r of kl.shared.remote) lines.push(`- ${r}`);\n }\n lines.push('');\n }\n if (kl.personal) {\n lines.push(`### Personal Context (${agent.role})`);\n lines.push('```');\n lines.push(`/KnowledgeLibrary/${agent.role}/`);\n if (kl.personal.context) { lines.push('├── context/'); lines.push('│ └── current.txt'); }\n if (kl.personal.history) { lines.push('├── history/'); }\n if (kl.personal.inbox) { lines.push('├── inbox/'); }\n if (kl.personal.outbox) { lines.push('├── outbox/'); }\n if (kl.personal.tech) { lines.push('├── tech/'); }\n if (kl.personal.control) {\n lines.push('└── control/');\n if (kl.personal.control.objectives) lines.push(' ├── objectives.txt');\n if (kl.personal.control.decisions) lines.push(' ├── decisions.txt');\n if (kl.personal.control.dependencies) lines.push(' ├── dependencies.txt');\n if (kl.personal.control.index) lines.push(' └── index.txt');\n }\n lines.push('```');\n lines.push('');\n }\n lines.push('---');\n lines.push('');\n}\n\nfunction generateCommunicationSection(agent: AgentDefinition, lines: string[]): void {\n const comm = agent.communication;\n if (!comm) return;\n lines.push('## Communication');\n lines.push('');\n if (comm.inbox) lines.push(`**Inbox:** \\`${comm.inbox}\\``);\n if (comm.outbox) lines.push(`**Outbox:** \\`${comm.outbox}\\``);\n lines.push('');\n if (comm.message_format || comm.outbox_format || comm.processed_dir) {\n lines.push('### Message Conventions');\n lines.push('');\n if (comm.message_format) lines.push(`- **Inbox message naming:** \\`${comm.message_format}\\``);\n if (comm.outbox_format) lines.push(`- **Outbox message naming:** \\`${comm.outbox_format}\\``);\n if (comm.processed_dir) lines.push(`- **Processed messages:** Move handled inbox messages to \\`${comm.processed_dir}\\``);\n lines.push('');\n }\n}\n\nfunction generateStartupProtocolSection(agent: AgentDefinition, lines: string[]): void {\n const p = agent.protocols;\n if (!p?.startup) return;\n lines.push('## When Invoked');\n lines.push('');\n lines.push('> **MANDATORY STARTUP PROTOCOL** - Execute before proceeding with any task.');\n lines.push('');\n lines.push('### Session Context Check');\n lines.push('');\n if (p.startup.first_session?.length) {\n lines.push('**If this is your FIRST invocation in this session:**');\n lines.push('');\n for (const s of p.startup.first_session) lines.push(`- [ ] ${s}`);\n lines.push('');\n lines.push('Acknowledge: \"Startup protocol complete. Full context loaded.\"');\n lines.push('');\n }\n if (p.startup.subsequent?.length) {\n lines.push('**If you have ALREADY loaded context in this session:**');\n lines.push('');\n for (const s of p.startup.subsequent) lines.push(`- [ ] ${s}`);\n lines.push('');\n lines.push('Acknowledge: \"Context already loaded. Checked inbox for new messages.\"');\n lines.push('');\n }\n lines.push('Then proceed with the task.');\n lines.push('');\n lines.push('---');\n lines.push('');\n}\n\nfunction generateCompletionProtocolSection(agent: AgentDefinition, lines: string[]): void {\n const p = agent.protocols;\n if (!p?.completion?.length) return;\n lines.push('## Before Finishing');\n lines.push('');\n lines.push('> **MANDATORY COMPLETION PROTOCOL** - Execute ALL steps before ending any task.');\n lines.push('');\n for (let i = 0; i < p.completion.length; i++) {\n lines.push(`### ${i + 1}. ${p.completion[i]}`);\n lines.push('');\n }\n lines.push('Acknowledge: \"Completion protocol finished. Context updated.\"');\n lines.push('');\n lines.push('---');\n lines.push('');\n}\n\n// --- Unified compilation ---\n\n/**\n * Compile a single agent.\n * MD templates use simple variable substitution.\n * YAML files use the deprecated structural transformation.\n */\nexport function compileAgent(\n agent: AgentDefinition,\n filePath: string,\n config?: CoreAIConfig,\n mcpServers?: string[]\n): string {\n const ext = extname(filePath).toLowerCase();\n\n if (ext === '.md') {\n return processAgentTemplate(filePath, agent, config, mcpServers);\n }\n\n // Deprecated YAML path\n const resolved = resolveAgentDefinition(agent, config);\n return generateAgentMarkdown(resolved, mcpServers);\n}\n\n/**\n * Load all agents from core and custom directories\n */\nexport function loadAllAgents(options: CompileOptions = {}): Map<string, AgentMetadata> {\n const agents = new Map<string, AgentMetadata>();\n\n if (options.coreAgentsDir && existsSync(options.coreAgentsDir)) {\n const coreAgents = loadAgentsFromDirectory(options.coreAgentsDir, 'core');\n for (const [role, metadata] of coreAgents) {\n agents.set(role, metadata);\n }\n }\n\n if (options.customAgentsDir && existsSync(options.customAgentsDir)) {\n const customAgents = loadAgentsFromDirectory(options.customAgentsDir, 'custom');\n for (const [role, metadata] of customAgents) {\n if (agents.has(role)) {\n metadata.source = 'override';\n }\n agents.set(role, metadata);\n }\n }\n\n return agents;\n}\n\n/**\n * Filter agents based on team configuration\n */\nexport function filterAgentsByTeam(\n agents: Map<string, AgentMetadata>,\n config?: CoreAIConfig\n): Map<string, AgentMetadata> {\n if (!config?.team?.agents || config.team.agents.length === 0) {\n return agents;\n }\n\n const filtered = new Map<string, AgentMetadata>();\n for (const [role, metadata] of agents) {\n if (metadata.source === 'custom' || metadata.source === 'override') {\n filtered.set(role, metadata);\n } else if (config.team.agents.includes(role)) {\n filtered.set(role, metadata);\n }\n }\n\n return filtered;\n}\n\n/**\n * Compile all agents and write to output directory\n */\nexport function compileAgents(config?: CoreAIConfig, options: CompileOptions = {}): CompileResult {\n const projectRoot = options.projectRoot ?? process.cwd();\n const outputDir = options.outputDir ?? join(projectRoot, '.claude', 'agents');\n const coreAgentsDir = options.coreAgentsDir ?? getCoreAgentsDir();\n const customAgentsDir = options.customAgentsDir ?? join(projectRoot, 'coreai', 'agents');\n\n const result: CompileResult = {\n compiled: [],\n errors: [],\n };\n\n const allAgents = loadAllAgents({\n ...options,\n coreAgentsDir,\n customAgentsDir,\n });\n\n const agents = filterAgentsByTeam(allAgents, config);\n\n if (!existsSync(outputDir)) {\n mkdirSync(outputDir, { recursive: true });\n }\n\n for (const [role, metadata] of agents) {\n if (options.filter && !options.filter(metadata.definition)) {\n continue;\n }\n\n try {\n const markdown = compileAgent(\n metadata.definition,\n metadata.filePath,\n config,\n options.mcpServers\n );\n const outputPath = join(outputDir, `${role}.md`);\n writeFileSync(outputPath, markdown, 'utf-8');\n\n result.compiled.push({\n role,\n source: metadata.source,\n outputPath,\n });\n } catch (error) {\n result.errors.push({\n role,\n source: metadata.source,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n return result;\n}\n\n/**\n * Get the default core agents directory\n */\nexport function getCoreAgentsDir(): string {\n let currentDir = dirname(import.meta.url.replace('file://', ''));\n for (let i = 0; i < 5; i++) {\n if (existsSync(join(currentDir, 'package.json'))) {\n return join(currentDir, 'agents');\n }\n currentDir = dirname(currentDir);\n }\n return join(dirname(dirname(dirname(import.meta.url.replace('file://', '')))), 'agents');\n}\n","/**\n * MCP Integration Types\n *\n * Types for MCP server configuration and integration.\n */\n\n/**\n * Transport type for MCP servers\n */\nexport type McpTransportType = 'stdio' | 'http' | 'sse';\n\n/**\n * Configuration for a stdio-based MCP server\n */\nexport interface StdioServerConfig {\n transport: 'stdio';\n command: string;\n args?: string[];\n env?: Record<string, string>;\n cwd?: string;\n}\n\n/**\n * Configuration for an HTTP-based MCP server\n */\nexport interface HttpServerConfig {\n transport: 'http' | 'sse';\n url: string;\n headers?: Record<string, string>;\n}\n\n/**\n * Union type for all MCP server configurations\n */\nexport type McpServerConfig = StdioServerConfig | HttpServerConfig;\n\n/**\n * MCP server definition from config\n */\nexport interface McpServerDefinition {\n /**\n * Unique name for this server\n */\n name: string;\n\n /**\n * Server configuration\n */\n config: McpServerConfig;\n\n /**\n * Whether this server is enabled\n */\n enabled?: boolean;\n\n /**\n * Description of what this server provides\n */\n description?: string;\n}\n\n/**\n * MCP config file structure (e.g., mcp.json)\n */\nexport interface McpConfigFile {\n /**\n * MCP servers to connect to\n */\n mcpServers?: Record<string, McpServerConfig>;\n}\n\n/**\n * Information about a connected MCP server\n */\nexport interface McpServerInfo {\n /**\n * Server name\n */\n name: string;\n\n /**\n * Server version (if available)\n */\n version?: string;\n\n /**\n * Protocol version\n */\n protocolVersion?: string;\n\n /**\n * Server capabilities\n */\n capabilities?: McpCapabilities;\n\n /**\n * Server instructions (if any)\n */\n instructions?: string;\n\n /**\n * Whether the server is connected\n */\n connected: boolean;\n}\n\n/**\n * MCP server capabilities\n */\nexport interface McpCapabilities {\n tools?: boolean;\n resources?: boolean;\n prompts?: boolean;\n logging?: boolean;\n}\n\n/**\n * MCP tool definition\n */\nexport interface McpTool {\n /**\n * Tool name\n */\n name: string;\n\n /**\n * Tool description\n */\n description?: string;\n\n /**\n * Input schema for the tool\n */\n inputSchema: {\n type: 'object';\n properties?: Record<string, unknown>;\n required?: string[];\n };\n\n /**\n * Tool annotations\n */\n annotations?: {\n title?: string;\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n };\n}\n\n/**\n * MCP resource definition\n */\nexport interface McpResource {\n /**\n * Resource URI\n */\n uri: string;\n\n /**\n * Resource name\n */\n name: string;\n\n /**\n * Resource description\n */\n description?: string;\n\n /**\n * MIME type\n */\n mimeType?: string;\n}\n\n/**\n * Result of calling an MCP tool\n */\nexport interface McpToolResult {\n /**\n * Tool output content\n */\n content: McpContent[];\n\n /**\n * Whether the tool call resulted in an error\n */\n isError?: boolean;\n\n /**\n * Structured content (if tool has outputSchema)\n */\n structuredContent?: Record<string, unknown>;\n}\n\n/**\n * Content returned by MCP tools and resources\n */\nexport type McpContent = McpTextContent | McpImageContent | McpResourceContent;\n\n/**\n * Text content\n */\nexport interface McpTextContent {\n type: 'text';\n text: string;\n}\n\n/**\n * Image content\n */\nexport interface McpImageContent {\n type: 'image';\n data: string;\n mimeType: string;\n}\n\n/**\n * Embedded resource content\n */\nexport interface McpResourceContent {\n type: 'resource';\n resource: {\n uri: string;\n text?: string;\n blob?: string;\n mimeType?: string;\n };\n}\n\n/**\n * Error from MCP operations\n */\nexport class McpError extends Error {\n constructor(\n message: string,\n public readonly code: McpErrorCode,\n public readonly server?: string,\n cause?: Error\n ) {\n super(message, { cause });\n this.name = 'McpError';\n }\n}\n\n/**\n * MCP error codes\n */\nexport type McpErrorCode =\n | 'connection_failed'\n | 'connection_closed'\n | 'server_not_found'\n | 'tool_not_found'\n | 'resource_not_found'\n | 'invalid_config'\n | 'transport_error'\n | 'protocol_error'\n | 'timeout';\n","/**\n * MCP Client Wrapper\n *\n * Provides a simplified interface for connecting to and communicating with MCP servers.\n */\n\nimport { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';\nimport type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';\nimport type {\n McpServerConfig,\n McpServerInfo,\n McpTool,\n McpResource,\n McpToolResult,\n McpCapabilities,\n McpContent,\n StdioServerConfig,\n} from './types.js';\nimport { McpError } from './types.js';\n\n/**\n * Options for creating an MCP client\n */\nexport interface McpClientOptions {\n /**\n * Client name to report to servers\n */\n clientName?: string;\n\n /**\n * Client version to report to servers\n */\n clientVersion?: string;\n\n /**\n * Timeout for operations in milliseconds\n */\n timeout?: number;\n}\n\nconst DEFAULT_OPTIONS: Required<McpClientOptions> = {\n clientName: 'coreai',\n clientVersion: '0.1.0',\n timeout: 30000,\n};\n\n/**\n * MCP Client Wrapper\n *\n * Manages a connection to a single MCP server and provides\n * a simplified API for tool calls, resource access, etc.\n */\nexport class McpClient {\n private client: Client | null = null;\n private transport: Transport | null = null;\n private _serverInfo: McpServerInfo | null = null;\n private options: Required<McpClientOptions>;\n private serverName: string;\n private config: McpServerConfig;\n\n constructor(serverName: string, config: McpServerConfig, options?: McpClientOptions) {\n this.serverName = serverName;\n this.config = config;\n this.options = { ...DEFAULT_OPTIONS, ...options };\n }\n\n /**\n * Connect to the MCP server\n */\n async connect(): Promise<void> {\n if (this.client && this.isConnected()) {\n return;\n }\n\n try {\n // Create the appropriate transport\n this.transport = await this.createTransport();\n\n // Create the MCP client\n this.client = new Client(\n {\n name: this.options.clientName,\n version: this.options.clientVersion,\n },\n {\n capabilities: {\n roots: { listChanged: true },\n },\n }\n );\n\n // Connect to the server\n await this.client.connect(this.transport);\n\n // Store server info\n const serverVersion = this.client.getServerVersion();\n const serverCapabilities = this.client.getServerCapabilities();\n\n const info: McpServerInfo = {\n name: this.serverName,\n connected: true,\n };\n\n if (serverVersion?.version) {\n info.version = serverVersion.version;\n }\n\n const caps = this.parseCapabilities(serverCapabilities);\n if (caps) {\n info.capabilities = caps;\n }\n\n const instructions = this.client.getInstructions();\n if (instructions) {\n info.instructions = instructions;\n }\n\n this._serverInfo = info;\n } catch (error) {\n throw new McpError(\n `Failed to connect to MCP server \"${this.serverName}\": ${error instanceof Error ? error.message : String(error)}`,\n 'connection_failed',\n this.serverName,\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /**\n * Disconnect from the MCP server\n */\n async disconnect(): Promise<void> {\n if (this.transport) {\n await this.transport.close();\n this.transport = null;\n }\n\n this.client = null;\n\n if (this._serverInfo) {\n this._serverInfo.connected = false;\n }\n }\n\n /**\n * Check if connected to the server\n */\n isConnected(): boolean {\n return this._serverInfo?.connected ?? false;\n }\n\n /**\n * Get server information\n */\n getServerInfo(): McpServerInfo | null {\n return this._serverInfo;\n }\n\n /**\n * List available tools from the server\n */\n async listTools(): Promise<McpTool[]> {\n const client = this.ensureConnected();\n\n const result = await client.listTools();\n\n return result.tools.map((tool) => {\n // Build inputSchema with only defined properties\n const inputSchema: McpTool['inputSchema'] = { type: 'object' };\n if (tool.inputSchema.properties) {\n inputSchema.properties = tool.inputSchema.properties as Record<string, unknown>;\n }\n if (tool.inputSchema.required) {\n inputSchema.required = tool.inputSchema.required;\n }\n\n const mapped: McpTool = {\n name: tool.name,\n inputSchema,\n };\n\n if (tool.description) {\n mapped.description = tool.description;\n }\n\n if (tool.annotations) {\n const annotations: McpTool['annotations'] = {};\n if (tool.annotations.title) annotations.title = tool.annotations.title;\n if (tool.annotations.readOnlyHint !== undefined)\n annotations.readOnlyHint = tool.annotations.readOnlyHint;\n if (tool.annotations.destructiveHint !== undefined)\n annotations.destructiveHint = tool.annotations.destructiveHint;\n if (tool.annotations.idempotentHint !== undefined)\n annotations.idempotentHint = tool.annotations.idempotentHint;\n if (Object.keys(annotations).length > 0) {\n mapped.annotations = annotations;\n }\n }\n\n return mapped;\n });\n }\n\n /**\n * Call a tool on the server\n */\n async callTool(name: string, args?: Record<string, unknown>): Promise<McpToolResult> {\n const client = this.ensureConnected();\n\n try {\n const result = await client.callTool({\n name,\n arguments: args,\n });\n\n // Handle the different result formats\n if ('content' in result && Array.isArray(result.content)) {\n const content: McpContent[] = [];\n\n for (const c of result.content) {\n if (typeof c === 'object' && c !== null && 'type' in c) {\n const item = c as { type: string; [key: string]: unknown };\n if (item.type === 'text' && typeof item.text === 'string') {\n content.push({ type: 'text', text: item.text });\n } else if (\n item.type === 'image' &&\n typeof item.data === 'string' &&\n typeof item.mimeType === 'string'\n ) {\n content.push({ type: 'image', data: item.data, mimeType: item.mimeType });\n } else if (item.type === 'resource' && typeof item.resource === 'object') {\n const res = item.resource as {\n uri: string;\n text?: string;\n blob?: string;\n mimeType?: string;\n };\n const resourceContent: {\n uri: string;\n text?: string;\n blob?: string;\n mimeType?: string;\n } = {\n uri: res.uri,\n };\n if (res.text) resourceContent.text = res.text;\n if (res.blob) resourceContent.blob = res.blob;\n if (res.mimeType) resourceContent.mimeType = res.mimeType;\n content.push({\n type: 'resource',\n resource: resourceContent,\n });\n } else {\n // Default to text for unknown types\n content.push({ type: 'text', text: JSON.stringify(c) });\n }\n }\n }\n\n const toolResult: McpToolResult = { content };\n\n if (typeof result.isError === 'boolean') {\n toolResult.isError = result.isError;\n }\n\n if (typeof result.structuredContent === 'object' && result.structuredContent !== null) {\n toolResult.structuredContent = result.structuredContent as Record<string, unknown>;\n }\n\n return toolResult;\n }\n\n // Handle legacy toolResult format\n if ('toolResult' in result) {\n return {\n content: [{ type: 'text', text: JSON.stringify(result.toolResult) }],\n };\n }\n\n return {\n content: [],\n };\n } catch (error) {\n throw new McpError(\n `Failed to call tool \"${name}\": ${error instanceof Error ? error.message : String(error)}`,\n 'protocol_error',\n this.serverName,\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /**\n * List available resources from the server\n */\n async listResources(): Promise<McpResource[]> {\n const client = this.ensureConnected();\n\n const result = await client.listResources();\n\n return result.resources.map((resource) => {\n const mapped: McpResource = {\n uri: resource.uri,\n name: resource.name,\n };\n if (resource.description) {\n mapped.description = resource.description;\n }\n if (resource.mimeType) {\n mapped.mimeType = resource.mimeType;\n }\n return mapped;\n });\n }\n\n /**\n * Read a resource from the server\n */\n async readResource(uri: string): Promise<string> {\n const client = this.ensureConnected();\n\n const result = await client.readResource({ uri });\n\n // Return the first text content, or blob as base64\n for (const content of result.contents) {\n if ('text' in content) {\n return content.text;\n }\n if ('blob' in content) {\n return content.blob;\n }\n }\n\n return '';\n }\n\n /**\n * Create the appropriate transport for the server config\n */\n private async createTransport(): Promise<Transport> {\n if (this.config.transport === 'stdio') {\n return this.createStdioTransport(this.config);\n }\n\n // HTTP/SSE transports would be added here\n throw new McpError(\n `Unsupported transport type: ${this.config.transport}`,\n 'invalid_config',\n this.serverName\n );\n }\n\n /**\n * Create a stdio transport for local MCP servers\n */\n private createStdioTransport(config: StdioServerConfig): Transport {\n const params: {\n command: string;\n args?: string[];\n env?: Record<string, string>;\n cwd?: string;\n } = {\n command: config.command,\n };\n\n if (config.args) {\n params.args = config.args;\n }\n if (config.env) {\n params.env = config.env;\n }\n if (config.cwd) {\n params.cwd = config.cwd;\n }\n\n return new StdioClientTransport(params);\n }\n\n /**\n * Parse server capabilities into our format\n */\n private parseCapabilities(capabilities?: Record<string, unknown>): McpCapabilities | undefined {\n if (!capabilities) return undefined;\n\n return {\n tools: !!capabilities.tools,\n resources: !!capabilities.resources,\n prompts: !!capabilities.prompts,\n logging: !!capabilities.logging,\n };\n }\n\n /**\n * Ensure the client is connected and return the client instance\n */\n private ensureConnected(): Client {\n if (!this.client || !this.isConnected()) {\n throw new McpError(\n `Not connected to MCP server \"${this.serverName}\"`,\n 'connection_closed',\n this.serverName\n );\n }\n return this.client;\n }\n\n /**\n * Set server info (for mock/testing purposes)\n */\n protected setServerInfo(info: McpServerInfo): void {\n this._serverInfo = info;\n }\n}\n\n/**\n * Create a mock MCP client for testing\n */\nexport function createMockMcpClient(\n serverName: string,\n tools: McpTool[] = [],\n resources: McpResource[] = []\n): McpClient {\n // Create a client with in-memory transport for testing\n const client = new McpClient(serverName, { transport: 'stdio', command: 'mock' });\n\n // Store mock data\n const mockTools = tools;\n const mockResources = resources;\n\n // Override connect to set up mock state\n client.connect = async function (this: McpClient) {\n const info: McpServerInfo = {\n name: serverName,\n version: '1.0.0',\n connected: true,\n capabilities: { tools: true, resources: true },\n };\n (this as McpClient & { setServerInfo(info: McpServerInfo): void }).setServerInfo(info);\n };\n\n client.listTools = async function () {\n return mockTools;\n };\n\n client.listResources = async function () {\n return mockResources;\n };\n\n return client;\n}\n","/**\n * MCP Server Discovery\n *\n * Discovers and loads MCP server configurations from various sources.\n */\n\nimport { existsSync, readFileSync } from 'fs';\nimport { join, dirname } from 'path';\nimport { homedir } from 'os';\nimport type {\n McpConfigFile,\n McpServerConfig,\n McpServerDefinition,\n StdioServerConfig,\n HttpServerConfig,\n} from './types.js';\nimport { McpError } from './types.js';\n\n/**\n * Options for discovering MCP servers\n */\nexport interface DiscoveryOptions {\n /**\n * Project root directory to search from\n */\n projectRoot?: string;\n\n /**\n * Whether to include global config from home directory\n */\n includeGlobal?: boolean;\n\n /**\n * Additional config file paths to check\n */\n additionalPaths?: string[];\n}\n\n/**\n * Known config file locations\n */\nconst CONFIG_FILENAMES = ['mcp.json', '.mcp.json', 'claude_desktop_config.json'];\n\nconst PROJECT_CONFIG_DIRS = ['.claude', '.config', ''];\n\n/**\n * Discover MCP servers from configuration files\n */\nexport function discoverMcpServers(options: DiscoveryOptions = {}): McpServerDefinition[] {\n const projectRoot = options.projectRoot ?? process.cwd();\n const includeGlobal = options.includeGlobal ?? true;\n const additionalPaths = options.additionalPaths ?? [];\n\n const servers: McpServerDefinition[] = [];\n const seenServers = new Set<string>();\n\n // Build list of config file paths to check\n const configPaths: string[] = [];\n\n // Project-level configs (highest priority)\n for (const dir of PROJECT_CONFIG_DIRS) {\n for (const filename of CONFIG_FILENAMES) {\n const path = dir ? join(projectRoot, dir, filename) : join(projectRoot, filename);\n configPaths.push(path);\n }\n }\n\n // Additional paths\n configPaths.push(...additionalPaths);\n\n // Global config (lowest priority)\n if (includeGlobal) {\n const homeDir = homedir();\n const globalPaths = [\n join(homeDir, '.config', 'claude', 'mcp.json'),\n join(homeDir, '.claude', 'mcp.json'),\n join(homeDir, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json'),\n ];\n configPaths.push(...globalPaths);\n }\n\n // Load servers from each config file (earlier files take precedence)\n for (const configPath of configPaths) {\n if (!existsSync(configPath)) continue;\n\n try {\n const fileServers = loadServersFromFile(configPath);\n\n for (const server of fileServers) {\n // Skip if we already have a server with this name\n if (seenServers.has(server.name)) continue;\n\n seenServers.add(server.name);\n servers.push(server);\n }\n } catch (error) {\n // Log warning but continue with other files\n console.warn(\n `Warning: Failed to load MCP config from ${configPath}: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n return servers;\n}\n\n/**\n * Load MCP servers from a config file\n */\nexport function loadServersFromFile(filePath: string): McpServerDefinition[] {\n if (!existsSync(filePath)) {\n throw new McpError(`Config file not found: ${filePath}`, 'invalid_config');\n }\n\n const content = readFileSync(filePath, 'utf-8');\n let config: McpConfigFile;\n\n try {\n config = JSON.parse(content);\n } catch (error) {\n throw new McpError(\n `Invalid JSON in config file ${filePath}: ${error instanceof Error ? error.message : String(error)}`,\n 'invalid_config',\n undefined,\n error instanceof Error ? error : undefined\n );\n }\n\n return parseServersFromConfig(config, filePath);\n}\n\n/**\n * Parse server definitions from config object\n */\nexport function parseServersFromConfig(\n config: McpConfigFile,\n sourcePath?: string\n): McpServerDefinition[] {\n const servers: McpServerDefinition[] = [];\n\n if (!config.mcpServers) {\n return servers;\n }\n\n for (const [name, serverConfig] of Object.entries(config.mcpServers)) {\n try {\n const validConfig = validateServerConfig(serverConfig, name);\n\n // Resolve relative paths for stdio commands\n if (validConfig.transport === 'stdio' && sourcePath) {\n validConfig.cwd = validConfig.cwd ?? dirname(sourcePath);\n }\n\n servers.push({\n name,\n config: validConfig,\n enabled: true,\n });\n } catch (error) {\n console.warn(\n `Warning: Invalid server config for \"${name}\": ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n return servers;\n}\n\n/**\n * Validate and normalize a server configuration\n */\nexport function validateServerConfig(config: unknown, serverName: string): McpServerConfig {\n if (!config || typeof config !== 'object') {\n throw new McpError(\n `Server config for \"${serverName}\" must be an object`,\n 'invalid_config',\n serverName\n );\n }\n\n const cfg = config as Record<string, unknown>;\n\n // Determine transport type\n // If 'command' exists, it's stdio\n // If 'url' exists, it's http/sse\n // Otherwise check explicit 'transport' field\n\n if ('command' in cfg && typeof cfg.command === 'string') {\n return validateStdioConfig(cfg, serverName);\n }\n\n if ('url' in cfg && typeof cfg.url === 'string') {\n return validateHttpConfig(cfg, serverName);\n }\n\n // Check explicit transport\n if ('transport' in cfg) {\n const transport = cfg.transport;\n if (transport === 'stdio') {\n return validateStdioConfig(cfg, serverName);\n }\n if (transport === 'http' || transport === 'sse') {\n return validateHttpConfig(cfg, serverName);\n }\n throw new McpError(\n `Unknown transport type \"${transport}\" for server \"${serverName}\"`,\n 'invalid_config',\n serverName\n );\n }\n\n throw new McpError(\n `Server config for \"${serverName}\" must have either 'command' (stdio) or 'url' (http)`,\n 'invalid_config',\n serverName\n );\n}\n\n/**\n * Validate stdio server configuration\n */\nfunction validateStdioConfig(cfg: Record<string, unknown>, serverName: string): StdioServerConfig {\n if (!cfg.command || typeof cfg.command !== 'string') {\n throw new McpError(\n `Server \"${serverName}\" requires a 'command' string`,\n 'invalid_config',\n serverName\n );\n }\n\n const config: StdioServerConfig = {\n transport: 'stdio',\n command: cfg.command,\n };\n\n if (cfg.args !== undefined) {\n if (!Array.isArray(cfg.args) || !cfg.args.every((a) => typeof a === 'string')) {\n throw new McpError(\n `Server \"${serverName}\" 'args' must be an array of strings`,\n 'invalid_config',\n serverName\n );\n }\n config.args = cfg.args;\n }\n\n if (cfg.env !== undefined) {\n if (typeof cfg.env !== 'object' || cfg.env === null) {\n throw new McpError(\n `Server \"${serverName}\" 'env' must be an object`,\n 'invalid_config',\n serverName\n );\n }\n config.env = cfg.env as Record<string, string>;\n }\n\n if (cfg.cwd !== undefined) {\n if (typeof cfg.cwd !== 'string') {\n throw new McpError(\n `Server \"${serverName}\" 'cwd' must be a string`,\n 'invalid_config',\n serverName\n );\n }\n config.cwd = cfg.cwd;\n }\n\n return config;\n}\n\n/**\n * Validate HTTP/SSE server configuration\n */\nfunction validateHttpConfig(cfg: Record<string, unknown>, serverName: string): HttpServerConfig {\n if (!cfg.url || typeof cfg.url !== 'string') {\n throw new McpError(\n `Server \"${serverName}\" requires a 'url' string`,\n 'invalid_config',\n serverName\n );\n }\n\n // Validate URL\n try {\n new URL(cfg.url);\n } catch {\n throw new McpError(\n `Server \"${serverName}\" has invalid URL: ${cfg.url}`,\n 'invalid_config',\n serverName\n );\n }\n\n const transport = cfg.transport === 'sse' ? 'sse' : 'http';\n\n const config: HttpServerConfig = {\n transport,\n url: cfg.url,\n };\n\n if (cfg.headers !== undefined) {\n if (typeof cfg.headers !== 'object' || cfg.headers === null) {\n throw new McpError(\n `Server \"${serverName}\" 'headers' must be an object`,\n 'invalid_config',\n serverName\n );\n }\n config.headers = cfg.headers as Record<string, string>;\n }\n\n return config;\n}\n\n/**\n * Find an MCP config file in the project\n */\nexport function findMcpConfigFile(projectRoot?: string): string | null {\n const root = projectRoot ?? process.cwd();\n\n for (const dir of PROJECT_CONFIG_DIRS) {\n for (const filename of CONFIG_FILENAMES) {\n const path = dir ? join(root, dir, filename) : join(root, filename);\n if (existsSync(path)) {\n return path;\n }\n }\n }\n\n return null;\n}\n\n/**\n * Get the default MCP config path for a project\n */\nexport function getDefaultMcpConfigPath(projectRoot?: string): string {\n const root = projectRoot ?? process.cwd();\n return join(root, '.claude', 'mcp.json');\n}\n","/**\n * Native GitHub Adapter\n *\n * Implements GitProviderAdapter using the GitHub CLI (gh).\n * Requires the gh CLI to be installed and authenticated.\n */\n\nimport { execFile } from 'child_process';\nimport { promisify } from 'util';\nimport type { GitProviderAdapter } from '../interfaces.js';\nimport type {\n AdapterInfo,\n PullRequest,\n PullRequestQuery,\n CreatePullRequestData,\n Review,\n CreateReviewData,\n PullRequestStatus,\n ReviewDecision,\n} from '../types.js';\nimport { AdapterError } from '../types.js';\n\nconst execFileAsync = promisify(execFile);\n\n/**\n * Options for creating a GitHub adapter\n */\nexport interface GitHubAdapterOptions {\n /**\n * Repository in owner/repo format\n */\n repository: string;\n\n /**\n * Path to gh CLI (default: 'gh')\n */\n ghPath?: string;\n}\n\n/**\n * Native GitHub adapter using gh CLI\n */\nexport class GitHubAdapter implements GitProviderAdapter {\n private repository: string;\n private ghPath: string;\n private connected = false;\n private owner: string;\n private repo: string;\n\n constructor(options: GitHubAdapterOptions) {\n this.repository = options.repository;\n this.ghPath = options.ghPath ?? 'gh';\n\n const [owner, repo] = this.repository.split('/');\n if (!owner || !repo) {\n throw new AdapterError(\n `Invalid repository format: ${this.repository}. Expected owner/repo`,\n 'invalid_config',\n this.getInfo()\n );\n }\n this.owner = owner;\n this.repo = repo;\n }\n\n /**\n * Get adapter info\n */\n getInfo(): AdapterInfo {\n return {\n type: 'git',\n provider: 'github',\n implementation: 'native',\n connected: this.connected,\n };\n }\n\n /**\n * Check if connected\n */\n isConnected(): boolean {\n return this.connected;\n }\n\n /**\n * Connect (verify gh CLI is available and authenticated)\n */\n async connect(): Promise<void> {\n try {\n // Check gh is installed and authenticated\n await this.gh(['auth', 'status']);\n\n // Verify we can access the repository\n await this.gh(['repo', 'view', this.repository, '--json', 'name']);\n\n this.connected = true;\n } catch (error) {\n throw new AdapterError(\n `Failed to connect to GitHub: ${error instanceof Error ? error.message : String(error)}`,\n 'connection_failed',\n this.getInfo(),\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /**\n * Disconnect\n */\n async disconnect(): Promise<void> {\n this.connected = false;\n }\n\n /**\n * Get a pull request by number\n */\n async getPullRequest(idOrNumber: string | number): Promise<PullRequest> {\n this.ensureConnected();\n\n try {\n const result = await this.gh([\n 'pr',\n 'view',\n String(idOrNumber),\n '-R',\n this.repository,\n '--json',\n 'number,title,body,state,author,headRefName,baseRefName,createdAt,updatedAt,mergedAt,url,reviewRequests',\n ]);\n\n const data = JSON.parse(result);\n return this.mapPullRequest(data);\n } catch (error) {\n if (this.isNotFoundError(error)) {\n throw new AdapterError(\n `Pull request #${idOrNumber} not found`,\n 'not_found',\n this.getInfo()\n );\n }\n throw this.wrapError(error, `Failed to get pull request #${idOrNumber}`);\n }\n }\n\n /**\n * List pull requests\n */\n async listPullRequests(query?: PullRequestQuery): Promise<PullRequest[]> {\n this.ensureConnected();\n\n try {\n const args = [\n 'pr',\n 'list',\n '-R',\n this.repository,\n '--json',\n 'number,title,body,state,author,headRefName,baseRefName,createdAt,updatedAt,url',\n ];\n\n // Map status to gh CLI state\n if (query?.status) {\n const states = Array.isArray(query.status) ? query.status : [query.status];\n const ghStates = states\n .map((s) => this.mapStatusToGh(s))\n .filter((s): s is string => s !== undefined);\n if (ghStates.length > 0 && ghStates[0]) {\n args.push('--state', ghStates[0]);\n }\n }\n\n if (query?.author) {\n args.push('--author', query.author);\n }\n\n if (query?.limit) {\n args.push('--limit', String(query.limit));\n }\n\n const result = await this.gh(args);\n const data = JSON.parse(result) as unknown[];\n\n return data.map((pr) => this.mapPullRequest(pr as Record<string, unknown>));\n } catch (error) {\n throw this.wrapError(error, 'Failed to list pull requests');\n }\n }\n\n /**\n * Create a pull request\n */\n async createPullRequest(data: CreatePullRequestData): Promise<PullRequest> {\n this.ensureConnected();\n\n try {\n const args = [\n 'pr',\n 'create',\n '-R',\n this.repository,\n '--head',\n data.source_branch,\n '--base',\n data.target_branch,\n '--title',\n data.title,\n ];\n\n if (data.description) {\n args.push('--body', data.description);\n }\n\n if (data.draft) {\n args.push('--draft');\n }\n\n if (data.reviewers && data.reviewers.length > 0) {\n args.push('--reviewer', data.reviewers.join(','));\n }\n\n // Create and get the PR details\n const createResult = await this.gh(args);\n\n // Parse the URL from the output to get the PR number\n const urlMatch = createResult.match(/https:\\/\\/github\\.com\\/[^/]+\\/[^/]+\\/pull\\/(\\d+)/);\n if (urlMatch?.[1]) {\n return this.getPullRequest(parseInt(urlMatch[1], 10));\n }\n\n // Fallback: list to find the just-created PR\n const prs = await this.listPullRequests({ limit: 1 });\n const firstPr = prs[0];\n if (firstPr) {\n return firstPr;\n }\n\n throw new Error('Failed to retrieve created pull request');\n } catch (error) {\n throw this.wrapError(error, 'Failed to create pull request');\n }\n }\n\n /**\n * Update a pull request\n */\n async updatePullRequest(\n idOrNumber: string | number,\n data: Partial<CreatePullRequestData>\n ): Promise<PullRequest> {\n this.ensureConnected();\n\n try {\n const args = ['pr', 'edit', String(idOrNumber), '-R', this.repository];\n\n if (data.title) {\n args.push('--title', data.title);\n }\n\n if (data.description !== undefined) {\n args.push('--body', data.description);\n }\n\n if (data.target_branch) {\n args.push('--base', data.target_branch);\n }\n\n if (data.reviewers && data.reviewers.length > 0) {\n args.push('--add-reviewer', data.reviewers.join(','));\n }\n\n await this.gh(args);\n\n return this.getPullRequest(idOrNumber);\n } catch (error) {\n throw this.wrapError(error, `Failed to update pull request #${idOrNumber}`);\n }\n }\n\n /**\n * Merge a pull request\n */\n async mergePullRequest(\n idOrNumber: string | number,\n options?: { method?: 'merge' | 'squash' | 'rebase'; message?: string }\n ): Promise<void> {\n this.ensureConnected();\n\n try {\n const args = ['pr', 'merge', String(idOrNumber), '-R', this.repository];\n\n const method = options?.method ?? 'merge';\n args.push(`--${method}`);\n\n if (options?.message) {\n args.push('--body', options.message);\n }\n\n // Auto-confirm the merge\n args.push('--delete-branch=false');\n\n await this.gh(args);\n } catch (error) {\n throw this.wrapError(error, `Failed to merge pull request #${idOrNumber}`);\n }\n }\n\n /**\n * Close a pull request\n */\n async closePullRequest(idOrNumber: string | number): Promise<void> {\n this.ensureConnected();\n\n try {\n await this.gh(['pr', 'close', String(idOrNumber), '-R', this.repository]);\n } catch (error) {\n throw this.wrapError(error, `Failed to close pull request #${idOrNumber}`);\n }\n }\n\n /**\n * Add a review to a pull request\n */\n async addReview(idOrNumber: string | number, review: CreateReviewData): Promise<Review> {\n this.ensureConnected();\n\n try {\n const args = ['pr', 'review', String(idOrNumber), '-R', this.repository];\n\n // Map decision to gh CLI flag\n switch (review.decision) {\n case 'approve':\n args.push('--approve');\n break;\n case 'request_changes':\n args.push('--request-changes');\n break;\n case 'comment':\n args.push('--comment');\n break;\n }\n\n if (review.body) {\n args.push('--body', review.body);\n }\n\n await this.gh(args);\n\n // Return the review data (gh doesn't return review ID)\n const reviewResult: Review = {\n id: `review-${Date.now()}`,\n pull_request_id: String(idOrNumber),\n author: 'current-user',\n decision: review.decision,\n body: review.body ?? '',\n created_at: new Date().toISOString(),\n };\n return reviewResult;\n } catch (error) {\n throw this.wrapError(error, `Failed to add review to pull request #${idOrNumber}`);\n }\n }\n\n /**\n * Get reviews for a pull request\n */\n async getReviews(idOrNumber: string | number): Promise<Review[]> {\n this.ensureConnected();\n\n try {\n const result = await this.gh([\n 'pr',\n 'view',\n String(idOrNumber),\n '-R',\n this.repository,\n '--json',\n 'reviews',\n ]);\n\n const data = JSON.parse(result);\n const reviews = data.reviews || [];\n\n return reviews.map((r: Record<string, unknown>) => ({\n id: String(r.id || `review-${Date.now()}`),\n pull_request_id: String(idOrNumber),\n author: (r.author as { login?: string })?.login || 'unknown',\n decision: this.mapGhStateToDecision(String(r.state || 'COMMENTED')),\n body: String(r.body || ''),\n created_at: String(r.submittedAt || new Date().toISOString()),\n }));\n } catch (error) {\n throw this.wrapError(error, `Failed to get reviews for pull request #${idOrNumber}`);\n }\n }\n\n /**\n * Request reviewers for a pull request\n */\n async requestReviewers(idOrNumber: string | number, reviewers: string[]): Promise<void> {\n this.ensureConnected();\n\n try {\n await this.gh([\n 'pr',\n 'edit',\n String(idOrNumber),\n '-R',\n this.repository,\n '--add-reviewer',\n reviewers.join(','),\n ]);\n } catch (error) {\n throw this.wrapError(error, `Failed to request reviewers for pull request #${idOrNumber}`);\n }\n }\n\n /**\n * Add a comment to a pull request\n */\n async addPullRequestComment(idOrNumber: string | number, comment: string): Promise<void> {\n this.ensureConnected();\n\n try {\n await this.gh([\n 'pr',\n 'comment',\n String(idOrNumber),\n '-R',\n this.repository,\n '--body',\n comment,\n ]);\n } catch (error) {\n throw this.wrapError(error, `Failed to add comment to pull request #${idOrNumber}`);\n }\n }\n\n /**\n * Get the diff for a pull request\n */\n async getPullRequestDiff(idOrNumber: string | number): Promise<string> {\n this.ensureConnected();\n\n try {\n return await this.gh(['pr', 'diff', String(idOrNumber), '-R', this.repository]);\n } catch (error) {\n throw this.wrapError(error, `Failed to get diff for pull request #${idOrNumber}`);\n }\n }\n\n /**\n * Get files changed in a pull request\n */\n async getPullRequestFiles(idOrNumber: string | number): Promise<string[]> {\n this.ensureConnected();\n\n try {\n const result = await this.gh([\n 'pr',\n 'view',\n String(idOrNumber),\n '-R',\n this.repository,\n '--json',\n 'files',\n ]);\n\n const data = JSON.parse(result);\n const files = data.files || [];\n\n return files.map((f: { path?: string }) => f.path || '');\n } catch (error) {\n throw this.wrapError(error, `Failed to get files for pull request #${idOrNumber}`);\n }\n }\n\n /**\n * Execute gh CLI command\n */\n private async gh(args: string[]): Promise<string> {\n try {\n const { stdout } = await execFileAsync(this.ghPath, args, {\n maxBuffer: 10 * 1024 * 1024, // 10MB\n });\n return stdout;\n } catch (error) {\n const execError = error as { stderr?: string; message?: string };\n throw new Error(execError.stderr || execError.message || 'Unknown gh error');\n }\n }\n\n /**\n * Ensure adapter is connected\n */\n private ensureConnected(): void {\n if (!this.connected) {\n throw new AdapterError(\n 'GitHub adapter is not connected. Call connect() first.',\n 'not_connected',\n this.getInfo()\n );\n }\n }\n\n /**\n * Map gh PR data to PullRequest type\n */\n private mapPullRequest(data: Record<string, unknown>): PullRequest {\n const pr: PullRequest = {\n id: String(data.number),\n number: Number(data.number),\n title: String(data.title || ''),\n source_branch: String(data.headRefName || ''),\n target_branch: String(data.baseRefName || ''),\n status: this.mapGhStateToPrStatus(String(data.state || 'OPEN')),\n };\n\n if (data.body) {\n pr.description = String(data.body);\n }\n\n if (data.author && typeof data.author === 'object') {\n const login = (data.author as { login?: string }).login;\n if (login) {\n pr.author = login;\n }\n }\n\n if (data.createdAt) {\n pr.created_at = String(data.createdAt);\n }\n\n if (data.updatedAt) {\n pr.updated_at = String(data.updatedAt);\n }\n\n if (data.mergedAt) {\n pr.merged_at = String(data.mergedAt);\n }\n\n if (data.url) {\n pr.url = String(data.url);\n }\n\n if (data.reviewRequests && Array.isArray(data.reviewRequests)) {\n pr.reviewers = data.reviewRequests\n .map((r: { login?: string }) => r.login || '')\n .filter(Boolean);\n }\n\n return pr;\n }\n\n /**\n * Map gh state to PullRequestStatus\n */\n private mapGhStateToPrStatus(state: string): PullRequestStatus {\n switch (state.toUpperCase()) {\n case 'OPEN':\n return 'open';\n case 'CLOSED':\n return 'closed';\n case 'MERGED':\n return 'merged';\n default:\n return 'open';\n }\n }\n\n /**\n * Map PullRequestStatus to gh CLI state\n */\n private mapStatusToGh(status: PullRequestStatus): string | undefined {\n switch (status) {\n case 'open':\n return 'open';\n case 'closed':\n return 'closed';\n case 'merged':\n return 'merged';\n default:\n return undefined;\n }\n }\n\n /**\n * Map gh review state to ReviewDecision\n */\n private mapGhStateToDecision(state: string): ReviewDecision {\n switch (state.toUpperCase()) {\n case 'APPROVED':\n return 'approve';\n case 'CHANGES_REQUESTED':\n return 'request_changes';\n case 'COMMENTED':\n default:\n return 'comment';\n }\n }\n\n /**\n * Check if error is a not found error\n */\n private isNotFoundError(error: unknown): boolean {\n const message = error instanceof Error ? error.message : String(error);\n return message.includes('Could not resolve') || message.includes('not found');\n }\n\n /**\n * Wrap error in AdapterError\n */\n private wrapError(error: unknown, message: string): AdapterError {\n return new AdapterError(\n `${message}: ${error instanceof Error ? error.message : String(error)}`,\n 'operation_failed',\n this.getInfo(),\n error instanceof Error ? error : undefined\n );\n }\n}\n\n/**\n * Create a GitHub adapter\n */\nexport function createGitHubAdapter(options: GitHubAdapterOptions): GitHubAdapter {\n return new GitHubAdapter(options);\n}\n","/**\n * Cache Types\n *\n * Type definitions for the shared context cache system.\n */\n\n/**\n * Source type for cached content\n */\nexport type CacheSource = 'confluence' | 'github' | 'notion' | 'local' | 'custom';\n\n/**\n * Cache entry status\n */\nexport type CacheStatus = 'valid' | 'stale' | 'expired' | 'error';\n\n/**\n * Metadata for a cached entry\n */\nexport interface CacheMetadata {\n /**\n * Unique key for this cache entry\n */\n key: string;\n\n /**\n * Source provider (e.g., 'confluence', 'github')\n */\n source: CacheSource;\n\n /**\n * Original source URL or identifier\n */\n sourceUrl: string;\n\n /**\n * When the content was cached\n */\n cachedAt: string;\n\n /**\n * When the content expires (ISO date string)\n */\n expiresAt: string;\n\n /**\n * ETag or version hash from source (for conditional fetching)\n */\n etag?: string;\n\n /**\n * Content hash for integrity checking\n */\n contentHash: string;\n\n /**\n * Size in bytes\n */\n size: number;\n\n /**\n * Content type (e.g., 'text/markdown', 'application/json')\n */\n contentType: string;\n\n /**\n * Original title or name\n */\n title?: string;\n\n /**\n * Last modified timestamp from source\n */\n lastModified?: string;\n\n /**\n * Custom tags for categorization\n */\n tags?: string[];\n}\n\n/**\n * A cached content entry\n */\nexport interface CacheEntry<T = string> {\n /**\n * Entry metadata\n */\n metadata: CacheMetadata;\n\n /**\n * The cached content\n */\n content: T;\n}\n\n/**\n * Options for cache operations\n */\nexport interface CacheOptions {\n /**\n * Time-to-live in seconds (default: 3600 = 1 hour)\n */\n ttl?: number;\n\n /**\n * Force refresh even if cached\n */\n forceRefresh?: boolean;\n\n /**\n * Skip cache and fetch directly\n */\n skipCache?: boolean;\n\n /**\n * Custom tags to apply\n */\n tags?: string[];\n}\n\n/**\n * Options for listing cache entries\n */\nexport interface CacheListOptions {\n /**\n * Filter by source\n */\n source?: CacheSource;\n\n /**\n * Filter by tag\n */\n tag?: string;\n\n /**\n * Filter by status\n */\n status?: CacheStatus;\n\n /**\n * Maximum entries to return\n */\n limit?: number;\n}\n\n/**\n * Cache statistics\n */\nexport interface CacheStats {\n /**\n * Total number of entries\n */\n totalEntries: number;\n\n /**\n * Total size in bytes\n */\n totalSize: number;\n\n /**\n * Number of valid entries\n */\n validEntries: number;\n\n /**\n * Number of stale entries\n */\n staleEntries: number;\n\n /**\n * Number of expired entries\n */\n expiredEntries: number;\n\n /**\n * Entries by source\n */\n bySource: Record<CacheSource, number>;\n\n /**\n * Oldest entry timestamp\n */\n oldestEntry?: string;\n\n /**\n * Newest entry timestamp\n */\n newestEntry?: string;\n}\n\n/**\n * Result of a sync operation\n */\nexport interface SyncResult {\n /**\n * Number of entries added\n */\n added: number;\n\n /**\n * Number of entries updated\n */\n updated: number;\n\n /**\n * Number of entries removed\n */\n removed: number;\n\n /**\n * Number of entries that failed to sync\n */\n failed: number;\n\n /**\n * Error messages for failed entries\n */\n errors: { key: string; error: string }[];\n\n /**\n * Duration of sync in milliseconds\n */\n duration: number;\n}\n\n/**\n * Cache error codes\n */\nexport type CacheErrorCode =\n | 'not_found'\n | 'expired'\n | 'invalid_key'\n | 'write_failed'\n | 'read_failed'\n | 'fetch_failed'\n | 'invalid_config'\n | 'storage_full';\n\n/**\n * Cache-specific error\n */\nexport class CacheError extends Error {\n constructor(\n message: string,\n public readonly code: CacheErrorCode,\n public readonly key?: string,\n public override readonly cause?: Error\n ) {\n super(message);\n this.name = 'CacheError';\n }\n}\n\n/**\n * Default cache directory paths\n */\nexport const CACHE_PATHS = {\n /**\n * Root cache directory (relative to project root)\n */\n ROOT: '.coreai/cache',\n\n /**\n * Content storage directory\n */\n CONTENT: '.coreai/cache/content',\n\n /**\n * Metadata storage directory\n */\n METADATA: '.coreai/cache/metadata',\n\n /**\n * Index file for fast lookups\n */\n INDEX: '.coreai/cache/index.json',\n\n /**\n * Lock file for concurrent access\n */\n LOCK: '.coreai/cache/.lock',\n} as const;\n\n/**\n * Default cache configuration\n */\nexport const DEFAULT_CACHE_CONFIG = {\n /**\n * Default TTL in seconds (1 hour)\n */\n ttl: 3600,\n\n /**\n * Maximum cache size in bytes (100MB)\n */\n maxSize: 100 * 1024 * 1024,\n\n /**\n * Maximum number of entries\n */\n maxEntries: 1000,\n\n /**\n * Enable automatic cleanup of expired entries\n */\n autoCleanup: true,\n\n /**\n * Cleanup interval in seconds (1 hour)\n */\n cleanupInterval: 3600,\n} as const;\n","/**\n * File-based Cache Provider\n *\n * Implements CacheProvider using the local filesystem.\n * Stores content in files with separate metadata JSON files.\n */\n\nimport { promises as fs } from 'fs';\nimport { join, dirname } from 'path';\nimport { createHash } from 'crypto';\nimport type {\n CacheEntry,\n CacheMetadata,\n CacheOptions,\n CacheListOptions,\n CacheStats,\n CacheStatus,\n CacheSource,\n} from './types.js';\nimport { CacheError, CACHE_PATHS, DEFAULT_CACHE_CONFIG } from './types.js';\nimport type { CacheProvider } from './interfaces.js';\n\n/**\n * No-op function for ignoring errors\n */\nfunction noop(): void {\n // Intentionally empty\n}\n\n/**\n * Options for creating a file cache provider\n */\nexport interface FileCacheProviderOptions {\n /**\n * Base path for cache storage (project root)\n */\n basePath: string;\n\n /**\n * Default TTL in seconds\n */\n ttl?: number;\n\n /**\n * Maximum cache size in bytes\n */\n maxSize?: number;\n\n /**\n * Maximum number of entries\n */\n maxEntries?: number;\n}\n\n/**\n * Cache index structure for fast lookups\n */\ninterface CacheIndex {\n version: number;\n entries: Record<string, CacheIndexEntry>;\n stats: {\n totalSize: number;\n entryCount: number;\n lastCleanup: string | null;\n };\n}\n\n/**\n * Index entry for quick access\n */\ninterface CacheIndexEntry {\n key: string;\n source: CacheSource;\n cachedAt: string;\n expiresAt: string;\n size: number;\n contentFile: string;\n metadataFile: string;\n}\n\nconst INDEX_VERSION = 1;\n\n/**\n * File-based cache provider implementation\n */\nexport class FileCacheProvider implements CacheProvider {\n private basePath: string;\n private cachePath: string;\n private contentPath: string;\n private metadataPath: string;\n private indexPath: string;\n private ttl: number;\n private maxSize: number;\n private maxEntries: number;\n private initialized = false;\n private index: CacheIndex | null = null;\n\n constructor(options: FileCacheProviderOptions) {\n this.basePath = options.basePath;\n this.cachePath = join(this.basePath, CACHE_PATHS.ROOT);\n this.contentPath = join(this.basePath, CACHE_PATHS.CONTENT);\n this.metadataPath = join(this.basePath, CACHE_PATHS.METADATA);\n this.indexPath = join(this.basePath, CACHE_PATHS.INDEX);\n this.ttl = options.ttl ?? DEFAULT_CACHE_CONFIG.ttl;\n this.maxSize = options.maxSize ?? DEFAULT_CACHE_CONFIG.maxSize;\n this.maxEntries = options.maxEntries ?? DEFAULT_CACHE_CONFIG.maxEntries;\n }\n\n /**\n * Initialize the cache (create directories, load index)\n */\n async initialize(): Promise<void> {\n if (this.initialized) return;\n\n try {\n // Create cache directories\n await fs.mkdir(this.contentPath, { recursive: true });\n await fs.mkdir(this.metadataPath, { recursive: true });\n\n // Load or create index\n this.index = await this.loadIndex();\n\n // Save index to ensure file exists\n await this.saveIndex();\n\n this.initialized = true;\n } catch (error) {\n throw new CacheError(\n `Failed to initialize cache: ${error instanceof Error ? error.message : String(error)}`,\n 'write_failed',\n undefined,\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /**\n * Check if the cache is initialized\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n\n /**\n * Get a cached entry by key\n */\n async get<T = string>(key: string, options?: CacheOptions): Promise<CacheEntry<T> | null> {\n this.ensureInitialized();\n\n if (options?.skipCache) {\n return null;\n }\n\n const indexEntry = this.index?.entries[key];\n if (!indexEntry) {\n return null;\n }\n\n // Check expiration (unless force refresh)\n if (!options?.forceRefresh) {\n const status = this.getEntryStatus(indexEntry);\n if (status === 'expired') {\n return null;\n }\n }\n\n try {\n // Read metadata\n const metadataContent = await fs.readFile(indexEntry.metadataFile, 'utf-8');\n const metadata: CacheMetadata = JSON.parse(metadataContent);\n\n // Read content\n const contentRaw = await fs.readFile(indexEntry.contentFile, 'utf-8');\n let content: T;\n\n // Try to parse as JSON if content type indicates it\n if (metadata.contentType.includes('json')) {\n content = JSON.parse(contentRaw) as T;\n } else {\n content = contentRaw as T;\n }\n\n return { metadata, content };\n } catch {\n // Entry exists in index but files are missing - clean up\n await this.delete(key);\n return null;\n }\n }\n\n /**\n * Get the content only (convenience method)\n */\n async getContent<T = string>(key: string, options?: CacheOptions): Promise<T | null> {\n const entry = await this.get<T>(key, options);\n return entry?.content ?? null;\n }\n\n /**\n * Set a cache entry\n */\n async set<T = string>(\n key: string,\n content: T,\n metadata: Partial<CacheMetadata>,\n options?: CacheOptions\n ): Promise<void> {\n this.ensureInitialized();\n\n const now = new Date();\n const ttl = options?.ttl ?? this.ttl;\n const expiresAt = new Date(now.getTime() + ttl * 1000);\n\n // Serialize content\n const contentStr = typeof content === 'string' ? content : JSON.stringify(content, null, 2);\n const contentHash = this.hashContent(contentStr);\n const size = Buffer.byteLength(contentStr, 'utf-8');\n\n // Generate file paths\n const safeKey = this.sanitizeKey(key);\n const contentFile = join(this.contentPath, `${safeKey}.cache`);\n const metadataFile = join(this.metadataPath, `${safeKey}.json`);\n\n // Build full metadata\n const fullMetadata: CacheMetadata = {\n key,\n source: metadata.source ?? 'custom',\n sourceUrl: metadata.sourceUrl ?? '',\n cachedAt: now.toISOString(),\n expiresAt: expiresAt.toISOString(),\n contentHash,\n size,\n contentType:\n metadata.contentType ?? (typeof content === 'string' ? 'text/plain' : 'application/json'),\n };\n // Conditionally add optional properties\n if (metadata.etag) {\n fullMetadata.etag = metadata.etag;\n }\n if (metadata.title) {\n fullMetadata.title = metadata.title;\n }\n if (metadata.lastModified) {\n fullMetadata.lastModified = metadata.lastModified;\n }\n const tags = options?.tags ?? metadata.tags;\n if (tags) {\n fullMetadata.tags = tags;\n }\n\n try {\n // Ensure directories exist\n await fs.mkdir(dirname(contentFile), { recursive: true });\n await fs.mkdir(dirname(metadataFile), { recursive: true });\n\n // Write files\n await fs.writeFile(contentFile, contentStr, 'utf-8');\n await fs.writeFile(metadataFile, JSON.stringify(fullMetadata, null, 2), 'utf-8');\n\n // Update index\n if (this.index) {\n // Remove old size from stats if updating\n const oldEntry = this.index.entries[key];\n if (oldEntry) {\n this.index.stats.totalSize -= oldEntry.size;\n } else {\n this.index.stats.entryCount++;\n }\n\n this.index.entries[key] = {\n key,\n source: fullMetadata.source,\n cachedAt: fullMetadata.cachedAt,\n expiresAt: fullMetadata.expiresAt,\n size,\n contentFile,\n metadataFile,\n };\n this.index.stats.totalSize += size;\n\n await this.saveIndex();\n }\n } catch (error) {\n throw new CacheError(\n `Failed to write cache entry: ${error instanceof Error ? error.message : String(error)}`,\n 'write_failed',\n key,\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /**\n * Check if a key exists in the cache\n */\n async has(key: string): Promise<boolean> {\n this.ensureInitialized();\n return key in (this.index?.entries ?? {});\n }\n\n /**\n * Delete a cache entry\n */\n async delete(key: string): Promise<boolean> {\n this.ensureInitialized();\n\n const indexEntry = this.index?.entries[key];\n if (!indexEntry) {\n return false;\n }\n\n try {\n // Delete files (ignore if already missing)\n await fs.unlink(indexEntry.contentFile).catch(noop);\n await fs.unlink(indexEntry.metadataFile).catch(noop);\n\n // Update index\n if (this.index) {\n this.index.stats.totalSize -= indexEntry.size;\n this.index.stats.entryCount--;\n // Remove entry from index using destructuring\n const { [key]: _removed, ...remaining } = this.index.entries;\n this.index.entries = remaining;\n await this.saveIndex();\n }\n\n return true;\n } catch (error) {\n throw new CacheError(\n `Failed to delete cache entry: ${error instanceof Error ? error.message : String(error)}`,\n 'write_failed',\n key,\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /**\n * Get the status of a cache entry\n */\n async getStatus(key: string): Promise<CacheStatus | null> {\n this.ensureInitialized();\n\n const indexEntry = this.index?.entries[key];\n if (!indexEntry) {\n return null;\n }\n\n return this.getEntryStatus(indexEntry);\n }\n\n /**\n * Get metadata for a cache entry\n */\n async getMetadata(key: string): Promise<CacheMetadata | null> {\n this.ensureInitialized();\n\n const indexEntry = this.index?.entries[key];\n if (!indexEntry) {\n return null;\n }\n\n try {\n const content = await fs.readFile(indexEntry.metadataFile, 'utf-8');\n return JSON.parse(content);\n } catch {\n return null;\n }\n }\n\n /**\n * Update metadata for a cache entry\n */\n async updateMetadata(key: string, metadata: Partial<CacheMetadata>): Promise<void> {\n this.ensureInitialized();\n\n const existing = await this.getMetadata(key);\n if (!existing) {\n throw new CacheError(`Cache entry not found: ${key}`, 'not_found', key);\n }\n\n const indexEntry = this.index?.entries[key];\n if (!indexEntry) {\n throw new CacheError(`Cache entry not found: ${key}`, 'not_found', key);\n }\n\n const updated: CacheMetadata = {\n ...existing,\n ...metadata,\n key: existing.key, // Can't change key\n };\n\n try {\n await fs.writeFile(indexEntry.metadataFile, JSON.stringify(updated, null, 2), 'utf-8');\n\n // Update index if relevant fields changed\n if (this.index && indexEntry) {\n if (metadata.source) indexEntry.source = metadata.source;\n if (metadata.expiresAt) indexEntry.expiresAt = metadata.expiresAt;\n await this.saveIndex();\n }\n } catch (error) {\n throw new CacheError(\n `Failed to update metadata: ${error instanceof Error ? error.message : String(error)}`,\n 'write_failed',\n key,\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /**\n * List cache entries\n */\n async list(options?: CacheListOptions): Promise<CacheMetadata[]> {\n this.ensureInitialized();\n\n if (!this.index) return [];\n\n let entries = Object.values(this.index.entries);\n\n // Apply filters\n if (options?.source) {\n entries = entries.filter((e) => e.source === options.source);\n }\n\n if (options?.status) {\n entries = entries.filter((e) => this.getEntryStatus(e) === options.status);\n }\n\n // Load full metadata for tag filtering and return\n const metadataPromises = entries.map(async (e) => {\n const metadata = await this.getMetadata(e.key);\n return metadata;\n });\n\n let results = (await Promise.all(metadataPromises)).filter(\n (m): m is CacheMetadata => m !== null\n );\n\n // Filter by tag if specified\n if (options?.tag) {\n const tag = options.tag;\n results = results.filter((m) => m.tags?.includes(tag));\n }\n\n // Apply limit\n if (options?.limit && results.length > options.limit) {\n results = results.slice(0, options.limit);\n }\n\n return results;\n }\n\n /**\n * Get cache statistics\n */\n async getStats(): Promise<CacheStats> {\n this.ensureInitialized();\n\n if (!this.index) {\n return {\n totalEntries: 0,\n totalSize: 0,\n validEntries: 0,\n staleEntries: 0,\n expiredEntries: 0,\n bySource: {\n confluence: 0,\n github: 0,\n notion: 0,\n local: 0,\n custom: 0,\n },\n };\n }\n\n const entries = Object.values(this.index.entries);\n const bySource: Record<CacheSource, number> = {\n confluence: 0,\n github: 0,\n notion: 0,\n local: 0,\n custom: 0,\n };\n\n let validEntries = 0;\n let staleEntries = 0;\n let expiredEntries = 0;\n let oldestEntry: string | undefined;\n let newestEntry: string | undefined;\n\n for (const entry of entries) {\n bySource[entry.source]++;\n\n const status = this.getEntryStatus(entry);\n if (status === 'valid') validEntries++;\n else if (status === 'stale') staleEntries++;\n else if (status === 'expired') expiredEntries++;\n\n if (!oldestEntry || entry.cachedAt < oldestEntry) {\n oldestEntry = entry.cachedAt;\n }\n if (!newestEntry || entry.cachedAt > newestEntry) {\n newestEntry = entry.cachedAt;\n }\n }\n\n const stats: CacheStats = {\n totalEntries: this.index.stats.entryCount,\n totalSize: this.index.stats.totalSize,\n validEntries,\n staleEntries,\n expiredEntries,\n bySource,\n };\n\n if (oldestEntry) stats.oldestEntry = oldestEntry;\n if (newestEntry) stats.newestEntry = newestEntry;\n\n return stats;\n }\n\n /**\n * Clear all cache entries\n */\n async clear(): Promise<number> {\n this.ensureInitialized();\n\n if (!this.index) return 0;\n\n const count = this.index.stats.entryCount;\n\n try {\n // Delete all content and metadata files\n await fs.rm(this.contentPath, { recursive: true, force: true });\n await fs.rm(this.metadataPath, { recursive: true, force: true });\n\n // Recreate directories\n await fs.mkdir(this.contentPath, { recursive: true });\n await fs.mkdir(this.metadataPath, { recursive: true });\n\n // Reset index\n this.index = this.createEmptyIndex();\n await this.saveIndex();\n\n return count;\n } catch (error) {\n throw new CacheError(\n `Failed to clear cache: ${error instanceof Error ? error.message : String(error)}`,\n 'write_failed',\n undefined,\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /**\n * Clear expired entries only\n */\n async clearExpired(): Promise<number> {\n this.ensureInitialized();\n\n if (!this.index) return 0;\n\n const expiredKeys = Object.entries(this.index.entries)\n .filter(([, entry]) => this.getEntryStatus(entry) === 'expired')\n .map(([key]) => key);\n\n for (const key of expiredKeys) {\n await this.delete(key);\n }\n\n if (this.index) {\n this.index.stats.lastCleanup = new Date().toISOString();\n await this.saveIndex();\n }\n\n return expiredKeys.length;\n }\n\n /**\n * Clear entries by source\n */\n async clearBySource(source: string): Promise<number> {\n this.ensureInitialized();\n\n if (!this.index) return 0;\n\n const keys = Object.entries(this.index.entries)\n .filter(([, entry]) => entry.source === source)\n .map(([key]) => key);\n\n for (const key of keys) {\n await this.delete(key);\n }\n\n return keys.length;\n }\n\n /**\n * Clear entries by tag\n */\n async clearByTag(tag: string): Promise<number> {\n this.ensureInitialized();\n\n const entries = await this.list({ tag });\n for (const entry of entries) {\n await this.delete(entry.key);\n }\n\n return entries.length;\n }\n\n // Private helpers\n\n private ensureInitialized(): void {\n if (!this.initialized) {\n throw new CacheError('Cache not initialized. Call initialize() first.', 'invalid_config');\n }\n }\n\n private async loadIndex(): Promise<CacheIndex> {\n try {\n const content = await fs.readFile(this.indexPath, 'utf-8');\n const index = JSON.parse(content) as CacheIndex;\n\n // Validate version\n if (index.version !== INDEX_VERSION) {\n // Index version mismatch - rebuild\n return this.rebuildIndex();\n }\n\n return index;\n } catch {\n // Index doesn't exist or is invalid - create new one\n return this.createEmptyIndex();\n }\n }\n\n private async saveIndex(): Promise<void> {\n if (!this.index) return;\n\n try {\n await fs.writeFile(this.indexPath, JSON.stringify(this.index, null, 2), 'utf-8');\n } catch (error) {\n throw new CacheError(\n `Failed to save cache index: ${error instanceof Error ? error.message : String(error)}`,\n 'write_failed',\n undefined,\n error instanceof Error ? error : undefined\n );\n }\n }\n\n private createEmptyIndex(): CacheIndex {\n return {\n version: INDEX_VERSION,\n entries: {},\n stats: {\n totalSize: 0,\n entryCount: 0,\n lastCleanup: null,\n },\n };\n }\n\n private async rebuildIndex(): Promise<CacheIndex> {\n const index = this.createEmptyIndex();\n\n try {\n const metadataFiles = await fs.readdir(this.metadataPath);\n\n for (const file of metadataFiles) {\n if (!file.endsWith('.json')) continue;\n\n try {\n const metadataPath = join(this.metadataPath, file);\n const content = await fs.readFile(metadataPath, 'utf-8');\n const metadata: CacheMetadata = JSON.parse(content);\n\n const safeKey = this.sanitizeKey(metadata.key);\n const contentFile = join(this.contentPath, `${safeKey}.cache`);\n\n // Verify content file exists\n await fs.access(contentFile);\n\n index.entries[metadata.key] = {\n key: metadata.key,\n source: metadata.source,\n cachedAt: metadata.cachedAt,\n expiresAt: metadata.expiresAt,\n size: metadata.size,\n contentFile,\n metadataFile: metadataPath,\n };\n\n index.stats.totalSize += metadata.size;\n index.stats.entryCount++;\n } catch {\n // Skip invalid entries\n }\n }\n } catch {\n // Metadata directory doesn't exist or is empty\n }\n\n return index;\n }\n\n private getEntryStatus(entry: CacheIndexEntry): CacheStatus {\n const now = new Date();\n const expiresAt = new Date(entry.expiresAt);\n const cachedAt = new Date(entry.cachedAt);\n\n if (now > expiresAt) {\n return 'expired';\n }\n\n // Consider stale if more than 80% of TTL has passed\n const totalTtl = expiresAt.getTime() - cachedAt.getTime();\n const elapsed = now.getTime() - cachedAt.getTime();\n if (elapsed > totalTtl * 0.8) {\n return 'stale';\n }\n\n return 'valid';\n }\n\n private sanitizeKey(key: string): string {\n // Create a safe filename from the key\n return createHash('sha256').update(key).digest('hex').substring(0, 32);\n }\n\n private hashContent(content: string): string {\n return createHash('sha256').update(content).digest('hex');\n }\n}\n\n/**\n * Create a file cache provider\n */\nexport function createFileCacheProvider(options: FileCacheProviderOptions): FileCacheProvider {\n return new FileCacheProvider(options);\n}\n","/**\n * Cache Manager\n *\n * Higher-level cache management that combines caching with remote fetching.\n * Implements cache-first resolution with remote fallback strategy.\n */\n\nimport type { CacheEntry, CacheMetadata, CacheOptions, CacheSource, SyncResult } from './types.js';\nimport { CacheError } from './types.js';\nimport type {\n CacheProvider,\n CacheManager as ICacheManager,\n RemoteFetcher,\n FetchOptions,\n SyncOptions,\n} from './interfaces.js';\n\n/**\n * Options for creating a cache manager\n */\nexport interface CacheManagerOptions {\n /**\n * The underlying cache provider\n */\n cache: CacheProvider;\n\n /**\n * Default TTL in seconds\n */\n defaultTtl?: number;\n\n /**\n * Default source for new entries\n */\n defaultSource?: CacheSource;\n}\n\n/**\n * Cache manager implementation\n *\n * Provides cache-first resolution strategy:\n * 1. Check cache for valid entry\n * 2. If cached and valid, return cached content\n * 3. If stale or missing, fetch from remote\n * 4. Cache the fetched content\n * 5. Return the content\n */\nexport class CacheManager implements ICacheManager {\n private cache: CacheProvider;\n private fetchers = new Map<string, RemoteFetcher>();\n private defaultTtl: number;\n private defaultSource: CacheSource;\n\n constructor(options: CacheManagerOptions) {\n this.cache = options.cache;\n this.defaultTtl = options.defaultTtl ?? 3600;\n this.defaultSource = options.defaultSource ?? 'custom';\n }\n\n /**\n * Get content with cache-first strategy\n */\n async getWithFallback<T = string>(\n key: string,\n url: string,\n options?: CacheOptions & FetchOptions\n ): Promise<CacheEntry<T>> {\n // Try cache first (unless skipCache is set)\n if (!options?.skipCache && !options?.forceRefresh) {\n const cached = await this.cache.get<T>(key);\n if (cached) {\n const status = await this.cache.getStatus(key);\n // Return if valid (not stale or expired)\n if (status === 'valid') {\n return cached;\n }\n // If stale, try to refresh but fall back to stale if fetch fails\n if (status === 'stale') {\n try {\n return await this.fetchAndCache<T>(key, url, options);\n } catch {\n // Return stale content on fetch failure\n return cached;\n }\n }\n }\n }\n\n // Cache miss or forceRefresh - fetch from remote\n return this.fetchAndCache<T>(key, url, options);\n }\n\n /**\n * Sync all entries from a source\n */\n async syncSource(source: string, options?: SyncOptions): Promise<SyncResult> {\n const startTime = Date.now();\n const result: SyncResult = {\n added: 0,\n updated: 0,\n removed: 0,\n failed: 0,\n errors: [],\n duration: 0,\n };\n\n // Get all entries from this source\n const entries = await this.cache.list({ source: source as CacheSource });\n\n // Sync each entry\n const concurrency = options?.concurrency ?? 5;\n const chunks = this.chunkArray(entries, concurrency);\n\n for (const chunk of chunks) {\n const promises = chunk.map(async (entry) => {\n try {\n const fetcher = this.fetchers.get(source);\n if (!fetcher) {\n throw new Error(`No fetcher registered for source: ${source}`);\n }\n\n // Check if content has changed\n const hasChanged = await fetcher.hasChanged(entry.sourceUrl, entry.etag);\n\n if (hasChanged || options?.force) {\n // Fetch and update\n const fetchOptions: FetchOptions = {};\n if (entry.etag) {\n fetchOptions.etag = entry.etag;\n }\n const { content, metadata } = await fetcher.fetch(entry.sourceUrl, fetchOptions);\n\n await this.cache.set(entry.key, content, {\n ...entry,\n ...metadata,\n });\n\n result.updated++;\n }\n } catch (error) {\n result.failed++;\n result.errors.push({\n key: entry.key,\n error: error instanceof Error ? error.message : String(error),\n });\n\n if (!options?.continueOnError) {\n throw error;\n }\n }\n });\n\n await Promise.all(promises);\n }\n\n // Report final progress\n if (options?.onProgress) {\n options.onProgress(entries.length, entries.length);\n }\n\n result.duration = Date.now() - startTime;\n return result;\n }\n\n /**\n * Sync specific entries\n */\n async syncEntries(keys: string[], options?: SyncOptions): Promise<SyncResult> {\n const startTime = Date.now();\n const result: SyncResult = {\n added: 0,\n updated: 0,\n removed: 0,\n failed: 0,\n errors: [],\n duration: 0,\n };\n\n const concurrency = options?.concurrency ?? 5;\n const chunks = this.chunkArray(keys, concurrency);\n\n for (const chunk of chunks) {\n const promises = chunk.map(async (key) => {\n try {\n const metadata = await this.cache.getMetadata(key);\n if (!metadata) {\n result.failed++;\n result.errors.push({ key, error: 'Entry not found in cache' });\n return;\n }\n\n const fetcher = this.fetchers.get(metadata.source);\n if (!fetcher) {\n result.failed++;\n result.errors.push({ key, error: `No fetcher for source: ${metadata.source}` });\n return;\n }\n\n // Check if content has changed\n const hasChanged = await fetcher.hasChanged(metadata.sourceUrl, metadata.etag);\n\n if (hasChanged || options?.force) {\n const fetchOpts: FetchOptions = {};\n if (metadata.etag) {\n fetchOpts.etag = metadata.etag;\n }\n const { content, metadata: newMeta } = await fetcher.fetch(\n metadata.sourceUrl,\n fetchOpts\n );\n\n await this.cache.set(key, content, {\n ...metadata,\n ...newMeta,\n });\n\n result.updated++;\n }\n } catch (error) {\n result.failed++;\n result.errors.push({\n key,\n error: error instanceof Error ? error.message : String(error),\n });\n\n if (!options?.continueOnError) {\n throw error;\n }\n }\n });\n\n await Promise.all(promises);\n }\n\n // Report final progress\n if (options?.onProgress) {\n options.onProgress(keys.length, keys.length);\n }\n\n result.duration = Date.now() - startTime;\n return result;\n }\n\n /**\n * Register a fetcher for a source\n */\n registerFetcher(source: string, fetcher: RemoteFetcher): void {\n this.fetchers.set(source, fetcher);\n }\n\n /**\n * Get the underlying cache provider\n */\n getCache(): CacheProvider {\n return this.cache;\n }\n\n /**\n * Check if a fetcher is registered for a source\n */\n hasFetcher(source: string): boolean {\n return this.fetchers.has(source);\n }\n\n /**\n * Get all registered sources\n */\n getRegisteredSources(): string[] {\n return Array.from(this.fetchers.keys());\n }\n\n // Private helpers\n\n private async fetchAndCache<T>(\n key: string,\n url: string,\n options?: CacheOptions & FetchOptions\n ): Promise<CacheEntry<T>> {\n // Determine source from URL\n const source = this.getSourceFromUrl(url);\n const fetcher = this.fetchers.get(source);\n\n if (!fetcher) {\n throw new CacheError(\n `No fetcher registered for source: ${source}. Register one with registerFetcher().`,\n 'fetch_failed',\n key\n );\n }\n\n try {\n // Fetch from remote\n const fetchOpts: FetchOptions = {};\n if (options?.timeout) {\n fetchOpts.timeout = options.timeout;\n }\n if (options?.headers) {\n fetchOpts.headers = options.headers;\n }\n const { content, metadata } = await fetcher.fetch(url, fetchOpts);\n\n // Build full metadata\n const fullMetadata: Partial<CacheMetadata> = {\n source: source as CacheSource,\n sourceUrl: url,\n contentType: metadata.contentType ?? 'text/plain',\n };\n if (metadata.etag) {\n fullMetadata.etag = metadata.etag;\n }\n if (metadata.title) {\n fullMetadata.title = metadata.title;\n }\n if (metadata.lastModified) {\n fullMetadata.lastModified = metadata.lastModified;\n }\n if (options?.tags) {\n fullMetadata.tags = options.tags;\n }\n\n // Cache the content\n const cacheOpts: CacheOptions = {\n ttl: options?.ttl ?? this.defaultTtl,\n };\n if (options?.tags) {\n cacheOpts.tags = options.tags;\n }\n await this.cache.set(key, content, fullMetadata, cacheOpts);\n\n // Return the entry\n const entry = await this.cache.get<T>(key);\n if (!entry) {\n throw new CacheError('Failed to retrieve cached entry after write', 'read_failed', key);\n }\n\n return entry;\n } catch (error) {\n if (error instanceof CacheError) {\n throw error;\n }\n throw new CacheError(\n `Failed to fetch content: ${error instanceof Error ? error.message : String(error)}`,\n 'fetch_failed',\n key,\n error instanceof Error ? error : undefined\n );\n }\n }\n\n private getSourceFromUrl(url: string): string {\n try {\n const parsed = new URL(url);\n const hostname = parsed.hostname.toLowerCase();\n\n // Map common hostnames to sources\n if (hostname.includes('confluence') || hostname.includes('atlassian.net')) {\n return 'confluence';\n }\n if (hostname.includes('github.com') || hostname.includes('github')) {\n return 'github';\n }\n if (hostname.includes('notion.so') || hostname.includes('notion')) {\n return 'notion';\n }\n\n // Default to custom\n return this.defaultSource;\n } catch {\n // Invalid URL, might be a file path\n return 'local';\n }\n }\n\n private chunkArray<T>(array: T[], size: number): T[][] {\n const chunks: T[][] = [];\n for (let i = 0; i < array.length; i += size) {\n chunks.push(array.slice(i, i + size));\n }\n return chunks;\n }\n}\n\n/**\n * Create a cache manager\n */\nexport function createCacheManager(options: CacheManagerOptions): CacheManager {\n return new CacheManager(options);\n}\n","/**\n * Skill Generator\n *\n * Discovers skill source files from skills/ directory and compiles them\n * to .claude/skills/<name>/SKILL.md format for Claude Code.\n *\n * Source: skills/<category>/<name>/SKILL.md (grouped by category)\n * Output: .claude/skills/<name>/SKILL.md (flat, one level deep)\n */\n\nimport { existsSync, mkdirSync, writeFileSync, readFileSync, readdirSync, statSync } from 'fs';\nimport { join, dirname } from 'path';\nimport type { ResolvedCoreAIConfig } from '../config/types.js';\nimport type {\n SkillTemplate,\n SkillVariables,\n GenerateSkillsOptions,\n GenerateSkillsResult,\n GeneratedSkill,\n SkillDependency,\n SkillCategory,\n} from './types.js';\n\n/**\n * Get the default core skills directory (bundled with CoreAI package)\n */\nexport function getCoreSkillsDir(): string {\n let currentDir = dirname(import.meta.url.replace('file://', ''));\n for (let i = 0; i < 5; i++) {\n if (existsSync(join(currentDir, 'package.json'))) {\n return join(currentDir, 'skills');\n }\n currentDir = dirname(currentDir);\n }\n return join(dirname(dirname(dirname(import.meta.url.replace('file://', '')))), 'skills');\n}\n\n/**\n * Discover skill source files from a skills directory.\n *\n * Scans skills/<category>/<name>/SKILL.md structure.\n * Each category directory (core, git, etc.) contains skill directories.\n */\nexport function discoverSkills(skillsDir: string): SkillTemplate[] {\n const templates: SkillTemplate[] = [];\n\n if (!existsSync(skillsDir)) {\n return templates;\n }\n\n // Scan category directories (core/, git/, etc.)\n const categories = readdirSync(skillsDir);\n\n for (const category of categories) {\n const categoryPath = join(skillsDir, category);\n const stat = statSync(categoryPath);\n if (!stat.isDirectory()) continue;\n\n // Skip hidden/underscore directories\n if (category.startsWith('.') || category.startsWith('_')) continue;\n\n // Scan skill directories within this category\n const skillDirs = readdirSync(categoryPath);\n\n for (const skillName of skillDirs) {\n const skillDir = join(categoryPath, skillName);\n const skillStat = statSync(skillDir);\n if (!skillStat.isDirectory()) continue;\n\n const skillFile = join(skillDir, 'SKILL.md');\n if (!existsSync(skillFile)) continue;\n\n try {\n const content = readFileSync(skillFile, 'utf-8');\n const template = parseSkillFile(skillName, category as SkillCategory, content);\n templates.push(template);\n } catch {\n // Skip invalid skill files\n }\n }\n }\n\n return templates;\n}\n\n/**\n * Parse a SKILL.md file into a SkillTemplate\n */\nexport function parseSkillFile(\n name: string,\n category: SkillCategory,\n content: string\n): SkillTemplate {\n const template: SkillTemplate = {\n name,\n description: name,\n category,\n content,\n };\n\n // Parse frontmatter\n const frontmatterMatch = content.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n/);\n if (!frontmatterMatch) {\n return template;\n }\n\n const frontmatter = frontmatterMatch[1]!;\n const lines = frontmatter.split(/\\r?\\n/);\n const dependencies: SkillDependency[] = [];\n\n for (const line of lines) {\n const colonIndex = line.indexOf(':');\n if (colonIndex === -1) continue;\n\n const key = line.slice(0, colonIndex).trim();\n let value = line.slice(colonIndex + 1).trim();\n\n // Remove quotes\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n\n switch (key) {\n case 'name':\n template.name = value;\n break;\n case 'description':\n template.description = value;\n break;\n case 'argument-hint':\n template.argumentHint = value;\n break;\n case 'requires':\n if (value.startsWith('[') && value.endsWith(']')) {\n const items = value\n .slice(1, -1)\n .split(',')\n .map((s) => s.trim().replace(/['\"]/g, ''));\n for (const item of items) {\n if (item) {\n dependencies.push({\n type: mapIntegrationName(item),\n required: true,\n });\n }\n }\n }\n break;\n case 'optional':\n if (value.startsWith('[') && value.endsWith(']')) {\n const items = value\n .slice(1, -1)\n .split(',')\n .map((s) => s.trim().replace(/['\"]/g, ''));\n for (const item of items) {\n if (item) {\n dependencies.push({\n type: mapIntegrationName(item),\n required: false,\n });\n }\n }\n }\n break;\n }\n }\n\n if (dependencies.length > 0) {\n template.dependencies = dependencies;\n }\n\n return template;\n}\n\n/**\n * Map integration name to adapter type\n */\nfunction mapIntegrationName(name: string): 'issue_tracker' | 'git' | 'documentation' | 'state' {\n const lower = name.toLowerCase();\n\n if (['jira', 'linear', 'issue_tracker', 'issues', 'github-issues'].includes(lower)) {\n return 'issue_tracker';\n }\n if (['git', 'github', 'gitlab', 'bitbucket'].includes(lower)) {\n return 'git';\n }\n if (['docs', 'documentation', 'confluence', 'notion', 'wiki'].includes(lower)) {\n return 'documentation';\n }\n\n return 'state';\n}\n\n/**\n * Extract variables from config for template substitution\n */\nexport function extractVariables(config?: ResolvedCoreAIConfig | null): SkillVariables {\n const vars: SkillVariables = {};\n\n if (!config) {\n return vars;\n }\n\n // Project variables\n vars.PROJECT_NAME = config.project.name;\n vars.PROJECT_ROOT = config.project.root;\n // Issue tracker variables\n if (config.integrations?.issue_tracker) {\n const tracker = config.integrations.issue_tracker;\n if (tracker.config?.project_key) {\n vars.JIRA_PROJECT = tracker.config.project_key;\n }\n if (tracker.config?.base_url) {\n vars.JIRA_URL = tracker.config.base_url;\n }\n }\n\n // Git variables\n if (config.integrations?.git) {\n const git = config.integrations.git;\n if (git.config?.repo) {\n vars.GITHUB_REPO = git.config.repo;\n }\n if (git.config?.owner) {\n vars.GITHUB_OWNER = git.config.owner;\n }\n if (git.config?.default_branch) {\n vars.DEFAULT_BRANCH = git.config.default_branch;\n }\n }\n\n // Documentation variables\n if (config.integrations?.documentation) {\n const docs = config.integrations.documentation;\n if (docs.config?.space_key) {\n vars.CONFLUENCE_SPACE = docs.config.space_key;\n }\n if (docs.config?.base_url) {\n vars.CONFLUENCE_URL = docs.config.base_url;\n }\n if (docs.config?.base_path) {\n vars.DOCS_PATH = docs.config.base_path;\n }\n }\n\n // Quality gate commands\n if (config.quality_gates) {\n const gates = config.quality_gates;\n // Map common gate names to variables\n const gateMappings: Record<string, keyof SkillVariables> = {\n lint: 'LINT_CMD',\n test: 'TEST_CMD',\n build: 'BUILD_CMD',\n static_analysis: 'STATIC_ANALYSIS_CMD',\n staticAnalysis: 'STATIC_ANALYSIS_CMD',\n };\n\n for (const [gateName, gate] of Object.entries(gates)) {\n const varName = gateMappings[gateName];\n if (varName) {\n vars[varName] = gate.command;\n }\n }\n }\n\n return vars;\n}\n\n/**\n * Substitute variables in template content\n */\nexport function substituteVariables(content: string, variables: SkillVariables): string {\n let result = content;\n\n for (const [key, value] of Object.entries(variables)) {\n if (value !== undefined) {\n // Replace {{VARIABLE}} pattern\n const pattern = new RegExp(`\\\\{\\\\{${key}\\\\}\\\\}`, 'g');\n result = result.replace(pattern, value);\n }\n }\n\n return result;\n}\n\n/**\n * Check if a skill's dependencies are satisfied\n */\nexport function checkDependencies(\n skill: SkillTemplate,\n config?: ResolvedCoreAIConfig | null\n): { satisfied: boolean; missing: SkillDependency[] } {\n if (!skill.dependencies || skill.dependencies.length === 0) {\n return { satisfied: true, missing: [] };\n }\n\n const missing: SkillDependency[] = [];\n\n for (const dep of skill.dependencies) {\n if (!dep.required) {\n // Optional dependencies don't block skill generation\n continue;\n }\n\n // Check if the integration is configured\n let hasIntegration = false;\n\n if (config?.integrations) {\n switch (dep.type) {\n case 'issue_tracker':\n hasIntegration = !!config.integrations.issue_tracker;\n break;\n case 'git':\n hasIntegration = !!config.integrations.git;\n break;\n case 'documentation':\n hasIntegration = !!config.integrations.documentation;\n break;\n case 'state':\n hasIntegration = !!config.integrations.state;\n break;\n }\n }\n\n if (!hasIntegration) {\n missing.push(dep);\n }\n }\n\n return {\n satisfied: missing.length === 0,\n missing,\n };\n}\n\n/**\n * Generate skills from source files to Claude Code output format.\n *\n * Discovers skills from skills/<category>/<name>/SKILL.md and writes\n * compiled output to .claude/skills/<name>/SKILL.md (flattened).\n */\nexport function generateSkills(\n config: ResolvedCoreAIConfig | undefined,\n options: GenerateSkillsOptions = {}\n): GenerateSkillsResult {\n const projectRoot = options.projectRoot ?? process.cwd();\n const coreSkillsDir = options.coreSkillsDir ?? getCoreSkillsDir();\n const outputDir = options.outputDir ?? join(projectRoot, '.claude', 'skills');\n const includeCoreSkills = options.includeCoreSkills ?? true;\n const overwrite = options.overwrite ?? true;\n\n const result: GenerateSkillsResult = {\n generated: [],\n errors: [],\n variables: {},\n };\n\n // Extract variables from config\n const variables = extractVariables(config);\n\n // Merge custom variables\n if (options.variables) {\n Object.assign(variables, options.variables);\n }\n\n result.variables = variables;\n\n // Discover skill templates from source directory\n let templates: SkillTemplate[] = [];\n\n if (includeCoreSkills) {\n const discovered = discoverSkills(coreSkillsDir);\n templates.push(...discovered);\n }\n\n // Add custom templates if provided\n if (options.customTemplatesDir && existsSync(options.customTemplatesDir)) {\n const custom = discoverSkills(options.customTemplatesDir);\n templates.push(...custom);\n }\n\n // Filter to specific skills if requested\n if (options.skills && options.skills.length > 0) {\n const skillsToInclude = options.skills;\n templates = templates.filter((t) => skillsToInclude.includes(t.name));\n }\n\n // Generate each skill\n for (const template of templates) {\n try {\n const generated = generateSkill(template, variables, config, outputDir, overwrite);\n result.generated.push(generated);\n } catch (error) {\n result.errors.push({\n name: template.name,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n return result;\n}\n\n/**\n * Generate a single skill to .claude/skills/<name>/SKILL.md\n */\nfunction generateSkill(\n template: SkillTemplate,\n variables: SkillVariables,\n config: ResolvedCoreAIConfig | undefined,\n outputDir: string,\n overwrite: boolean\n): GeneratedSkill {\n // Output is directory-per-skill: .claude/skills/<name>/SKILL.md\n const skillDir = join(outputDir, template.name);\n const outputPath = join(skillDir, 'SKILL.md');\n\n // Check if file exists and we shouldn't overwrite\n if (existsSync(outputPath) && !overwrite) {\n return {\n name: template.name,\n category: template.category,\n outputPath,\n action: 'skipped',\n skipReason: 'File already exists',\n };\n }\n\n // Check dependencies\n const { satisfied, missing } = checkDependencies(template, config);\n\n if (!satisfied) {\n const missingTypes = missing.map((d) => d.type).join(', ');\n return {\n name: template.name,\n category: template.category,\n outputPath,\n action: 'skipped',\n skipReason: `Missing required integrations: ${missingTypes}`,\n };\n }\n\n // Substitute variables in content\n const content = substituteVariables(template.content, variables);\n\n // Check if content changed (for update vs create)\n const isUpdate = existsSync(outputPath);\n\n // Ensure skill directory exists\n if (!existsSync(skillDir)) {\n mkdirSync(skillDir, { recursive: true });\n }\n\n // Write the skill file\n writeFileSync(outputPath, content, 'utf-8');\n\n return {\n name: template.name,\n category: template.category,\n outputPath,\n action: isUpdate ? 'updated' : 'created',\n };\n}\n\n/**\n * Format skill generation result for display\n */\nexport function formatGenerateResult(result: GenerateSkillsResult): string {\n const lines: string[] = [];\n\n const created = result.generated.filter((g) => g.action === 'created');\n const updated = result.generated.filter((g) => g.action === 'updated');\n const skipped = result.generated.filter((g) => g.action === 'skipped');\n\n if (created.length > 0) {\n lines.push(`Created ${created.length} skill(s):`);\n for (const skill of created) {\n lines.push(` \\u2713 ${skill.name}`);\n }\n lines.push('');\n }\n\n if (updated.length > 0) {\n lines.push(`Updated ${updated.length} skill(s):`);\n for (const skill of updated) {\n lines.push(` \\u2713 ${skill.name}`);\n }\n lines.push('');\n }\n\n if (skipped.length > 0) {\n lines.push(`Skipped ${skipped.length} skill(s):`);\n for (const skill of skipped) {\n lines.push(` - ${skill.name}: ${skill.skipReason}`);\n }\n lines.push('');\n }\n\n if (result.errors.length > 0) {\n lines.push(`Failed to generate ${result.errors.length} skill(s):`);\n for (const error of result.errors) {\n lines.push(` \\u2717 ${error.name}: ${error.error}`);\n }\n lines.push('');\n }\n\n const total = created.length + updated.length;\n if (total > 0) {\n lines.push(`Generated ${total} skill(s) to .claude/skills/`);\n } else if (result.generated.length === 0 && result.errors.length === 0) {\n lines.push('No skills to generate.');\n }\n\n return lines.join('\\n');\n}\n","/**\n * KnowledgeLibrary Manager\n *\n * Manages the KnowledgeLibrary directory structure and agent state.\n */\n\nimport {\n existsSync,\n mkdirSync,\n writeFileSync,\n readFileSync,\n readdirSync,\n renameSync,\n statSync,\n} from 'fs';\nimport { join, basename } from 'path';\nimport type {\n AgentDirectories,\n AgentKnowledgeState,\n InitKnowledgeLibraryOptions,\n InitKnowledgeLibraryResult,\n KnowledgeLibraryState,\n Message,\n MessageMetadata,\n ReadMessagesOptions,\n WriteMessageOptions,\n AgentContext,\n} from './types.js';\n\n/**\n * Default KnowledgeLibrary base path\n */\nexport const DEFAULT_KNOWLEDGE_LIBRARY_PATH = 'KnowledgeLibrary';\n\n/**\n * Standard files in a KnowledgeLibrary\n */\nexport const STANDARD_FILES = {\n context: 'context.txt',\n architecture: 'architecture.txt',\n prd: 'prd.txt',\n} as const;\n\n/**\n * Standard directories for each agent\n */\nexport const AGENT_DIRECTORIES = [\n 'inbox',\n 'inbox/processed',\n 'outbox',\n 'context',\n 'control',\n 'history',\n 'tech',\n] as const;\n\n/**\n * Standard files in an agent's control directory\n */\nexport const CONTROL_FILES = {\n objectives: 'objectives.txt',\n decisions: 'decisions.txt',\n dependencies: 'dependencies.txt',\n} as const;\n\n/**\n * Get the path to an agent's directories\n */\nexport function getAgentDirectories(basePath: string, agentName: string): AgentDirectories {\n const root = join(basePath, agentName);\n return {\n root,\n inbox: join(root, 'inbox'),\n inboxProcessed: join(root, 'inbox', 'processed'),\n outbox: join(root, 'outbox'),\n context: join(root, 'context'),\n control: join(root, 'control'),\n history: join(root, 'history'),\n tech: join(root, 'tech'),\n };\n}\n\n/**\n * Initialize the KnowledgeLibrary base structure\n */\nexport function initKnowledgeLibrary(\n options: InitKnowledgeLibraryOptions = {}\n): InitKnowledgeLibraryResult {\n const projectRoot = options.projectRoot ?? process.cwd();\n const basePath = join(projectRoot, options.basePath ?? DEFAULT_KNOWLEDGE_LIBRARY_PATH);\n const createDefaults = options.createDefaults ?? true;\n\n const createdDirs: string[] = [];\n const createdFiles: string[] = [];\n\n try {\n // Create base directory\n if (!existsSync(basePath)) {\n mkdirSync(basePath, { recursive: true });\n createdDirs.push(basePath);\n }\n\n // Create default global files if requested\n if (createDefaults) {\n // context.txt\n const contextPath = join(basePath, STANDARD_FILES.context);\n if (!existsSync(contextPath)) {\n writeFileSync(\n contextPath,\n `# Project Context\n\n## Current Sprint\n- Sprint: [Sprint name/number]\n- Goals: [Sprint goals]\n- Deadline: [Sprint deadline]\n\n## Priorities\n1. [Priority 1]\n2. [Priority 2]\n3. [Priority 3]\n\n## Notes\n[Project-wide notes and context]\n`,\n 'utf-8'\n );\n createdFiles.push(contextPath);\n }\n\n // architecture.txt\n const architecturePath = join(basePath, STANDARD_FILES.architecture);\n if (!existsSync(architecturePath)) {\n writeFileSync(\n architecturePath,\n `# Architecture Notes\n\n## Technical Decisions\n[Record major technical decisions here]\n\n## System Overview\n[High-level system architecture]\n\n## Key Components\n[Important system components]\n`,\n 'utf-8'\n );\n createdFiles.push(architecturePath);\n }\n\n // prd.txt\n const prdPath = join(basePath, STANDARD_FILES.prd);\n if (!existsSync(prdPath)) {\n writeFileSync(\n prdPath,\n `# Product Requirements Document\n\n## Overview\n[Product overview]\n\n## Goals\n[Product goals]\n\n## Features\n[Feature list]\n\n## Requirements\n[Detailed requirements]\n`,\n 'utf-8'\n );\n createdFiles.push(prdPath);\n }\n }\n\n return {\n success: true,\n createdDirs,\n createdFiles,\n };\n } catch (error) {\n return {\n success: false,\n createdDirs,\n createdFiles,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n/**\n * Initialize an agent's KnowledgeLibrary directories\n */\nexport function initAgentKnowledgeLibrary(\n agentName: string,\n options: InitKnowledgeLibraryOptions = {}\n): InitKnowledgeLibraryResult {\n const projectRoot = options.projectRoot ?? process.cwd();\n const basePath = join(projectRoot, options.basePath ?? DEFAULT_KNOWLEDGE_LIBRARY_PATH);\n const createDefaults = options.createDefaults ?? true;\n\n const createdDirs: string[] = [];\n const createdFiles: string[] = [];\n\n try {\n // Ensure base KnowledgeLibrary exists\n if (!existsSync(basePath)) {\n const baseResult = initKnowledgeLibrary(options);\n if (!baseResult.success) {\n return baseResult;\n }\n createdDirs.push(...baseResult.createdDirs);\n createdFiles.push(...baseResult.createdFiles);\n }\n\n // Get agent directories\n const dirs = getAgentDirectories(basePath, agentName);\n\n // Create all agent directories\n for (const dir of AGENT_DIRECTORIES) {\n const dirPath = join(dirs.root, dir);\n if (!existsSync(dirPath)) {\n mkdirSync(dirPath, { recursive: true });\n createdDirs.push(dirPath);\n }\n }\n\n // Create default files if requested\n if (createDefaults) {\n // context/current.txt\n const currentContextPath = join(dirs.context, 'current.txt');\n if (!existsSync(currentContextPath)) {\n writeFileSync(\n currentContextPath,\n `# ${agentName} Current Context\n\n## Status\n- State: idle\n- Current Task: None\n- Last Updated: ${new Date().toISOString()}\n\n## Notes\n[Agent-specific context notes]\n`,\n 'utf-8'\n );\n createdFiles.push(currentContextPath);\n }\n\n // control/objectives.txt\n const objectivesPath = join(dirs.control, CONTROL_FILES.objectives);\n if (!existsSync(objectivesPath)) {\n writeFileSync(\n objectivesPath,\n `# ${agentName} Objectives\n\n## Current Objectives\n[None]\n\n## Success Criteria\n[Define success criteria for objectives]\n`,\n 'utf-8'\n );\n createdFiles.push(objectivesPath);\n }\n\n // control/decisions.txt\n const decisionsPath = join(dirs.control, CONTROL_FILES.decisions);\n if (!existsSync(decisionsPath)) {\n writeFileSync(\n decisionsPath,\n `# ${agentName} Decision Log\n\n## Decisions\n[Record important decisions here]\n\nFormat:\n- Date: YYYY-MM-DD\n- Decision: [What was decided]\n- Reasoning: [Why]\n- Related: [Ticket or task reference]\n`,\n 'utf-8'\n );\n createdFiles.push(decisionsPath);\n }\n\n // control/dependencies.txt\n const dependenciesPath = join(dirs.control, CONTROL_FILES.dependencies);\n if (!existsSync(dependenciesPath)) {\n writeFileSync(\n dependenciesPath,\n `# ${agentName} Dependencies\n\n## Blocked By\n[Tasks/agents blocking this agent]\n\n## Blocking\n[Tasks/agents this agent is blocking]\n\nLast Updated: ${new Date().toISOString()}\n`,\n 'utf-8'\n );\n createdFiles.push(dependenciesPath);\n }\n }\n\n return {\n success: true,\n createdDirs,\n createdFiles,\n };\n } catch (error) {\n return {\n success: false,\n createdDirs,\n createdFiles,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n/**\n * Check if a KnowledgeLibrary exists for an agent\n */\nexport function agentKnowledgeLibraryExists(\n agentName: string,\n options: { projectRoot?: string; basePath?: string } = {}\n): boolean {\n const projectRoot = options.projectRoot ?? process.cwd();\n const basePath = join(projectRoot, options.basePath ?? DEFAULT_KNOWLEDGE_LIBRARY_PATH);\n const agentRoot = join(basePath, agentName);\n\n return existsSync(agentRoot) && existsSync(join(agentRoot, 'inbox'));\n}\n\n/**\n * Get the KnowledgeLibrary state for an agent\n */\nexport function getAgentKnowledgeState(\n agentName: string,\n options: { projectRoot?: string; basePath?: string } = {}\n): AgentKnowledgeState {\n const projectRoot = options.projectRoot ?? process.cwd();\n const basePath = join(projectRoot, options.basePath ?? DEFAULT_KNOWLEDGE_LIBRARY_PATH);\n const dirs = getAgentDirectories(basePath, agentName);\n\n const initialized = agentKnowledgeLibraryExists(agentName, options);\n\n // Get pending messages\n const pendingMessages = initialized ? readInboxMessages(agentName, options) : [];\n\n // Get context\n let context: AgentContext | undefined;\n const currentContextPath = join(dirs.context, 'current.txt');\n if (existsSync(currentContextPath)) {\n const content = readFileSync(currentContextPath, 'utf-8');\n context = parseContextFile(content);\n }\n\n const state: AgentKnowledgeState = {\n agentName,\n directories: dirs,\n pendingMessages,\n initialized,\n };\n\n if (context) {\n state.context = context;\n }\n\n return state;\n}\n\n/**\n * Parse a context file into AgentContext\n */\nfunction parseContextFile(content: string): AgentContext {\n const context: AgentContext = {\n lastUpdated: new Date(),\n };\n\n // Simple parsing - look for key patterns\n const statusMatch = content.match(/State:\\s*(.+)/i);\n if (statusMatch && statusMatch[1]) {\n context.status = statusMatch[1].trim();\n }\n\n const taskMatch = content.match(/Current Task:\\s*(.+)/i);\n if (taskMatch && taskMatch[1] && taskMatch[1].trim() !== 'None') {\n context.currentTask = taskMatch[1].trim();\n }\n\n const ticketMatch = content.match(/Current Ticket:\\s*([A-Z]+-\\d+)/i);\n if (ticketMatch && ticketMatch[1]) {\n context.currentTicket = ticketMatch[1];\n }\n\n const updatedMatch = content.match(/Last Updated:\\s*(.+)/i);\n if (updatedMatch) {\n const dateStr = updatedMatch[1]?.trim();\n if (dateStr) {\n const parsed = new Date(dateStr);\n if (!isNaN(parsed.getTime())) {\n context.lastUpdated = parsed;\n }\n }\n }\n\n return context;\n}\n\n/**\n * Generate a message filename\n */\nexport function generateMessageFilename(from: string, subject: string): string {\n const now = new Date();\n const timestamp = now.toISOString().replace(/[-:T]/g, '').slice(0, 12); // YYYYMMDDHHMM\n const sanitizedSubject = subject\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .slice(0, 30);\n return `${timestamp}-${from}-${sanitizedSubject}.md`;\n}\n\n/**\n * Parse message frontmatter\n */\nfunction parseMessageFrontmatter(content: string): {\n metadata: Partial<MessageMetadata>;\n body: string;\n} {\n const match = content.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n([\\s\\S]*)$/);\n\n if (!match) {\n return { metadata: {}, body: content };\n }\n\n const frontmatter = match[1] ?? '';\n const body = match[2] ?? '';\n const metadata: Partial<MessageMetadata> = {};\n\n for (const line of frontmatter.split(/\\r?\\n/)) {\n const colonIndex = line.indexOf(':');\n if (colonIndex === -1) continue;\n\n const key = line.slice(0, colonIndex).trim();\n const value = line.slice(colonIndex + 1).trim();\n\n switch (key) {\n case 'type':\n metadata.type = value as MessageMetadata['type'];\n break;\n case 'from':\n metadata.from = value;\n break;\n case 'to':\n metadata.to = value;\n break;\n case 'date':\n metadata.date = new Date(value);\n break;\n case 'ticket':\n metadata.ticket = value;\n break;\n case 'priority':\n if (value === 'P0' || value === 'P1' || value === 'P2' || value === 'P3') {\n metadata.priority = value;\n }\n break;\n case 'subject':\n metadata.subject = value;\n break;\n }\n }\n\n return { metadata, body };\n}\n\n/**\n * Read inbox messages for an agent\n */\nexport function readInboxMessages(\n agentName: string,\n options: { projectRoot?: string; basePath?: string } & ReadMessagesOptions = {}\n): Message[] {\n const projectRoot = options.projectRoot ?? process.cwd();\n const basePath = join(projectRoot, options.basePath ?? DEFAULT_KNOWLEDGE_LIBRARY_PATH);\n const dirs = getAgentDirectories(basePath, agentName);\n\n const messages: Message[] = [];\n\n // Read inbox\n if (existsSync(dirs.inbox)) {\n const files = readdirSync(dirs.inbox).filter(\n (f) => f.endsWith('.md') && statSync(join(dirs.inbox, f)).isFile()\n );\n\n for (const file of files) {\n const filePath = join(dirs.inbox, file);\n const rawContent = readFileSync(filePath, 'utf-8');\n const { metadata, body } = parseMessageFrontmatter(rawContent);\n\n // Apply filters\n if (options.type && metadata.type !== options.type) continue;\n if (options.from && metadata.from !== options.from) continue;\n if (options.priority && metadata.priority !== options.priority) continue;\n\n messages.push({\n filename: file,\n path: filePath,\n metadata: metadata as MessageMetadata,\n rawContent,\n body,\n });\n }\n }\n\n // Include processed if requested\n if (options.includeProcessed && existsSync(dirs.inboxProcessed)) {\n const files = readdirSync(dirs.inboxProcessed).filter(\n (f) => f.endsWith('.md') && statSync(join(dirs.inboxProcessed, f)).isFile()\n );\n\n for (const file of files) {\n const filePath = join(dirs.inboxProcessed, file);\n const rawContent = readFileSync(filePath, 'utf-8');\n const { metadata, body } = parseMessageFrontmatter(rawContent);\n\n // Apply filters\n if (options.type && metadata.type !== options.type) continue;\n if (options.from && metadata.from !== options.from) continue;\n if (options.priority && metadata.priority !== options.priority) continue;\n\n messages.push({\n filename: file,\n path: filePath,\n metadata: metadata as MessageMetadata,\n rawContent,\n body,\n });\n }\n }\n\n // Sort by date (newest first)\n messages.sort((a, b) => {\n const dateA = a.metadata.date?.getTime() ?? 0;\n const dateB = b.metadata.date?.getTime() ?? 0;\n return dateB - dateA;\n });\n\n // Apply limit\n if (options.limit && messages.length > options.limit) {\n return messages.slice(0, options.limit);\n }\n\n return messages;\n}\n\n/**\n * Write a message to an agent's inbox\n */\nexport function writeInboxMessage(\n options: WriteMessageOptions & { projectRoot?: string; basePath?: string }\n): { success: boolean; path?: string; error?: string } {\n const projectRoot = options.projectRoot ?? process.cwd();\n const basePath = join(projectRoot, options.basePath ?? DEFAULT_KNOWLEDGE_LIBRARY_PATH);\n const dirs = getAgentDirectories(basePath, options.to);\n\n try {\n // Ensure agent inbox exists\n if (!existsSync(dirs.inbox)) {\n mkdirSync(dirs.inbox, { recursive: true });\n }\n\n // Generate filename\n const filename = generateMessageFilename(options.from, options.subject);\n const filePath = join(dirs.inbox, filename);\n\n // Format message\n const now = new Date();\n const content = formatMessage(options, now);\n\n // Write file\n writeFileSync(filePath, content, 'utf-8');\n\n // Also copy to sender's outbox\n const senderDirs = getAgentDirectories(basePath, options.from);\n if (existsSync(senderDirs.outbox)) {\n writeFileSync(join(senderDirs.outbox, filename), content, 'utf-8');\n }\n\n return { success: true, path: filePath };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n/**\n * Format a message with frontmatter\n */\nfunction formatMessage(options: WriteMessageOptions, date: Date): string {\n let frontmatter = `---\ntype: ${options.type}\nfrom: ${options.from}\nto: ${options.to}\ndate: ${date.toISOString().slice(0, 16).replace('T', ' ')}`;\n\n if (options.ticket) {\n frontmatter += `\\nticket: ${options.ticket}`;\n }\n\n if (options.priority) {\n frontmatter += `\\npriority: ${options.priority}`;\n }\n\n frontmatter += `\\nsubject: ${options.subject}`;\n\n frontmatter += `\\n---\n\n## ${options.subject}\n\n${options.body}`;\n\n return frontmatter;\n}\n\n/**\n * Mark a message as processed (move to processed folder)\n */\nexport function markMessageProcessed(\n agentName: string,\n messageFilename: string,\n options: { projectRoot?: string; basePath?: string } = {}\n): { success: boolean; error?: string } {\n const projectRoot = options.projectRoot ?? process.cwd();\n const basePath = join(projectRoot, options.basePath ?? DEFAULT_KNOWLEDGE_LIBRARY_PATH);\n const dirs = getAgentDirectories(basePath, agentName);\n\n const sourcePath = join(dirs.inbox, messageFilename);\n const destPath = join(dirs.inboxProcessed, messageFilename);\n\n try {\n if (!existsSync(sourcePath)) {\n return { success: false, error: `Message not found: ${messageFilename}` };\n }\n\n if (!existsSync(dirs.inboxProcessed)) {\n mkdirSync(dirs.inboxProcessed, { recursive: true });\n }\n\n renameSync(sourcePath, destPath);\n return { success: true };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n/**\n * Get global KnowledgeLibrary state\n */\nexport function getKnowledgeLibraryState(\n options: { projectRoot?: string; basePath?: string } = {}\n): KnowledgeLibraryState | null {\n const projectRoot = options.projectRoot ?? process.cwd();\n const basePath = join(projectRoot, options.basePath ?? DEFAULT_KNOWLEDGE_LIBRARY_PATH);\n\n if (!existsSync(basePath)) {\n return null;\n }\n\n // Get list of agents\n const agents: string[] = [];\n const entries = readdirSync(basePath);\n for (const entry of entries) {\n const entryPath = join(basePath, entry);\n if (statSync(entryPath).isDirectory() && existsSync(join(entryPath, 'inbox'))) {\n agents.push(entry);\n }\n }\n\n return {\n basePath,\n contextPath: join(basePath, STANDARD_FILES.context),\n architecturePath: join(basePath, STANDARD_FILES.architecture),\n prdPath: join(basePath, STANDARD_FILES.prd),\n agents,\n };\n}\n\n/**\n * Update agent context\n */\nexport function updateAgentContext(\n agentName: string,\n context: Partial<AgentContext>,\n options: { projectRoot?: string; basePath?: string } = {}\n): { success: boolean; error?: string } {\n const projectRoot = options.projectRoot ?? process.cwd();\n const basePath = join(projectRoot, options.basePath ?? DEFAULT_KNOWLEDGE_LIBRARY_PATH);\n const dirs = getAgentDirectories(basePath, agentName);\n const contextPath = join(dirs.context, 'current.txt');\n\n try {\n const now = new Date();\n const content = `# ${agentName} Current Context\n\n## Status\n- State: ${context.status ?? 'idle'}\n- Current Task: ${context.currentTask ?? 'None'}\n${context.currentTicket ? `- Current Ticket: ${context.currentTicket}` : ''}- Last Updated: ${now.toISOString()}\n\n## Notes\n${context.notes ?? '[Agent-specific context notes]'}\n`;\n\n if (!existsSync(dirs.context)) {\n mkdirSync(dirs.context, { recursive: true });\n }\n\n writeFileSync(contextPath, content, 'utf-8');\n return { success: true };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n/**\n * Format KnowledgeLibrary state for display\n */\nexport function formatKnowledgeLibraryState(state: KnowledgeLibraryState | null): string {\n if (!state) {\n return 'KnowledgeLibrary not initialized.';\n }\n\n const lines: string[] = [];\n lines.push(`KnowledgeLibrary: ${state.basePath}\\n`);\n\n lines.push('Global files:');\n lines.push(` - ${basename(state.contextPath)}`);\n lines.push(` - ${basename(state.architecturePath)}`);\n lines.push(` - ${basename(state.prdPath)}`);\n lines.push('');\n\n if (state.agents.length > 0) {\n lines.push(`Agents (${state.agents.length}):`);\n for (const agent of state.agents) {\n lines.push(` - ${agent}`);\n }\n } else {\n lines.push('No agents initialized.');\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Format agent knowledge state for display\n */\nexport function formatAgentKnowledgeState(state: AgentKnowledgeState): string {\n const lines: string[] = [];\n\n lines.push(`Agent: ${state.agentName}`);\n lines.push(`Status: ${state.initialized ? 'Initialized' : 'Not initialized'}`);\n lines.push('');\n\n if (state.context) {\n lines.push('Context:');\n lines.push(` State: ${state.context.status ?? 'unknown'}`);\n if (state.context.currentTask) {\n lines.push(` Current Task: ${state.context.currentTask}`);\n }\n if (state.context.currentTicket) {\n lines.push(` Current Ticket: ${state.context.currentTicket}`);\n }\n lines.push(` Last Updated: ${state.context.lastUpdated.toISOString()}`);\n lines.push('');\n }\n\n if (state.pendingMessages.length > 0) {\n lines.push(`Pending Messages (${state.pendingMessages.length}):`);\n for (const msg of state.pendingMessages) {\n const type = msg.metadata.type ?? 'unknown';\n const from = msg.metadata.from ?? 'unknown';\n const subject = msg.metadata.subject ?? msg.filename;\n lines.push(` - [${type}] from ${from}: ${subject}`);\n }\n } else {\n lines.push('No pending messages.');\n }\n\n return lines.join('\\n');\n}\n","/**\n * Cache Commands\n *\n * Commands for managing the local cache.\n */\n\nimport { join } from 'path';\nimport { FileCacheProvider, CACHE_PATHS, type CacheStats } from '../../cache/index.js';\n\n/**\n * Options for cache commands\n */\nexport interface CacheCommandOptions {\n /**\n * Project root directory\n */\n projectRoot?: string;\n\n /**\n * Custom cache path (overrides default)\n */\n cachePath?: string;\n\n /**\n * Output format\n */\n format?: 'text' | 'json';\n}\n\n/**\n * Result of cache status command\n */\nexport interface CacheStatusResult {\n initialized: boolean;\n path: string;\n stats: CacheStats | null;\n entries: {\n key: string;\n source: string;\n status: string;\n size: number;\n cachedAt: string;\n expiresAt: string;\n }[];\n}\n\n/**\n * Result of cache clear command\n */\nexport interface CacheClearResult {\n cleared: number;\n success: boolean;\n error?: string;\n}\n\n/**\n * Get the cache path for a project\n */\nfunction getCachePath(options: CacheCommandOptions): string {\n if (options.cachePath) {\n return options.cachePath;\n }\n const root = options.projectRoot ?? process.cwd();\n return join(root, CACHE_PATHS.ROOT);\n}\n\n/**\n * Get cache status\n */\nexport async function cacheStatus(options: CacheCommandOptions = {}): Promise<CacheStatusResult> {\n const cachePath = getCachePath(options);\n\n const provider = new FileCacheProvider({ basePath: cachePath });\n\n try {\n await provider.initialize();\n } catch {\n return {\n initialized: false,\n path: cachePath,\n stats: null,\n entries: [],\n };\n }\n\n const stats = await provider.getStats();\n const metadataList = await provider.list();\n\n const entries = await Promise.all(\n metadataList.map(async (metadata) => {\n const status = await provider.getStatus(metadata.key);\n return {\n key: metadata.key,\n source: metadata.source,\n status: status ?? 'unknown',\n size: metadata.size,\n cachedAt: metadata.cachedAt,\n expiresAt: metadata.expiresAt,\n };\n })\n );\n\n return {\n initialized: true,\n path: cachePath,\n stats,\n entries,\n };\n}\n\n/**\n * Clear all cache entries\n */\nexport async function cacheClear(options: CacheCommandOptions = {}): Promise<CacheClearResult> {\n const cachePath = getCachePath(options);\n\n const provider = new FileCacheProvider({ basePath: cachePath });\n\n try {\n await provider.initialize();\n const cleared = await provider.clear();\n return { cleared, success: true };\n } catch (error) {\n return {\n cleared: 0,\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n/**\n * Clear expired cache entries\n */\nexport async function cacheClearExpired(\n options: CacheCommandOptions = {}\n): Promise<CacheClearResult> {\n const cachePath = getCachePath(options);\n\n const provider = new FileCacheProvider({ basePath: cachePath });\n\n try {\n await provider.initialize();\n const cleared = await provider.clearExpired();\n return { cleared, success: true };\n } catch (error) {\n return {\n cleared: 0,\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n/**\n * Format bytes to human-readable string\n */\nexport function formatBytes(bytes: number): string {\n if (bytes === 0) return '0 B';\n const k = 1024;\n const sizes = ['B', 'KB', 'MB', 'GB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\n}\n\n/**\n * Format cache status for terminal output\n */\nexport function formatCacheStatus(result: CacheStatusResult): string {\n const lines: string[] = [];\n\n lines.push('Cache Status');\n lines.push('============');\n lines.push('');\n\n if (!result.initialized) {\n lines.push(`Path: ${result.path}`);\n lines.push('Status: Not initialized (no cache found)');\n return lines.join('\\n');\n }\n\n lines.push(`Path: ${result.path}`);\n lines.push('Status: Initialized');\n lines.push('');\n\n if (result.stats) {\n lines.push('Statistics:');\n lines.push(` Entries: ${result.stats.totalEntries}`);\n lines.push(` Total size: ${formatBytes(result.stats.totalSize)}`);\n lines.push(\n ` Valid: ${result.stats.validEntries}, Stale: ${result.stats.staleEntries}, Expired: ${result.stats.expiredEntries}`\n );\n if (result.stats.newestEntry) {\n lines.push(` Last updated: ${result.stats.newestEntry}`);\n }\n }\n\n if (result.entries.length > 0) {\n lines.push('');\n lines.push('Entries:');\n lines.push('');\n\n // Group by source\n const bySource = new Map<string, typeof result.entries>();\n for (const entry of result.entries) {\n const source = entry.source;\n if (!bySource.has(source)) {\n bySource.set(source, []);\n }\n const entries = bySource.get(source);\n if (entries) {\n entries.push(entry);\n }\n }\n\n for (const [source, entries] of bySource) {\n lines.push(` ${source}:`);\n for (const entry of entries) {\n const statusIcon = entry.status === 'valid' ? '✓' : entry.status === 'stale' ? '○' : '✗';\n lines.push(` ${statusIcon} ${entry.key} (${formatBytes(entry.size)})`);\n }\n }\n } else {\n lines.push('');\n lines.push('No entries in cache.');\n }\n\n return lines.join('\\n');\n}\n","/**\n * Sync Command\n *\n * Syncs shared context from remote sources.\n */\n\nimport { join } from 'path';\nimport {\n FileCacheProvider,\n CACHE_PATHS,\n type SyncResult,\n type CacheSource,\n} from '../../cache/index.js';\nimport { CacheManager } from '../../cache/manager.js';\nimport type { RemoteFetcher } from '../../cache/interfaces.js';\n\n/**\n * Options for sync command\n */\nexport interface SyncCommandOptions {\n /**\n * Project root directory\n */\n projectRoot?: string;\n\n /**\n * Custom cache path\n */\n cachePath?: string;\n\n /**\n * Force refresh all entries\n */\n force?: boolean;\n\n /**\n * Filter by source type\n */\n source?: CacheSource;\n\n /**\n * Continue on error\n */\n continueOnError?: boolean;\n\n /**\n * Maximum concurrent fetches\n */\n concurrency?: number;\n\n /**\n * Progress callback\n */\n onProgress?: (completed: number, total: number, message: string) => void;\n}\n\n/**\n * Result of sync command\n */\nexport interface SyncCommandResult {\n success: boolean;\n result: SyncResult | null;\n error?: string;\n sources: string[];\n}\n\n/**\n * Create a mock fetcher for a source (placeholder until real fetchers are implemented)\n *\n * In a real implementation, these would be replaced with actual fetchers\n * that use the documentation adapter interfaces.\n */\nfunction createPlaceholderFetcher(source: string): RemoteFetcher {\n return {\n async fetch(url: string) {\n // This is a placeholder - real implementation would use adapters\n throw new Error(\n `No fetcher implementation for source \"${source}\". ` +\n `URL: ${url}. Configure a documentation provider in coreai.config.yaml.`\n );\n },\n async hasChanged(_url: string, _etag?: string) {\n // Always return true for placeholder\n return true;\n },\n };\n}\n\n/**\n * Get the cache path for a project\n */\nfunction getCachePath(options: SyncCommandOptions): string {\n if (options.cachePath) {\n return options.cachePath;\n }\n const root = options.projectRoot ?? process.cwd();\n return join(root, CACHE_PATHS.base);\n}\n\n/**\n * Sync cached entries from remote sources\n *\n * This command refreshes cached content by re-fetching from remote sources.\n * If --force is specified, it clears stale/expired status and fetches fresh content.\n */\nexport async function sync(options: SyncCommandOptions = {}): Promise<SyncCommandResult> {\n const cachePath = getCachePath(options);\n\n const provider = new FileCacheProvider({ basePath: cachePath });\n\n try {\n await provider.initialize();\n } catch (error) {\n return {\n success: false,\n result: null,\n error: `Failed to initialize cache: ${error instanceof Error ? error.message : String(error)}`,\n sources: [],\n };\n }\n\n // Get all cached entries\n const entries = await provider.list({ source: options.source });\n\n if (entries.length === 0) {\n return {\n success: true,\n result: {\n added: 0,\n updated: 0,\n removed: 0,\n failed: 0,\n errors: [],\n duration: 0,\n },\n sources: [],\n };\n }\n\n // Create cache manager\n const manager = new CacheManager({\n cache: provider,\n defaultTtl: 3600,\n });\n\n // Collect unique sources and register placeholder fetchers\n const sources = new Set<string>();\n for (const entry of entries) {\n sources.add(entry.source);\n }\n\n // Register fetchers for each source\n // In a real implementation, these would be actual fetcher implementations\n for (const source of sources) {\n if (!manager.hasFetcher(source)) {\n manager.registerFetcher(source, createPlaceholderFetcher(source));\n }\n }\n\n // Get keys to sync\n const keys = entries.map((e) => e.key);\n\n // Report progress\n if (options.onProgress) {\n options.onProgress(0, keys.length, 'Starting sync...');\n }\n\n // Sync entries\n try {\n const result = await manager.syncEntries(keys, {\n force: options.force,\n continueOnError: options.continueOnError ?? true,\n concurrency: options.concurrency ?? 5,\n onProgress: (completed, total) => {\n if (options.onProgress) {\n options.onProgress(completed, total, `Syncing ${completed}/${total} entries...`);\n }\n },\n });\n\n return {\n success: result.failed === 0 || options.continueOnError === true,\n result,\n sources: Array.from(sources),\n };\n } catch (error) {\n return {\n success: false,\n result: null,\n error: error instanceof Error ? error.message : String(error),\n sources: Array.from(sources),\n };\n }\n}\n\n/**\n * Format sync result for terminal output\n */\nexport function formatSyncResult(result: SyncCommandResult): string {\n const lines: string[] = [];\n\n lines.push('Sync Results');\n lines.push('============');\n lines.push('');\n\n if (!result.success && result.error) {\n lines.push(`Error: ${result.error}`);\n return lines.join('\\n');\n }\n\n if (!result.result) {\n lines.push('No sync operation performed.');\n return lines.join('\\n');\n }\n\n const r = result.result;\n\n if (r.added === 0 && r.updated === 0 && r.removed === 0 && r.failed === 0) {\n lines.push('Cache is empty. Nothing to sync.');\n lines.push('');\n lines.push('Tip: Add context sources to your coreai.config.yaml to fetch remote content.');\n return lines.join('\\n');\n }\n\n lines.push(`Duration: ${r.duration}ms`);\n lines.push('');\n\n if (result.sources.length > 0) {\n lines.push(`Sources: ${result.sources.join(', ')}`);\n lines.push('');\n }\n\n lines.push('Summary:');\n if (r.added > 0) lines.push(` ✓ Added: ${r.added}`);\n if (r.updated > 0) lines.push(` ✓ Updated: ${r.updated}`);\n if (r.removed > 0) lines.push(` ○ Removed: ${r.removed}`);\n if (r.failed > 0) lines.push(` ✗ Failed: ${r.failed}`);\n\n if (r.errors.length > 0) {\n lines.push('');\n lines.push('Errors:');\n for (const err of r.errors.slice(0, 10)) {\n lines.push(` - ${err.key}: ${err.error}`);\n }\n if (r.errors.length > 10) {\n lines.push(` ... and ${r.errors.length - 10} more errors`);\n }\n }\n\n return lines.join('\\n');\n}\n","/**\n * Init Command\n *\n * Initializes a new CoreAI project with configuration file and directory structure.\n */\n\nimport { existsSync, writeFileSync, mkdirSync, readFileSync } from 'fs';\nimport { join, basename } from 'path';\nimport { execSync } from 'child_process';\nimport type { GitProvider } from '../../config/types.js';\nimport { configExists } from '../../config/loader.js';\n\n/**\n * Options for init command\n */\nexport interface InitCommandOptions {\n /**\n * Project root directory\n */\n projectRoot?: string;\n\n /**\n * Overwrite existing configuration\n */\n force?: boolean;\n\n /**\n * Skip interactive prompts\n */\n nonInteractive?: boolean;\n\n /**\n * Project name (for non-interactive mode)\n */\n name?: string;\n\n /**\n * Skip creating directory structure\n */\n skipDirs?: boolean;\n}\n\n/**\n * Result of init command\n */\nexport interface InitCommandResult {\n success: boolean;\n configPath?: string;\n createdDirs?: string[];\n error?: string;\n gitInfo?: {\n provider?: GitProvider;\n owner?: string;\n repo?: string;\n };\n}\n\n/**\n * Detect git remote information\n */\nfunction detectGitInfo(): { provider?: GitProvider; owner?: string; repo?: string } | null {\n try {\n const remoteUrl = execSync('git remote get-url origin', { encoding: 'utf-8' }).trim();\n\n // GitHub HTTPS: https://github.com/owner/repo.git\n const httpsMatch = remoteUrl.match(/https:\\/\\/github\\.com\\/([^/]+)\\/([^/.]+)/);\n if (httpsMatch) {\n return { provider: 'github', owner: httpsMatch[1], repo: httpsMatch[2] };\n }\n\n // GitHub SSH: git@github.com:owner/repo.git\n const sshMatch = remoteUrl.match(/git@github\\.com:([^/]+)\\/([^/.]+)/);\n if (sshMatch) {\n return { provider: 'github', owner: sshMatch[1], repo: sshMatch[2] };\n }\n\n // GitLab HTTPS\n const gitlabHttps = remoteUrl.match(/https:\\/\\/gitlab\\.com\\/([^/]+)\\/([^/.]+)/);\n if (gitlabHttps) {\n return { provider: 'gitlab', owner: gitlabHttps[1], repo: gitlabHttps[2] };\n }\n\n // GitLab SSH\n const gitlabSsh = remoteUrl.match(/git@gitlab\\.com:([^/]+)\\/([^/.]+)/);\n if (gitlabSsh) {\n return { provider: 'gitlab', owner: gitlabSsh[1], repo: gitlabSsh[2] };\n }\n\n return null;\n } catch {\n // Not a git repo or no remote\n return null;\n }\n}\n\n/**\n * Detect project name from directory or package.json\n */\nfunction detectProjectName(projectRoot: string): string {\n // Try package.json first\n const packageJsonPath = join(projectRoot, 'package.json');\n if (existsSync(packageJsonPath)) {\n try {\n const content = JSON.parse(readFileSync(packageJsonPath, 'utf-8')) as { name?: string };\n if (content.name) {\n return content.name;\n }\n } catch {\n // Ignore parse errors\n }\n }\n\n // Fall back to directory name\n return basename(projectRoot);\n}\n\n/**\n * Detect quality gate commands from project files\n */\nfunction detectQualityGates(projectRoot: string): { lint?: string; test?: string } {\n const gates: { lint?: string; test?: string } = {};\n\n // Try package.json scripts\n const packageJsonPath = join(projectRoot, 'package.json');\n if (existsSync(packageJsonPath)) {\n try {\n const pkg = JSON.parse(readFileSync(packageJsonPath, 'utf-8')) as {\n scripts?: Record<string, string>;\n };\n if (pkg.scripts?.lint) {\n gates.lint = 'npm run lint';\n }\n if (pkg.scripts?.test) {\n gates.test = 'npm test';\n }\n } catch {\n // Ignore parse errors\n }\n }\n\n return gates;\n}\n\n/**\n * Generate config file content\n */\nfunction generateConfigYaml(options: {\n name: string;\n gitInfo?: { provider?: GitProvider; owner?: string; repo?: string } | null;\n qualityGates?: { lint?: string; test?: string };\n}): string {\n const lines: string[] = [\n '# CoreAI Configuration',\n '# See https://coreai.dev/docs/config for full schema',\n '',\n 'version: \"1.0\"',\n '',\n 'project:',\n ` name: \"${options.name}\"`,\n ' # description: \"Brief description of your project\"',\n '',\n '# Agents to compile. Add more with: coreai agents add <name>',\n '# See available agents with: coreai agents list',\n 'team:',\n ' agents:',\n ' - engineering-manager',\n '',\n ];\n\n // Quality gates - uncommented if detected, commented examples otherwise\n const gates = options.qualityGates;\n if (gates?.lint || gates?.test) {\n lines.push('# Commands agents must run before finishing work.');\n lines.push('quality_gates:');\n if (gates.lint) {\n lines.push(' lint:');\n lines.push(` command: ${gates.lint}`);\n lines.push(' required: true');\n }\n if (gates.test) {\n lines.push(' test:');\n lines.push(` command: ${gates.test}`);\n lines.push(' required: true');\n }\n lines.push(' # typecheck:');\n lines.push(' # command: npx tsc --noEmit');\n lines.push(' # required: true');\n } else {\n lines.push('# Commands agents must run before finishing work.');\n lines.push('# quality_gates:');\n lines.push('# lint:');\n lines.push('# command: npm run lint');\n lines.push('# required: true');\n lines.push('# test:');\n lines.push('# command: npm test');\n lines.push('# required: true');\n }\n lines.push('');\n\n // Integrations\n if (options.gitInfo?.provider) {\n lines.push('integrations:');\n lines.push(' git:');\n lines.push(` provider: ${options.gitInfo.provider}`);\n lines.push(' config:');\n lines.push(` owner: \"${options.gitInfo.owner}\"`);\n lines.push(` repo: \"${options.gitInfo.repo}\"`);\n lines.push(' # issue_tracker:');\n lines.push('# provider: jira # jira | linear | github-issues | azure-devops');\n lines.push('# config:');\n lines.push('# project_key: \"PROJ\"');\n lines.push('# base_url: \"https://your-instance.atlassian.net\"');\n lines.push(' # documentation:');\n lines.push('# provider: confluence # confluence | notion | github-wiki | local');\n lines.push('# config:');\n lines.push('# base_url: \"https://your-instance.atlassian.net/wiki\"');\n lines.push('# space_key: \"TEAM\"');\n } else {\n lines.push('# External tool integrations');\n lines.push('# integrations:');\n lines.push('# git:');\n lines.push('# provider: github # github | gitlab | bitbucket | azure-devops');\n lines.push('# config:');\n lines.push('# owner: \"your-org\"');\n lines.push('# repo: \"your-repo\"');\n lines.push('# issue_tracker:');\n lines.push('# provider: jira # jira | linear | github-issues | azure-devops');\n lines.push('# config:');\n lines.push('# project_key: \"PROJ\"');\n lines.push('# base_url: \"https://your-instance.atlassian.net\"');\n lines.push('# documentation:');\n lines.push('# provider: confluence # confluence | notion | github-wiki | local');\n lines.push('# config:');\n lines.push('# base_url: \"https://your-instance.atlassian.net/wiki\"');\n lines.push('# space_key: \"TEAM\"');\n }\n lines.push('');\n\n return lines.join('\\n');\n}\n\n/**\n * Create directory structure for CoreAI\n */\nfunction createDirectories(projectRoot: string): string[] {\n const dirs = [\n join(projectRoot, 'coreai', 'agents'),\n join(projectRoot, 'coreai', 'commands'),\n join(projectRoot, '.coreai', 'cache'),\n ];\n\n const created: string[] = [];\n\n for (const dir of dirs) {\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n created.push(dir);\n }\n }\n\n return created;\n}\n\n/**\n * Initialize a new CoreAI project\n */\nexport function init(options: InitCommandOptions = {}): InitCommandResult {\n const projectRoot = options.projectRoot ?? process.cwd();\n\n // Check if config already exists\n if (configExists(projectRoot) && !options.force) {\n return {\n success: false,\n error: 'CoreAI configuration already exists. Use --force to overwrite.',\n };\n }\n\n // Detect git info\n const gitInfo = detectGitInfo();\n\n // Determine project name\n const name = options.name ?? detectProjectName(projectRoot);\n\n // Detect quality gates from project files\n const qualityGates = detectQualityGates(projectRoot);\n\n // Generate config\n const configContent = generateConfigYaml({ name, gitInfo, qualityGates });\n\n // Write config file\n const configPath = join(projectRoot, 'coreai.config.yaml');\n try {\n writeFileSync(configPath, configContent, 'utf-8');\n } catch (error) {\n return {\n success: false,\n error: `Failed to write config file: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n\n // Create directories unless skipped\n let createdDirs: string[] = [];\n if (!options.skipDirs) {\n try {\n createdDirs = createDirectories(projectRoot);\n } catch (error) {\n return {\n success: false,\n configPath,\n error: `Failed to create directories: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n\n return {\n success: true,\n configPath,\n createdDirs,\n gitInfo: gitInfo ?? undefined,\n };\n}\n\n/**\n * Format init result for display\n */\nexport function formatInitResult(result: InitCommandResult): string {\n if (!result.success) {\n return `Error: ${result.error}`;\n }\n\n const lines: string[] = [];\n\n lines.push('CoreAI project initialized successfully!\\n');\n\n if (result.configPath) {\n lines.push(`Created: ${result.configPath}`);\n }\n\n if (result.createdDirs && result.createdDirs.length > 0) {\n lines.push('\\nCreated directories:');\n for (const dir of result.createdDirs) {\n lines.push(` - ${dir}`);\n }\n }\n\n if (result.gitInfo?.provider) {\n lines.push(\n `\\nDetected ${result.gitInfo.provider} repository: ${result.gitInfo.owner}/${result.gitInfo.repo}`\n );\n }\n\n lines.push('\\nNext steps:');\n lines.push(' 1. Edit coreai.config.yaml to configure your project');\n lines.push(' 2. Add agents with `coreai agents add <name>`');\n lines.push(' 3. Run `coreai build` to compile agents');\n\n return lines.join('\\n');\n}\n","/**\n * Build Command\n *\n * Compiles agent definitions and skills to Claude-compatible format.\n */\n\nimport { configExists, loadConfig, ConfigError } from '../../config/loader.js';\nimport type { ResolvedCoreAIConfig } from '../../config/types.js';\nimport { compileAgents, type CompileOptions, type CompileResult } from '../../agents/index.js';\nimport { generateSkills, type GenerateSkillsResult } from '../../skills/index.js';\nimport { initAgentKnowledgeLibrary } from '../../knowledge-library/index.js';\nimport { discoverMcpServers } from '../../adapters/mcp/index.js';\n\n/**\n * Options for build command\n */\nexport interface BuildCommandOptions {\n /**\n * Project root directory\n */\n projectRoot?: string;\n\n /**\n * Path to core agents directory\n */\n coreAgentsDir?: string;\n\n /**\n * Output directory for compiled agents\n */\n outputDir?: string;\n\n /**\n * Watch for changes (not yet implemented)\n */\n watch?: boolean;\n\n /**\n * Only compile specific agents\n */\n agents?: string[];\n\n /**\n * Skip validation before build\n */\n skipValidation?: boolean;\n\n /**\n * Initialize KnowledgeLibrary directories for agents\n */\n initKnowledgeLibrary?: boolean;\n\n /**\n * Include MCP servers as agent tools.\n * If true, discovers MCP servers from config files.\n * If an array, uses the specified server names.\n * Default: true (auto-discover)\n */\n mcpServers?: boolean | string[];\n\n /**\n * Skip skill generation\n */\n skipSkills?: boolean;\n\n /**\n * Only generate specific skills\n */\n skills?: string[];\n}\n\n/**\n * Result of build command\n */\nexport interface BuildCommandResult {\n success: boolean;\n result?: CompileResult;\n skillsResult?: GenerateSkillsResult;\n config?: ResolvedCoreAIConfig;\n error?: string;\n warnings?: string[];\n knowledgeLibraryInitialized?: string[];\n mcpServers?: string[];\n}\n\n/**\n * Build agents\n */\nexport function build(options: BuildCommandOptions = {}): BuildCommandResult {\n const projectRoot = options.projectRoot ?? process.cwd();\n const warnings: string[] = [];\n\n // Load config if available\n let config: ResolvedCoreAIConfig | undefined;\n if (configExists(projectRoot)) {\n try {\n config = loadConfig(projectRoot);\n } catch (error) {\n if (error instanceof ConfigError) {\n return {\n success: false,\n error: `Configuration error: ${error.message}`,\n };\n }\n return {\n success: false,\n error: `Failed to load config: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n } else {\n warnings.push('No configuration file found. Building with defaults.');\n }\n\n // Set up compile options\n const compileOptions: CompileOptions = {\n projectRoot,\n };\n\n if (options.coreAgentsDir) {\n compileOptions.coreAgentsDir = options.coreAgentsDir;\n }\n\n if (options.outputDir) {\n compileOptions.outputDir = options.outputDir;\n }\n\n // Filter to specific agents if requested\n if (options.agents && options.agents.length > 0) {\n const agentsList = options.agents;\n compileOptions.filter = (agent) => agentsList.includes(agent.role);\n }\n\n // Discover MCP servers for tools\n const includeMcpServers = options.mcpServers ?? true;\n if (includeMcpServers !== false) {\n try {\n if (Array.isArray(includeMcpServers)) {\n // Use explicitly provided server names\n compileOptions.mcpServers = includeMcpServers;\n } else {\n // Auto-discover from config files\n const discoveredServers = discoverMcpServers({\n projectRoot,\n includeGlobal: false, // Only use project-level MCP config\n });\n if (discoveredServers.length > 0) {\n compileOptions.mcpServers = discoveredServers.map((s) => s.name);\n }\n }\n } catch {\n // MCP discovery failed, continue without MCP tools\n // This is non-fatal - agents will just use default tools\n }\n }\n\n // Compile agents\n try {\n const result = compileAgents(config, compileOptions);\n\n // Check for errors\n if (result.errors.length > 0) {\n return {\n success: false,\n result,\n config,\n error: `Failed to compile ${result.errors.length} agent(s)`,\n warnings,\n };\n }\n\n // Generate skills\n let skillsResult: GenerateSkillsResult | undefined;\n if (!options.skipSkills) {\n skillsResult = generateSkills(config, {\n projectRoot,\n skills: options.skills,\n overwrite: true,\n });\n }\n\n // Initialize KnowledgeLibrary for agents if requested\n let knowledgeLibraryInitialized: string[] | undefined;\n if (options.initKnowledgeLibrary) {\n knowledgeLibraryInitialized = [];\n for (const compiled of result.compiled) {\n const initResult = initAgentKnowledgeLibrary(compiled.role, {\n projectRoot,\n createDefaults: true,\n });\n if (initResult.success && initResult.createdDirs.length > 0) {\n knowledgeLibraryInitialized.push(compiled.role);\n }\n }\n }\n\n return {\n success: true,\n result,\n skillsResult,\n config,\n warnings: warnings.length > 0 ? warnings : undefined,\n knowledgeLibraryInitialized,\n mcpServers: compileOptions.mcpServers,\n };\n } catch (error) {\n return {\n success: false,\n error: `Build failed: ${error instanceof Error ? error.message : String(error)}`,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n }\n}\n\n/**\n * Format build result for display\n */\nexport function formatBuildResult(result: BuildCommandResult): string {\n const lines: string[] = [];\n\n // Warnings\n if (result.warnings && result.warnings.length > 0) {\n for (const warning of result.warnings) {\n lines.push(`⚠ ${warning}`);\n }\n lines.push('');\n }\n\n if (!result.success) {\n lines.push(`Build failed: ${result.error}`);\n\n // Show individual errors\n if (result.result?.errors && result.result.errors.length > 0) {\n lines.push('');\n for (const error of result.result.errors) {\n lines.push(` ✗ ${error.role}: ${error.error}`);\n }\n }\n\n return lines.join('\\n');\n }\n\n const compileResult = result.result;\n if (!compileResult) {\n lines.push('No agents to compile.');\n return lines.join('\\n');\n }\n\n if (compileResult.compiled.length === 0) {\n lines.push('No agents to compile.');\n return lines.join('\\n');\n }\n\n lines.push(`Compiled ${compileResult.compiled.length} agent(s):\\n`);\n\n // Group by source\n const coreAgents = compileResult.compiled.filter((a) => a.source === 'core');\n const customAgents = compileResult.compiled.filter((a) => a.source === 'custom');\n const overrideAgents = compileResult.compiled.filter((a) => a.source === 'override');\n\n if (coreAgents.length > 0) {\n lines.push('Core agents:');\n for (const agent of coreAgents) {\n lines.push(` ✓ ${agent.role}`);\n lines.push(` → ${agent.outputPath}`);\n }\n lines.push('');\n }\n\n if (customAgents.length > 0) {\n lines.push('Custom agents:');\n for (const agent of customAgents) {\n lines.push(` ✓ ${agent.role}`);\n lines.push(` → ${agent.outputPath}`);\n }\n lines.push('');\n }\n\n if (overrideAgents.length > 0) {\n lines.push('Override agents:');\n for (const agent of overrideAgents) {\n lines.push(` ✓ ${agent.role} (overrides core)`);\n lines.push(` → ${agent.outputPath}`);\n }\n lines.push('');\n }\n\n // Skills generated\n if (result.skillsResult) {\n const created = result.skillsResult.generated.filter((g) => g.action === 'created');\n const updated = result.skillsResult.generated.filter((g) => g.action === 'updated');\n const total = created.length + updated.length;\n if (total > 0) {\n lines.push(`Generated ${total} skill(s):`);\n for (const skill of [...created, ...updated]) {\n lines.push(` \\u2713 ${skill.name} \\u2192 ${skill.outputPath}`);\n }\n lines.push('');\n }\n if (result.skillsResult.errors.length > 0) {\n for (const error of result.skillsResult.errors) {\n lines.push(` \\u2717 skill ${error.name}: ${error.error}`);\n }\n lines.push('');\n }\n }\n\n // MCP servers included\n if (result.mcpServers && result.mcpServers.length > 0) {\n lines.push(`MCP tools included: ${result.mcpServers.map((s) => `mcp__${s}`).join(', ')}`);\n lines.push('');\n }\n\n // KnowledgeLibrary initialization\n if (result.knowledgeLibraryInitialized && result.knowledgeLibraryInitialized.length > 0) {\n lines.push(\n `KnowledgeLibrary initialized for ${result.knowledgeLibraryInitialized.length} agent(s):`\n );\n for (const agent of result.knowledgeLibraryInitialized) {\n lines.push(` ✓ ${agent}`);\n }\n lines.push('');\n }\n\n lines.push('Build complete!');\n\n return lines.join('\\n');\n}\n","/**\n * Validate Command\n *\n * Validates CoreAI configuration and project setup.\n */\n\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport { configExists, loadConfig, ConfigError } from '../../config/loader.js';\nimport type { ResolvedCoreAIConfig } from '../../config/types.js';\nimport { loadAllAgents } from '../../agents/index.js';\n\n/**\n * Options for validate command\n */\nexport interface ValidateCommandOptions {\n /**\n * Project root directory\n */\n projectRoot?: string;\n\n /**\n * Path to core agents directory\n */\n coreAgentsDir?: string;\n\n /**\n * Check if configured agents exist\n */\n checkAgents?: boolean;\n\n /**\n * Check directory structure\n */\n checkDirs?: boolean;\n\n /**\n * Check quality gates commands exist\n */\n checkQualityGates?: boolean;\n}\n\n/**\n * Single validation issue\n */\nexport interface ValidationIssue {\n level: 'error' | 'warning' | 'info';\n category: 'config' | 'agents' | 'directories' | 'quality_gates' | 'integrations';\n message: string;\n fix?: string;\n}\n\n/**\n * Result of validate command\n */\nexport interface ValidateCommandResult {\n success: boolean;\n valid: boolean;\n config?: ResolvedCoreAIConfig;\n issues: ValidationIssue[];\n summary: {\n errors: number;\n warnings: number;\n info: number;\n };\n}\n\n/**\n * Validate configuration file\n */\nfunction validateConfig(projectRoot: string): {\n config?: ResolvedCoreAIConfig;\n issues: ValidationIssue[];\n} {\n const issues: ValidationIssue[] = [];\n\n if (!configExists(projectRoot)) {\n issues.push({\n level: 'error',\n category: 'config',\n message: 'No CoreAI configuration file found',\n fix: 'Run `coreai init` to create a configuration file',\n });\n return { issues };\n }\n\n try {\n const config = loadConfig(projectRoot);\n return { config, issues };\n } catch (error) {\n if (error instanceof ConfigError) {\n issues.push({\n level: 'error',\n category: 'config',\n message: `Configuration error: ${error.message}`,\n fix: 'Check coreai.config.yaml for syntax errors',\n });\n } else {\n issues.push({\n level: 'error',\n category: 'config',\n message: `Failed to load config: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n return { issues };\n }\n}\n\n/**\n * Validate configured agents exist\n */\nfunction validateAgents(\n config: ResolvedCoreAIConfig,\n coreAgentsDir: string,\n projectRoot: string\n): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n const customAgentsDir = join(projectRoot, 'coreai', 'agents');\n\n // Load available agents\n let availableAgents: Map<string, unknown>;\n try {\n availableAgents = loadAllAgents({\n coreAgentsDir,\n customAgentsDir,\n });\n } catch (error) {\n issues.push({\n level: 'warning',\n category: 'agents',\n message: `Could not load agents: ${error instanceof Error ? error.message : String(error)}`,\n });\n return issues;\n }\n\n // Check each configured agent\n const configuredAgents = config.team.agents;\n for (const agentRole of configuredAgents) {\n if (!availableAgents.has(agentRole)) {\n issues.push({\n level: 'error',\n category: 'agents',\n message: `Configured agent '${agentRole}' not found`,\n fix: `Add agent definition to coreai/agents/${agentRole}.yaml or remove from config`,\n });\n }\n }\n\n // Info about available but not configured agents\n const unconfigured = Array.from(availableAgents.keys()).filter(\n (role) => !configuredAgents.includes(role)\n );\n if (unconfigured.length > 0) {\n issues.push({\n level: 'info',\n category: 'agents',\n message: `${unconfigured.length} available agent(s) not configured: ${unconfigured.join(', ')}`,\n });\n }\n\n return issues;\n}\n\n/**\n * Validate directory structure\n */\nfunction validateDirectories(projectRoot: string): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n\n const requiredDirs = [{ path: 'coreai', description: 'CoreAI configuration directory' }];\n\n const optionalDirs = [\n { path: 'coreai/agents', description: 'Custom agent definitions' },\n { path: 'coreai/commands', description: 'Custom command definitions' },\n { path: '.coreai', description: 'CoreAI runtime directory' },\n { path: '.coreai/cache', description: 'Cache directory' },\n { path: '.claude/agents', description: 'Compiled agents output' },\n ];\n\n // Check required directories\n for (const dir of requiredDirs) {\n const fullPath = join(projectRoot, dir.path);\n if (!existsSync(fullPath)) {\n issues.push({\n level: 'warning',\n category: 'directories',\n message: `Missing directory: ${dir.path} (${dir.description})`,\n fix: `Run mkdir -p ${dir.path}`,\n });\n }\n }\n\n // Check optional directories (info only)\n for (const dir of optionalDirs) {\n const fullPath = join(projectRoot, dir.path);\n if (!existsSync(fullPath)) {\n issues.push({\n level: 'info',\n category: 'directories',\n message: `Optional directory not found: ${dir.path} (${dir.description})`,\n });\n }\n }\n\n return issues;\n}\n\n/**\n * Validate integrations configuration\n */\nfunction validateIntegrations(config: ResolvedCoreAIConfig): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n\n if (!config.integrations) {\n issues.push({\n level: 'info',\n category: 'integrations',\n message: 'No integrations configured',\n });\n return issues;\n }\n\n // Check git integration\n if (config.integrations.git) {\n const git = config.integrations.git;\n if (!git.config?.owner || !git.config?.repo) {\n issues.push({\n level: 'warning',\n category: 'integrations',\n message: 'Git integration configured but owner/repo not specified',\n fix: 'Add integrations.git.config.owner and integrations.git.config.repo to config',\n });\n }\n }\n\n // Check issue tracker\n if (config.integrations.issue_tracker) {\n const tracker = config.integrations.issue_tracker;\n if (tracker.provider === 'jira' && !tracker.config?.base_url) {\n issues.push({\n level: 'warning',\n category: 'integrations',\n message: 'Jira integration configured but base_url not specified',\n fix: 'Add integrations.issue_tracker.config.base_url to config',\n });\n }\n }\n\n return issues;\n}\n\n/**\n * Validate the CoreAI project\n */\nexport function validate(options: ValidateCommandOptions = {}): ValidateCommandResult {\n const projectRoot = options.projectRoot ?? process.cwd();\n const coreAgentsDir =\n options.coreAgentsDir ?? join(projectRoot, 'node_modules', '@coreai', 'cli', 'agents');\n const checkAgents = options.checkAgents ?? true;\n const checkDirs = options.checkDirs ?? true;\n\n const allIssues: ValidationIssue[] = [];\n\n // Validate config\n const { config, issues: configIssues } = validateConfig(projectRoot);\n allIssues.push(...configIssues);\n\n // If config loaded successfully, validate other aspects\n if (config) {\n // Validate agents\n if (checkAgents) {\n allIssues.push(...validateAgents(config, coreAgentsDir, projectRoot));\n }\n\n // Validate integrations\n allIssues.push(...validateIntegrations(config));\n }\n\n // Validate directories (independent of config)\n if (checkDirs) {\n allIssues.push(...validateDirectories(projectRoot));\n }\n\n // Calculate summary\n const summary = {\n errors: allIssues.filter((i) => i.level === 'error').length,\n warnings: allIssues.filter((i) => i.level === 'warning').length,\n info: allIssues.filter((i) => i.level === 'info').length,\n };\n\n return {\n success: true,\n valid: summary.errors === 0,\n config,\n issues: allIssues,\n summary,\n };\n}\n\n/**\n * Format validate result for display\n */\nexport function formatValidateResult(result: ValidateCommandResult): string {\n const lines: string[] = [];\n\n // Header\n if (result.valid) {\n lines.push('✓ Configuration is valid\\n');\n } else {\n lines.push('✗ Configuration has errors\\n');\n }\n\n // Group issues by category\n const categories = ['config', 'agents', 'integrations', 'directories', 'quality_gates'] as const;\n\n for (const category of categories) {\n const categoryIssues = result.issues.filter((i) => i.category === category);\n if (categoryIssues.length === 0) continue;\n\n const categoryLabel = category.charAt(0).toUpperCase() + category.slice(1).replace('_', ' ');\n lines.push(`${categoryLabel}:`);\n\n for (const issue of categoryIssues) {\n const prefix = issue.level === 'error' ? ' ✗' : issue.level === 'warning' ? ' ⚠' : ' ℹ';\n lines.push(`${prefix} ${issue.message}`);\n if (issue.fix) {\n lines.push(` → ${issue.fix}`);\n }\n }\n lines.push('');\n }\n\n // Summary\n lines.push('Summary:');\n lines.push(` Errors: ${result.summary.errors}`);\n lines.push(` Warnings: ${result.summary.warnings}`);\n lines.push(` Info: ${result.summary.info}`);\n\n return lines.join('\\n');\n}\n","/**\n * Skills Command\n *\n * Generates Claude skills from templates based on project configuration.\n */\n\nimport { configExists, loadConfig, ConfigError } from '../../config/loader.js';\nimport type { ResolvedCoreAIConfig } from '../../config/types.js';\nimport {\n generateSkills,\n formatGenerateResult,\n discoverSkills,\n getCoreSkillsDir,\n type GenerateSkillsOptions,\n type GenerateSkillsResult,\n} from '../../skills/index.js';\n\n/**\n * Options for skills generate command\n */\nexport interface SkillsGenerateOptions {\n /**\n * Project root directory\n */\n projectRoot?: string;\n\n /**\n * Output directory for generated skills\n */\n outputDir?: string;\n\n /**\n * Directory containing custom skill templates\n */\n customTemplatesDir?: string;\n\n /**\n * Only generate specific skills\n */\n skills?: string[];\n\n /**\n * Include core skills (default: true)\n */\n includeCoreSkills?: boolean;\n\n /**\n * Overwrite existing skill files\n */\n overwrite?: boolean;\n\n /**\n * Additional variables for template substitution\n */\n variables?: Record<string, string>;\n}\n\n/**\n * Result of skills generate command\n */\nexport interface SkillsGenerateResult {\n success: boolean;\n result?: GenerateSkillsResult;\n config?: ResolvedCoreAIConfig;\n error?: string;\n warnings?: string[];\n}\n\n/**\n * Generate skills from templates\n */\nexport function skillsGenerate(options: SkillsGenerateOptions = {}): SkillsGenerateResult {\n const projectRoot = options.projectRoot ?? process.cwd();\n const warnings: string[] = [];\n\n // Load config if available\n let config: ResolvedCoreAIConfig | undefined;\n if (configExists(projectRoot)) {\n try {\n config = loadConfig(projectRoot);\n } catch (error) {\n if (error instanceof ConfigError) {\n return {\n success: false,\n error: `Configuration error: ${error.message}`,\n };\n }\n return {\n success: false,\n error: `Failed to load config: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n } else {\n warnings.push('No configuration file found. Generating skills with defaults.');\n }\n\n // Set up generate options\n const generateOptions: GenerateSkillsOptions = {\n projectRoot,\n includeCoreSkills: options.includeCoreSkills ?? true,\n overwrite: options.overwrite ?? true,\n };\n\n if (options.outputDir) {\n generateOptions.outputDir = options.outputDir;\n }\n\n if (options.customTemplatesDir) {\n generateOptions.customTemplatesDir = options.customTemplatesDir;\n }\n\n if (options.skills && options.skills.length > 0) {\n generateOptions.skills = options.skills;\n }\n\n if (options.variables) {\n generateOptions.variables = options.variables;\n }\n\n // Generate skills\n try {\n const result = generateSkills(config, generateOptions);\n\n // Check for errors\n if (result.errors.length > 0) {\n return {\n success: false,\n result,\n config,\n error: `Failed to generate ${result.errors.length} skill(s)`,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n }\n\n return {\n success: true,\n result,\n config,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n } catch (error) {\n return {\n success: false,\n error: `Skill generation failed: ${error instanceof Error ? error.message : String(error)}`,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n }\n}\n\n/**\n * Format skills generate result for display\n */\nexport function formatSkillsGenerateResult(result: SkillsGenerateResult): string {\n const lines: string[] = [];\n\n // Warnings\n if (result.warnings && result.warnings.length > 0) {\n for (const warning of result.warnings) {\n lines.push(`⚠ ${warning}`);\n }\n lines.push('');\n }\n\n if (!result.success) {\n lines.push(`Skill generation failed: ${result.error}`);\n\n // Show individual errors\n if (result.result?.errors && result.result.errors.length > 0) {\n lines.push('');\n for (const error of result.result.errors) {\n lines.push(` ✗ ${error.name}: ${error.error}`);\n }\n }\n\n return lines.join('\\n');\n }\n\n // Use the generator's format function for the detailed output\n if (result.result) {\n return formatGenerateResult(result.result);\n }\n\n lines.push('No skills to generate.');\n return lines.join('\\n');\n}\n\n/**\n * List available skills\n */\nexport interface SkillsListOptions {\n /**\n * Project root directory\n */\n projectRoot?: string;\n\n /**\n * Directory containing custom skill templates\n */\n customTemplatesDir?: string;\n\n /**\n * Include core skills\n */\n includeCoreSkills?: boolean;\n}\n\n/**\n * Information about an available skill\n */\nexport interface SkillInfo {\n name: string;\n description: string;\n category: string;\n dependencies?: string[];\n argumentHint?: string;\n}\n\n/**\n * Result of skills list command\n */\nexport interface SkillsListResult {\n success: boolean;\n skills?: SkillInfo[];\n error?: string;\n}\n\n/**\n * List available skills\n */\nexport function skillsList(options: SkillsListOptions = {}): SkillsListResult {\n try {\n const skills: SkillInfo[] = [];\n\n // Discover skills from source directory\n const coreSkillsDir = getCoreSkillsDir();\n const discovered = discoverSkills(coreSkillsDir);\n\n const includeCoreSkills = options.includeCoreSkills ?? true;\n\n for (const skill of discovered) {\n if (skill.category === 'core' && !includeCoreSkills) continue;\n\n skills.push({\n name: skill.name,\n description: skill.description,\n category: skill.category,\n dependencies: skill.dependencies?.filter((d) => d.required).map((d) => d.type),\n argumentHint: skill.argumentHint,\n });\n }\n\n // Add custom skills if directory specified\n if (options.customTemplatesDir) {\n const customSkills = discoverSkills(options.customTemplatesDir);\n for (const skill of customSkills) {\n skills.push({\n name: skill.name,\n description: skill.description,\n category: skill.category,\n dependencies: skill.dependencies?.filter((d) => d.required).map((d) => d.type),\n argumentHint: skill.argumentHint,\n });\n }\n }\n\n return {\n success: true,\n skills,\n };\n } catch (error) {\n return {\n success: false,\n error: `Failed to list skills: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n}\n\n/**\n * Format skills list result for display\n */\nexport function formatSkillsListResult(result: SkillsListResult): string {\n if (!result.success) {\n return `Error: ${result.error}`;\n }\n\n if (!result.skills || result.skills.length === 0) {\n return 'No skills available.';\n }\n\n const lines: string[] = [];\n lines.push('Available skills:\\n');\n\n // Group by category\n const coreSkills = result.skills.filter((s) => s.category === 'core');\n const customSkills = result.skills.filter((s) => s.category === 'custom');\n\n if (coreSkills.length > 0) {\n lines.push('Core skills:');\n for (const skill of coreSkills) {\n lines.push(` ${skill.name}`);\n lines.push(` ${skill.description}`);\n if (skill.argumentHint) {\n lines.push(` Argument: ${skill.argumentHint}`);\n }\n }\n lines.push('');\n }\n\n if (customSkills.length > 0) {\n lines.push('Custom skills:');\n for (const skill of customSkills) {\n lines.push(` ${skill.name}`);\n lines.push(` ${skill.description}`);\n if (skill.argumentHint) {\n lines.push(` Argument: ${skill.argumentHint}`);\n }\n }\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n","/**\n * Status Command\n *\n * Shows agent states and pending messages.\n */\n\nimport { configExists, loadConfig, ConfigError } from '../../config/loader.js';\nimport type { ResolvedCoreAIConfig } from '../../config/types.js';\nimport {\n getKnowledgeLibraryState,\n getAgentKnowledgeState,\n initKnowledgeLibrary,\n type KnowledgeLibraryState,\n} from '../../knowledge-library/index.js';\n\n/**\n * Options for status command\n */\nexport interface StatusCommandOptions {\n /**\n * Project root directory\n */\n projectRoot?: string;\n\n /**\n * Show status for specific agent only\n */\n agent?: string;\n\n /**\n * Show detailed status including message subjects\n */\n detailed?: boolean;\n\n /**\n * Initialize KnowledgeLibrary if not exists\n */\n init?: boolean;\n}\n\n/**\n * Agent status info\n */\nexport interface AgentStatus {\n /**\n * Agent name/role\n */\n name: string;\n\n /**\n * Whether the agent's KnowledgeLibrary is initialized\n */\n initialized: boolean;\n\n /**\n * Current status (e.g., \"idle\", \"working\")\n */\n status?: string;\n\n /**\n * Current task\n */\n currentTask?: string;\n\n /**\n * Current ticket\n */\n currentTicket?: string;\n\n /**\n * Number of pending inbox messages\n */\n pendingMessages: number;\n\n /**\n * Last activity timestamp\n */\n lastActivity?: Date;\n\n /**\n * Message details (if detailed mode)\n */\n messageDetails?: {\n type: string;\n from: string;\n subject: string;\n date?: Date;\n }[];\n}\n\n/**\n * Result of status command\n */\nexport interface StatusCommandResult {\n success: boolean;\n knowledgeLibrary?: KnowledgeLibraryState;\n agents: AgentStatus[];\n error?: string;\n warnings?: string[];\n}\n\n/**\n * Get status of agents and KnowledgeLibrary\n */\nexport function status(options: StatusCommandOptions = {}): StatusCommandResult {\n const projectRoot = options.projectRoot ?? process.cwd();\n const warnings: string[] = [];\n\n // Load config if available to get team agents\n let config: ResolvedCoreAIConfig | undefined;\n let configuredAgents: string[] = [];\n\n if (configExists(projectRoot)) {\n try {\n config = loadConfig(projectRoot);\n if (config.team?.agents) {\n configuredAgents = config.team.agents;\n }\n } catch (error) {\n if (error instanceof ConfigError) {\n warnings.push(`Configuration error: ${error.message}`);\n } else {\n warnings.push(\n `Failed to load config: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n } else {\n warnings.push('No configuration file found.');\n }\n\n // Get KnowledgeLibrary state\n let klState = getKnowledgeLibraryState({ projectRoot });\n\n // Initialize if requested and doesn't exist\n if (!klState && options.init) {\n const initResult = initKnowledgeLibrary({ projectRoot, createDefaults: true });\n if (initResult.success) {\n klState = getKnowledgeLibraryState({ projectRoot });\n } else {\n return {\n success: false,\n agents: [],\n error: `Failed to initialize KnowledgeLibrary: ${initResult.error}`,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n }\n }\n\n if (!klState) {\n return {\n success: true,\n agents: [],\n warnings: [\n ...warnings,\n 'KnowledgeLibrary not initialized. Run `coreai status --init` to create it.',\n ],\n };\n }\n\n // Determine which agents to show status for\n let agentsToCheck: string[];\n if (options.agent) {\n agentsToCheck = [options.agent];\n } else {\n // Combine configured agents and discovered agents\n agentsToCheck = [...new Set([...configuredAgents, ...klState.agents])];\n }\n\n // Get status for each agent\n const agentStatuses: AgentStatus[] = [];\n\n for (const agentName of agentsToCheck) {\n const agentState = getAgentKnowledgeState(agentName, { projectRoot });\n\n const agentStatus: AgentStatus = {\n name: agentName,\n initialized: agentState.initialized,\n pendingMessages: agentState.pendingMessages.length,\n };\n\n if (agentState.context) {\n agentStatus.status = agentState.context.status;\n agentStatus.currentTask = agentState.context.currentTask;\n agentStatus.currentTicket = agentState.context.currentTicket;\n agentStatus.lastActivity = agentState.context.lastUpdated;\n }\n\n // Add message details if detailed mode\n if (options.detailed && agentState.pendingMessages.length > 0) {\n agentStatus.messageDetails = agentState.pendingMessages.map((msg) => ({\n type: msg.metadata.type ?? 'unknown',\n from: msg.metadata.from ?? 'unknown',\n subject: msg.metadata.subject ?? msg.filename,\n date: msg.metadata.date,\n }));\n }\n\n agentStatuses.push(agentStatus);\n }\n\n // Sort by pending messages (most first), then by name\n agentStatuses.sort((a, b) => {\n if (b.pendingMessages !== a.pendingMessages) {\n return b.pendingMessages - a.pendingMessages;\n }\n return a.name.localeCompare(b.name);\n });\n\n return {\n success: true,\n knowledgeLibrary: klState,\n agents: agentStatuses,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n}\n\n/**\n * Format status result for display\n */\nexport function formatStatusResult(result: StatusCommandResult): string {\n const lines: string[] = [];\n\n // Warnings\n if (result.warnings && result.warnings.length > 0) {\n for (const warning of result.warnings) {\n lines.push(`⚠ ${warning}`);\n }\n lines.push('');\n }\n\n if (!result.success) {\n lines.push(`Error: ${result.error}`);\n return lines.join('\\n');\n }\n\n if (result.agents.length === 0) {\n lines.push('No agents found.');\n return lines.join('\\n');\n }\n\n lines.push('Agent Status\\n');\n\n // Summary table header\n const activeAgents = result.agents.filter((a) => a.status === 'working');\n const idleAgents = result.agents.filter(\n (a) => a.initialized && (!a.status || a.status === 'idle')\n );\n const uninitializedAgents = result.agents.filter((a) => !a.initialized);\n const totalPending = result.agents.reduce((sum, a) => sum + a.pendingMessages, 0);\n\n lines.push(`Total agents: ${result.agents.length}`);\n if (activeAgents.length > 0) {\n lines.push(` Active: ${activeAgents.length}`);\n }\n if (idleAgents.length > 0) {\n lines.push(` Idle: ${idleAgents.length}`);\n }\n if (uninitializedAgents.length > 0) {\n lines.push(` Not initialized: ${uninitializedAgents.length}`);\n }\n if (totalPending > 0) {\n lines.push(` Total pending messages: ${totalPending}`);\n }\n lines.push('');\n\n // Detailed agent list\n for (const agent of result.agents) {\n const statusIcon = !agent.initialized ? '○' : agent.pendingMessages > 0 ? '●' : '◎';\n const statusText = !agent.initialized ? 'not initialized' : (agent.status ?? 'idle');\n\n lines.push(`${statusIcon} ${agent.name}`);\n lines.push(` Status: ${statusText}`);\n\n if (agent.currentTask) {\n lines.push(` Task: ${agent.currentTask}`);\n }\n\n if (agent.currentTicket) {\n lines.push(` Ticket: ${agent.currentTicket}`);\n }\n\n if (agent.pendingMessages > 0) {\n lines.push(` Pending messages: ${agent.pendingMessages}`);\n\n // Show message details if available\n if (agent.messageDetails && agent.messageDetails.length > 0) {\n for (const msg of agent.messageDetails) {\n const dateStr = msg.date ? msg.date.toISOString().slice(0, 16).replace('T', ' ') : '';\n lines.push(` - [${msg.type}] from ${msg.from}: ${msg.subject}`);\n if (dateStr) {\n lines.push(` ${dateStr}`);\n }\n }\n }\n }\n\n if (agent.lastActivity) {\n const activityStr = agent.lastActivity.toISOString().slice(0, 16).replace('T', ' ');\n lines.push(` Last activity: ${activityStr}`);\n }\n\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Format a compact status summary\n */\nexport function formatStatusSummary(result: StatusCommandResult): string {\n if (!result.success) {\n return `Error: ${result.error}`;\n }\n\n const activeCount = result.agents.filter((a) => a.status === 'working').length;\n const pendingCount = result.agents.reduce((sum, a) => sum + a.pendingMessages, 0);\n\n const parts: string[] = [];\n parts.push(`${result.agents.length} agents`);\n\n if (activeCount > 0) {\n parts.push(`${activeCount} active`);\n }\n\n if (pendingCount > 0) {\n parts.push(`${pendingCount} pending messages`);\n }\n\n return parts.join(', ');\n}\n","/**\n * Agents Commands\n *\n * Commands to manage agents in the CoreAI configuration.\n */\n\nimport { readFileSync, writeFileSync } from 'fs';\nimport { join, dirname } from 'path';\nimport { parse as parseYaml, stringify as stringifyYaml } from 'yaml';\nimport { loadAllAgents } from '../../agents/index.js';\nimport { findConfigFile } from '../../config/loader.js';\nimport type { CoreAIConfig } from '../../config/types.js';\n\n/**\n * Options for agents add command\n */\nexport interface AgentsAddOptions {\n /**\n * Project root directory\n */\n projectRoot?: string | undefined;\n\n /**\n * Core agents directory\n */\n coreAgentsDir?: string | undefined;\n\n /**\n * Skip rebuilding agents after adding\n */\n skipBuild?: boolean | undefined;\n\n /**\n * Add all available core agents\n */\n all?: boolean | undefined;\n}\n\n/**\n * Result of agents add command\n */\nexport interface AgentsAddResult {\n success: boolean;\n added: string[];\n alreadyExists: string[];\n notFound: string[];\n configPath?: string;\n error?: string;\n}\n\n/**\n * Options for agents remove command\n */\nexport interface AgentsRemoveOptions {\n /**\n * Project root directory\n */\n projectRoot?: string | undefined;\n\n /**\n * Core agents directory\n */\n coreAgentsDir?: string | undefined;\n\n /**\n * Skip rebuilding agents after removing\n */\n skipBuild?: boolean | undefined;\n\n /**\n * Remove all agents from config\n */\n all?: boolean | undefined;\n}\n\n/**\n * Result of agents remove command\n */\nexport interface AgentsRemoveResult {\n success: boolean;\n removed: string[];\n notInConfig: string[];\n configPath?: string;\n error?: string;\n}\n\n/**\n * Read and parse the config file preserving structure\n */\nfunction readConfigFile(configPath: string): { content: string; parsed: CoreAIConfig } {\n const content = readFileSync(configPath, 'utf-8');\n const parsed = parseYaml(content) as CoreAIConfig;\n return { content, parsed };\n}\n\n/**\n * Update the team.agents array in the config file\n * Preserves comments and formatting as much as possible\n */\nfunction updateConfigAgents(configPath: string, agents: string[]): void {\n const content = readFileSync(configPath, 'utf-8');\n const parsed = parseYaml(content) as CoreAIConfig;\n\n // Initialize team if not exists\n if (!parsed.team) {\n parsed.team = {};\n }\n\n // Update agents list\n parsed.team.agents = agents;\n\n // Write back to file\n const newContent = stringifyYaml(parsed, {\n indent: 2,\n lineWidth: 0,\n singleQuote: false,\n });\n\n writeFileSync(configPath, newContent, 'utf-8');\n}\n\n/**\n * Get list of available agent roles\n */\nfunction getAvailableAgents(\n coreAgentsDir: string,\n customAgentsDir: string\n): Map<string, 'core' | 'custom'> {\n const available = new Map<string, 'core' | 'custom'>();\n\n const allAgents = loadAllAgents({\n coreAgentsDir,\n customAgentsDir,\n });\n\n for (const [role, meta] of allAgents) {\n available.set(role, meta.source === 'core' ? 'core' : 'custom');\n }\n\n return available;\n}\n\n/**\n * Add agents to the CoreAI configuration\n */\nexport function agentsAdd(agents: string[], options: AgentsAddOptions = {}): AgentsAddResult {\n const projectRoot = options.projectRoot ?? process.cwd();\n const coreAgentsDir = options.coreAgentsDir ?? join(dirname(dirname(dirname(__dirname))), 'agents');\n const customAgentsDir = join(projectRoot, 'coreai', 'agents');\n\n // Find config file\n const configPath = findConfigFile(projectRoot);\n if (!configPath) {\n return {\n success: false,\n added: [],\n alreadyExists: [],\n notFound: [],\n error: 'No coreai.config.yaml found. Run `coreai init` first.',\n };\n }\n\n // Get available agents\n const availableAgents = getAvailableAgents(coreAgentsDir, customAgentsDir);\n\n // If --all flag, use all available agents\n const agentsToAdd = options.all ? Array.from(availableAgents.keys()) : agents;\n\n if (agentsToAdd.length === 0) {\n return {\n success: false,\n added: [],\n alreadyExists: [],\n notFound: [],\n configPath,\n error: 'No agents specified. Use --all to add all agents or provide a comma-separated list.',\n };\n }\n\n // Read current config\n const { parsed } = readConfigFile(configPath);\n const currentAgents = parsed.team?.agents ?? [];\n\n const added: string[] = [];\n const alreadyExists: string[] = [];\n const notFound: string[] = [];\n\n for (const agent of agentsToAdd) {\n const trimmedAgent = agent.trim();\n\n if (!availableAgents.has(trimmedAgent)) {\n notFound.push(trimmedAgent);\n continue;\n }\n\n if (currentAgents.includes(trimmedAgent)) {\n alreadyExists.push(trimmedAgent);\n continue;\n }\n\n added.push(trimmedAgent);\n }\n\n // Update config if there are agents to add\n if (added.length > 0) {\n const newAgents = [...currentAgents, ...added].sort();\n try {\n updateConfigAgents(configPath, newAgents);\n } catch (error) {\n return {\n success: false,\n added: [],\n alreadyExists,\n notFound,\n configPath,\n error: `Failed to update config: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n\n return {\n success: notFound.length === 0,\n added,\n alreadyExists,\n notFound,\n configPath,\n };\n}\n\n/**\n * Remove agents from the CoreAI configuration\n */\nexport function agentsRemove(agents: string[], options: AgentsRemoveOptions = {}): AgentsRemoveResult {\n const projectRoot = options.projectRoot ?? process.cwd();\n\n // Find config file\n const configPath = findConfigFile(projectRoot);\n if (!configPath) {\n return {\n success: false,\n removed: [],\n notInConfig: [],\n error: 'No coreai.config.yaml found. Run `coreai init` first.',\n };\n }\n\n // Read current config\n const { parsed } = readConfigFile(configPath);\n const currentAgents = parsed.team?.agents ?? [];\n\n // If --all flag, remove all agents\n const agentsToRemove = options.all ? [...currentAgents] : agents;\n\n if (agentsToRemove.length === 0) {\n return {\n success: false,\n removed: [],\n notInConfig: [],\n configPath,\n error: 'No agents specified. Use --all to remove all agents or provide a comma-separated list.',\n };\n }\n\n const removed: string[] = [];\n const notInConfig: string[] = [];\n\n for (const agent of agentsToRemove) {\n const trimmedAgent = agent.trim();\n\n if (!currentAgents.includes(trimmedAgent)) {\n notInConfig.push(trimmedAgent);\n continue;\n }\n\n removed.push(trimmedAgent);\n }\n\n // Update config if there are agents to remove\n if (removed.length > 0) {\n const newAgents = currentAgents.filter((a) => !removed.includes(a));\n try {\n updateConfigAgents(configPath, newAgents);\n } catch (error) {\n return {\n success: false,\n removed: [],\n notInConfig,\n configPath,\n error: `Failed to update config: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n\n return {\n success: true,\n removed,\n notInConfig,\n configPath,\n };\n}\n\n/**\n * Format agents add result for display\n */\nexport function formatAgentsAddResult(result: AgentsAddResult): string {\n const lines: string[] = [];\n\n if (!result.success && result.error) {\n return `Error: ${result.error}`;\n }\n\n if (result.added.length > 0) {\n lines.push('Added agents:');\n for (const agent of result.added) {\n lines.push(` + ${agent}`);\n }\n }\n\n if (result.alreadyExists.length > 0) {\n if (lines.length > 0) lines.push('');\n lines.push('Already in config:');\n for (const agent of result.alreadyExists) {\n lines.push(` = ${agent}`);\n }\n }\n\n if (result.notFound.length > 0) {\n if (lines.length > 0) lines.push('');\n lines.push('Not found (run `coreai agents list` to see available):');\n for (const agent of result.notFound) {\n lines.push(` ! ${agent}`);\n }\n }\n\n if (result.added.length === 0 && result.alreadyExists.length === 0 && result.notFound.length === 0) {\n lines.push('No changes made.');\n }\n\n if (result.added.length > 0) {\n lines.push('');\n lines.push('Run `coreai build` to compile the updated agent list.');\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Format agents remove result for display\n */\nexport function formatAgentsRemoveResult(result: AgentsRemoveResult): string {\n const lines: string[] = [];\n\n if (!result.success && result.error) {\n return `Error: ${result.error}`;\n }\n\n if (result.removed.length > 0) {\n lines.push('Removed agents:');\n for (const agent of result.removed) {\n lines.push(` - ${agent}`);\n }\n }\n\n if (result.notInConfig.length > 0) {\n if (lines.length > 0) lines.push('');\n lines.push('Not in config:');\n for (const agent of result.notInConfig) {\n lines.push(` ? ${agent}`);\n }\n }\n\n if (result.removed.length === 0 && result.notInConfig.length === 0) {\n lines.push('No changes made.');\n }\n\n if (result.removed.length > 0) {\n lines.push('');\n lines.push('Run `coreai build` to compile the updated agent list.');\n }\n\n return lines.join('\\n');\n}\n"],"mappings":";;;AAQA,SAAS,QAAAA,QAAM,WAAAC,gBAAe;AAC9B,SAAS,iBAAAC,sBAAqB;AAC9B,SAAS,eAAe;;;ACJxB,SAAS,gBAAAC,qBAAoB;AAC7B,SAAS,WAAAC,UAAS,QAAAC,aAAY;AAC9B,SAAS,qBAAqB;;;ACF9B,SAAS,YAAY,oBAAoB;AACzC,SAAS,SAAS,MAAM,eAAe;AACvC,SAAS,SAAS,iBAAiB;AACnC,OAAO,SAA+B;AACtC,OAAO,gBAAgB;AAIvB,SAAS,qBAAqB;AAC9B,IAAMC,WAAU,cAAc,YAAY,GAAG;AAC7C,IAAM,eAAeA,SAAQ,yCAAyC;AAEtE,IAAM,mBAAmB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,KAAK,CAAC;AAAA,IAChB;AAAA,EACF;AACF;AAEF,UACG,QAAQ,MAAM,EACd,YAAY,uBAAuB,EACnC,OAAO,aAAa,qBAAqB,EACzC,OAAO,UAAU,gBAAgB,EACjC,OAAO,CAAC,YAAgD;AACvD,QAAM,SAAS,WAAW;AAAA,IACxB,aAAa,QAAQ,IAAI;AAAA,IACzB,mBAAmB,QAAQ,SAAS;AAAA,EACtC,CAAC;AAED,MAAI,QAAQ,MAAM;AAChB,YAAQ,IAAI,KAAK,UAAU,QAAQ,MAAM,CAAC,CAAC;AAC3C;AAAA,EACF;AAEA,UAAQ,IAAI,uBAAuB,MAAM,CAAC;AAE1C,MAAI,CAAC,OAAO,SAAS;AACnB,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF,CAAC;AAEH,QAAQ,MAAM;","names":["join","dirname","fileURLToPath","readFileSync","dirname","join","require","validate","existsSync","readFileSync","join","parseYaml","Ajv","createRequire","require","validate","agents","existsSync","readFileSync","join","dirname","extname","parseYaml","join","existsSync","readFileSync","dirname","parseYaml","extname","agents","existsSync","readFileSync","join","dirname","join","existsSync","readFileSync","dirname","join","dirname","join","status","dirname","status","existsSync","mkdirSync","writeFileSync","readFileSync","readdirSync","join","dirname","extractVariables","existsSync","mkdirSync","writeFileSync","readFileSync","readdirSync","statSync","join","basename","join","existsSync","readdirSync","statSync","readFileSync","join","existsSync","agents","readdirSync","statSync","dirname","join","readFileSync","join","join","status","join","getCachePath","join","existsSync","writeFileSync","mkdirSync","readFileSync","join","basename","join","existsSync","readFileSync","basename","mkdirSync","writeFileSync","existsSync","join","validateConfig","join","existsSync","readFileSync","writeFileSync","join","dirname","parseYaml","stringifyYaml","readFileSync","parseYaml","agents","stringifyYaml","writeFileSync","join","dirname","fileURLToPath","__dirname","dirname","join","agents"]}