bluera-knowledge 0.11.19 → 0.11.21
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.
- package/.claude-plugin/plugin.json +1 -1
- package/CHANGELOG.md +44 -0
- package/README.md +42 -5
- package/commands/crawl.md +7 -7
- package/commands/search.md +9 -2
- package/dist/{chunk-QEHSDQTL.js → chunk-C4SYGLAI.js} +47 -28
- package/dist/chunk-C4SYGLAI.js.map +1 -0
- package/dist/{chunk-VP4VZULK.js → chunk-CC6EGZ4D.js} +51 -8
- package/dist/chunk-CC6EGZ4D.js.map +1 -0
- package/dist/{chunk-GOAOBPOA.js → chunk-QCSFBMYW.js} +2 -2
- package/dist/index.js +64 -12
- package/dist/index.js.map +1 -1
- package/dist/mcp/server.js +2 -2
- package/dist/workers/background-worker-cli.js +2 -2
- package/package.json +1 -1
- package/src/analysis/code-graph.test.ts +30 -0
- package/src/analysis/code-graph.ts +10 -2
- package/src/cli/commands/store.test.ts +78 -0
- package/src/cli/commands/store.ts +19 -0
- package/src/cli/commands/sync.test.ts +1 -1
- package/src/cli/commands/sync.ts +50 -1
- package/src/db/lance.test.ts +3 -4
- package/src/db/lance.ts +14 -19
- package/src/mcp/commands/sync.commands.test.ts +94 -6
- package/src/mcp/commands/sync.commands.ts +36 -6
- package/src/mcp/handlers/search.handler.ts +3 -1
- package/src/mcp/handlers/store.handler.test.ts +3 -0
- package/src/mcp/handlers/store.handler.ts +5 -2
- package/src/mcp/schemas/index.test.ts +36 -0
- package/src/mcp/schemas/index.ts +6 -0
- package/src/mcp/server.test.ts +56 -1
- package/src/mcp/server.ts +16 -1
- package/src/services/code-graph.service.ts +11 -1
- package/src/services/job.service.test.ts +23 -0
- package/src/services/job.service.ts +10 -6
- package/src/services/search.service.ts +15 -9
- package/vitest.config.ts +1 -1
- package/dist/chunk-QEHSDQTL.js.map +0 -1
- package/dist/chunk-VP4VZULK.js.map +0 -1
- /package/dist/{chunk-GOAOBPOA.js.map → chunk-QCSFBMYW.js.map} +0 -0
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/cli/commands/crawl.ts","../src/cli/commands/index-cmd.ts","../src/cli/commands/mcp.ts","../src/cli/commands/plugin-api.ts","../src/plugin/commands.ts","../src/analysis/dependency-usage-analyzer.ts","../src/analysis/repo-url-resolver.ts","../src/cli/commands/search.ts","../src/cli/commands/serve.ts","../src/server/app.ts","../src/cli/commands/setup.ts","../src/defaults/repos.ts","../src/cli/commands/store.ts","../src/cli/commands/sync.ts","../src/cli/program.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { Command } from 'commander';\nimport { AdapterRegistry } from './analysis/adapter-registry.js';\nimport { ZilAdapter } from './analysis/zil/index.js';\nimport { createCrawlCommand } from './cli/commands/crawl.js';\nimport { createIndexCommand } from './cli/commands/index-cmd.js';\nimport { createMCPCommand } from './cli/commands/mcp.js';\nimport {\n createAddRepoCommand,\n createAddFolderCommand,\n createStoresCommand,\n createSuggestCommand,\n} from './cli/commands/plugin-api.js';\nimport { createSearchCommand } from './cli/commands/search.js';\nimport { createServeCommand } from './cli/commands/serve.js';\nimport { createSetupCommand } from './cli/commands/setup.js';\nimport { createStoreCommand } from './cli/commands/store.js';\nimport { createSyncCommand } from './cli/commands/sync.js';\nimport { createProgram, getGlobalOptions } from './cli/program.js';\n\n// Register built-in language adapters\nconst registry = AdapterRegistry.getInstance();\nregistry.register(new ZilAdapter());\n\n// Default paths\nconst DEFAULT_DATA_DIR = join(homedir(), '.bluera', 'bluera-knowledge', 'data');\nconst DEFAULT_CONFIG = join(homedir(), '.bluera', 'bluera-knowledge', 'config.json');\nconst DEFAULT_REPOS_DIR = join(homedir(), '.bluera', 'bluera-knowledge', 'repos');\n\n/**\n * Format a command and its subcommands recursively for comprehensive help output.\n */\nfunction formatCommandHelp(cmd: Command, indent: string = ''): string[] {\n const lines: string[] = [];\n const name = cmd.name();\n const desc = cmd.description();\n const args = cmd.registeredArguments\n .map((a) => {\n const req = a.required;\n return req ? `<${a.name()}>` : `[${a.name()}]`;\n })\n .join(' ');\n\n // Command header with arguments\n lines.push(`${indent}${name}${args ? ` ${args}` : ''}`);\n if (desc) {\n lines.push(`${indent} ${desc}`);\n }\n\n // Options (skip -h, --help which is auto-added)\n const options = cmd.options.filter((o) => o.flags !== '-h, --help');\n for (const opt of options) {\n lines.push(`${indent} ${opt.flags.padEnd(28)} ${opt.description}`);\n }\n\n // Subcommands (recursive)\n const subcommands = cmd.commands.filter((c) => c.name() !== 'help');\n for (const sub of subcommands) {\n lines.push('');\n lines.push(...formatCommandHelp(sub, `${indent} `));\n }\n\n return lines;\n}\n\n/**\n * Print comprehensive help showing all commands, subcommands, and options.\n */\nfunction printFullHelp(program: Command): void {\n console.log('bluera-knowledge - CLI tool for managing knowledge stores with semantic search\\n');\n\n // Active paths\n console.log('Paths:');\n console.log(` data ${DEFAULT_DATA_DIR}`);\n console.log(` config ${DEFAULT_CONFIG}`);\n console.log(` repos ${DEFAULT_REPOS_DIR}`);\n\n // Global options\n console.log('\\nGlobal options:');\n const globalOpts = program.options.filter(\n (o) => o.flags !== '-h, --help' && o.flags !== '-V, --version'\n );\n for (const opt of globalOpts) {\n console.log(` ${opt.flags.padEnd(28)} ${opt.description}`);\n }\n\n console.log('\\nCommands:\\n');\n\n // All commands except help\n const commands = program.commands.filter((c) => c.name() !== 'help');\n for (const cmd of commands) {\n console.log(formatCommandHelp(cmd).join('\\n'));\n console.log('');\n }\n}\n\nconst program = createProgram();\n\n// Plugin API commands (simple interface)\nprogram.addCommand(createAddRepoCommand(() => getGlobalOptions(program)));\nprogram.addCommand(createAddFolderCommand(() => getGlobalOptions(program)));\nprogram.addCommand(createStoresCommand(() => getGlobalOptions(program)));\nprogram.addCommand(createSuggestCommand(() => getGlobalOptions(program)));\n\n// Advanced CLI commands\nprogram.addCommand(createStoreCommand(() => getGlobalOptions(program)));\nprogram.addCommand(createSearchCommand(() => getGlobalOptions(program)));\nprogram.addCommand(createIndexCommand(() => getGlobalOptions(program)));\nprogram.addCommand(createServeCommand(() => getGlobalOptions(program)));\nprogram.addCommand(createCrawlCommand(() => getGlobalOptions(program)));\nprogram.addCommand(createSetupCommand(() => getGlobalOptions(program)));\nprogram.addCommand(createSyncCommand(() => getGlobalOptions(program)));\nprogram.addCommand(createMCPCommand(() => getGlobalOptions(program)));\n\n// Show comprehensive help when no arguments provided\nif (process.argv.length <= 2) {\n printFullHelp(program);\n process.exit(0);\n}\n\nprogram.parse();\n","import { createHash } from 'node:crypto';\nimport { Command } from 'commander';\nimport ora, { type Ora } from 'ora';\nimport { IntelligentCrawler, type CrawlProgress } from '../../crawl/intelligent-crawler.js';\nimport { ChunkingService } from '../../services/chunking.service.js';\nimport { createServices, destroyServices } from '../../services/index.js';\nimport { classifyWebContentType } from '../../services/index.service.js';\nimport { createDocumentId } from '../../types/brands.js';\nimport type { Document } from '../../types/document.js';\nimport type { WebStore } from '../../types/store.js';\nimport type { GlobalOptions } from '../program.js';\n\nexport function createCrawlCommand(getOptions: () => GlobalOptions): Command {\n return new Command('crawl')\n .description('Crawl web pages with natural language control and index into store')\n .argument('<url>', 'URL to crawl')\n .argument('<store>', 'Target web store to add crawled content to')\n .option(\n '--crawl <instruction>',\n 'Natural language instruction for what to crawl (e.g., \"all Getting Started pages\")'\n )\n .option(\n '--extract <instruction>',\n 'Natural language instruction for what to extract (e.g., \"extract API references\")'\n )\n .option('--simple', 'Use simple BFS mode instead of intelligent crawling')\n .option('--max-pages <number>', 'Maximum number of pages to crawl', '50')\n .option('--fast', 'Use fast axios-only mode (may fail on JavaScript-heavy sites)')\n .action(\n async (\n url: string,\n storeIdOrName: string,\n cmdOptions: {\n crawl?: string;\n extract?: string;\n simple?: boolean;\n maxPages?: string;\n fast?: boolean;\n }\n ) => {\n const globalOpts = getOptions();\n const services = await createServices(globalOpts.config, globalOpts.dataDir);\n\n // Look up or auto-create web store\n let store: WebStore;\n let storeCreated = false;\n const existingStore = await services.store.getByIdOrName(storeIdOrName);\n\n if (!existingStore) {\n // Auto-create web store\n const result = await services.store.create({\n name: storeIdOrName,\n type: 'web',\n url,\n });\n if (!result.success) {\n await destroyServices(services);\n throw new Error(`Failed to create store: ${result.error.message}`);\n }\n // Type narrowing: success check above ensures result.data is Store\n // We know it's a WebStore because we created it with type: 'web'\n const createdStore = result.data;\n if (createdStore.type !== 'web') {\n throw new Error('Unexpected store type after creation');\n }\n store = createdStore;\n storeCreated = true;\n if (globalOpts.quiet !== true && globalOpts.format !== 'json') {\n console.log(`Created web store: ${store.name}`);\n }\n } else if (existingStore.type !== 'web') {\n await destroyServices(services);\n throw new Error(\n `Store \"${storeIdOrName}\" exists but is not a web store (type: ${existingStore.type})`\n );\n } else {\n store = existingStore;\n }\n\n const maxPages = cmdOptions.maxPages !== undefined ? parseInt(cmdOptions.maxPages, 10) : 50;\n\n // Use spinner in interactive mode\n const isInteractive =\n process.stdout.isTTY && globalOpts.quiet !== true && globalOpts.format !== 'json';\n let spinner: Ora | undefined;\n\n if (isInteractive) {\n const mode = cmdOptions.simple === true ? 'simple' : 'intelligent';\n spinner = ora(`Crawling ${url} (${mode} mode)`).start();\n } else if (globalOpts.quiet !== true && globalOpts.format !== 'json') {\n console.log(`Crawling ${url}`);\n }\n\n const crawler = new IntelligentCrawler();\n // Use web preset for larger prose-friendly chunks\n const webChunker = ChunkingService.forContentType('web');\n let pagesIndexed = 0;\n let chunksCreated = 0;\n let exitCode = 0;\n\n // Listen for progress events\n crawler.on('progress', (progress: CrawlProgress) => {\n if (spinner) {\n if (progress.type === 'strategy') {\n spinner.text = progress.message ?? 'Analyzing crawl strategy...';\n } else if (progress.type === 'page') {\n const url = progress.currentUrl ?? 'unknown';\n spinner.text = `Crawling ${String(progress.pagesVisited + 1)}/${String(maxPages)} - ${url}`;\n } else if (progress.type === 'extraction') {\n const url = progress.currentUrl ?? 'unknown';\n spinner.text = `Extracting from ${url}...`;\n } else if (progress.type === 'error' && progress.message !== undefined) {\n spinner.warn(progress.message);\n }\n }\n });\n\n try {\n await services.lance.initialize(store.id);\n const docs: Document[] = [];\n\n // Crawl pages using IntelligentCrawler\n for await (const result of crawler.crawl(url, {\n ...(cmdOptions.crawl !== undefined && { crawlInstruction: cmdOptions.crawl }),\n ...(cmdOptions.extract !== undefined && { extractInstruction: cmdOptions.extract }),\n maxPages,\n ...(cmdOptions.simple !== undefined && { simple: cmdOptions.simple }),\n useHeadless: !(cmdOptions.fast ?? false), // Default true (headless), --fast disables\n })) {\n // Use extracted content if available, otherwise markdown\n const contentToProcess = result.extracted ?? result.markdown;\n\n // Chunk the content using markdown-aware chunking (web content is converted to markdown)\n const chunks = webChunker.chunk(contentToProcess, `${result.url}.md`);\n const fileType = classifyWebContentType(result.url, result.title);\n const urlHash = createHash('md5').update(result.url).digest('hex');\n\n for (const chunk of chunks) {\n const chunkId =\n chunks.length > 1\n ? `${store.id}-${urlHash}-${String(chunk.chunkIndex)}`\n : `${store.id}-${urlHash}`;\n const vector = await services.embeddings.embed(chunk.content);\n\n docs.push({\n id: createDocumentId(chunkId),\n content: chunk.content,\n vector,\n metadata: {\n type: chunks.length > 1 ? 'chunk' : 'web',\n storeId: store.id,\n url: result.url,\n title: result.title,\n extracted: result.extracted !== undefined,\n depth: result.depth,\n indexedAt: new Date(),\n fileType,\n chunkIndex: chunk.chunkIndex,\n totalChunks: chunk.totalChunks,\n sectionHeader: chunk.sectionHeader,\n },\n });\n chunksCreated++;\n }\n\n pagesIndexed++;\n }\n\n // Index all documents\n if (docs.length > 0) {\n if (spinner) {\n spinner.text = 'Indexing documents...';\n }\n await services.lance.addDocuments(store.id, docs);\n // Create FTS index for full-text search\n await services.lance.createFtsIndex(store.id);\n }\n\n const crawlResult = {\n success: true,\n store: store.name,\n storeCreated,\n url,\n pagesCrawled: pagesIndexed,\n chunksCreated,\n mode: cmdOptions.simple === true ? 'simple' : 'intelligent',\n hadCrawlInstruction: cmdOptions.crawl !== undefined,\n hadExtractInstruction: cmdOptions.extract !== undefined,\n };\n\n if (globalOpts.format === 'json') {\n console.log(JSON.stringify(crawlResult, null, 2));\n } else if (spinner !== undefined) {\n spinner.succeed(\n `Crawled ${String(pagesIndexed)} pages, indexed ${String(chunksCreated)} chunks`\n );\n } else if (globalOpts.quiet !== true) {\n console.log(\n `Crawled ${String(pagesIndexed)} pages, indexed ${String(chunksCreated)} chunks`\n );\n }\n } catch (error) {\n const message = `Crawl failed: ${error instanceof Error ? error.message : String(error)}`;\n if (spinner) {\n spinner.fail(message);\n } else {\n console.error(`Error: ${message}`);\n }\n exitCode = 6;\n } finally {\n await crawler.stop();\n await destroyServices(services);\n }\n\n if (exitCode !== 0) {\n process.exit(exitCode);\n }\n }\n );\n}\n","import { Command } from 'commander';\nimport ora, { type Ora } from 'ora';\nimport { createServices, destroyServices } from '../../services/index.js';\nimport type { GlobalOptions } from '../program.js';\n\nexport function createIndexCommand(getOptions: () => GlobalOptions): Command {\n const index = new Command('index')\n .description('Scan store files, chunk text, generate embeddings, save to LanceDB')\n .argument('<store>', 'Store ID or name')\n .option('--force', 'Re-index all files even if unchanged')\n .action(async (storeIdOrName: string, _options: { force?: boolean }) => {\n const globalOpts = getOptions();\n const services = await createServices(globalOpts.config, globalOpts.dataDir);\n let exitCode = 0;\n try {\n indexLogic: {\n const store = await services.store.getByIdOrName(storeIdOrName);\n\n if (store === undefined) {\n console.error(`Error: Store not found: ${storeIdOrName}`);\n exitCode = 3;\n\n break indexLogic;\n }\n\n // Use spinner in interactive mode (not quiet, not json output)\n const isInteractive =\n process.stdout.isTTY && globalOpts.quiet !== true && globalOpts.format !== 'json';\n let spinner: Ora | undefined;\n\n if (isInteractive) {\n spinner = ora(`Indexing store: ${store.name}`).start();\n } else if (globalOpts.quiet !== true && globalOpts.format !== 'json') {\n console.log(`Indexing store: ${store.name}`);\n }\n\n await services.lance.initialize(store.id);\n\n const result = await services.index.indexStore(store, (event) => {\n if (event.type === 'progress') {\n if (spinner) {\n spinner.text = `Indexing: ${String(event.current)}/${String(event.total)} files - ${event.message}`;\n }\n }\n });\n\n if (result.success) {\n if (globalOpts.format === 'json') {\n console.log(JSON.stringify(result.data, null, 2));\n } else {\n const message = `Indexed ${String(result.data.documentsIndexed)} documents, ${String(result.data.chunksCreated)} chunks in ${String(result.data.timeMs)}ms`;\n if (spinner !== undefined) {\n spinner.succeed(message);\n } else if (globalOpts.quiet !== true) {\n console.log(message);\n }\n }\n } else {\n const message = `Error: ${result.error.message}`;\n if (spinner !== undefined) {\n spinner.fail(message);\n } else {\n console.error(message);\n }\n exitCode = 4;\n\n break indexLogic;\n }\n }\n } finally {\n await destroyServices(services);\n }\n\n if (exitCode !== 0) {\n process.exit(exitCode);\n }\n });\n\n index\n .command('watch <store>')\n .description('Watch store directory; re-index when files change')\n .option(\n '--debounce <ms>',\n 'Wait N ms after last change before re-indexing (default: 1000)',\n '1000'\n )\n .action(async (storeIdOrName: string, options: { debounce?: string }) => {\n const globalOpts = getOptions();\n const services = await createServices(globalOpts.config, globalOpts.dataDir);\n\n const store = await services.store.getByIdOrName(storeIdOrName);\n if (store === undefined || (store.type !== 'file' && store.type !== 'repo')) {\n console.error(`Error: File/repo store not found: ${storeIdOrName}`);\n process.exit(3);\n }\n\n const { WatchService } = await import('../../services/watch.service.js');\n const watchService = new WatchService(services.index, services.lance);\n\n if (globalOpts.quiet !== true) {\n console.log(`Watching ${store.name} for changes...`);\n }\n await watchService.watch(\n store,\n parseInt(options.debounce ?? '1000', 10),\n () => {\n if (globalOpts.quiet !== true) {\n console.log(`Re-indexed ${store.name}`);\n }\n },\n (error: Error) => {\n console.error(`Watch error: ${error.message}`);\n }\n );\n\n // Keep process alive\n process.on('SIGINT', () => {\n void (async (): Promise<void> => {\n await watchService.unwatchAll();\n process.exit(0);\n })().catch(() => {\n // Error during shutdown - process.exit already called\n });\n });\n });\n\n return index;\n}\n","import { Command } from 'commander';\nimport { runMCPServer } from '../../mcp/server.js';\nimport type { GlobalOptions } from '../program.js';\n\nexport function createMCPCommand(getOptions: () => GlobalOptions): Command {\n const mcp = new Command('mcp')\n .description('Start MCP (Model Context Protocol) server for AI agent integration')\n .action(async () => {\n const opts = getOptions();\n\n await runMCPServer({\n dataDir: opts.dataDir,\n config: opts.config,\n });\n });\n\n return mcp;\n}\n","import { Command } from 'commander';\nimport {\n handleAddRepo,\n handleAddFolder,\n handleStores,\n handleSuggest,\n} from '../../plugin/commands.js';\nimport type { GlobalOptions } from '../program.js';\n\n/**\n * CLI commands that mirror the plugin API for consistency.\n * These commands provide a simpler interface that matches the plugin commands.\n */\n\nexport function createAddRepoCommand(getOptions: () => GlobalOptions): Command {\n return new Command('add-repo')\n .description('Clone and index a library source repository')\n .argument('<url>', 'Git repository URL')\n .option('--name <name>', 'Store name (defaults to repo name)')\n .option('--branch <branch>', 'Git branch to clone')\n .action(async (url: string, options: { name?: string; branch?: string }) => {\n const globalOpts = getOptions();\n await handleAddRepo(\n { url, ...options },\n {\n config: globalOpts.config,\n dataDir: globalOpts.dataDir,\n projectRoot: globalOpts.projectRoot,\n format: globalOpts.format,\n quiet: globalOpts.quiet,\n }\n );\n });\n}\n\nexport function createAddFolderCommand(getOptions: () => GlobalOptions): Command {\n return new Command('add-folder')\n .description('Index a local folder of reference material')\n .argument('<path>', 'Folder path to index')\n .option('--name <name>', 'Store name (defaults to folder name)')\n .action(async (path: string, options: { name?: string }) => {\n const globalOpts = getOptions();\n await handleAddFolder(\n { path, ...options },\n {\n config: globalOpts.config,\n dataDir: globalOpts.dataDir,\n projectRoot: globalOpts.projectRoot,\n format: globalOpts.format,\n quiet: globalOpts.quiet,\n }\n );\n });\n}\n\nexport function createStoresCommand(getOptions: () => GlobalOptions): Command {\n return new Command('stores').description('List all indexed library stores').action(async () => {\n const globalOpts = getOptions();\n await handleStores({\n config: globalOpts.config,\n dataDir: globalOpts.dataDir,\n projectRoot: globalOpts.projectRoot,\n format: globalOpts.format,\n quiet: globalOpts.quiet,\n });\n });\n}\n\nexport function createSuggestCommand(getOptions: () => GlobalOptions): Command {\n return new Command('suggest')\n .description('Suggest important dependencies to add to knowledge stores')\n .action(async () => {\n const globalOpts = getOptions();\n await handleSuggest({\n config: globalOpts.config,\n dataDir: globalOpts.dataDir,\n projectRoot: globalOpts.projectRoot,\n format: globalOpts.format,\n quiet: globalOpts.quiet,\n });\n });\n}\n","import ora from 'ora';\nimport { extractRepoName } from './git-clone.js';\nimport { DependencyUsageAnalyzer } from '../analysis/dependency-usage-analyzer.js';\nimport { RepoUrlResolver } from '../analysis/repo-url-resolver.js';\nimport { createServices, destroyServices } from '../services/index.js';\n\n/**\n * Options passed from CLI global options to plugin command handlers.\n */\nexport interface CommandOptions {\n config?: string | undefined;\n dataDir?: string | undefined;\n projectRoot?: string | undefined;\n format?: 'json' | 'table' | 'plain' | undefined;\n quiet?: boolean | undefined;\n}\n\nexport async function handleSearch(args: {\n query: string;\n stores?: string;\n limit?: string;\n}): Promise<void> {\n // PWD is set by Claude Code to user's project directory\n const services = await createServices(undefined, undefined, process.env['PWD']);\n\n try {\n const storeNames = args.stores?.split(',').map((s: string) => s.trim());\n\n const allStores = await services.store.list();\n const targetStores =\n storeNames !== undefined ? allStores.filter((s) => storeNames.includes(s.name)) : allStores;\n\n if (targetStores.length === 0) {\n console.error('No stores found to search');\n process.exit(1);\n }\n\n // Initialize stores\n for (const store of targetStores) {\n await services.lance.initialize(store.id);\n }\n\n const results = await services.search.search({\n query: args.query,\n stores: targetStores.map((s) => s.id),\n mode: 'hybrid',\n limit: parseInt(args.limit ?? '10', 10),\n detail: 'contextual',\n });\n\n console.log(`Found ${String(results.totalResults)} results:\\n`);\n for (const r of results.results) {\n if (r.summary !== undefined) {\n console.log(`Score: ${r.score.toFixed(2)} - ${r.summary.location}`);\n console.log(r.summary.purpose);\n }\n console.log('---');\n }\n } finally {\n await destroyServices(services);\n }\n}\n\nexport async function handleAddRepo(\n args: {\n url: string;\n name?: string;\n branch?: string;\n },\n options: CommandOptions = {}\n): Promise<void> {\n const services = await createServices(\n options.config,\n options.dataDir,\n options.projectRoot ?? process.env['PWD']\n );\n\n try {\n const storeName = args.name ?? extractRepoName(args.url);\n\n console.log(`Cloning ${args.url}...`);\n\n const result = await services.store.create({\n name: storeName,\n type: 'repo',\n url: args.url,\n ...(args.branch !== undefined ? { branch: args.branch } : {}),\n });\n\n if (!result.success) {\n console.error(`Error: ${result.error.message}`);\n process.exit(1);\n }\n\n console.log(`Created store: ${storeName} (${result.data.id})`);\n if ('path' in result.data) {\n console.log(`Location: ${result.data.path}`);\n }\n\n // Auto-index\n console.log('\\nIndexing...');\n const indexResult = await services.index.indexStore(result.data);\n\n if (indexResult.success) {\n console.log(`Indexed ${String(indexResult.data.documentsIndexed)} files`);\n } else {\n console.error(`Indexing failed: ${indexResult.error.message}`);\n }\n } finally {\n await destroyServices(services);\n }\n}\n\nexport async function handleAddFolder(\n args: { path: string; name?: string },\n options: CommandOptions = {}\n): Promise<void> {\n const services = await createServices(\n options.config,\n options.dataDir,\n options.projectRoot ?? process.env['PWD']\n );\n\n try {\n const { basename } = await import('node:path');\n const storeName = args.name ?? basename(args.path);\n\n console.log(`Adding folder: ${args.path}...`);\n\n const result = await services.store.create({\n name: storeName,\n type: 'file',\n path: args.path,\n });\n\n if (!result.success) {\n console.error(`Error: ${result.error.message}`);\n process.exit(1);\n }\n\n console.log(`Created store: ${storeName} (${result.data.id})`);\n if ('path' in result.data) {\n console.log(`Location: ${result.data.path}`);\n }\n\n // Auto-index\n console.log('\\nIndexing...');\n const indexResult = await services.index.indexStore(result.data);\n\n if (indexResult.success) {\n console.log(`Indexed ${String(indexResult.data.documentsIndexed)} files`);\n } else {\n console.error(`Indexing failed: ${indexResult.error.message}`);\n }\n } finally {\n await destroyServices(services);\n }\n}\n\nexport async function handleIndex(args: { store: string }): Promise<void> {\n // PWD is set by Claude Code to user's project directory\n const services = await createServices(undefined, undefined, process.env['PWD']);\n\n try {\n const store = await services.store.getByIdOrName(args.store);\n\n if (store === undefined) {\n console.error(`Store not found: ${args.store}`);\n process.exit(1);\n }\n\n console.log(`Indexing ${store.name}...`);\n const result = await services.index.indexStore(store);\n\n if (result.success) {\n console.log(\n `Indexed ${String(result.data.documentsIndexed)} documents in ${String(result.data.timeMs)}ms`\n );\n } else {\n console.error(`Error: ${result.error.message}`);\n process.exit(1);\n }\n } finally {\n await destroyServices(services);\n }\n}\n\nexport async function handleStores(options: CommandOptions = {}): Promise<void> {\n const services = await createServices(\n options.config,\n options.dataDir,\n options.projectRoot ?? process.env['PWD']\n );\n\n try {\n const stores = await services.store.list();\n\n if (stores.length === 0) {\n console.log('No stores found.');\n console.log('\\nCreate a store with:');\n console.log(' /bluera-knowledge:add-repo <url> --name=<name>');\n console.log(' /bluera-knowledge:add-folder <path> --name=<name>');\n return;\n }\n\n // Table header\n console.log('| Name | Type | ID | Source |');\n console.log('|------|------|----|--------------------|');\n\n // Table rows\n for (const store of stores) {\n const name = store.name;\n const type = store.type;\n const id = store.id;\n let source = '';\n\n if ('url' in store && store.url !== undefined) {\n source = store.url;\n } else if ('path' in store) {\n source = store.path;\n }\n\n console.log(`| ${name} | ${type} | ${id.substring(0, 8)}... | ${source} |`);\n }\n } finally {\n await destroyServices(services);\n }\n}\n\nexport async function handleSuggest(options: CommandOptions = {}): Promise<void> {\n const projectRoot = options.projectRoot ?? process.env['PWD'] ?? process.cwd();\n\n console.log('Analyzing project dependencies...\\n');\n\n // Create analyzer instance\n const services = await createServices(options.config, options.dataDir, projectRoot);\n\n try {\n const analyzer = new DependencyUsageAnalyzer();\n const resolver = new RepoUrlResolver();\n\n // Analyze with progress indicator\n const spinner = ora('Scanning source files...').start();\n\n const result = await analyzer.analyze(projectRoot, (current, total, message) => {\n spinner.text = `${message} (${String(current)}/${String(total)})`;\n });\n\n spinner.stop();\n\n if (!result.success) {\n console.error(`Error: ${result.error.message}`);\n process.exit(1);\n }\n\n const { usages, totalFilesScanned, skippedFiles } = result.data;\n\n console.log(\n `✔ Scanned ${String(totalFilesScanned)} files${skippedFiles > 0 ? ` (skipped ${String(skippedFiles)})` : ''}\\n`\n );\n\n if (usages.length === 0) {\n console.log('No external dependencies found in this project.');\n console.log('\\nMake sure you have a package.json or requirements.txt file.');\n return;\n }\n\n // Filter out packages already in stores\n const existingStores = await services.store.list();\n const existingRepoNames = new Set(existingStores.map((s) => s.name));\n\n const newUsages = usages.filter((u) => !existingRepoNames.has(u.packageName));\n\n if (newUsages.length === 0) {\n console.log('✔ All dependencies are already in knowledge stores!');\n return;\n }\n\n // Show top 5 suggestions\n const topSuggestions = newUsages.slice(0, 5);\n\n console.log('Top dependencies by usage in this project:\\n');\n topSuggestions.forEach((usage, i) => {\n console.log(`${String(i + 1)}. ${usage.packageName}`);\n console.log(\n ` ${String(usage.importCount)} imports across ${String(usage.fileCount)} files\\n`\n );\n });\n\n console.log('Searching for repository URLs...\\n');\n\n // For each package, find repo URL\n for (const usage of topSuggestions) {\n const repoResult = await resolver.findRepoUrl(usage.packageName, usage.language);\n\n if (repoResult.url !== null) {\n console.log(`✔ ${usage.packageName}: ${repoResult.url}`);\n console.log(` /bluera-knowledge:add-repo ${repoResult.url} --name=${usage.packageName}\\n`);\n } else {\n console.log(`✗ ${usage.packageName}: Could not find repository URL`);\n console.log(\n ` You can manually add it: /bluera-knowledge:add-repo <url> --name=${usage.packageName}\\n`\n );\n }\n }\n\n console.log('Use the commands above to add repositories to your knowledge stores.');\n } finally {\n await destroyServices(services);\n }\n}\n","import { existsSync } from 'node:fs';\nimport { readFile, readdir } from 'node:fs/promises';\nimport { join, extname } from 'node:path';\nimport { ASTParser } from './ast-parser.js';\nimport { ok, err } from '../types/result.js';\nimport type { SupportedLanguage } from './repo-url-resolver.js';\nimport type { Result } from '../types/result.js';\n\nconst TEXT_EXTENSIONS = new Set([\n '.ts',\n '.tsx',\n '.js',\n '.jsx',\n '.mjs',\n '.cjs',\n '.py',\n '.rb',\n '.go',\n '.java',\n '.rs',\n '.php',\n '.md',\n '.txt',\n '.json',\n '.yml',\n '.yaml',\n '.toml',\n]);\n\nexport interface PackageUsage {\n packageName: string;\n importCount: number;\n fileCount: number;\n files: string[];\n isDevDependency: boolean;\n language: SupportedLanguage;\n}\n\nexport interface DependencyAnalysisResult {\n usages: PackageUsage[];\n totalFilesScanned: number;\n skippedFiles: number;\n analysisTimeMs: number;\n}\n\ninterface DeclaredDependency {\n name: string;\n isDev: boolean;\n language: SupportedLanguage;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport class DependencyUsageAnalyzer {\n private readonly astParser: ASTParser;\n\n constructor() {\n this.astParser = new ASTParser();\n }\n\n async analyze(\n projectRoot: string,\n onProgress?: (current: number, total: number, message: string) => void\n ): Promise<Result<DependencyAnalysisResult>> {\n const startTime = Date.now();\n\n try {\n // 1. Read declared dependencies from package.json/requirements.txt\n const declaredDeps = await this.readDeclaredDependencies(projectRoot);\n\n if (declaredDeps.size === 0) {\n return ok({\n usages: [],\n totalFilesScanned: 0,\n skippedFiles: 0,\n analysisTimeMs: Date.now() - startTime,\n });\n }\n\n // 2. Scan all source files\n const files = await this.scanDirectory(projectRoot);\n\n if (files.length === 0) {\n return ok({\n usages: [],\n totalFilesScanned: 0,\n skippedFiles: 0,\n analysisTimeMs: Date.now() - startTime,\n });\n }\n\n // 3. Count imports for each package\n const usageMap = new Map<string, PackageUsage>();\n let processedCount = 0;\n let skippedCount = 0;\n\n for (const filePath of files) {\n try {\n const content = await readFile(filePath, 'utf-8');\n const imports = this.extractImportsForFile(filePath, content);\n\n for (const importInfo of imports) {\n const packageName = this.extractPackageName(importInfo.source);\n\n if (packageName !== null && declaredDeps.has(packageName)) {\n const dep = declaredDeps.get(packageName);\n if (dep !== undefined) {\n this.incrementUsage(usageMap, packageName, filePath, dep.isDev, dep.language);\n }\n }\n }\n\n processedCount++;\n if (onProgress !== undefined && processedCount % 10 === 0) {\n onProgress(\n processedCount,\n files.length,\n `Analyzed ${String(processedCount)}/${String(files.length)} files`\n );\n }\n } catch {\n // Skip files that can't be read or parsed\n skippedCount++;\n }\n }\n\n // 4. Sort by usage frequency\n const sortedUsages = Array.from(usageMap.values()).sort(\n (a, b) => b.importCount - a.importCount\n );\n\n return ok({\n usages: sortedUsages,\n totalFilesScanned: processedCount,\n skippedFiles: skippedCount,\n analysisTimeMs: Date.now() - startTime,\n });\n } catch (error) {\n const errorObj = new Error(\n error instanceof Error ? error.message : 'Unknown error during analysis'\n );\n errorObj.name = 'ANALYSIS_ERROR';\n return err(errorObj);\n }\n }\n\n private extractPackageName(importSource: string): string | null {\n // Relative imports (./foo, ../bar, /absolute) -> null\n if (importSource.startsWith('.') || importSource.startsWith('/')) {\n return null;\n }\n\n // Node built-ins (node:fs, node:path) -> null\n if (importSource.startsWith('node:')) {\n return null;\n }\n\n // Scoped packages: @org/package/path -> @org/package\n if (importSource.startsWith('@')) {\n const parts = importSource.split('/');\n if (parts.length >= 2 && parts[0] !== undefined && parts[1] !== undefined) {\n return `${parts[0]}/${parts[1]}`;\n }\n return null;\n }\n\n // Regular packages: lodash/get -> lodash\n const firstPart = importSource.split('/')[0];\n return firstPart ?? null;\n }\n\n private extractImportsForFile(filePath: string, content: string): Array<{ source: string }> {\n const ext = extname(filePath);\n\n // JavaScript/TypeScript - use AST parser\n if (['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'].includes(ext)) {\n try {\n return this.astParser.extractImports(content);\n } catch {\n // Fallback to regex for malformed files\n return this.extractImportsRegex(content, 'javascript');\n }\n }\n\n // Python - use regex\n if (ext === '.py') {\n return this.extractImportsRegex(content, 'python');\n }\n\n return [];\n }\n\n private extractImportsRegex(\n content: string,\n language: 'javascript' | 'python'\n ): Array<{ source: string }> {\n const imports: Array<{ source: string }> = [];\n\n if (language === 'javascript') {\n // Match: import ... from 'package'\n // Match: require('package')\n const importPattern = /import\\s+.*?from\\s+['\"]([^'\"]+)['\"]/g;\n const requirePattern = /require\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g;\n\n for (const match of content.matchAll(importPattern)) {\n if (match[1] !== undefined) imports.push({ source: match[1] });\n }\n\n for (const match of content.matchAll(requirePattern)) {\n if (match[1] !== undefined) imports.push({ source: match[1] });\n }\n } else {\n // Match: import package\n // Match: from package import ...\n const importPattern = /^import\\s+([a-zA-Z0-9_]+)/gm;\n const fromPattern = /^from\\s+([a-zA-Z0-9_]+)/gm;\n\n for (const match of content.matchAll(importPattern)) {\n if (match[1] !== undefined) imports.push({ source: match[1] });\n }\n\n for (const match of content.matchAll(fromPattern)) {\n if (match[1] !== undefined) imports.push({ source: match[1] });\n }\n }\n\n return imports;\n }\n\n private incrementUsage(\n usageMap: Map<string, PackageUsage>,\n packageName: string,\n filePath: string,\n isDevDependency: boolean,\n language: SupportedLanguage\n ): void {\n const existing = usageMap.get(packageName);\n\n if (existing) {\n existing.importCount++;\n if (!existing.files.includes(filePath)) {\n existing.fileCount++;\n existing.files.push(filePath);\n }\n } else {\n usageMap.set(packageName, {\n packageName,\n importCount: 1,\n fileCount: 1,\n files: [filePath],\n isDevDependency,\n language,\n });\n }\n }\n\n private async scanDirectory(dir: string): Promise<string[]> {\n const files: string[] = [];\n\n try {\n const entries = await readdir(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = join(dir, entry.name);\n\n if (entry.isDirectory()) {\n // Skip common ignored directories\n if (\n ![\n 'node_modules',\n '.git',\n 'dist',\n 'build',\n 'coverage',\n '__pycache__',\n '.venv',\n 'venv',\n ].includes(entry.name)\n ) {\n files.push(...(await this.scanDirectory(fullPath)));\n }\n } else if (entry.isFile()) {\n const ext = extname(entry.name);\n if (TEXT_EXTENSIONS.has(ext)) {\n files.push(fullPath);\n }\n }\n }\n } catch {\n // Ignore permission errors\n }\n\n return files;\n }\n\n private async readDeclaredDependencies(\n projectRoot: string\n ): Promise<Map<string, DeclaredDependency>> {\n const deps = new Map<string, DeclaredDependency>();\n\n // Read package.json (Node.js)\n const packageJsonPath = join(projectRoot, 'package.json');\n if (existsSync(packageJsonPath)) {\n try {\n const content = await readFile(packageJsonPath, 'utf-8');\n const parsed: unknown = JSON.parse(content);\n\n if (isRecord(parsed)) {\n // Regular dependencies\n if (isRecord(parsed['dependencies'])) {\n for (const name of Object.keys(parsed['dependencies'])) {\n deps.set(name, { name, isDev: false, language: 'javascript' });\n }\n }\n\n // Dev dependencies\n if (isRecord(parsed['devDependencies'])) {\n for (const name of Object.keys(parsed['devDependencies'])) {\n deps.set(name, { name, isDev: true, language: 'javascript' });\n }\n }\n }\n } catch {\n // Ignore parse errors\n }\n }\n\n // Read requirements.txt (Python)\n const reqPath = join(projectRoot, 'requirements.txt');\n if (existsSync(reqPath)) {\n try {\n const content = await readFile(reqPath, 'utf-8');\n const lines = content.split('\\n');\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed === '' || trimmed.startsWith('#')) continue;\n\n // Parse package name (before ==, >=, etc.)\n const match = /^([a-zA-Z0-9_-]+)/.exec(trimmed);\n if (match?.[1] !== undefined) {\n const name = match[1].toLowerCase();\n deps.set(name, { name, isDev: false, language: 'python' });\n }\n }\n } catch {\n // Ignore errors\n }\n }\n\n // Read pyproject.toml (Python)\n const pyprojectPath = join(projectRoot, 'pyproject.toml');\n if (existsSync(pyprojectPath)) {\n try {\n const content = await readFile(pyprojectPath, 'utf-8');\n // Simple regex extraction (good enough for dependency names)\n const depMatches = content.matchAll(/\"([a-zA-Z0-9_-]+)\"/g);\n\n for (const match of depMatches) {\n if (match[1] !== undefined) {\n const name = match[1].toLowerCase();\n deps.set(name, { name, isDev: false, language: 'python' });\n }\n }\n } catch {\n // Ignore errors\n }\n }\n\n // Read Cargo.toml (Rust)\n const cargoPath = join(projectRoot, 'Cargo.toml');\n if (existsSync(cargoPath)) {\n try {\n const content = await readFile(cargoPath, 'utf-8');\n // Match [dependencies] section entries like: serde = \"1.0\"\n // or serde = { version = \"1.0\", features = [...] }\n const inDepsSection = /\\[dependencies\\]([\\s\\S]*?)(?=\\n\\[|$)/;\n const depsMatch = inDepsSection.exec(content);\n if (depsMatch?.[1] !== undefined) {\n const depsSection = depsMatch[1];\n // Match crate names at start of lines\n const cratePattern = /^([a-zA-Z0-9_-]+)\\s*=/gm;\n for (const match of depsSection.matchAll(cratePattern)) {\n if (match[1] !== undefined) {\n deps.set(match[1], { name: match[1], isDev: false, language: 'rust' });\n }\n }\n }\n\n // Also check [dev-dependencies]\n const inDevDepsSection = /\\[dev-dependencies\\]([\\s\\S]*?)(?=\\n\\[|$)/;\n const devDepsMatch = inDevDepsSection.exec(content);\n if (devDepsMatch?.[1] !== undefined) {\n const devDepsSection = devDepsMatch[1];\n const cratePattern = /^([a-zA-Z0-9_-]+)\\s*=/gm;\n for (const match of devDepsSection.matchAll(cratePattern)) {\n if (match[1] !== undefined) {\n deps.set(match[1], { name: match[1], isDev: true, language: 'rust' });\n }\n }\n }\n } catch {\n // Ignore errors\n }\n }\n\n // Read go.mod (Go)\n const goModPath = join(projectRoot, 'go.mod');\n if (existsSync(goModPath)) {\n try {\n const content = await readFile(goModPath, 'utf-8');\n // Match require blocks and single requires\n // require github.com/gorilla/mux v1.8.0\n // require (\n // github.com/gorilla/mux v1.8.0\n // )\n const requirePattern = /^\\s*([a-zA-Z0-9._/-]+)\\s+v[\\d.]+/gm;\n for (const match of content.matchAll(requirePattern)) {\n if (match[1] !== undefined && !match[1].startsWith('//')) {\n // Go modules use the full path as the name\n deps.set(match[1], { name: match[1], isDev: false, language: 'go' });\n }\n }\n } catch {\n // Ignore errors\n }\n }\n\n return deps;\n }\n}\n","export interface RepoSearchResult {\n url: string | null;\n confidence: 'high' | 'medium' | 'low';\n source: 'registry' | 'search' | 'fallback';\n}\n\n/**\n * Type guard to check if a value is a non-null object\n */\nfunction isObject(value: unknown): value is Record<PropertyKey, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nexport type SupportedLanguage = 'javascript' | 'python' | 'rust' | 'go';\n\nexport class RepoUrlResolver {\n /**\n * Find the GitHub repository URL for a package\n */\n async findRepoUrl(\n packageName: string,\n language: SupportedLanguage = 'javascript'\n ): Promise<RepoSearchResult> {\n // Strategy 1: Try package registry API (fast, accurate)\n let registryUrl: string | null = null;\n\n switch (language) {\n case 'javascript':\n registryUrl = await this.tryNpmRegistry(packageName);\n break;\n case 'python':\n registryUrl = await this.tryPyPiRegistry(packageName);\n break;\n case 'rust':\n registryUrl = await this.tryCratesRegistry(packageName);\n break;\n case 'go':\n registryUrl = await this.tryGoModule(packageName);\n break;\n }\n\n if (registryUrl !== null) {\n return { url: registryUrl, confidence: 'high', source: 'registry' };\n }\n\n // Strategy 2: No URL found\n return { url: null, confidence: 'low', source: 'fallback' };\n }\n\n /**\n * Query NPM registry for package metadata\n */\n private async tryNpmRegistry(packageName: string): Promise<string | null> {\n try {\n const response = await fetch(`https://registry.npmjs.org/${packageName}`);\n\n if (!response.ok) {\n return null;\n }\n\n const data: unknown = await response.json();\n if (!isObject(data)) {\n return null;\n }\n\n // Extract repository URL - safely access nested property\n if ('repository' in data) {\n const repo = data['repository'];\n if (isObject(repo) && 'url' in repo) {\n const urlValue = repo['url'];\n const url = String(urlValue);\n return this.normalizeRepoUrl(url);\n }\n\n if (typeof repo === 'string') {\n return this.normalizeRepoUrl(repo);\n }\n }\n\n return null;\n } catch {\n return null;\n }\n }\n\n /**\n * Query PyPI registry for package metadata\n */\n private async tryPyPiRegistry(packageName: string): Promise<string | null> {\n try {\n const response = await fetch(`https://pypi.org/pypi/${packageName}/json`);\n\n if (!response.ok) {\n return null;\n }\n\n const data: unknown = await response.json();\n if (!isObject(data)) {\n return null;\n }\n\n // Extract repository URL from project URLs\n if ('info' in data) {\n const info = data['info'];\n if (isObject(info) && 'project_urls' in info) {\n const projectUrls = info['project_urls'];\n\n if (isObject(projectUrls)) {\n // Try various common keys\n const urlKeys = ['Source', 'Repository', 'Code', 'Homepage'];\n\n for (const key of urlKeys) {\n if (key in projectUrls) {\n const urlValue = projectUrls[key];\n const url = String(urlValue);\n if (url.includes('github.com')) {\n return this.normalizeRepoUrl(url);\n }\n }\n }\n }\n }\n }\n\n return null;\n } catch {\n return null;\n }\n }\n\n /**\n * Query crates.io registry for Rust crate metadata\n */\n private async tryCratesRegistry(crateName: string): Promise<string | null> {\n try {\n const response = await fetch(`https://crates.io/api/v1/crates/${crateName}`, {\n headers: {\n // crates.io requires a User-Agent header\n 'User-Agent': 'bluera-knowledge (https://github.com/blueraai/bluera-knowledge)',\n },\n });\n\n if (!response.ok) {\n return null;\n }\n\n const data: unknown = await response.json();\n if (!isObject(data)) {\n return null;\n }\n\n // Extract repository URL from crate metadata\n if ('crate' in data) {\n const crate = data['crate'];\n if (isObject(crate) && 'repository' in crate) {\n const repo = crate['repository'];\n if (typeof repo === 'string') {\n return this.normalizeRepoUrl(repo);\n }\n }\n }\n\n return null;\n } catch {\n return null;\n }\n }\n\n /**\n * Resolve Go module to GitHub repository\n * Go modules often use GitHub URLs directly (e.g., github.com/gorilla/mux)\n */\n private async tryGoModule(moduleName: string): Promise<string | null> {\n try {\n // Go modules that start with github.com are already GitHub URLs\n if (moduleName.startsWith('github.com/')) {\n // Extract owner/repo from module path (e.g., github.com/gorilla/mux/v2 -> github.com/gorilla/mux)\n const parts = moduleName.split('/');\n const owner = parts[1];\n const repo = parts[2];\n if (owner !== undefined && repo !== undefined) {\n return `https://github.com/${owner}/${repo}`;\n }\n }\n\n // For other modules, try pkg.go.dev API\n // The pkg.go.dev API returns module info including repository URL\n const response = await fetch(`https://proxy.golang.org/${moduleName}/@latest`, {\n headers: {\n 'User-Agent': 'bluera-knowledge (https://github.com/blueraai/bluera-knowledge)',\n },\n });\n\n if (!response.ok) {\n return null;\n }\n\n // The Go proxy returns module info, but repository URL needs to be inferred\n // from the module path or VCS info. For now, we only support direct GitHub modules.\n // Most popular Go packages use github.com paths anyway.\n return null;\n } catch {\n return null;\n }\n }\n\n /**\n * Normalize various repository URL formats to standard GitHub URL\n */\n private normalizeRepoUrl(url: string): string | null {\n // Remove git+ prefix\n let normalized = url.replace(/^git\\+/, '');\n\n // Remove .git suffix\n normalized = normalized.replace(/\\.git$/, '');\n\n // Convert git:// to https://\n normalized = normalized.replace(/^git:\\/\\//, 'https://');\n\n // Convert ssh:// to https://\n normalized = normalized.replace(/^ssh:\\/\\/git@/, 'https://');\n\n // Convert git@github.com: to https://github.com/\n normalized = normalized.replace(/^git@github\\.com:/, 'https://github.com/');\n\n // Only return if it's a GitHub URL\n if (normalized.includes('github.com')) {\n return normalized;\n }\n\n return null;\n }\n}\n","import { Command } from 'commander';\nimport { createServices, destroyServices } from '../../services/index.js';\nimport type { SearchMode, DetailLevel } from '../../types/search.js';\nimport type { GlobalOptions } from '../program.js';\n\nexport function createSearchCommand(getOptions: () => GlobalOptions): Command {\n const search = new Command('search')\n .description('Search indexed documents using vector similarity + full-text matching')\n .argument('<query>', 'Search query')\n .option(\n '-s, --stores <stores>',\n 'Limit search to specific stores (comma-separated IDs or names)'\n )\n .option(\n '-m, --mode <mode>',\n 'vector (embeddings only), fts (text only), hybrid (both, default)',\n 'hybrid'\n )\n .option('-n, --limit <count>', 'Maximum results to return (default: 10)', '10')\n .option('-t, --threshold <score>', 'Minimum score 0-1; omit low-relevance results')\n .option(\n '--min-relevance <score>',\n 'Minimum raw cosine similarity 0-1; returns empty if no results meet threshold'\n )\n .option('--include-content', 'Show full document content, not just preview snippet')\n .option(\n '--detail <level>',\n 'Context detail: minimal, contextual, full (default: minimal)',\n 'minimal'\n )\n .action(\n async (\n query: string,\n options: {\n stores?: string;\n mode?: SearchMode;\n limit?: string;\n threshold?: string;\n minRelevance?: string;\n includeContent?: boolean;\n detail?: DetailLevel;\n }\n ) => {\n const globalOpts = getOptions();\n const services = await createServices(globalOpts.config, globalOpts.dataDir);\n let exitCode = 0;\n try {\n // Get store IDs\n let storeIds = (await services.store.list()).map((s) => s.id);\n\n searchLogic: {\n if (options.stores !== undefined) {\n const requestedStores = options.stores.split(',').map((s) => s.trim());\n const resolvedStores = [];\n\n for (const requested of requestedStores) {\n const store = await services.store.getByIdOrName(requested);\n if (store !== undefined) {\n resolvedStores.push(store.id);\n } else {\n console.error(`Error: Store not found: ${requested}`);\n exitCode = 3;\n\n break searchLogic;\n }\n }\n\n storeIds = resolvedStores;\n }\n\n if (storeIds.length === 0) {\n console.error('No stores to search. Create a store first.');\n exitCode = 1;\n\n break searchLogic;\n }\n\n // Initialize LanceDB for each store\n for (const storeId of storeIds) {\n await services.lance.initialize(storeId);\n }\n\n const results = await services.search.search({\n query,\n stores: storeIds,\n mode: options.mode ?? 'hybrid',\n limit: parseInt(options.limit ?? '10', 10),\n threshold:\n options.threshold !== undefined ? parseFloat(options.threshold) : undefined,\n minRelevance:\n options.minRelevance !== undefined ? parseFloat(options.minRelevance) : undefined,\n includeContent: options.includeContent,\n detail: options.detail ?? 'minimal',\n });\n\n if (globalOpts.format === 'json') {\n console.log(JSON.stringify(results, null, 2));\n } else if (globalOpts.quiet === true) {\n // Quiet mode: just list matching paths/URLs, one per line\n for (const r of results.results) {\n const path = r.metadata.path ?? r.metadata.url ?? 'unknown';\n console.log(path);\n }\n } else {\n console.log(`\\nSearch: \"${query}\"`);\n\n // Build status line with optional confidence info\n let statusLine = `Mode: ${results.mode} | Detail: ${String(options.detail)} | Stores: ${String(results.stores.length)} | Results: ${String(results.totalResults)} | Time: ${String(results.timeMs)}ms`;\n if (results.confidence !== undefined) {\n statusLine += ` | Confidence: ${results.confidence}`;\n }\n if (results.maxRawScore !== undefined) {\n statusLine += ` | MaxRaw: ${results.maxRawScore.toFixed(3)}`;\n }\n console.log(`${statusLine}\\n`);\n\n if (results.results.length === 0) {\n if (results.confidence === 'low') {\n console.log('No sufficiently relevant results found.\\n');\n } else {\n console.log('No results found.\\n');\n }\n } else {\n for (let i = 0; i < results.results.length; i++) {\n const r = results.results[i];\n if (r === undefined) continue;\n\n if (r.summary) {\n console.log(\n `${String(i + 1)}. [${r.score.toFixed(2)}] ${r.summary.type}: ${r.summary.name}`\n );\n console.log(` ${r.summary.location}`);\n console.log(` ${r.summary.purpose}`);\n\n // Contextual: Show imports, concepts, and usage stats\n if (r.context && options.detail !== 'minimal') {\n if (r.context.keyImports.length > 0) {\n console.log(` Imports: ${r.context.keyImports.slice(0, 3).join(', ')}`);\n }\n if (r.context.relatedConcepts.length > 0) {\n console.log(\n ` Related: ${r.context.relatedConcepts.slice(0, 3).join(', ')}`\n );\n }\n // Show usage stats from code graph\n const { calledBy, calls } = r.context.usage;\n if (calledBy > 0 || calls > 0) {\n console.log(\n ` Usage: Called by ${String(calledBy)} | Calls ${String(calls)}`\n );\n }\n }\n\n // Full: Show complete code and documentation\n if (r.full && options.detail === 'full') {\n if (r.full.completeCode) {\n console.log(` ---`);\n const codeLines = r.full.completeCode.split('\\n');\n console.log(` ${codeLines.slice(0, 10).join('\\n ')}`);\n if (codeLines.length > 10) {\n console.log(` ... (truncated)`);\n }\n }\n if (r.full.documentation) {\n console.log(` Doc: ${r.full.documentation.slice(0, 100)}`);\n }\n }\n\n console.log();\n } else {\n // Display without summary\n const path = r.metadata.path ?? r.metadata.url ?? 'unknown';\n console.log(`${String(i + 1)}. [${r.score.toFixed(2)}] ${path}`);\n const preview =\n r.highlight ??\n r.content.slice(0, 150).replace(/\\n/g, ' ') +\n (r.content.length > 150 ? '...' : '');\n console.log(` ${preview}\\n`);\n }\n }\n }\n }\n }\n } finally {\n await destroyServices(services);\n }\n\n if (exitCode !== 0) {\n // Set exit code and let Node.js exit naturally after event loop drains\n // Using process.exit() causes mutex crashes from native code (LanceDB, tree-sitter)\n process.exitCode = exitCode;\n }\n }\n );\n\n return search;\n}\n","import { serve } from '@hono/node-server';\nimport { Command } from 'commander';\nimport { createApp } from '../../server/app.js';\nimport { createServices, destroyServices } from '../../services/index.js';\nimport type { GlobalOptions } from '../program.js';\n\nexport function createServeCommand(getOptions: () => GlobalOptions): Command {\n return new Command('serve')\n .description('Start HTTP API server for programmatic search access')\n .option('-p, --port <port>', 'Port to listen on (default: 3847)', '3847')\n .option(\n '--host <host>',\n 'Bind address (default: 127.0.0.1, use 0.0.0.0 for all interfaces)',\n '127.0.0.1'\n )\n .action(async (options: { port?: string; host?: string }) => {\n const globalOpts = getOptions();\n const services = await createServices(globalOpts.config, globalOpts.dataDir);\n const app = createApp(services);\n\n const port = parseInt(options.port ?? '3847', 10);\n const host = options.host ?? '127.0.0.1';\n\n // Graceful shutdown handler\n const shutdown = (): void => {\n void (async (): Promise<void> => {\n await destroyServices(services);\n process.exit(0);\n })();\n };\n\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n\n console.log(`Starting server on http://${host}:${String(port)}`);\n\n serve({\n fetch: app.fetch,\n port,\n hostname: host,\n });\n });\n}\n","import { Hono } from 'hono';\nimport { cors } from 'hono/cors';\nimport { z } from 'zod';\nimport { createStoreId } from '../types/brands.js';\nimport type { ServiceContainer } from '../services/index.js';\nimport type { SearchQuery } from '../types/search.js';\n\n// HTTP API validation schemas (consistent with MCP schemas)\nconst CreateStoreBodySchema = z\n .object({\n name: z.string().min(1, 'Store name must be a non-empty string'),\n type: z.enum(['file', 'repo', 'web']),\n path: z.string().min(1).optional(),\n url: z.string().min(1).optional(),\n description: z.string().optional(),\n tags: z.array(z.string()).optional(),\n branch: z.string().optional(),\n depth: z.number().int().positive().optional(),\n })\n .refine(\n (data) => {\n switch (data.type) {\n case 'file':\n return data.path !== undefined;\n case 'web':\n return data.url !== undefined;\n case 'repo':\n return data.path !== undefined || data.url !== undefined;\n }\n },\n {\n message:\n 'Missing required field: file stores need path, web stores need url, repo stores need path or url',\n }\n );\n\nconst SearchBodySchema = z.object({\n query: z.string().min(1, 'Query must be a non-empty string'),\n detail: z.enum(['minimal', 'contextual', 'full']).optional(),\n limit: z.number().int().positive().optional(),\n stores: z.array(z.string()).optional(),\n});\n\nexport function createApp(services: ServiceContainer): Hono {\n const app = new Hono();\n\n app.use('*', cors());\n\n // Health check\n app.get('/health', (c) => c.json({ status: 'ok' }));\n\n // Stores\n app.get('/api/stores', async (c) => {\n const stores = await services.store.list();\n return c.json(stores);\n });\n\n app.post('/api/stores', async (c) => {\n const jsonData: unknown = await c.req.json();\n const parseResult = CreateStoreBodySchema.safeParse(jsonData);\n if (!parseResult.success) {\n return c.json({ error: parseResult.error.issues[0]?.message ?? 'Invalid request body' }, 400);\n }\n const result = await services.store.create(parseResult.data);\n if (result.success) {\n return c.json(result.data, 201);\n }\n return c.json({ error: result.error.message }, 400);\n });\n\n app.get('/api/stores/:id', async (c) => {\n const store = await services.store.getByIdOrName(c.req.param('id'));\n if (!store) return c.json({ error: 'Not found' }, 404);\n return c.json(store);\n });\n\n app.delete('/api/stores/:id', async (c) => {\n const store = await services.store.getByIdOrName(c.req.param('id'));\n if (!store) return c.json({ error: 'Not found' }, 404);\n const result = await services.store.delete(store.id);\n if (result.success) return c.json({ deleted: true });\n return c.json({ error: result.error.message }, 400);\n });\n\n // Search\n app.post('/api/search', async (c) => {\n const jsonData: unknown = await c.req.json();\n const parseResult = SearchBodySchema.safeParse(jsonData);\n if (!parseResult.success) {\n return c.json({ error: parseResult.error.issues[0]?.message ?? 'Invalid request body' }, 400);\n }\n\n const storeIds = (await services.store.list()).map((s) => s.id);\n\n for (const id of storeIds) {\n await services.lance.initialize(id);\n }\n\n // Convert user-provided store strings to StoreIds, or use all stores\n const requestedStores =\n parseResult.data.stores !== undefined\n ? parseResult.data.stores.map((s) => createStoreId(s))\n : storeIds;\n\n const query: SearchQuery = {\n query: parseResult.data.query,\n detail: parseResult.data.detail ?? 'minimal',\n limit: parseResult.data.limit ?? 10,\n stores: requestedStores,\n };\n const results = await services.search.search(query);\n return c.json(results);\n });\n\n // Index\n app.post('/api/stores/:id/index', async (c) => {\n const store = await services.store.getByIdOrName(c.req.param('id'));\n if (!store) return c.json({ error: 'Not found' }, 404);\n\n await services.lance.initialize(store.id);\n const result = await services.index.indexStore(store);\n\n if (result.success) return c.json(result.data);\n return c.json({ error: result.error.message }, 400);\n });\n\n return app;\n}\n","import { spawnSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { mkdir } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { Command } from 'commander';\nimport ora from 'ora';\nimport { DEFAULT_REPOS, type DefaultRepo } from '../../defaults/repos.js';\nimport { createServices, destroyServices } from '../../services/index.js';\nimport type { GlobalOptions } from '../program.js';\n\nconst DEFAULT_REPOS_DIR = join(homedir(), '.bluera', 'bluera-knowledge', 'repos');\n\nexport function createSetupCommand(getOptions: () => GlobalOptions): Command {\n const setup = new Command('setup').description(\n 'Quick-start with pre-configured Claude/Anthropic documentation repos'\n );\n\n setup\n .command('repos')\n .description(\n 'Clone repos to ~/.bluera/bluera-knowledge/repos/, create stores, index all content'\n )\n .option(\n '--repos-dir <path>',\n 'Clone destination (default: ~/.bluera/bluera-knowledge/repos/)',\n DEFAULT_REPOS_DIR\n )\n .option('--skip-clone', \"Don't clone; assume repos already exist locally\")\n .option('--skip-index', \"Clone and create stores but don't index yet\")\n .option('--only <names>', 'Only process matching repos (comma-separated, partial match)')\n .option('--list', 'Print available repos without cloning/indexing')\n .action(\n async (options: {\n reposDir: string;\n skipClone?: boolean;\n skipIndex?: boolean;\n only?: string;\n list?: boolean;\n }) => {\n const globalOpts = getOptions();\n\n // List mode: just show available repos\n if (options.list === true) {\n console.log('\\nDefault repositories:\\n');\n for (const repo of DEFAULT_REPOS) {\n console.log(` ${repo.name}`);\n console.log(` URL: ${repo.url}`);\n console.log(` Description: ${repo.description}`);\n console.log(` Tags: ${repo.tags.join(', ')}`);\n console.log('');\n }\n return;\n }\n\n const services = await createServices(globalOpts.config, globalOpts.dataDir);\n try {\n // Filter repos if --only specified\n let repos: readonly DefaultRepo[] = DEFAULT_REPOS;\n if (options.only !== undefined && options.only !== '') {\n const onlyNames = options.only.split(',').map((n) => n.trim().toLowerCase());\n repos = DEFAULT_REPOS.filter((r) =>\n onlyNames.some((n) => r.name.toLowerCase().includes(n))\n );\n if (repos.length === 0) {\n console.error(`No repos matched: ${options.only}`);\n console.log('Available repos:', DEFAULT_REPOS.map((r) => r.name).join(', '));\n process.exit(1);\n }\n }\n\n console.log(`\\nSetting up ${String(repos.length)} repositories...\\n`);\n\n // Ensure repos directory exists\n await mkdir(options.reposDir, { recursive: true });\n\n for (const repo of repos) {\n const repoPath = join(options.reposDir, repo.name);\n const spinner = ora(`Processing ${repo.name}`).start();\n\n try {\n // Step 1: Clone if needed\n if (options.skipClone !== true) {\n if (existsSync(repoPath)) {\n spinner.text = `${repo.name}: Already cloned, pulling latest...`;\n const pullResult = spawnSync('git', ['pull', '--ff-only'], {\n cwd: repoPath,\n stdio: 'pipe',\n });\n if (pullResult.status !== 0) {\n // Pull failed (maybe diverged), that's okay\n spinner.text = `${repo.name}: Pull skipped (local changes)`;\n }\n } else {\n spinner.text = `${repo.name}: Cloning...`;\n const cloneResult = spawnSync('git', ['clone', repo.url, repoPath], {\n stdio: 'pipe',\n });\n if (cloneResult.status !== 0) {\n const errorMessage =\n cloneResult.stderr.length > 0\n ? cloneResult.stderr.toString()\n : 'Git clone failed';\n throw new Error(errorMessage);\n }\n }\n }\n\n // Step 2: Create store if needed\n spinner.text = `${repo.name}: Creating store...`;\n const existingStore = await services.store.getByIdOrName(repo.name);\n\n let storeId: string;\n if (existingStore) {\n storeId = existingStore.id;\n spinner.text = `${repo.name}: Store already exists`;\n } else {\n const result = await services.store.create({\n name: repo.name,\n type: 'repo',\n path: repoPath,\n description: repo.description,\n tags: repo.tags,\n });\n\n if (!result.success) {\n throw new Error(\n result.error instanceof Error ? result.error.message : String(result.error)\n );\n }\n storeId = result.data.id;\n }\n\n // Step 3: Index if needed\n if (options.skipIndex !== true) {\n spinner.text = `${repo.name}: Indexing...`;\n const store = await services.store.getByIdOrName(storeId);\n if (store) {\n await services.lance.initialize(store.id);\n const indexResult = await services.index.indexStore(store, (event) => {\n if (event.type === 'progress') {\n spinner.text = `${repo.name}: Indexing ${String(event.current)}/${String(event.total)} files`;\n }\n });\n\n if (indexResult.success) {\n spinner.succeed(\n `${repo.name}: ${String(indexResult.data.documentsIndexed)} docs, ${String(indexResult.data.chunksCreated)} chunks`\n );\n } else {\n throw new Error(\n indexResult.error instanceof Error\n ? indexResult.error.message\n : String(indexResult.error)\n );\n }\n }\n } else {\n spinner.succeed(`${repo.name}: Ready (indexing skipped)`);\n }\n } catch (error) {\n spinner.fail(\n `${repo.name}: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n console.log('\\nSetup complete! Use \"bluera-knowledge search <query>\" to search.\\n');\n } finally {\n await destroyServices(services);\n }\n }\n );\n\n return setup;\n}\n","/**\n * Default repositories for quick setup.\n * These are Anthropic/Claude-related repositories that provide\n * useful knowledge for Claude Code development.\n */\n\nexport interface DefaultRepo {\n /** Git URL for cloning */\n url: string;\n /** Friendly name for the store */\n name: string;\n /** Description of what this repo contains */\n description: string;\n /** Tags for categorization */\n tags: string[];\n}\n\nexport const DEFAULT_REPOS: readonly DefaultRepo[] = [\n {\n url: 'git@github.com:ericbuess/claude-code-docs.git',\n name: 'claude-code-docs',\n description: 'Claude Code documentation',\n tags: ['claude', 'docs', 'claude-code'],\n },\n {\n url: 'git@github.com:anthropics/claude-code.git',\n name: 'claude-code',\n description: 'Claude Code CLI tool source',\n tags: ['claude', 'cli', 'anthropic'],\n },\n {\n url: 'git@github.com:anthropics/claude-agent-sdk-python.git',\n name: 'claude-agent-sdk-python',\n description: 'Claude Agent SDK for Python',\n tags: ['claude', 'sdk', 'python', 'agents'],\n },\n {\n url: 'git@github.com:anthropics/skills.git',\n name: 'claude-skills',\n description: 'Claude skills and capabilities',\n tags: ['claude', 'skills'],\n },\n {\n url: 'git@github.com:anthropics/claude-quickstarts.git',\n name: 'claude-quickstarts',\n description: 'Claude quickstart examples and tutorials',\n tags: ['claude', 'examples', 'tutorials'],\n },\n {\n url: 'git@github.com:anthropics/claude-plugins-official.git',\n name: 'claude-plugins',\n description: 'Official Claude plugins',\n tags: ['claude', 'plugins'],\n },\n {\n url: 'git@github.com:anthropics/claude-agent-sdk-typescript.git',\n name: 'claude-agent-sdk-typescript',\n description: 'Claude Agent SDK for TypeScript',\n tags: ['claude', 'sdk', 'typescript', 'agents'],\n },\n {\n url: 'git@github.com:anthropics/claude-agent-sdk-demos.git',\n name: 'claude-agent-sdk-demos',\n description: 'Claude Agent SDK demo applications',\n tags: ['claude', 'sdk', 'demos', 'examples'],\n },\n];\n","import { Command } from 'commander';\nimport { createServices, destroyServices } from '../../services/index.js';\nimport type { StoreType } from '../../types/store.js';\nimport type { GlobalOptions } from '../program.js';\n\nexport function createStoreCommand(getOptions: () => GlobalOptions): Command {\n const store = new Command('store').description(\n 'Manage knowledge stores (collections of indexed documents)'\n );\n\n store\n .command('list')\n .description('Show all stores with their type (file/repo/web) and ID')\n .option('-t, --type <type>', 'Filter by type: file, repo, or web')\n .action(async (options: { type?: StoreType }) => {\n const globalOpts = getOptions();\n const services = await createServices(globalOpts.config, globalOpts.dataDir);\n try {\n const stores = await services.store.list(options.type);\n\n if (globalOpts.format === 'json') {\n console.log(JSON.stringify(stores, null, 2));\n } else if (globalOpts.quiet === true) {\n // Quiet mode: just list store names, one per line\n for (const s of stores) {\n console.log(s.name);\n }\n } else {\n if (stores.length === 0) {\n console.log('No stores found.');\n } else {\n console.log('\\nStores:\\n');\n for (const s of stores) {\n console.log(` ${s.name} (${s.type}) - ${s.id}`);\n }\n console.log('');\n }\n }\n } finally {\n await destroyServices(services);\n }\n });\n\n store\n .command('create <name>')\n .description('Create a new store pointing to a local path or URL')\n .requiredOption(\n '-t, --type <type>',\n 'Store type: file (local dir), repo (git), web (crawled site)'\n )\n .requiredOption('-s, --source <path>', 'Local path for file/repo stores, URL for web stores')\n .option('-d, --description <desc>', 'Optional description for the store')\n .option('--tags <tags>', 'Comma-separated tags for filtering')\n .action(\n async (\n name: string,\n options: {\n type: StoreType;\n source: string;\n description?: string;\n tags?: string;\n }\n ) => {\n const globalOpts = getOptions();\n const services = await createServices(globalOpts.config, globalOpts.dataDir);\n let exitCode = 0;\n try {\n // Detect if source is a URL (for repo stores that should clone from remote)\n const isUrl =\n options.source.startsWith('http://') || options.source.startsWith('https://');\n const result = await services.store.create({\n name,\n type: options.type,\n path:\n options.type === 'file' || (options.type === 'repo' && !isUrl)\n ? options.source\n : undefined,\n url:\n options.type === 'web' || (options.type === 'repo' && isUrl)\n ? options.source\n : undefined,\n description: options.description,\n tags: options.tags?.split(',').map((t) => t.trim()),\n });\n\n if (result.success) {\n if (globalOpts.format === 'json') {\n console.log(JSON.stringify(result.data, null, 2));\n } else {\n console.log(`\\nCreated store: ${result.data.name} (${result.data.id})\\n`);\n }\n } else {\n console.error(`Error: ${result.error.message}`);\n exitCode = 1;\n }\n } finally {\n await destroyServices(services);\n }\n if (exitCode !== 0) {\n // Set exit code and let Node.js exit naturally after event loop drains\n // Using process.exit() causes mutex crashes from native code (LanceDB, tree-sitter)\n process.exitCode = exitCode;\n }\n }\n );\n\n store\n .command('info <store>')\n .description('Show store details: ID, type, path/URL, timestamps')\n .action(async (storeIdOrName: string) => {\n const globalOpts = getOptions();\n const services = await createServices(globalOpts.config, globalOpts.dataDir);\n let exitCode = 0;\n storeInfo: try {\n const s = await services.store.getByIdOrName(storeIdOrName);\n\n if (s === undefined) {\n console.error(`Error: Store not found: ${storeIdOrName}`);\n exitCode = 3;\n break storeInfo;\n }\n\n if (globalOpts.format === 'json') {\n console.log(JSON.stringify(s, null, 2));\n } else {\n console.log(`\\nStore: ${s.name}`);\n console.log(` ID: ${s.id}`);\n console.log(` Type: ${s.type}`);\n if ('path' in s) console.log(` Path: ${s.path}`);\n if ('url' in s && s.url !== undefined) console.log(` URL: ${s.url}`);\n if (s.description !== undefined) console.log(` Description: ${s.description}`);\n console.log(` Created: ${s.createdAt.toISOString()}`);\n console.log(` Updated: ${s.updatedAt.toISOString()}`);\n console.log('');\n }\n } finally {\n await destroyServices(services);\n }\n if (exitCode !== 0) {\n // Set exit code and let Node.js exit naturally after event loop drains\n // Using process.exit() causes mutex crashes from native code (LanceDB, tree-sitter)\n process.exitCode = exitCode;\n }\n });\n\n store\n .command('delete <store>')\n .description('Remove store and its indexed documents from LanceDB')\n .option('-f, --force', 'Delete without confirmation prompt')\n .option('-y, --yes', 'Alias for --force')\n .action(async (storeIdOrName: string, options: { force?: boolean; yes?: boolean }) => {\n const globalOpts = getOptions();\n const services = await createServices(globalOpts.config, globalOpts.dataDir);\n let exitCode = 0;\n storeDelete: try {\n const s = await services.store.getByIdOrName(storeIdOrName);\n\n if (s === undefined) {\n console.error(`Error: Store not found: ${storeIdOrName}`);\n exitCode = 3;\n break storeDelete;\n }\n\n // Require --force or -y in non-TTY mode, prompt in TTY mode\n const skipConfirmation = options.force === true || options.yes === true;\n if (!skipConfirmation) {\n if (!process.stdin.isTTY) {\n console.error(\n 'Error: Use --force or -y to delete without confirmation in non-interactive mode'\n );\n exitCode = 1;\n break storeDelete;\n }\n // Interactive confirmation\n const readline = await import('node:readline');\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n const answer = await new Promise<string>((resolve) => {\n rl.question(`Delete store \"${s.name}\"? [y/N] `, resolve);\n });\n rl.close();\n if (answer.toLowerCase() !== 'y' && answer.toLowerCase() !== 'yes') {\n console.log('Cancelled.');\n // exitCode stays 0 for user-initiated cancellation\n break storeDelete;\n }\n }\n\n const result = await services.store.delete(s.id);\n\n if (result.success) {\n console.log(`Deleted store: ${s.name}`);\n } else {\n console.error(`Error: ${result.error.message}`);\n exitCode = 1;\n }\n } finally {\n await destroyServices(services);\n }\n if (exitCode !== 0) {\n // Set exit code and let Node.js exit naturally after event loop drains\n // Using process.exit() causes mutex crashes from native code (LanceDB, tree-sitter)\n process.exitCode = exitCode;\n }\n });\n\n return store;\n}\n","import { Command } from 'commander';\nimport { createServices, destroyServices } from '../../services/index.js';\nimport { StoreDefinitionService } from '../../services/store-definition.service.js';\nimport {\n isFileStoreDefinition,\n isRepoStoreDefinition,\n isWebStoreDefinition,\n} from '../../types/store-definition.js';\nimport type { StoreService } from '../../services/store.service.js';\nimport type { StoreDefinition } from '../../types/store-definition.js';\nimport type { GlobalOptions } from '../program.js';\n\ninterface SyncResult {\n created: string[];\n skipped: string[];\n failed: Array<{ name: string; error: string }>;\n orphans: string[];\n pruned: string[];\n dryRun: boolean;\n wouldCreate: string[];\n wouldPrune: string[];\n}\n\n/**\n * Create a store from a definition\n */\nasync function createStoreFromDefinition(\n def: StoreDefinition,\n defService: StoreDefinitionService,\n storeService: StoreService\n): Promise<{ success: true } | { success: false; error: string }> {\n try {\n if (isFileStoreDefinition(def)) {\n const resolvedPath = defService.resolvePath(def.path);\n const createResult = await storeService.create(\n {\n name: def.name,\n type: 'file',\n path: resolvedPath,\n description: def.description,\n tags: def.tags,\n },\n { skipDefinitionSync: true }\n );\n if (!createResult.success) {\n return { success: false, error: createResult.error.message };\n }\n return { success: true };\n }\n\n if (isRepoStoreDefinition(def)) {\n const createResult = await storeService.create(\n {\n name: def.name,\n type: 'repo',\n url: def.url,\n branch: def.branch,\n depth: def.depth,\n description: def.description,\n tags: def.tags,\n },\n { skipDefinitionSync: true }\n );\n if (!createResult.success) {\n return { success: false, error: createResult.error.message };\n }\n return { success: true };\n }\n\n if (isWebStoreDefinition(def)) {\n const createResult = await storeService.create(\n {\n name: def.name,\n type: 'web',\n url: def.url,\n depth: def.depth,\n description: def.description,\n tags: def.tags,\n },\n { skipDefinitionSync: true }\n );\n if (!createResult.success) {\n return { success: false, error: createResult.error.message };\n }\n return { success: true };\n }\n\n return { success: false, error: 'Unknown store definition type' };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\nexport function createSyncCommand(getOptions: () => GlobalOptions): Command {\n const sync = new Command('sync').description(\n 'Sync stores from definitions config (bootstrap on fresh clone)'\n );\n\n sync\n .option('--dry-run', 'Show what would happen without making changes')\n .option('--prune', 'Remove stores not in definitions')\n .option('--reindex', 'Re-index existing stores after sync')\n .action(async (options: { dryRun?: boolean; prune?: boolean; reindex?: boolean }) => {\n const globalOpts = getOptions();\n const projectRoot = globalOpts.projectRoot ?? process.cwd();\n\n const defService = new StoreDefinitionService(projectRoot);\n const services = await createServices(globalOpts.config, globalOpts.dataDir, projectRoot);\n\n try {\n const config = await defService.load();\n const existingStores = await services.store.list();\n const existingNames = new Set(existingStores.map((s) => s.name));\n const definedNames = new Set(config.stores.map((d) => d.name));\n\n const result: SyncResult = {\n created: [],\n skipped: [],\n failed: [],\n orphans: [],\n pruned: [],\n dryRun: options.dryRun === true,\n wouldCreate: [],\n wouldPrune: [],\n };\n\n // Process each definition\n for (const def of config.stores) {\n if (existingNames.has(def.name)) {\n result.skipped.push(def.name);\n continue;\n }\n\n if (options.dryRun === true) {\n result.wouldCreate.push(def.name);\n continue;\n }\n\n const createResult = await createStoreFromDefinition(def, defService, services.store);\n if (createResult.success) {\n result.created.push(def.name);\n } else {\n result.failed.push({ name: def.name, error: createResult.error });\n }\n }\n\n // Find orphans\n for (const store of existingStores) {\n if (!definedNames.has(store.name)) {\n result.orphans.push(store.name);\n }\n }\n\n // Prune orphans if requested\n if (options.prune === true && result.orphans.length > 0) {\n if (options.dryRun === true) {\n result.wouldPrune = [...result.orphans];\n } else {\n for (const orphanName of result.orphans) {\n const store = await services.store.getByName(orphanName);\n if (store !== undefined) {\n const deleteResult = await services.store.delete(store.id, {\n skipDefinitionSync: true,\n });\n if (deleteResult.success) {\n result.pruned.push(orphanName);\n }\n }\n }\n }\n }\n\n // Output result\n if (globalOpts.format === 'json') {\n console.log(JSON.stringify(result, null, 2));\n } else {\n printHumanReadable(result, globalOpts.quiet === true);\n }\n } finally {\n await destroyServices(services);\n }\n });\n\n return sync;\n}\n\nfunction printHumanReadable(result: SyncResult, quiet: boolean): void {\n if (quiet) {\n // Just print created/pruned store names\n for (const name of result.created) {\n console.log(`created: ${name}`);\n }\n for (const name of result.pruned) {\n console.log(`pruned: ${name}`);\n }\n for (const name of result.wouldCreate) {\n console.log(`would create: ${name}`);\n }\n for (const name of result.wouldPrune) {\n console.log(`would prune: ${name}`);\n }\n return;\n }\n\n if (result.dryRun) {\n console.log('\\n[DRY RUN] No changes made.\\n');\n } else {\n console.log('\\nSync completed.\\n');\n }\n\n if (result.created.length > 0) {\n console.log(`Created (${String(result.created.length)}):`);\n for (const name of result.created) {\n console.log(` + ${name}`);\n }\n }\n\n if (result.wouldCreate.length > 0) {\n console.log(`Would create (${String(result.wouldCreate.length)}):`);\n for (const name of result.wouldCreate) {\n console.log(` + ${name}`);\n }\n }\n\n if (result.skipped.length > 0) {\n console.log(`Skipped (already exist) (${String(result.skipped.length)}):`);\n for (const name of result.skipped) {\n console.log(` - ${name}`);\n }\n }\n\n if (result.failed.length > 0) {\n console.log(`Failed (${String(result.failed.length)}):`);\n for (const { name, error } of result.failed) {\n console.log(` ! ${name}: ${error}`);\n }\n }\n\n if (result.orphans.length > 0) {\n console.log(`Orphans (not in definitions) (${String(result.orphans.length)}):`);\n for (const name of result.orphans) {\n console.log(` ? ${name}`);\n }\n }\n\n if (result.pruned.length > 0) {\n console.log(`Pruned (${String(result.pruned.length)}):`);\n for (const name of result.pruned) {\n console.log(` x ${name}`);\n }\n }\n\n if (result.wouldPrune.length > 0) {\n console.log(`Would prune (${String(result.wouldPrune.length)}):`);\n for (const name of result.wouldPrune) {\n console.log(` x ${name}`);\n }\n }\n\n console.log('');\n}\n","import { readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { Command } from 'commander';\n\ninterface PackageJson {\n version: string;\n}\n\nfunction getVersion(): string {\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n const content = readFileSync(join(__dirname, '../package.json'), 'utf-8');\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const pkg: PackageJson = JSON.parse(content);\n return pkg.version;\n}\n\nconst version = getVersion();\n\nexport function createProgram(): Command {\n const program = new Command();\n\n program\n .name('bluera-knowledge')\n .description('CLI tool for managing knowledge stores with semantic search')\n .version(version);\n\n program\n .option('-c, --config <path>', 'Path to config file')\n .option('-d, --data-dir <path>', 'Data directory')\n .option('-p, --project-root <path>', 'Project root directory (for resolving relative paths)')\n .option('-f, --format <format>', 'Output format: json | table | plain', 'table')\n .option('-q, --quiet', 'Suppress non-essential output')\n .option('-v, --verbose', 'Enable verbose logging');\n\n return program;\n}\n\nexport interface GlobalOptions {\n config?: string | undefined;\n dataDir?: string | undefined;\n projectRoot?: string | undefined;\n format: 'json' | 'table' | 'plain';\n quiet?: boolean | undefined;\n verbose?: boolean | undefined;\n}\n\nexport function getGlobalOptions(program: Command): GlobalOptions {\n const opts = program.opts<GlobalOptions>();\n return {\n config: opts.config,\n dataDir: opts.dataDir,\n projectRoot: opts.projectRoot,\n format: opts.format,\n quiet: opts.quiet,\n verbose: opts.verbose,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,SAAS,WAAAA,gBAAe;AACxB,SAAS,QAAAC,aAAY;;;ACHrB,SAAS,kBAAkB;AAC3B,SAAS,eAAe;AACxB,OAAO,SAAuB;AAUvB,SAAS,mBAAmB,YAA0C;AAC3E,SAAO,IAAI,QAAQ,OAAO,EACvB,YAAY,oEAAoE,EAChF,SAAS,SAAS,cAAc,EAChC,SAAS,WAAW,4CAA4C,EAChE;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC,OAAO,YAAY,qDAAqD,EACxE,OAAO,wBAAwB,oCAAoC,IAAI,EACvE,OAAO,UAAU,+DAA+D,EAChF;AAAA,IACC,OACE,KACA,eACA,eAOG;AACH,YAAM,aAAa,WAAW;AAC9B,YAAM,WAAW,MAAM,eAAe,WAAW,QAAQ,WAAW,OAAO;AAG3E,UAAI;AACJ,UAAI,eAAe;AACnB,YAAM,gBAAgB,MAAM,SAAS,MAAM,cAAc,aAAa;AAEtE,UAAI,CAAC,eAAe;AAElB,cAAM,SAAS,MAAM,SAAS,MAAM,OAAO;AAAA,UACzC,MAAM;AAAA,UACN,MAAM;AAAA,UACN;AAAA,QAC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AA,EAC5D;AAEA,UAAQ,IAAI,eAAe;AAG3B,QAAM,WAAWA,SAAQ,SAAS,OAAO,CAAC,MAAM,EAAE,KAAK,MAAM,MAAM;AACnE,aAAW,OAAO,UAAU;AAC1B,YAAQ,IAAI,kBAAkB,GAAG,EAAE,KAAK,IAAI,CAAC;AAC7C,YAAQ,IAAI,EAAE;AAAA,EAChB;AACF;AAEA,IAAM,UAAU,cAAc;AAG9B,QAAQ,WAAW,qBAAqB,MAAM,iBAAiB,OAAO,CAAC,CAAC;AACxE,QAAQ,WAAW,uBAAuB,MAAM,iBAAiB,OAAO,CAAC,CAAC;AAC1E,QAAQ,WAAW,oBAAoB,MAAM,iBAAiB,OAAO,CAAC,CAAC;AACvE,QAAQ,WAAW,qBAAqB,MAAM,iBAAiB,OAAO,CAAC,CAAC;AAGxE,QAAQ,WAAW,mBAAmB,MAAM,iBAAiB,OAAO,CAAC,CAAC;AACtE,QAAQ,WAAW,oBAAoB,MAAM,iBAAiB,OAAO,CAAC,CAAC;AACvE,QAAQ,WAAW,mBAAmB,MAAM,iBAAiB,OAAO,CAAC,CAAC;AACtE,QAAQ,WAAW,mBAAmB,MAAM,iBAAiB,OAAO,CAAC,CAAC;AACtE,QAAQ,WAAW,mBAAmB,MAAM,iBAAiB,OAAO,CAAC,CAAC;AACtE,QAAQ,WAAW,mBAAmB,MAAM,iBAAiB,OAAO,CAAC,CAAC;AACtE,QAAQ,WAAW,kBAAkB,MAAM,iBAAiB,OAAO,CAAC,CAAC;AACrE,QAAQ,WAAW,iBAAiB,MAAM,iBAAiB,OAAO,CAAC,CAAC;AAGpE,IAAI,QAAQ,KAAK,UAAU,GAAG;AAC5B,gBAAc,OAAO;AACrB,UAAQ,KAAK,CAAC;AAChB;AAEA,QAAQ,MAAM;","names":["homedir","join","url","Command","ora","Command","ora","Command","Command","Command","ora","ora","Command","Command","Command","Command","Command","existsSync","join","Command","ora","join","Command","ora","existsSync","Command","Command","Command","Command","join","Command","__filename","__dirname","program","join","homedir","DEFAULT_REPOS_DIR","program"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/cli/commands/crawl.ts","../src/cli/commands/index-cmd.ts","../src/cli/commands/mcp.ts","../src/cli/commands/plugin-api.ts","../src/plugin/commands.ts","../src/analysis/dependency-usage-analyzer.ts","../src/analysis/repo-url-resolver.ts","../src/cli/commands/search.ts","../src/cli/commands/serve.ts","../src/server/app.ts","../src/cli/commands/setup.ts","../src/defaults/repos.ts","../src/cli/commands/store.ts","../src/cli/commands/sync.ts","../src/cli/program.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { Command } from 'commander';\nimport { AdapterRegistry } from './analysis/adapter-registry.js';\nimport { ZilAdapter } from './analysis/zil/index.js';\nimport { createCrawlCommand } from './cli/commands/crawl.js';\nimport { createIndexCommand } from './cli/commands/index-cmd.js';\nimport { createMCPCommand } from './cli/commands/mcp.js';\nimport {\n createAddRepoCommand,\n createAddFolderCommand,\n createStoresCommand,\n createSuggestCommand,\n} from './cli/commands/plugin-api.js';\nimport { createSearchCommand } from './cli/commands/search.js';\nimport { createServeCommand } from './cli/commands/serve.js';\nimport { createSetupCommand } from './cli/commands/setup.js';\nimport { createStoreCommand } from './cli/commands/store.js';\nimport { createSyncCommand } from './cli/commands/sync.js';\nimport { createProgram, getGlobalOptions } from './cli/program.js';\n\n// Register built-in language adapters\nconst registry = AdapterRegistry.getInstance();\nregistry.register(new ZilAdapter());\n\n// Default paths\nconst DEFAULT_DATA_DIR = join(homedir(), '.bluera', 'bluera-knowledge', 'data');\nconst DEFAULT_CONFIG = join(homedir(), '.bluera', 'bluera-knowledge', 'config.json');\nconst DEFAULT_REPOS_DIR = join(homedir(), '.bluera', 'bluera-knowledge', 'repos');\n\n/**\n * Format a command and its subcommands recursively for comprehensive help output.\n */\nfunction formatCommandHelp(cmd: Command, indent: string = ''): string[] {\n const lines: string[] = [];\n const name = cmd.name();\n const desc = cmd.description();\n const args = cmd.registeredArguments\n .map((a) => {\n const req = a.required;\n return req ? `<${a.name()}>` : `[${a.name()}]`;\n })\n .join(' ');\n\n // Command header with arguments\n lines.push(`${indent}${name}${args ? ` ${args}` : ''}`);\n if (desc) {\n lines.push(`${indent} ${desc}`);\n }\n\n // Options (skip -h, --help which is auto-added)\n const options = cmd.options.filter((o) => o.flags !== '-h, --help');\n for (const opt of options) {\n lines.push(`${indent} ${opt.flags.padEnd(28)} ${opt.description}`);\n }\n\n // Subcommands (recursive)\n const subcommands = cmd.commands.filter((c) => c.name() !== 'help');\n for (const sub of subcommands) {\n lines.push('');\n lines.push(...formatCommandHelp(sub, `${indent} `));\n }\n\n return lines;\n}\n\n/**\n * Print comprehensive help showing all commands, subcommands, and options.\n */\nfunction printFullHelp(program: Command): void {\n console.log('bluera-knowledge - CLI tool for managing knowledge stores with semantic search\\n');\n\n // Active paths\n console.log('Paths:');\n console.log(` data ${DEFAULT_DATA_DIR}`);\n console.log(` config ${DEFAULT_CONFIG}`);\n console.log(` repos ${DEFAULT_REPOS_DIR}`);\n\n // Global options\n console.log('\\nGlobal options:');\n const globalOpts = program.options.filter(\n (o) => o.flags !== '-h, --help' && o.flags !== '-V, --version'\n );\n for (const opt of globalOpts) {\n console.log(` ${opt.flags.padEnd(28)} ${opt.description}`);\n }\n\n console.log('\\nCommands:\\n');\n\n // All commands except help\n const commands = program.commands.filter((c) => c.name() !== 'help');\n for (const cmd of commands) {\n console.log(formatCommandHelp(cmd).join('\\n'));\n console.log('');\n }\n}\n\nconst program = createProgram();\n\n// Plugin API commands (simple interface)\nprogram.addCommand(createAddRepoCommand(() => getGlobalOptions(program)));\nprogram.addCommand(createAddFolderCommand(() => getGlobalOptions(program)));\nprogram.addCommand(createStoresCommand(() => getGlobalOptions(program)));\nprogram.addCommand(createSuggestCommand(() => getGlobalOptions(program)));\n\n// Advanced CLI commands\nprogram.addCommand(createStoreCommand(() => getGlobalOptions(program)));\nprogram.addCommand(createSearchCommand(() => getGlobalOptions(program)));\nprogram.addCommand(createIndexCommand(() => getGlobalOptions(program)));\nprogram.addCommand(createServeCommand(() => getGlobalOptions(program)));\nprogram.addCommand(createCrawlCommand(() => getGlobalOptions(program)));\nprogram.addCommand(createSetupCommand(() => getGlobalOptions(program)));\nprogram.addCommand(createSyncCommand(() => getGlobalOptions(program)));\nprogram.addCommand(createMCPCommand(() => getGlobalOptions(program)));\n\n// Show comprehensive help when no arguments provided\nif (process.argv.length <= 2) {\n printFullHelp(program);\n process.exit(0);\n}\n\nprogram.parse();\n","import { createHash } from 'node:crypto';\nimport { Command } from 'commander';\nimport ora, { type Ora } from 'ora';\nimport { IntelligentCrawler, type CrawlProgress } from '../../crawl/intelligent-crawler.js';\nimport { ChunkingService } from '../../services/chunking.service.js';\nimport { createServices, destroyServices } from '../../services/index.js';\nimport { classifyWebContentType } from '../../services/index.service.js';\nimport { createDocumentId } from '../../types/brands.js';\nimport type { Document } from '../../types/document.js';\nimport type { WebStore } from '../../types/store.js';\nimport type { GlobalOptions } from '../program.js';\n\nexport function createCrawlCommand(getOptions: () => GlobalOptions): Command {\n return new Command('crawl')\n .description('Crawl web pages with natural language control and index into store')\n .argument('<url>', 'URL to crawl')\n .argument('<store>', 'Target web store to add crawled content to')\n .option(\n '--crawl <instruction>',\n 'Natural language instruction for what to crawl (e.g., \"all Getting Started pages\")'\n )\n .option(\n '--extract <instruction>',\n 'Natural language instruction for what to extract (e.g., \"extract API references\")'\n )\n .option('--simple', 'Use simple BFS mode instead of intelligent crawling')\n .option('--max-pages <number>', 'Maximum number of pages to crawl', '50')\n .option('--fast', 'Use fast axios-only mode (may fail on JavaScript-heavy sites)')\n .action(\n async (\n url: string,\n storeIdOrName: string,\n cmdOptions: {\n crawl?: string;\n extract?: string;\n simple?: boolean;\n maxPages?: string;\n fast?: boolean;\n }\n ) => {\n const globalOpts = getOptions();\n const services = await createServices(globalOpts.config, globalOpts.dataDir);\n\n // Look up or auto-create web store\n let store: WebStore;\n let storeCreated = false;\n const existingStore = await services.store.getByIdOrName(storeIdOrName);\n\n if (!existingStore) {\n // Auto-create web store\n const result = await services.store.create({\n name: storeIdOrName,\n type: 'web',\n url,\n });\n if (!result.success) {\n await destroyServices(services);\n throw new Error(`Failed to create store: ${result.error.message}`);\n }\n // Type narrowing: success check above ensures result.data is Store\n // We know it's a WebStore because we created it with type: 'web'\n const createdStore = result.data;\n if (createdStore.type !== 'web') {\n throw new Error('Unexpected store type after creation');\n }\n store = createdStore;\n storeCreated = true;\n if (globalOpts.quiet !== true && globalOpts.format !== 'json') {\n console.log(`Created web store: ${store.name}`);\n }\n } else if (existingStore.type !== 'web') {\n await destroyServices(services);\n throw new Error(\n `Store \"${storeIdOrName}\" exists but is not a web store (type: ${existingStore.type})`\n );\n } else {\n store = existingStore;\n }\n\n const maxPages = cmdOptions.maxPages !== undefined ? parseInt(cmdOptions.maxPages, 10) : 50;\n\n // Use spinner in interactive mode\n const isInteractive =\n process.stdout.isTTY && globalOpts.quiet !== true && globalOpts.format !== 'json';\n let spinner: Ora | undefined;\n\n if (isInteractive) {\n const mode = cmdOptions.simple === true ? 'simple' : 'intelligent';\n spinner = ora(`Crawling ${url} (${mode} mode)`).start();\n } else if (globalOpts.quiet !== true && globalOpts.format !== 'json') {\n console.log(`Crawling ${url}`);\n }\n\n const crawler = new IntelligentCrawler();\n // Use web preset for larger prose-friendly chunks\n const webChunker = ChunkingService.forContentType('web');\n let pagesIndexed = 0;\n let chunksCreated = 0;\n let exitCode = 0;\n\n // Listen for progress events\n crawler.on('progress', (progress: CrawlProgress) => {\n if (spinner) {\n if (progress.type === 'strategy') {\n spinner.text = progress.message ?? 'Analyzing crawl strategy...';\n } else if (progress.type === 'page') {\n const url = progress.currentUrl ?? 'unknown';\n spinner.text = `Crawling ${String(progress.pagesVisited + 1)}/${String(maxPages)} - ${url}`;\n } else if (progress.type === 'extraction') {\n const url = progress.currentUrl ?? 'unknown';\n spinner.text = `Extracting from ${url}...`;\n } else if (progress.type === 'error' && progress.message !== undefined) {\n spinner.warn(progress.message);\n }\n }\n });\n\n try {\n await services.lance.initialize(store.id);\n const docs: Document[] = [];\n\n // Crawl pages using IntelligentCrawler\n for await (const result of crawler.crawl(url, {\n ...(cmdOptions.crawl !== undefined && { crawlInstruction: cmdOptions.crawl }),\n ...(cmdOptions.extract !== undefined && { extractInstruction: cmdOptions.extract }),\n maxPages,\n ...(cmdOptions.simple !== undefined && { simple: cmdOptions.simple }),\n useHeadless: !(cmdOptions.fast ?? false), // Default true (headless), --fast disables\n })) {\n // Use extracted content if available, otherwise markdown\n const contentToProcess = result.extracted ?? result.markdown;\n\n // Chunk the content using markdown-aware chunking (web content is converted to markdown)\n const chunks = webChunker.chunk(contentToProcess, `${result.url}.md`);\n const fileType = classifyWebContentType(result.url, result.title);\n const urlHash = createHash('md5').update(result.url).digest('hex');\n\n for (const chunk of chunks) {\n const chunkId =\n chunks.length > 1\n ? `${store.id}-${urlHash}-${String(chunk.chunkIndex)}`\n : `${store.id}-${urlHash}`;\n const vector = await services.embeddings.embed(chunk.content);\n\n docs.push({\n id: createDocumentId(chunkId),\n content: chunk.content,\n vector,\n metadata: {\n type: chunks.length > 1 ? 'chunk' : 'web',\n storeId: store.id,\n url: result.url,\n title: result.title,\n extracted: result.extracted !== undefined,\n depth: result.depth,\n indexedAt: new Date(),\n fileType,\n chunkIndex: chunk.chunkIndex,\n totalChunks: chunk.totalChunks,\n sectionHeader: chunk.sectionHeader,\n },\n });\n chunksCreated++;\n }\n\n pagesIndexed++;\n }\n\n // Index all documents\n if (docs.length > 0) {\n if (spinner) {\n spinner.text = 'Indexing documents...';\n }\n await services.lance.addDocuments(store.id, docs);\n // Create FTS index for full-text search\n await services.lance.createFtsIndex(store.id);\n }\n\n const crawlResult = {\n success: true,\n store: store.name,\n storeCreated,\n url,\n pagesCrawled: pagesIndexed,\n chunksCreated,\n mode: cmdOptions.simple === true ? 'simple' : 'intelligent',\n hadCrawlInstruction: cmdOptions.crawl !== undefined,\n hadExtractInstruction: cmdOptions.extract !== undefined,\n };\n\n if (globalOpts.format === 'json') {\n console.log(JSON.stringify(crawlResult, null, 2));\n } else if (spinner !== undefined) {\n spinner.succeed(\n `Crawled ${String(pagesIndexed)} pages, indexed ${String(chunksCreated)} chunks`\n );\n } else if (globalOpts.quiet !== true) {\n console.log(\n `Crawled ${String(pagesIndexed)} pages, indexed ${String(chunksCreated)} chunks`\n );\n }\n } catch (error) {\n const message = `Crawl failed: ${error instanceof Error ? error.message : String(error)}`;\n if (spinner) {\n spinner.fail(message);\n } else {\n console.error(`Error: ${message}`);\n }\n exitCode = 6;\n } finally {\n await crawler.stop();\n await destroyServices(services);\n }\n\n if (exitCode !== 0) {\n process.exit(exitCode);\n }\n }\n );\n}\n","import { Command } from 'commander';\nimport ora, { type Ora } from 'ora';\nimport { createServices, destroyServices } from '../../services/index.js';\nimport type { GlobalOptions } from '../program.js';\n\nexport function createIndexCommand(getOptions: () => GlobalOptions): Command {\n const index = new Command('index')\n .description('Scan store files, chunk text, generate embeddings, save to LanceDB')\n .argument('<store>', 'Store ID or name')\n .option('--force', 'Re-index all files even if unchanged')\n .action(async (storeIdOrName: string, _options: { force?: boolean }) => {\n const globalOpts = getOptions();\n const services = await createServices(globalOpts.config, globalOpts.dataDir);\n let exitCode = 0;\n try {\n indexLogic: {\n const store = await services.store.getByIdOrName(storeIdOrName);\n\n if (store === undefined) {\n console.error(`Error: Store not found: ${storeIdOrName}`);\n exitCode = 3;\n\n break indexLogic;\n }\n\n // Use spinner in interactive mode (not quiet, not json output)\n const isInteractive =\n process.stdout.isTTY && globalOpts.quiet !== true && globalOpts.format !== 'json';\n let spinner: Ora | undefined;\n\n if (isInteractive) {\n spinner = ora(`Indexing store: ${store.name}`).start();\n } else if (globalOpts.quiet !== true && globalOpts.format !== 'json') {\n console.log(`Indexing store: ${store.name}`);\n }\n\n await services.lance.initialize(store.id);\n\n const result = await services.index.indexStore(store, (event) => {\n if (event.type === 'progress') {\n if (spinner) {\n spinner.text = `Indexing: ${String(event.current)}/${String(event.total)} files - ${event.message}`;\n }\n }\n });\n\n if (result.success) {\n if (globalOpts.format === 'json') {\n console.log(JSON.stringify(result.data, null, 2));\n } else {\n const message = `Indexed ${String(result.data.documentsIndexed)} documents, ${String(result.data.chunksCreated)} chunks in ${String(result.data.timeMs)}ms`;\n if (spinner !== undefined) {\n spinner.succeed(message);\n } else if (globalOpts.quiet !== true) {\n console.log(message);\n }\n }\n } else {\n const message = `Error: ${result.error.message}`;\n if (spinner !== undefined) {\n spinner.fail(message);\n } else {\n console.error(message);\n }\n exitCode = 4;\n\n break indexLogic;\n }\n }\n } finally {\n await destroyServices(services);\n }\n\n if (exitCode !== 0) {\n process.exit(exitCode);\n }\n });\n\n index\n .command('watch <store>')\n .description('Watch store directory; re-index when files change')\n .option(\n '--debounce <ms>',\n 'Wait N ms after last change before re-indexing (default: 1000)',\n '1000'\n )\n .action(async (storeIdOrName: string, options: { debounce?: string }) => {\n const globalOpts = getOptions();\n const services = await createServices(globalOpts.config, globalOpts.dataDir);\n\n const store = await services.store.getByIdOrName(storeIdOrName);\n if (store === undefined || (store.type !== 'file' && store.type !== 'repo')) {\n console.error(`Error: File/repo store not found: ${storeIdOrName}`);\n process.exit(3);\n }\n\n const { WatchService } = await import('../../services/watch.service.js');\n const watchService = new WatchService(services.index, services.lance);\n\n if (globalOpts.quiet !== true) {\n console.log(`Watching ${store.name} for changes...`);\n }\n await watchService.watch(\n store,\n parseInt(options.debounce ?? '1000', 10),\n () => {\n if (globalOpts.quiet !== true) {\n console.log(`Re-indexed ${store.name}`);\n }\n },\n (error: Error) => {\n console.error(`Watch error: ${error.message}`);\n }\n );\n\n // Keep process alive\n process.on('SIGINT', () => {\n void (async (): Promise<void> => {\n await watchService.unwatchAll();\n process.exit(0);\n })().catch(() => {\n // Error during shutdown - process.exit already called\n });\n });\n });\n\n return index;\n}\n","import { Command } from 'commander';\nimport { runMCPServer } from '../../mcp/server.js';\nimport type { GlobalOptions } from '../program.js';\n\nexport function createMCPCommand(getOptions: () => GlobalOptions): Command {\n const mcp = new Command('mcp')\n .description('Start MCP (Model Context Protocol) server for AI agent integration')\n .action(async () => {\n const opts = getOptions();\n\n await runMCPServer({\n dataDir: opts.dataDir,\n config: opts.config,\n });\n });\n\n return mcp;\n}\n","import { Command } from 'commander';\nimport {\n handleAddRepo,\n handleAddFolder,\n handleStores,\n handleSuggest,\n} from '../../plugin/commands.js';\nimport type { GlobalOptions } from '../program.js';\n\n/**\n * CLI commands that mirror the plugin API for consistency.\n * These commands provide a simpler interface that matches the plugin commands.\n */\n\nexport function createAddRepoCommand(getOptions: () => GlobalOptions): Command {\n return new Command('add-repo')\n .description('Clone and index a library source repository')\n .argument('<url>', 'Git repository URL')\n .option('--name <name>', 'Store name (defaults to repo name)')\n .option('--branch <branch>', 'Git branch to clone')\n .action(async (url: string, options: { name?: string; branch?: string }) => {\n const globalOpts = getOptions();\n await handleAddRepo(\n { url, ...options },\n {\n config: globalOpts.config,\n dataDir: globalOpts.dataDir,\n projectRoot: globalOpts.projectRoot,\n format: globalOpts.format,\n quiet: globalOpts.quiet,\n }\n );\n });\n}\n\nexport function createAddFolderCommand(getOptions: () => GlobalOptions): Command {\n return new Command('add-folder')\n .description('Index a local folder of reference material')\n .argument('<path>', 'Folder path to index')\n .option('--name <name>', 'Store name (defaults to folder name)')\n .action(async (path: string, options: { name?: string }) => {\n const globalOpts = getOptions();\n await handleAddFolder(\n { path, ...options },\n {\n config: globalOpts.config,\n dataDir: globalOpts.dataDir,\n projectRoot: globalOpts.projectRoot,\n format: globalOpts.format,\n quiet: globalOpts.quiet,\n }\n );\n });\n}\n\nexport function createStoresCommand(getOptions: () => GlobalOptions): Command {\n return new Command('stores').description('List all indexed library stores').action(async () => {\n const globalOpts = getOptions();\n await handleStores({\n config: globalOpts.config,\n dataDir: globalOpts.dataDir,\n projectRoot: globalOpts.projectRoot,\n format: globalOpts.format,\n quiet: globalOpts.quiet,\n });\n });\n}\n\nexport function createSuggestCommand(getOptions: () => GlobalOptions): Command {\n return new Command('suggest')\n .description('Suggest important dependencies to add to knowledge stores')\n .action(async () => {\n const globalOpts = getOptions();\n await handleSuggest({\n config: globalOpts.config,\n dataDir: globalOpts.dataDir,\n projectRoot: globalOpts.projectRoot,\n format: globalOpts.format,\n quiet: globalOpts.quiet,\n });\n });\n}\n","import ora from 'ora';\nimport { extractRepoName } from './git-clone.js';\nimport { DependencyUsageAnalyzer } from '../analysis/dependency-usage-analyzer.js';\nimport { RepoUrlResolver } from '../analysis/repo-url-resolver.js';\nimport { createServices, destroyServices } from '../services/index.js';\n\n/**\n * Options passed from CLI global options to plugin command handlers.\n */\nexport interface CommandOptions {\n config?: string | undefined;\n dataDir?: string | undefined;\n projectRoot?: string | undefined;\n format?: 'json' | 'table' | 'plain' | undefined;\n quiet?: boolean | undefined;\n}\n\nexport async function handleSearch(args: {\n query: string;\n stores?: string;\n limit?: string;\n}): Promise<void> {\n // PWD is set by Claude Code to user's project directory\n const services = await createServices(undefined, undefined, process.env['PWD']);\n\n try {\n const storeNames = args.stores?.split(',').map((s: string) => s.trim());\n\n const allStores = await services.store.list();\n const targetStores =\n storeNames !== undefined ? allStores.filter((s) => storeNames.includes(s.name)) : allStores;\n\n if (targetStores.length === 0) {\n console.error('No stores found to search');\n process.exit(1);\n }\n\n // Initialize stores\n for (const store of targetStores) {\n await services.lance.initialize(store.id);\n }\n\n const results = await services.search.search({\n query: args.query,\n stores: targetStores.map((s) => s.id),\n mode: 'hybrid',\n limit: parseInt(args.limit ?? '10', 10),\n detail: 'contextual',\n });\n\n console.log(`Found ${String(results.totalResults)} results:\\n`);\n for (const r of results.results) {\n if (r.summary !== undefined) {\n console.log(`Score: ${r.score.toFixed(2)} - ${r.summary.location}`);\n console.log(r.summary.purpose);\n }\n console.log('---');\n }\n } finally {\n await destroyServices(services);\n }\n}\n\nexport async function handleAddRepo(\n args: {\n url: string;\n name?: string;\n branch?: string;\n },\n options: CommandOptions = {}\n): Promise<void> {\n const services = await createServices(\n options.config,\n options.dataDir,\n options.projectRoot ?? process.env['PWD']\n );\n\n try {\n const storeName = args.name ?? extractRepoName(args.url);\n\n console.log(`Cloning ${args.url}...`);\n\n const result = await services.store.create({\n name: storeName,\n type: 'repo',\n url: args.url,\n ...(args.branch !== undefined ? { branch: args.branch } : {}),\n });\n\n if (!result.success) {\n console.error(`Error: ${result.error.message}`);\n process.exit(1);\n }\n\n console.log(`Created store: ${storeName} (${result.data.id})`);\n if ('path' in result.data) {\n console.log(`Location: ${result.data.path}`);\n }\n\n // Auto-index\n console.log('\\nIndexing...');\n const indexResult = await services.index.indexStore(result.data);\n\n if (indexResult.success) {\n console.log(`Indexed ${String(indexResult.data.documentsIndexed)} files`);\n } else {\n console.error(`Indexing failed: ${indexResult.error.message}`);\n }\n } finally {\n await destroyServices(services);\n }\n}\n\nexport async function handleAddFolder(\n args: { path: string; name?: string },\n options: CommandOptions = {}\n): Promise<void> {\n const services = await createServices(\n options.config,\n options.dataDir,\n options.projectRoot ?? process.env['PWD']\n );\n\n try {\n const { basename } = await import('node:path');\n const storeName = args.name ?? basename(args.path);\n\n console.log(`Adding folder: ${args.path}...`);\n\n const result = await services.store.create({\n name: storeName,\n type: 'file',\n path: args.path,\n });\n\n if (!result.success) {\n console.error(`Error: ${result.error.message}`);\n process.exit(1);\n }\n\n console.log(`Created store: ${storeName} (${result.data.id})`);\n if ('path' in result.data) {\n console.log(`Location: ${result.data.path}`);\n }\n\n // Auto-index\n console.log('\\nIndexing...');\n const indexResult = await services.index.indexStore(result.data);\n\n if (indexResult.success) {\n console.log(`Indexed ${String(indexResult.data.documentsIndexed)} files`);\n } else {\n console.error(`Indexing failed: ${indexResult.error.message}`);\n }\n } finally {\n await destroyServices(services);\n }\n}\n\nexport async function handleIndex(args: { store: string }): Promise<void> {\n // PWD is set by Claude Code to user's project directory\n const services = await createServices(undefined, undefined, process.env['PWD']);\n\n try {\n const store = await services.store.getByIdOrName(args.store);\n\n if (store === undefined) {\n console.error(`Store not found: ${args.store}`);\n process.exit(1);\n }\n\n console.log(`Indexing ${store.name}...`);\n const result = await services.index.indexStore(store);\n\n if (result.success) {\n console.log(\n `Indexed ${String(result.data.documentsIndexed)} documents in ${String(result.data.timeMs)}ms`\n );\n } else {\n console.error(`Error: ${result.error.message}`);\n process.exit(1);\n }\n } finally {\n await destroyServices(services);\n }\n}\n\nexport async function handleStores(options: CommandOptions = {}): Promise<void> {\n const services = await createServices(\n options.config,\n options.dataDir,\n options.projectRoot ?? process.env['PWD']\n );\n\n try {\n const stores = await services.store.list();\n\n if (stores.length === 0) {\n console.log('No stores found.');\n console.log('\\nCreate a store with:');\n console.log(' /bluera-knowledge:add-repo <url> --name=<name>');\n console.log(' /bluera-knowledge:add-folder <path> --name=<name>');\n return;\n }\n\n // Table header\n console.log('| Name | Type | ID | Source |');\n console.log('|------|------|----|--------------------|');\n\n // Table rows\n for (const store of stores) {\n const name = store.name;\n const type = store.type;\n const id = store.id;\n let source = '';\n\n if ('url' in store && store.url !== undefined) {\n source = store.url;\n } else if ('path' in store) {\n source = store.path;\n }\n\n console.log(`| ${name} | ${type} | ${id.substring(0, 8)}... | ${source} |`);\n }\n } finally {\n await destroyServices(services);\n }\n}\n\nexport async function handleSuggest(options: CommandOptions = {}): Promise<void> {\n const projectRoot = options.projectRoot ?? process.env['PWD'] ?? process.cwd();\n\n console.log('Analyzing project dependencies...\\n');\n\n // Create analyzer instance\n const services = await createServices(options.config, options.dataDir, projectRoot);\n\n try {\n const analyzer = new DependencyUsageAnalyzer();\n const resolver = new RepoUrlResolver();\n\n // Analyze with progress indicator\n const spinner = ora('Scanning source files...').start();\n\n const result = await analyzer.analyze(projectRoot, (current, total, message) => {\n spinner.text = `${message} (${String(current)}/${String(total)})`;\n });\n\n spinner.stop();\n\n if (!result.success) {\n console.error(`Error: ${result.error.message}`);\n process.exit(1);\n }\n\n const { usages, totalFilesScanned, skippedFiles } = result.data;\n\n console.log(\n `✔ Scanned ${String(totalFilesScanned)} files${skippedFiles > 0 ? ` (skipped ${String(skippedFiles)})` : ''}\\n`\n );\n\n if (usages.length === 0) {\n console.log('No external dependencies found in this project.');\n console.log('\\nMake sure you have a package.json or requirements.txt file.');\n return;\n }\n\n // Filter out packages already in stores\n const existingStores = await services.store.list();\n const existingRepoNames = new Set(existingStores.map((s) => s.name));\n\n const newUsages = usages.filter((u) => !existingRepoNames.has(u.packageName));\n\n if (newUsages.length === 0) {\n console.log('✔ All dependencies are already in knowledge stores!');\n return;\n }\n\n // Show top 5 suggestions\n const topSuggestions = newUsages.slice(0, 5);\n\n console.log('Top dependencies by usage in this project:\\n');\n topSuggestions.forEach((usage, i) => {\n console.log(`${String(i + 1)}. ${usage.packageName}`);\n console.log(\n ` ${String(usage.importCount)} imports across ${String(usage.fileCount)} files\\n`\n );\n });\n\n console.log('Searching for repository URLs...\\n');\n\n // For each package, find repo URL\n for (const usage of topSuggestions) {\n const repoResult = await resolver.findRepoUrl(usage.packageName, usage.language);\n\n if (repoResult.url !== null) {\n console.log(`✔ ${usage.packageName}: ${repoResult.url}`);\n console.log(` /bluera-knowledge:add-repo ${repoResult.url} --name=${usage.packageName}\\n`);\n } else {\n console.log(`✗ ${usage.packageName}: Could not find repository URL`);\n console.log(\n ` You can manually add it: /bluera-knowledge:add-repo <url> --name=${usage.packageName}\\n`\n );\n }\n }\n\n console.log('Use the commands above to add repositories to your knowledge stores.');\n } finally {\n await destroyServices(services);\n }\n}\n","import { existsSync } from 'node:fs';\nimport { readFile, readdir } from 'node:fs/promises';\nimport { join, extname } from 'node:path';\nimport { ASTParser } from './ast-parser.js';\nimport { ok, err } from '../types/result.js';\nimport type { SupportedLanguage } from './repo-url-resolver.js';\nimport type { Result } from '../types/result.js';\n\nconst TEXT_EXTENSIONS = new Set([\n '.ts',\n '.tsx',\n '.js',\n '.jsx',\n '.mjs',\n '.cjs',\n '.py',\n '.rb',\n '.go',\n '.java',\n '.rs',\n '.php',\n '.md',\n '.txt',\n '.json',\n '.yml',\n '.yaml',\n '.toml',\n]);\n\nexport interface PackageUsage {\n packageName: string;\n importCount: number;\n fileCount: number;\n files: string[];\n isDevDependency: boolean;\n language: SupportedLanguage;\n}\n\nexport interface DependencyAnalysisResult {\n usages: PackageUsage[];\n totalFilesScanned: number;\n skippedFiles: number;\n analysisTimeMs: number;\n}\n\ninterface DeclaredDependency {\n name: string;\n isDev: boolean;\n language: SupportedLanguage;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport class DependencyUsageAnalyzer {\n private readonly astParser: ASTParser;\n\n constructor() {\n this.astParser = new ASTParser();\n }\n\n async analyze(\n projectRoot: string,\n onProgress?: (current: number, total: number, message: string) => void\n ): Promise<Result<DependencyAnalysisResult>> {\n const startTime = Date.now();\n\n try {\n // 1. Read declared dependencies from package.json/requirements.txt\n const declaredDeps = await this.readDeclaredDependencies(projectRoot);\n\n if (declaredDeps.size === 0) {\n return ok({\n usages: [],\n totalFilesScanned: 0,\n skippedFiles: 0,\n analysisTimeMs: Date.now() - startTime,\n });\n }\n\n // 2. Scan all source files\n const files = await this.scanDirectory(projectRoot);\n\n if (files.length === 0) {\n return ok({\n usages: [],\n totalFilesScanned: 0,\n skippedFiles: 0,\n analysisTimeMs: Date.now() - startTime,\n });\n }\n\n // 3. Count imports for each package\n const usageMap = new Map<string, PackageUsage>();\n let processedCount = 0;\n let skippedCount = 0;\n\n for (const filePath of files) {\n try {\n const content = await readFile(filePath, 'utf-8');\n const imports = this.extractImportsForFile(filePath, content);\n\n for (const importInfo of imports) {\n const packageName = this.extractPackageName(importInfo.source);\n\n if (packageName !== null && declaredDeps.has(packageName)) {\n const dep = declaredDeps.get(packageName);\n if (dep !== undefined) {\n this.incrementUsage(usageMap, packageName, filePath, dep.isDev, dep.language);\n }\n }\n }\n\n processedCount++;\n if (onProgress !== undefined && processedCount % 10 === 0) {\n onProgress(\n processedCount,\n files.length,\n `Analyzed ${String(processedCount)}/${String(files.length)} files`\n );\n }\n } catch {\n // Skip files that can't be read or parsed\n skippedCount++;\n }\n }\n\n // 4. Sort by usage frequency\n const sortedUsages = Array.from(usageMap.values()).sort(\n (a, b) => b.importCount - a.importCount\n );\n\n return ok({\n usages: sortedUsages,\n totalFilesScanned: processedCount,\n skippedFiles: skippedCount,\n analysisTimeMs: Date.now() - startTime,\n });\n } catch (error) {\n const errorObj = new Error(\n error instanceof Error ? error.message : 'Unknown error during analysis'\n );\n errorObj.name = 'ANALYSIS_ERROR';\n return err(errorObj);\n }\n }\n\n private extractPackageName(importSource: string): string | null {\n // Relative imports (./foo, ../bar, /absolute) -> null\n if (importSource.startsWith('.') || importSource.startsWith('/')) {\n return null;\n }\n\n // Node built-ins (node:fs, node:path) -> null\n if (importSource.startsWith('node:')) {\n return null;\n }\n\n // Scoped packages: @org/package/path -> @org/package\n if (importSource.startsWith('@')) {\n const parts = importSource.split('/');\n if (parts.length >= 2 && parts[0] !== undefined && parts[1] !== undefined) {\n return `${parts[0]}/${parts[1]}`;\n }\n return null;\n }\n\n // Regular packages: lodash/get -> lodash\n const firstPart = importSource.split('/')[0];\n return firstPart ?? null;\n }\n\n private extractImportsForFile(filePath: string, content: string): Array<{ source: string }> {\n const ext = extname(filePath);\n\n // JavaScript/TypeScript - use AST parser\n if (['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'].includes(ext)) {\n try {\n return this.astParser.extractImports(content);\n } catch {\n // Fallback to regex for malformed files\n return this.extractImportsRegex(content, 'javascript');\n }\n }\n\n // Python - use regex\n if (ext === '.py') {\n return this.extractImportsRegex(content, 'python');\n }\n\n return [];\n }\n\n private extractImportsRegex(\n content: string,\n language: 'javascript' | 'python'\n ): Array<{ source: string }> {\n const imports: Array<{ source: string }> = [];\n\n if (language === 'javascript') {\n // Match: import ... from 'package'\n // Match: require('package')\n const importPattern = /import\\s+.*?from\\s+['\"]([^'\"]+)['\"]/g;\n const requirePattern = /require\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g;\n\n for (const match of content.matchAll(importPattern)) {\n if (match[1] !== undefined) imports.push({ source: match[1] });\n }\n\n for (const match of content.matchAll(requirePattern)) {\n if (match[1] !== undefined) imports.push({ source: match[1] });\n }\n } else {\n // Match: import package\n // Match: from package import ...\n const importPattern = /^import\\s+([a-zA-Z0-9_]+)/gm;\n const fromPattern = /^from\\s+([a-zA-Z0-9_]+)/gm;\n\n for (const match of content.matchAll(importPattern)) {\n if (match[1] !== undefined) imports.push({ source: match[1] });\n }\n\n for (const match of content.matchAll(fromPattern)) {\n if (match[1] !== undefined) imports.push({ source: match[1] });\n }\n }\n\n return imports;\n }\n\n private incrementUsage(\n usageMap: Map<string, PackageUsage>,\n packageName: string,\n filePath: string,\n isDevDependency: boolean,\n language: SupportedLanguage\n ): void {\n const existing = usageMap.get(packageName);\n\n if (existing) {\n existing.importCount++;\n if (!existing.files.includes(filePath)) {\n existing.fileCount++;\n existing.files.push(filePath);\n }\n } else {\n usageMap.set(packageName, {\n packageName,\n importCount: 1,\n fileCount: 1,\n files: [filePath],\n isDevDependency,\n language,\n });\n }\n }\n\n private async scanDirectory(dir: string): Promise<string[]> {\n const files: string[] = [];\n\n try {\n const entries = await readdir(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = join(dir, entry.name);\n\n if (entry.isDirectory()) {\n // Skip common ignored directories\n if (\n ![\n 'node_modules',\n '.git',\n 'dist',\n 'build',\n 'coverage',\n '__pycache__',\n '.venv',\n 'venv',\n ].includes(entry.name)\n ) {\n files.push(...(await this.scanDirectory(fullPath)));\n }\n } else if (entry.isFile()) {\n const ext = extname(entry.name);\n if (TEXT_EXTENSIONS.has(ext)) {\n files.push(fullPath);\n }\n }\n }\n } catch {\n // Ignore permission errors\n }\n\n return files;\n }\n\n private async readDeclaredDependencies(\n projectRoot: string\n ): Promise<Map<string, DeclaredDependency>> {\n const deps = new Map<string, DeclaredDependency>();\n\n // Read package.json (Node.js)\n const packageJsonPath = join(projectRoot, 'package.json');\n if (existsSync(packageJsonPath)) {\n try {\n const content = await readFile(packageJsonPath, 'utf-8');\n const parsed: unknown = JSON.parse(content);\n\n if (isRecord(parsed)) {\n // Regular dependencies\n if (isRecord(parsed['dependencies'])) {\n for (const name of Object.keys(parsed['dependencies'])) {\n deps.set(name, { name, isDev: false, language: 'javascript' });\n }\n }\n\n // Dev dependencies\n if (isRecord(parsed['devDependencies'])) {\n for (const name of Object.keys(parsed['devDependencies'])) {\n deps.set(name, { name, isDev: true, language: 'javascript' });\n }\n }\n }\n } catch {\n // Ignore parse errors\n }\n }\n\n // Read requirements.txt (Python)\n const reqPath = join(projectRoot, 'requirements.txt');\n if (existsSync(reqPath)) {\n try {\n const content = await readFile(reqPath, 'utf-8');\n const lines = content.split('\\n');\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed === '' || trimmed.startsWith('#')) continue;\n\n // Parse package name (before ==, >=, etc.)\n const match = /^([a-zA-Z0-9_-]+)/.exec(trimmed);\n if (match?.[1] !== undefined) {\n const name = match[1].toLowerCase();\n deps.set(name, { name, isDev: false, language: 'python' });\n }\n }\n } catch {\n // Ignore errors\n }\n }\n\n // Read pyproject.toml (Python)\n const pyprojectPath = join(projectRoot, 'pyproject.toml');\n if (existsSync(pyprojectPath)) {\n try {\n const content = await readFile(pyprojectPath, 'utf-8');\n // Simple regex extraction (good enough for dependency names)\n const depMatches = content.matchAll(/\"([a-zA-Z0-9_-]+)\"/g);\n\n for (const match of depMatches) {\n if (match[1] !== undefined) {\n const name = match[1].toLowerCase();\n deps.set(name, { name, isDev: false, language: 'python' });\n }\n }\n } catch {\n // Ignore errors\n }\n }\n\n // Read Cargo.toml (Rust)\n const cargoPath = join(projectRoot, 'Cargo.toml');\n if (existsSync(cargoPath)) {\n try {\n const content = await readFile(cargoPath, 'utf-8');\n // Match [dependencies] section entries like: serde = \"1.0\"\n // or serde = { version = \"1.0\", features = [...] }\n const inDepsSection = /\\[dependencies\\]([\\s\\S]*?)(?=\\n\\[|$)/;\n const depsMatch = inDepsSection.exec(content);\n if (depsMatch?.[1] !== undefined) {\n const depsSection = depsMatch[1];\n // Match crate names at start of lines\n const cratePattern = /^([a-zA-Z0-9_-]+)\\s*=/gm;\n for (const match of depsSection.matchAll(cratePattern)) {\n if (match[1] !== undefined) {\n deps.set(match[1], { name: match[1], isDev: false, language: 'rust' });\n }\n }\n }\n\n // Also check [dev-dependencies]\n const inDevDepsSection = /\\[dev-dependencies\\]([\\s\\S]*?)(?=\\n\\[|$)/;\n const devDepsMatch = inDevDepsSection.exec(content);\n if (devDepsMatch?.[1] !== undefined) {\n const devDepsSection = devDepsMatch[1];\n const cratePattern = /^([a-zA-Z0-9_-]+)\\s*=/gm;\n for (const match of devDepsSection.matchAll(cratePattern)) {\n if (match[1] !== undefined) {\n deps.set(match[1], { name: match[1], isDev: true, language: 'rust' });\n }\n }\n }\n } catch {\n // Ignore errors\n }\n }\n\n // Read go.mod (Go)\n const goModPath = join(projectRoot, 'go.mod');\n if (existsSync(goModPath)) {\n try {\n const content = await readFile(goModPath, 'utf-8');\n // Match require blocks and single requires\n // require github.com/gorilla/mux v1.8.0\n // require (\n // github.com/gorilla/mux v1.8.0\n // )\n const requirePattern = /^\\s*([a-zA-Z0-9._/-]+)\\s+v[\\d.]+/gm;\n for (const match of content.matchAll(requirePattern)) {\n if (match[1] !== undefined && !match[1].startsWith('//')) {\n // Go modules use the full path as the name\n deps.set(match[1], { name: match[1], isDev: false, language: 'go' });\n }\n }\n } catch {\n // Ignore errors\n }\n }\n\n return deps;\n }\n}\n","export interface RepoSearchResult {\n url: string | null;\n confidence: 'high' | 'medium' | 'low';\n source: 'registry' | 'search' | 'fallback';\n}\n\n/**\n * Type guard to check if a value is a non-null object\n */\nfunction isObject(value: unknown): value is Record<PropertyKey, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nexport type SupportedLanguage = 'javascript' | 'python' | 'rust' | 'go';\n\nexport class RepoUrlResolver {\n /**\n * Find the GitHub repository URL for a package\n */\n async findRepoUrl(\n packageName: string,\n language: SupportedLanguage = 'javascript'\n ): Promise<RepoSearchResult> {\n // Strategy 1: Try package registry API (fast, accurate)\n let registryUrl: string | null = null;\n\n switch (language) {\n case 'javascript':\n registryUrl = await this.tryNpmRegistry(packageName);\n break;\n case 'python':\n registryUrl = await this.tryPyPiRegistry(packageName);\n break;\n case 'rust':\n registryUrl = await this.tryCratesRegistry(packageName);\n break;\n case 'go':\n registryUrl = await this.tryGoModule(packageName);\n break;\n }\n\n if (registryUrl !== null) {\n return { url: registryUrl, confidence: 'high', source: 'registry' };\n }\n\n // Strategy 2: No URL found\n return { url: null, confidence: 'low', source: 'fallback' };\n }\n\n /**\n * Query NPM registry for package metadata\n */\n private async tryNpmRegistry(packageName: string): Promise<string | null> {\n try {\n const response = await fetch(`https://registry.npmjs.org/${packageName}`);\n\n if (!response.ok) {\n return null;\n }\n\n const data: unknown = await response.json();\n if (!isObject(data)) {\n return null;\n }\n\n // Extract repository URL - safely access nested property\n if ('repository' in data) {\n const repo = data['repository'];\n if (isObject(repo) && 'url' in repo) {\n const urlValue = repo['url'];\n const url = String(urlValue);\n return this.normalizeRepoUrl(url);\n }\n\n if (typeof repo === 'string') {\n return this.normalizeRepoUrl(repo);\n }\n }\n\n return null;\n } catch {\n return null;\n }\n }\n\n /**\n * Query PyPI registry for package metadata\n */\n private async tryPyPiRegistry(packageName: string): Promise<string | null> {\n try {\n const response = await fetch(`https://pypi.org/pypi/${packageName}/json`);\n\n if (!response.ok) {\n return null;\n }\n\n const data: unknown = await response.json();\n if (!isObject(data)) {\n return null;\n }\n\n // Extract repository URL from project URLs\n if ('info' in data) {\n const info = data['info'];\n if (isObject(info) && 'project_urls' in info) {\n const projectUrls = info['project_urls'];\n\n if (isObject(projectUrls)) {\n // Try various common keys\n const urlKeys = ['Source', 'Repository', 'Code', 'Homepage'];\n\n for (const key of urlKeys) {\n if (key in projectUrls) {\n const urlValue = projectUrls[key];\n const url = String(urlValue);\n if (url.includes('github.com')) {\n return this.normalizeRepoUrl(url);\n }\n }\n }\n }\n }\n }\n\n return null;\n } catch {\n return null;\n }\n }\n\n /**\n * Query crates.io registry for Rust crate metadata\n */\n private async tryCratesRegistry(crateName: string): Promise<string | null> {\n try {\n const response = await fetch(`https://crates.io/api/v1/crates/${crateName}`, {\n headers: {\n // crates.io requires a User-Agent header\n 'User-Agent': 'bluera-knowledge (https://github.com/blueraai/bluera-knowledge)',\n },\n });\n\n if (!response.ok) {\n return null;\n }\n\n const data: unknown = await response.json();\n if (!isObject(data)) {\n return null;\n }\n\n // Extract repository URL from crate metadata\n if ('crate' in data) {\n const crate = data['crate'];\n if (isObject(crate) && 'repository' in crate) {\n const repo = crate['repository'];\n if (typeof repo === 'string') {\n return this.normalizeRepoUrl(repo);\n }\n }\n }\n\n return null;\n } catch {\n return null;\n }\n }\n\n /**\n * Resolve Go module to GitHub repository\n * Go modules often use GitHub URLs directly (e.g., github.com/gorilla/mux)\n */\n private async tryGoModule(moduleName: string): Promise<string | null> {\n try {\n // Go modules that start with github.com are already GitHub URLs\n if (moduleName.startsWith('github.com/')) {\n // Extract owner/repo from module path (e.g., github.com/gorilla/mux/v2 -> github.com/gorilla/mux)\n const parts = moduleName.split('/');\n const owner = parts[1];\n const repo = parts[2];\n if (owner !== undefined && repo !== undefined) {\n return `https://github.com/${owner}/${repo}`;\n }\n }\n\n // For other modules, try pkg.go.dev API\n // The pkg.go.dev API returns module info including repository URL\n const response = await fetch(`https://proxy.golang.org/${moduleName}/@latest`, {\n headers: {\n 'User-Agent': 'bluera-knowledge (https://github.com/blueraai/bluera-knowledge)',\n },\n });\n\n if (!response.ok) {\n return null;\n }\n\n // The Go proxy returns module info, but repository URL needs to be inferred\n // from the module path or VCS info. For now, we only support direct GitHub modules.\n // Most popular Go packages use github.com paths anyway.\n return null;\n } catch {\n return null;\n }\n }\n\n /**\n * Normalize various repository URL formats to standard GitHub URL\n */\n private normalizeRepoUrl(url: string): string | null {\n // Remove git+ prefix\n let normalized = url.replace(/^git\\+/, '');\n\n // Remove .git suffix\n normalized = normalized.replace(/\\.git$/, '');\n\n // Convert git:// to https://\n normalized = normalized.replace(/^git:\\/\\//, 'https://');\n\n // Convert ssh:// to https://\n normalized = normalized.replace(/^ssh:\\/\\/git@/, 'https://');\n\n // Convert git@github.com: to https://github.com/\n normalized = normalized.replace(/^git@github\\.com:/, 'https://github.com/');\n\n // Only return if it's a GitHub URL\n if (normalized.includes('github.com')) {\n return normalized;\n }\n\n return null;\n }\n}\n","import { Command } from 'commander';\nimport { createServices, destroyServices } from '../../services/index.js';\nimport type { SearchMode, DetailLevel } from '../../types/search.js';\nimport type { GlobalOptions } from '../program.js';\n\nexport function createSearchCommand(getOptions: () => GlobalOptions): Command {\n const search = new Command('search')\n .description('Search indexed documents using vector similarity + full-text matching')\n .argument('<query>', 'Search query')\n .option(\n '-s, --stores <stores>',\n 'Limit search to specific stores (comma-separated IDs or names)'\n )\n .option(\n '-m, --mode <mode>',\n 'vector (embeddings only), fts (text only), hybrid (both, default)',\n 'hybrid'\n )\n .option('-n, --limit <count>', 'Maximum results to return (default: 10)', '10')\n .option('-t, --threshold <score>', 'Minimum score 0-1; omit low-relevance results')\n .option(\n '--min-relevance <score>',\n 'Minimum raw cosine similarity 0-1; returns empty if no results meet threshold'\n )\n .option('--include-content', 'Show full document content, not just preview snippet')\n .option(\n '--detail <level>',\n 'Context detail: minimal, contextual, full (default: minimal)',\n 'minimal'\n )\n .action(\n async (\n query: string,\n options: {\n stores?: string;\n mode?: SearchMode;\n limit?: string;\n threshold?: string;\n minRelevance?: string;\n includeContent?: boolean;\n detail?: DetailLevel;\n }\n ) => {\n const globalOpts = getOptions();\n const services = await createServices(globalOpts.config, globalOpts.dataDir);\n let exitCode = 0;\n try {\n // Get store IDs\n let storeIds = (await services.store.list()).map((s) => s.id);\n\n searchLogic: {\n if (options.stores !== undefined) {\n const requestedStores = options.stores.split(',').map((s) => s.trim());\n const resolvedStores = [];\n\n for (const requested of requestedStores) {\n const store = await services.store.getByIdOrName(requested);\n if (store !== undefined) {\n resolvedStores.push(store.id);\n } else {\n console.error(`Error: Store not found: ${requested}`);\n exitCode = 3;\n\n break searchLogic;\n }\n }\n\n storeIds = resolvedStores;\n }\n\n if (storeIds.length === 0) {\n console.error('No stores to search. Create a store first.');\n exitCode = 1;\n\n break searchLogic;\n }\n\n // Initialize LanceDB for each store\n for (const storeId of storeIds) {\n await services.lance.initialize(storeId);\n }\n\n const results = await services.search.search({\n query,\n stores: storeIds,\n mode: options.mode ?? 'hybrid',\n limit: parseInt(options.limit ?? '10', 10),\n threshold:\n options.threshold !== undefined ? parseFloat(options.threshold) : undefined,\n minRelevance:\n options.minRelevance !== undefined ? parseFloat(options.minRelevance) : undefined,\n includeContent: options.includeContent,\n detail: options.detail ?? 'minimal',\n });\n\n if (globalOpts.format === 'json') {\n console.log(JSON.stringify(results, null, 2));\n } else if (globalOpts.quiet === true) {\n // Quiet mode: just list matching paths/URLs, one per line\n for (const r of results.results) {\n const path = r.metadata.path ?? r.metadata.url ?? 'unknown';\n console.log(path);\n }\n } else {\n console.log(`\\nSearch: \"${query}\"`);\n\n // Build status line with optional confidence info\n let statusLine = `Mode: ${results.mode} | Detail: ${String(options.detail)} | Stores: ${String(results.stores.length)} | Results: ${String(results.totalResults)} | Time: ${String(results.timeMs)}ms`;\n if (results.confidence !== undefined) {\n statusLine += ` | Confidence: ${results.confidence}`;\n }\n if (results.maxRawScore !== undefined) {\n statusLine += ` | MaxRaw: ${results.maxRawScore.toFixed(3)}`;\n }\n console.log(`${statusLine}\\n`);\n\n if (results.results.length === 0) {\n if (results.confidence === 'low') {\n console.log('No sufficiently relevant results found.\\n');\n } else {\n console.log('No results found.\\n');\n }\n } else {\n for (let i = 0; i < results.results.length; i++) {\n const r = results.results[i];\n if (r === undefined) continue;\n\n if (r.summary) {\n console.log(\n `${String(i + 1)}. [${r.score.toFixed(2)}] ${r.summary.type}: ${r.summary.name}`\n );\n console.log(` ${r.summary.location}`);\n console.log(` ${r.summary.purpose}`);\n\n // Contextual: Show imports, concepts, and usage stats\n if (r.context && options.detail !== 'minimal') {\n if (r.context.keyImports.length > 0) {\n console.log(` Imports: ${r.context.keyImports.slice(0, 3).join(', ')}`);\n }\n if (r.context.relatedConcepts.length > 0) {\n console.log(\n ` Related: ${r.context.relatedConcepts.slice(0, 3).join(', ')}`\n );\n }\n // Show usage stats from code graph\n const { calledBy, calls } = r.context.usage;\n if (calledBy > 0 || calls > 0) {\n console.log(\n ` Usage: Called by ${String(calledBy)} | Calls ${String(calls)}`\n );\n }\n }\n\n // Full: Show complete code and documentation\n if (r.full && options.detail === 'full') {\n if (r.full.completeCode) {\n console.log(` ---`);\n const codeLines = r.full.completeCode.split('\\n');\n console.log(` ${codeLines.slice(0, 10).join('\\n ')}`);\n if (codeLines.length > 10) {\n console.log(` ... (truncated)`);\n }\n }\n if (r.full.documentation) {\n console.log(` Doc: ${r.full.documentation.slice(0, 100)}`);\n }\n }\n\n console.log();\n } else {\n // Display without summary\n const path = r.metadata.path ?? r.metadata.url ?? 'unknown';\n console.log(`${String(i + 1)}. [${r.score.toFixed(2)}] ${path}`);\n const preview =\n r.highlight ??\n r.content.slice(0, 150).replace(/\\n/g, ' ') +\n (r.content.length > 150 ? '...' : '');\n console.log(` ${preview}\\n`);\n }\n }\n }\n }\n }\n } finally {\n await destroyServices(services);\n }\n\n if (exitCode !== 0) {\n // Set exit code and let Node.js exit naturally after event loop drains\n // Using process.exit() causes mutex crashes from native code (LanceDB, tree-sitter)\n process.exitCode = exitCode;\n }\n }\n );\n\n return search;\n}\n","import { serve } from '@hono/node-server';\nimport { Command } from 'commander';\nimport { createApp } from '../../server/app.js';\nimport { createServices, destroyServices } from '../../services/index.js';\nimport type { GlobalOptions } from '../program.js';\n\nexport function createServeCommand(getOptions: () => GlobalOptions): Command {\n return new Command('serve')\n .description('Start HTTP API server for programmatic search access')\n .option('-p, --port <port>', 'Port to listen on (default: 3847)', '3847')\n .option(\n '--host <host>',\n 'Bind address (default: 127.0.0.1, use 0.0.0.0 for all interfaces)',\n '127.0.0.1'\n )\n .action(async (options: { port?: string; host?: string }) => {\n const globalOpts = getOptions();\n const services = await createServices(globalOpts.config, globalOpts.dataDir);\n const app = createApp(services);\n\n const port = parseInt(options.port ?? '3847', 10);\n const host = options.host ?? '127.0.0.1';\n\n // Graceful shutdown handler\n const shutdown = (): void => {\n void (async (): Promise<void> => {\n await destroyServices(services);\n process.exit(0);\n })();\n };\n\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n\n console.log(`Starting server on http://${host}:${String(port)}`);\n\n serve({\n fetch: app.fetch,\n port,\n hostname: host,\n });\n });\n}\n","import { Hono } from 'hono';\nimport { cors } from 'hono/cors';\nimport { z } from 'zod';\nimport { createStoreId } from '../types/brands.js';\nimport type { ServiceContainer } from '../services/index.js';\nimport type { SearchQuery } from '../types/search.js';\n\n// HTTP API validation schemas (consistent with MCP schemas)\nconst CreateStoreBodySchema = z\n .object({\n name: z.string().min(1, 'Store name must be a non-empty string'),\n type: z.enum(['file', 'repo', 'web']),\n path: z.string().min(1).optional(),\n url: z.string().min(1).optional(),\n description: z.string().optional(),\n tags: z.array(z.string()).optional(),\n branch: z.string().optional(),\n depth: z.number().int().positive().optional(),\n })\n .refine(\n (data) => {\n switch (data.type) {\n case 'file':\n return data.path !== undefined;\n case 'web':\n return data.url !== undefined;\n case 'repo':\n return data.path !== undefined || data.url !== undefined;\n }\n },\n {\n message:\n 'Missing required field: file stores need path, web stores need url, repo stores need path or url',\n }\n );\n\nconst SearchBodySchema = z.object({\n query: z.string().min(1, 'Query must be a non-empty string'),\n detail: z.enum(['minimal', 'contextual', 'full']).optional(),\n limit: z.number().int().positive().optional(),\n stores: z.array(z.string()).optional(),\n});\n\nexport function createApp(services: ServiceContainer): Hono {\n const app = new Hono();\n\n app.use('*', cors());\n\n // Health check\n app.get('/health', (c) => c.json({ status: 'ok' }));\n\n // Stores\n app.get('/api/stores', async (c) => {\n const stores = await services.store.list();\n return c.json(stores);\n });\n\n app.post('/api/stores', async (c) => {\n const jsonData: unknown = await c.req.json();\n const parseResult = CreateStoreBodySchema.safeParse(jsonData);\n if (!parseResult.success) {\n return c.json({ error: parseResult.error.issues[0]?.message ?? 'Invalid request body' }, 400);\n }\n const result = await services.store.create(parseResult.data);\n if (result.success) {\n return c.json(result.data, 201);\n }\n return c.json({ error: result.error.message }, 400);\n });\n\n app.get('/api/stores/:id', async (c) => {\n const store = await services.store.getByIdOrName(c.req.param('id'));\n if (!store) return c.json({ error: 'Not found' }, 404);\n return c.json(store);\n });\n\n app.delete('/api/stores/:id', async (c) => {\n const store = await services.store.getByIdOrName(c.req.param('id'));\n if (!store) return c.json({ error: 'Not found' }, 404);\n const result = await services.store.delete(store.id);\n if (result.success) return c.json({ deleted: true });\n return c.json({ error: result.error.message }, 400);\n });\n\n // Search\n app.post('/api/search', async (c) => {\n const jsonData: unknown = await c.req.json();\n const parseResult = SearchBodySchema.safeParse(jsonData);\n if (!parseResult.success) {\n return c.json({ error: parseResult.error.issues[0]?.message ?? 'Invalid request body' }, 400);\n }\n\n const storeIds = (await services.store.list()).map((s) => s.id);\n\n for (const id of storeIds) {\n await services.lance.initialize(id);\n }\n\n // Convert user-provided store strings to StoreIds, or use all stores\n const requestedStores =\n parseResult.data.stores !== undefined\n ? parseResult.data.stores.map((s) => createStoreId(s))\n : storeIds;\n\n const query: SearchQuery = {\n query: parseResult.data.query,\n detail: parseResult.data.detail ?? 'minimal',\n limit: parseResult.data.limit ?? 10,\n stores: requestedStores,\n };\n const results = await services.search.search(query);\n return c.json(results);\n });\n\n // Index\n app.post('/api/stores/:id/index', async (c) => {\n const store = await services.store.getByIdOrName(c.req.param('id'));\n if (!store) return c.json({ error: 'Not found' }, 404);\n\n await services.lance.initialize(store.id);\n const result = await services.index.indexStore(store);\n\n if (result.success) return c.json(result.data);\n return c.json({ error: result.error.message }, 400);\n });\n\n return app;\n}\n","import { spawnSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { mkdir } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { Command } from 'commander';\nimport ora from 'ora';\nimport { DEFAULT_REPOS, type DefaultRepo } from '../../defaults/repos.js';\nimport { createServices, destroyServices } from '../../services/index.js';\nimport type { GlobalOptions } from '../program.js';\n\nconst DEFAULT_REPOS_DIR = join(homedir(), '.bluera', 'bluera-knowledge', 'repos');\n\nexport function createSetupCommand(getOptions: () => GlobalOptions): Command {\n const setup = new Command('setup').description(\n 'Quick-start with pre-configured Claude/Anthropic documentation repos'\n );\n\n setup\n .command('repos')\n .description(\n 'Clone repos to ~/.bluera/bluera-knowledge/repos/, create stores, index all content'\n )\n .option(\n '--repos-dir <path>',\n 'Clone destination (default: ~/.bluera/bluera-knowledge/repos/)',\n DEFAULT_REPOS_DIR\n )\n .option('--skip-clone', \"Don't clone; assume repos already exist locally\")\n .option('--skip-index', \"Clone and create stores but don't index yet\")\n .option('--only <names>', 'Only process matching repos (comma-separated, partial match)')\n .option('--list', 'Print available repos without cloning/indexing')\n .action(\n async (options: {\n reposDir: string;\n skipClone?: boolean;\n skipIndex?: boolean;\n only?: string;\n list?: boolean;\n }) => {\n const globalOpts = getOptions();\n\n // List mode: just show available repos\n if (options.list === true) {\n console.log('\\nDefault repositories:\\n');\n for (const repo of DEFAULT_REPOS) {\n console.log(` ${repo.name}`);\n console.log(` URL: ${repo.url}`);\n console.log(` Description: ${repo.description}`);\n console.log(` Tags: ${repo.tags.join(', ')}`);\n console.log('');\n }\n return;\n }\n\n const services = await createServices(globalOpts.config, globalOpts.dataDir);\n try {\n // Filter repos if --only specified\n let repos: readonly DefaultRepo[] = DEFAULT_REPOS;\n if (options.only !== undefined && options.only !== '') {\n const onlyNames = options.only.split(',').map((n) => n.trim().toLowerCase());\n repos = DEFAULT_REPOS.filter((r) =>\n onlyNames.some((n) => r.name.toLowerCase().includes(n))\n );\n if (repos.length === 0) {\n console.error(`No repos matched: ${options.only}`);\n console.log('Available repos:', DEFAULT_REPOS.map((r) => r.name).join(', '));\n process.exit(1);\n }\n }\n\n console.log(`\\nSetting up ${String(repos.length)} repositories...\\n`);\n\n // Ensure repos directory exists\n await mkdir(options.reposDir, { recursive: true });\n\n for (const repo of repos) {\n const repoPath = join(options.reposDir, repo.name);\n const spinner = ora(`Processing ${repo.name}`).start();\n\n try {\n // Step 1: Clone if needed\n if (options.skipClone !== true) {\n if (existsSync(repoPath)) {\n spinner.text = `${repo.name}: Already cloned, pulling latest...`;\n const pullResult = spawnSync('git', ['pull', '--ff-only'], {\n cwd: repoPath,\n stdio: 'pipe',\n });\n if (pullResult.status !== 0) {\n // Pull failed (maybe diverged), that's okay\n spinner.text = `${repo.name}: Pull skipped (local changes)`;\n }\n } else {\n spinner.text = `${repo.name}: Cloning...`;\n const cloneResult = spawnSync('git', ['clone', repo.url, repoPath], {\n stdio: 'pipe',\n });\n if (cloneResult.status !== 0) {\n const errorMessage =\n cloneResult.stderr.length > 0\n ? cloneResult.stderr.toString()\n : 'Git clone failed';\n throw new Error(errorMessage);\n }\n }\n }\n\n // Step 2: Create store if needed\n spinner.text = `${repo.name}: Creating store...`;\n const existingStore = await services.store.getByIdOrName(repo.name);\n\n let storeId: string;\n if (existingStore) {\n storeId = existingStore.id;\n spinner.text = `${repo.name}: Store already exists`;\n } else {\n const result = await services.store.create({\n name: repo.name,\n type: 'repo',\n path: repoPath,\n description: repo.description,\n tags: repo.tags,\n });\n\n if (!result.success) {\n throw new Error(\n result.error instanceof Error ? result.error.message : String(result.error)\n );\n }\n storeId = result.data.id;\n }\n\n // Step 3: Index if needed\n if (options.skipIndex !== true) {\n spinner.text = `${repo.name}: Indexing...`;\n const store = await services.store.getByIdOrName(storeId);\n if (store) {\n await services.lance.initialize(store.id);\n const indexResult = await services.index.indexStore(store, (event) => {\n if (event.type === 'progress') {\n spinner.text = `${repo.name}: Indexing ${String(event.current)}/${String(event.total)} files`;\n }\n });\n\n if (indexResult.success) {\n spinner.succeed(\n `${repo.name}: ${String(indexResult.data.documentsIndexed)} docs, ${String(indexResult.data.chunksCreated)} chunks`\n );\n } else {\n throw new Error(\n indexResult.error instanceof Error\n ? indexResult.error.message\n : String(indexResult.error)\n );\n }\n }\n } else {\n spinner.succeed(`${repo.name}: Ready (indexing skipped)`);\n }\n } catch (error) {\n spinner.fail(\n `${repo.name}: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n console.log('\\nSetup complete! Use \"bluera-knowledge search <query>\" to search.\\n');\n } finally {\n await destroyServices(services);\n }\n }\n );\n\n return setup;\n}\n","/**\n * Default repositories for quick setup.\n * These are Anthropic/Claude-related repositories that provide\n * useful knowledge for Claude Code development.\n */\n\nexport interface DefaultRepo {\n /** Git URL for cloning */\n url: string;\n /** Friendly name for the store */\n name: string;\n /** Description of what this repo contains */\n description: string;\n /** Tags for categorization */\n tags: string[];\n}\n\nexport const DEFAULT_REPOS: readonly DefaultRepo[] = [\n {\n url: 'git@github.com:ericbuess/claude-code-docs.git',\n name: 'claude-code-docs',\n description: 'Claude Code documentation',\n tags: ['claude', 'docs', 'claude-code'],\n },\n {\n url: 'git@github.com:anthropics/claude-code.git',\n name: 'claude-code',\n description: 'Claude Code CLI tool source',\n tags: ['claude', 'cli', 'anthropic'],\n },\n {\n url: 'git@github.com:anthropics/claude-agent-sdk-python.git',\n name: 'claude-agent-sdk-python',\n description: 'Claude Agent SDK for Python',\n tags: ['claude', 'sdk', 'python', 'agents'],\n },\n {\n url: 'git@github.com:anthropics/skills.git',\n name: 'claude-skills',\n description: 'Claude skills and capabilities',\n tags: ['claude', 'skills'],\n },\n {\n url: 'git@github.com:anthropics/claude-quickstarts.git',\n name: 'claude-quickstarts',\n description: 'Claude quickstart examples and tutorials',\n tags: ['claude', 'examples', 'tutorials'],\n },\n {\n url: 'git@github.com:anthropics/claude-plugins-official.git',\n name: 'claude-plugins',\n description: 'Official Claude plugins',\n tags: ['claude', 'plugins'],\n },\n {\n url: 'git@github.com:anthropics/claude-agent-sdk-typescript.git',\n name: 'claude-agent-sdk-typescript',\n description: 'Claude Agent SDK for TypeScript',\n tags: ['claude', 'sdk', 'typescript', 'agents'],\n },\n {\n url: 'git@github.com:anthropics/claude-agent-sdk-demos.git',\n name: 'claude-agent-sdk-demos',\n description: 'Claude Agent SDK demo applications',\n tags: ['claude', 'sdk', 'demos', 'examples'],\n },\n];\n","import { rm } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { Command } from 'commander';\nimport { createServices, destroyServices } from '../../services/index.js';\nimport type { StoreType } from '../../types/store.js';\nimport type { GlobalOptions } from '../program.js';\n\nexport function createStoreCommand(getOptions: () => GlobalOptions): Command {\n const store = new Command('store').description(\n 'Manage knowledge stores (collections of indexed documents)'\n );\n\n store\n .command('list')\n .description('Show all stores with their type (file/repo/web) and ID')\n .option('-t, --type <type>', 'Filter by type: file, repo, or web')\n .action(async (options: { type?: StoreType }) => {\n const globalOpts = getOptions();\n const services = await createServices(globalOpts.config, globalOpts.dataDir);\n try {\n const stores = await services.store.list(options.type);\n\n if (globalOpts.format === 'json') {\n console.log(JSON.stringify(stores, null, 2));\n } else if (globalOpts.quiet === true) {\n // Quiet mode: just list store names, one per line\n for (const s of stores) {\n console.log(s.name);\n }\n } else {\n if (stores.length === 0) {\n console.log('No stores found.');\n } else {\n console.log('\\nStores:\\n');\n for (const s of stores) {\n console.log(` ${s.name} (${s.type}) - ${s.id}`);\n }\n console.log('');\n }\n }\n } finally {\n await destroyServices(services);\n }\n });\n\n store\n .command('create <name>')\n .description('Create a new store pointing to a local path or URL')\n .requiredOption(\n '-t, --type <type>',\n 'Store type: file (local dir), repo (git), web (crawled site)'\n )\n .requiredOption('-s, --source <path>', 'Local path for file/repo stores, URL for web stores')\n .option('-b, --branch <branch>', 'Git branch to clone (repo stores only)')\n .option('-d, --description <desc>', 'Optional description for the store')\n .option('--tags <tags>', 'Comma-separated tags for filtering')\n .action(\n async (\n name: string,\n options: {\n type: StoreType;\n source: string;\n branch?: string;\n description?: string;\n tags?: string;\n }\n ) => {\n const globalOpts = getOptions();\n const services = await createServices(globalOpts.config, globalOpts.dataDir);\n let exitCode = 0;\n try {\n // Detect if source is a URL (for repo stores that should clone from remote)\n const isUrl =\n options.source.startsWith('http://') || options.source.startsWith('https://');\n const result = await services.store.create({\n name,\n type: options.type,\n path:\n options.type === 'file' || (options.type === 'repo' && !isUrl)\n ? options.source\n : undefined,\n url:\n options.type === 'web' || (options.type === 'repo' && isUrl)\n ? options.source\n : undefined,\n branch: options.type === 'repo' ? options.branch : undefined,\n description: options.description,\n tags: options.tags?.split(',').map((t) => t.trim()),\n });\n\n if (result.success) {\n if (globalOpts.format === 'json') {\n console.log(JSON.stringify(result.data, null, 2));\n } else {\n console.log(`\\nCreated store: ${result.data.name} (${result.data.id})\\n`);\n }\n } else {\n console.error(`Error: ${result.error.message}`);\n exitCode = 1;\n }\n } finally {\n await destroyServices(services);\n }\n if (exitCode !== 0) {\n // Set exit code and let Node.js exit naturally after event loop drains\n // Using process.exit() causes mutex crashes from native code (LanceDB, tree-sitter)\n process.exitCode = exitCode;\n }\n }\n );\n\n store\n .command('info <store>')\n .description('Show store details: ID, type, path/URL, timestamps')\n .action(async (storeIdOrName: string) => {\n const globalOpts = getOptions();\n const services = await createServices(globalOpts.config, globalOpts.dataDir);\n let exitCode = 0;\n storeInfo: try {\n const s = await services.store.getByIdOrName(storeIdOrName);\n\n if (s === undefined) {\n console.error(`Error: Store not found: ${storeIdOrName}`);\n exitCode = 3;\n break storeInfo;\n }\n\n if (globalOpts.format === 'json') {\n console.log(JSON.stringify(s, null, 2));\n } else {\n console.log(`\\nStore: ${s.name}`);\n console.log(` ID: ${s.id}`);\n console.log(` Type: ${s.type}`);\n if ('path' in s) console.log(` Path: ${s.path}`);\n if ('url' in s && s.url !== undefined) console.log(` URL: ${s.url}`);\n if (s.description !== undefined) console.log(` Description: ${s.description}`);\n console.log(` Created: ${s.createdAt.toISOString()}`);\n console.log(` Updated: ${s.updatedAt.toISOString()}`);\n console.log('');\n }\n } finally {\n await destroyServices(services);\n }\n if (exitCode !== 0) {\n // Set exit code and let Node.js exit naturally after event loop drains\n // Using process.exit() causes mutex crashes from native code (LanceDB, tree-sitter)\n process.exitCode = exitCode;\n }\n });\n\n store\n .command('delete <store>')\n .description('Remove store and its indexed documents from LanceDB')\n .option('-f, --force', 'Delete without confirmation prompt')\n .option('-y, --yes', 'Alias for --force')\n .action(async (storeIdOrName: string, options: { force?: boolean; yes?: boolean }) => {\n const globalOpts = getOptions();\n const services = await createServices(globalOpts.config, globalOpts.dataDir);\n let exitCode = 0;\n storeDelete: try {\n const s = await services.store.getByIdOrName(storeIdOrName);\n\n if (s === undefined) {\n console.error(`Error: Store not found: ${storeIdOrName}`);\n exitCode = 3;\n break storeDelete;\n }\n\n // Require --force or -y in non-TTY mode, prompt in TTY mode\n const skipConfirmation = options.force === true || options.yes === true;\n if (!skipConfirmation) {\n if (!process.stdin.isTTY) {\n console.error(\n 'Error: Use --force or -y to delete without confirmation in non-interactive mode'\n );\n exitCode = 1;\n break storeDelete;\n }\n // Interactive confirmation\n const readline = await import('node:readline');\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n const answer = await new Promise<string>((resolve) => {\n rl.question(`Delete store \"${s.name}\"? [y/N] `, resolve);\n });\n rl.close();\n if (answer.toLowerCase() !== 'y' && answer.toLowerCase() !== 'yes') {\n console.log('Cancelled.');\n // exitCode stays 0 for user-initiated cancellation\n break storeDelete;\n }\n }\n\n // Delete LanceDB table first (so searches don't return results for deleted store)\n await services.lance.deleteStore(s.id);\n\n // Delete code graph file\n await services.codeGraph.deleteGraph(s.id);\n\n // For repo stores cloned from URL, remove the cloned directory\n if (s.type === 'repo' && 'url' in s && s.url !== undefined) {\n const dataDir = services.config.resolveDataDir();\n const repoPath = join(dataDir, 'repos', s.id);\n await rm(repoPath, { recursive: true, force: true });\n }\n\n // Delete from registry last\n const result = await services.store.delete(s.id);\n\n if (result.success) {\n console.log(`Deleted store: ${s.name}`);\n } else {\n console.error(`Error: ${result.error.message}`);\n exitCode = 1;\n }\n } finally {\n await destroyServices(services);\n }\n if (exitCode !== 0) {\n // Set exit code and let Node.js exit naturally after event loop drains\n // Using process.exit() causes mutex crashes from native code (LanceDB, tree-sitter)\n process.exitCode = exitCode;\n }\n });\n\n return store;\n}\n","import { Command } from 'commander';\nimport { createServices, destroyServices } from '../../services/index.js';\nimport { JobService } from '../../services/job.service.js';\nimport { StoreDefinitionService } from '../../services/store-definition.service.js';\nimport {\n isFileStoreDefinition,\n isRepoStoreDefinition,\n isWebStoreDefinition,\n} from '../../types/store-definition.js';\nimport { spawnBackgroundWorker } from '../../workers/spawn-worker.js';\nimport type { StoreService } from '../../services/store.service.js';\nimport type { StoreDefinition } from '../../types/store-definition.js';\nimport type { GlobalOptions } from '../program.js';\n\ninterface SyncResult {\n created: string[];\n skipped: string[];\n failed: Array<{ name: string; error: string }>;\n orphans: string[];\n pruned: string[];\n dryRun: boolean;\n wouldCreate: string[];\n wouldPrune: string[];\n reindexJobs: Array<{ store: string; jobId: string }>;\n wouldReindex: string[];\n}\n\n/**\n * Create a store from a definition\n */\nasync function createStoreFromDefinition(\n def: StoreDefinition,\n defService: StoreDefinitionService,\n storeService: StoreService\n): Promise<{ success: true } | { success: false; error: string }> {\n try {\n if (isFileStoreDefinition(def)) {\n const resolvedPath = defService.resolvePath(def.path);\n const createResult = await storeService.create(\n {\n name: def.name,\n type: 'file',\n path: resolvedPath,\n description: def.description,\n tags: def.tags,\n },\n { skipDefinitionSync: true }\n );\n if (!createResult.success) {\n return { success: false, error: createResult.error.message };\n }\n return { success: true };\n }\n\n if (isRepoStoreDefinition(def)) {\n const createResult = await storeService.create(\n {\n name: def.name,\n type: 'repo',\n url: def.url,\n branch: def.branch,\n depth: def.depth,\n description: def.description,\n tags: def.tags,\n },\n { skipDefinitionSync: true }\n );\n if (!createResult.success) {\n return { success: false, error: createResult.error.message };\n }\n return { success: true };\n }\n\n if (isWebStoreDefinition(def)) {\n const createResult = await storeService.create(\n {\n name: def.name,\n type: 'web',\n url: def.url,\n depth: def.depth,\n description: def.description,\n tags: def.tags,\n },\n { skipDefinitionSync: true }\n );\n if (!createResult.success) {\n return { success: false, error: createResult.error.message };\n }\n return { success: true };\n }\n\n return { success: false, error: 'Unknown store definition type' };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\nexport function createSyncCommand(getOptions: () => GlobalOptions): Command {\n const sync = new Command('sync').description(\n 'Sync stores from definitions config (bootstrap on fresh clone)'\n );\n\n sync\n .option('--dry-run', 'Show what would happen without making changes')\n .option('--prune', 'Remove stores not in definitions')\n .option('--reindex', 'Re-index existing stores after sync')\n .action(async (options: { dryRun?: boolean; prune?: boolean; reindex?: boolean }) => {\n const globalOpts = getOptions();\n const projectRoot = globalOpts.projectRoot ?? process.cwd();\n\n const defService = new StoreDefinitionService(projectRoot);\n const services = await createServices(globalOpts.config, globalOpts.dataDir, projectRoot);\n\n try {\n const config = await defService.load();\n const existingStores = await services.store.list();\n const existingNames = new Set(existingStores.map((s) => s.name));\n const definedNames = new Set(config.stores.map((d) => d.name));\n\n const result: SyncResult = {\n created: [],\n skipped: [],\n failed: [],\n orphans: [],\n pruned: [],\n dryRun: options.dryRun === true,\n wouldCreate: [],\n wouldPrune: [],\n reindexJobs: [],\n wouldReindex: [],\n };\n\n // Process each definition\n for (const def of config.stores) {\n if (existingNames.has(def.name)) {\n result.skipped.push(def.name);\n continue;\n }\n\n if (options.dryRun === true) {\n result.wouldCreate.push(def.name);\n continue;\n }\n\n const createResult = await createStoreFromDefinition(def, defService, services.store);\n if (createResult.success) {\n result.created.push(def.name);\n } else {\n result.failed.push({ name: def.name, error: createResult.error });\n }\n }\n\n // Find orphans\n for (const store of existingStores) {\n if (!definedNames.has(store.name)) {\n result.orphans.push(store.name);\n }\n }\n\n // Prune orphans if requested\n if (options.prune === true && result.orphans.length > 0) {\n if (options.dryRun === true) {\n result.wouldPrune = [...result.orphans];\n } else {\n for (const orphanName of result.orphans) {\n const store = await services.store.getByName(orphanName);\n if (store !== undefined) {\n const deleteResult = await services.store.delete(store.id, {\n skipDefinitionSync: true,\n });\n if (deleteResult.success) {\n result.pruned.push(orphanName);\n }\n }\n }\n }\n }\n\n // Re-index existing stores if requested\n if (options.reindex === true && result.skipped.length > 0) {\n if (options.dryRun === true) {\n result.wouldReindex = [...result.skipped];\n } else {\n const dataDir = globalOpts.dataDir ?? services.config.resolveDataDir();\n const jobService = new JobService(dataDir);\n\n for (const storeName of result.skipped) {\n const store = await services.store.getByName(storeName);\n if (store !== undefined) {\n const job = jobService.createJob({\n type: 'index',\n details: { storeId: store.id, storeName: store.name },\n message: `Re-indexing ${storeName}...`,\n });\n spawnBackgroundWorker(job.id, dataDir);\n result.reindexJobs.push({ store: storeName, jobId: job.id });\n }\n }\n }\n }\n\n // Output result\n if (globalOpts.format === 'json') {\n console.log(JSON.stringify(result, null, 2));\n } else {\n printHumanReadable(result, globalOpts.quiet === true);\n }\n } finally {\n await destroyServices(services);\n }\n });\n\n return sync;\n}\n\nfunction printHumanReadable(result: SyncResult, quiet: boolean): void {\n if (quiet) {\n // Just print created/pruned/reindexed store names\n for (const name of result.created) {\n console.log(`created: ${name}`);\n }\n for (const name of result.pruned) {\n console.log(`pruned: ${name}`);\n }\n for (const { store, jobId } of result.reindexJobs) {\n console.log(`reindexing: ${store} (${jobId})`);\n }\n for (const name of result.wouldCreate) {\n console.log(`would create: ${name}`);\n }\n for (const name of result.wouldPrune) {\n console.log(`would prune: ${name}`);\n }\n for (const name of result.wouldReindex) {\n console.log(`would reindex: ${name}`);\n }\n return;\n }\n\n if (result.dryRun) {\n console.log('\\n[DRY RUN] No changes made.\\n');\n } else {\n console.log('\\nSync completed.\\n');\n }\n\n if (result.created.length > 0) {\n console.log(`Created (${String(result.created.length)}):`);\n for (const name of result.created) {\n console.log(` + ${name}`);\n }\n }\n\n if (result.wouldCreate.length > 0) {\n console.log(`Would create (${String(result.wouldCreate.length)}):`);\n for (const name of result.wouldCreate) {\n console.log(` + ${name}`);\n }\n }\n\n if (result.skipped.length > 0) {\n console.log(`Skipped (already exist) (${String(result.skipped.length)}):`);\n for (const name of result.skipped) {\n console.log(` - ${name}`);\n }\n }\n\n if (result.failed.length > 0) {\n console.log(`Failed (${String(result.failed.length)}):`);\n for (const { name, error } of result.failed) {\n console.log(` ! ${name}: ${error}`);\n }\n }\n\n if (result.orphans.length > 0) {\n console.log(`Orphans (not in definitions) (${String(result.orphans.length)}):`);\n for (const name of result.orphans) {\n console.log(` ? ${name}`);\n }\n }\n\n if (result.pruned.length > 0) {\n console.log(`Pruned (${String(result.pruned.length)}):`);\n for (const name of result.pruned) {\n console.log(` x ${name}`);\n }\n }\n\n if (result.wouldPrune.length > 0) {\n console.log(`Would prune (${String(result.wouldPrune.length)}):`);\n for (const name of result.wouldPrune) {\n console.log(` x ${name}`);\n }\n }\n\n if (result.reindexJobs.length > 0) {\n console.log(`Reindexing started (${String(result.reindexJobs.length)}):`);\n for (const { store, jobId } of result.reindexJobs) {\n console.log(` ↻ ${store} (Job: ${jobId})`);\n }\n }\n\n if (result.wouldReindex.length > 0) {\n console.log(`Would reindex (${String(result.wouldReindex.length)}):`);\n for (const name of result.wouldReindex) {\n console.log(` ↻ ${name}`);\n }\n }\n\n console.log('');\n}\n","import { readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { Command } from 'commander';\n\ninterface PackageJson {\n version: string;\n}\n\nfunction getVersion(): string {\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n const content = readFileSync(join(__dirname, '../package.json'), 'utf-8');\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const pkg: PackageJson = JSON.parse(content);\n return pkg.version;\n}\n\nconst version = getVersion();\n\nexport function createProgram(): Command {\n const program = new Command();\n\n program\n .name('bluera-knowledge')\n .description('CLI tool for managing knowledge stores with semantic search')\n .version(version);\n\n program\n .option('-c, --config <path>', 'Path to config file')\n .option('-d, --data-dir <path>', 'Data directory')\n .option('-p, --project-root <path>', 'Project root directory (for resolving relative paths)')\n .option('-f, --format <format>', 'Output format: json | table | plain', 'table')\n .option('-q, --quiet', 'Suppress non-essential output')\n .option('-v, --verbose', 'Enable verbose logging');\n\n return program;\n}\n\nexport interface GlobalOptions {\n config?: string | undefined;\n dataDir?: string | undefined;\n projectRoot?: string | undefined;\n format: 'json' | 'table' | 'plain';\n quiet?: boolean | undefined;\n verbose?: boolean | undefined;\n}\n\nexport function getGlobalOptions(program: Command): GlobalOptions {\n const opts = program.opts<GlobalOptions>();\n return {\n config: opts.config,\n dataDir: opts.dataDir,\n projectRoot: opts.projectRoot,\n format: opts.format,\n quiet: opts.quiet,\n verbose: opts.verbose,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,SAAS,WAAAA,gBAAe;AACxB,SAAS,QAAAC,aAAY;;;ACHrB,SAAS,kBAAkB;AAC3B,SAAS,eAAe;AACxB,OAAO,SAAuB;AAUvB,SAAS,mBAAmB,YAA0C;AAC3E,SAAO,IAAI,QAAQ,OAAO,EACvB,YAAY,oEAAoE,EAChF,SAAS,SAAS,cAAc,EAChC,SAAS,WAAW,4CAA4C,EAChE;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC,OAAO,YAAY,qDAAqD,EACxE,OAAO,wBAAwB,oCAAoC,IAAI,EACvE,OAAO,UAAU,+DAA+D,EAChF;AAAA,IACC,OACE,KACA,eACA,eAOG;AACH,YAAM,aAAa,WAAW;AAC9B,YAAM,WAAW,MAAM,eAAe,WAAW,QAAQ,WAAW,OAAO;AAG3E,UAAI;AACJ,UAAI,eAAe;AACnB,YAAM,gBAAgB,MAAM,SAAS,MAAM,cAAc,aAAa;AAEtE,UAAI,CAAC,eAAe;AAElB,cAAM,SAAS,MAAM,SAAS,MAAM,OAAO;AAAA,UACzC,MAAM;AAAA,UACN,MAAM;AAAA,UACN;AAAA,QACF,CAAC;AACD,YAAI,CAAC,OAAO,S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,WAAW,mBAAmB,MAAM,iBAAiB,OAAO,CAAC,CAAC;AACtE,QAAQ,WAAW,mBAAmB,MAAM,iBAAiB,OAAO,CAAC,CAAC;AACtE,QAAQ,WAAW,kBAAkB,MAAM,iBAAiB,OAAO,CAAC,CAAC;AACrE,QAAQ,WAAW,iBAAiB,MAAM,iBAAiB,OAAO,CAAC,CAAC;AAGpE,IAAI,QAAQ,KAAK,UAAU,GAAG;AAC5B,gBAAc,OAAO;AACrB,UAAQ,KAAK,CAAC;AAChB;AAEA,QAAQ,MAAM;","names":["homedir","join","url","Command","ora","Command","ora","Command","Command","Command","ora","ora","Command","Command","Command","Command","Command","existsSync","join","Command","ora","join","Command","ora","existsSync","join","Command","Command","join","Command","Command","join","Command","__filename","__dirname","program","join","homedir","DEFAULT_REPOS_DIR","program"]}
|