bluera-knowledge 0.9.43 → 0.10.1
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 +75 -0
- package/README.md +114 -42
- package/commands/sync.md +96 -0
- package/dist/{chunk-MQE32YY6.js → chunk-6U45VP5Z.js} +42 -6
- package/dist/chunk-6U45VP5Z.js.map +1 -0
- package/dist/{chunk-CUHYSPRV.js → chunk-DP5XBPQV.js} +372 -2
- package/dist/chunk-DP5XBPQV.js.map +1 -0
- package/dist/{chunk-DWAIT2OD.js → chunk-UE4ZIJYA.js} +74 -5
- package/dist/{chunk-DWAIT2OD.js.map → chunk-UE4ZIJYA.js.map} +1 -1
- package/dist/index.js +216 -7
- package/dist/index.js.map +1 -1
- package/dist/mcp/server.js +2 -2
- package/dist/workers/background-worker-cli.js +4 -3
- package/dist/workers/background-worker-cli.js.map +1 -1
- package/hooks/check-dependencies.sh +29 -0
- package/package.json +1 -1
- package/python/crawl_worker.py +6 -1
- package/src/cli/commands/crawl.test.ts +43 -3
- package/src/cli/commands/crawl.ts +3 -3
- package/src/cli/commands/sync.test.ts +54 -0
- package/src/cli/commands/sync.ts +264 -0
- package/src/cli/index.ts +1 -0
- package/src/crawl/claude-client.test.ts +195 -24
- package/src/crawl/claude-client.ts +38 -3
- package/src/crawl/intelligent-crawler.test.ts +65 -0
- package/src/crawl/intelligent-crawler.ts +14 -2
- package/src/index.ts +2 -0
- package/src/mcp/commands/index.ts +2 -0
- package/src/mcp/commands/sync.commands.test.ts +283 -0
- package/src/mcp/commands/sync.commands.ts +233 -0
- package/src/services/gitignore.service.test.ts +157 -0
- package/src/services/gitignore.service.ts +132 -0
- package/src/services/store-definition.service.test.ts +440 -0
- package/src/services/store-definition.service.ts +198 -0
- package/src/services/store.service.test.ts +279 -1
- package/src/services/store.service.ts +101 -4
- package/src/types/index.ts +18 -0
- package/src/types/store-definition.test.ts +492 -0
- package/src/types/store-definition.ts +129 -0
- package/src/workers/background-worker.ts +1 -1
- package/dist/chunk-CUHYSPRV.js.map +0 -1
- package/dist/chunk-MQE32YY6.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/crawl/intelligent-crawler.ts","../src/crawl/article-converter.ts","../src/crawl/markdown-utils.ts","../src/crawl/claude-client.ts"],"sourcesContent":["/**\n * Intelligent web crawler with natural language control\n * Two modes: Intelligent (Claude-driven) and Simple (BFS)\n */\n\nimport { EventEmitter } from 'node:events';\nimport axios from 'axios';\nimport { convertHtmlToMarkdown } from './article-converter.js';\nimport { PythonBridge, type CrawledLink } from './bridge.js';\nimport { ClaudeClient, type CrawlStrategy } from './claude-client.js';\nimport { createLogger, summarizePayload } from '../logging/index.js';\n\nconst logger = createLogger('crawler');\n\nexport interface CrawlOptions {\n crawlInstruction?: string; // Natural language: what to crawl\n extractInstruction?: string; // Natural language: what to extract\n maxPages?: number; // Max pages to crawl (default: 50)\n timeout?: number; // Per-page timeout in ms (default: 30000)\n simple?: boolean; // Force simple BFS mode\n useHeadless?: boolean; // Enable headless browser for JavaScript-rendered sites\n}\n\nexport interface CrawlResult {\n url: string;\n title?: string;\n markdown: string;\n extracted?: string;\n depth?: number;\n}\n\nexport interface CrawlProgress {\n type: 'start' | 'strategy' | 'page' | 'extraction' | 'complete' | 'error';\n pagesVisited: number;\n totalPages: number;\n currentUrl?: string;\n message?: string;\n error?: Error;\n}\n\n/**\n * Intelligent crawler that uses Claude CLI for strategy and extraction\n */\nexport class IntelligentCrawler extends EventEmitter {\n private readonly claudeClient: ClaudeClient;\n private readonly pythonBridge: PythonBridge;\n private readonly visited: Set<string>;\n private stopped: boolean;\n\n constructor() {\n super();\n this.claudeClient = new ClaudeClient();\n this.pythonBridge = new PythonBridge();\n this.visited = new Set();\n this.stopped = false;\n }\n\n /**\n * Crawl a website with intelligent or simple mode\n */\n async *crawl(seedUrl: string, options: CrawlOptions = {}): AsyncIterable<CrawlResult> {\n const { crawlInstruction, extractInstruction, maxPages = 50, simple = false } = options;\n\n this.visited.clear();\n this.stopped = false;\n\n logger.info(\n {\n seedUrl,\n maxPages,\n mode: simple\n ? 'simple'\n : crawlInstruction !== undefined && crawlInstruction !== ''\n ? 'intelligent'\n : 'simple',\n hasExtractInstruction: extractInstruction !== undefined,\n },\n 'Starting crawl'\n );\n\n const startProgress: CrawlProgress = {\n type: 'start',\n pagesVisited: 0,\n totalPages: maxPages,\n };\n this.emit('progress', startProgress);\n\n // Determine mode: intelligent (with crawl instruction) or simple (BFS)\n const useIntelligentMode = !simple && crawlInstruction !== undefined && crawlInstruction !== '';\n\n if (useIntelligentMode) {\n // TypeScript knows crawlInstruction is defined here due to useIntelligentMode check\n yield* this.crawlIntelligent(\n seedUrl,\n crawlInstruction,\n extractInstruction,\n maxPages,\n options.useHeadless ?? false\n );\n } else {\n yield* this.crawlSimple(seedUrl, extractInstruction, maxPages, options.useHeadless ?? false);\n }\n\n logger.info(\n {\n seedUrl,\n pagesVisited: this.visited.size,\n },\n 'Crawl complete'\n );\n\n // Warn if crawl discovered far fewer pages than requested\n if (this.visited.size === 1 && maxPages > 1) {\n const warningProgress: CrawlProgress = {\n type: 'error',\n pagesVisited: this.visited.size,\n totalPages: maxPages,\n message: `Warning: Only crawled 1 page despite maxPages=${String(maxPages)}. Link discovery may have failed. If using --fast mode, try without it for JavaScript-heavy sites.`,\n error: new Error('Low page discovery'),\n };\n this.emit('progress', warningProgress);\n }\n\n const completeProgress: CrawlProgress = {\n type: 'complete',\n pagesVisited: this.visited.size,\n totalPages: this.visited.size,\n };\n this.emit('progress', completeProgress);\n }\n\n /**\n * Intelligent mode: Use Claude to determine which URLs to crawl\n */\n private async *crawlIntelligent(\n seedUrl: string,\n crawlInstruction: string,\n extractInstruction: string | undefined,\n maxPages: number,\n useHeadless: boolean = false\n ): AsyncIterable<CrawlResult> {\n // Check if Claude CLI is available before attempting intelligent mode\n if (!ClaudeClient.isAvailable()) {\n const fallbackProgress: CrawlProgress = {\n type: 'error',\n pagesVisited: 0,\n totalPages: maxPages,\n message:\n 'Claude CLI not found, using simple crawl mode (install Claude Code for intelligent crawling)',\n error: new Error('Claude CLI not available'),\n };\n this.emit('progress', fallbackProgress);\n yield* this.crawlSimple(seedUrl, extractInstruction, maxPages, useHeadless);\n return;\n }\n\n let strategy: CrawlStrategy;\n\n try {\n // Step 1: Fetch seed page HTML\n const strategyStartProgress: CrawlProgress = {\n type: 'strategy',\n pagesVisited: 0,\n totalPages: maxPages,\n currentUrl: seedUrl,\n message: 'Analyzing page structure with Claude...',\n };\n this.emit('progress', strategyStartProgress);\n\n const seedHtml = await this.fetchHtml(seedUrl, useHeadless);\n\n // Step 2: Ask Claude which URLs to crawl (pass seedUrl for relative URL resolution)\n strategy = await this.claudeClient.determineCrawlUrls(seedUrl, seedHtml, crawlInstruction);\n\n const strategyCompleteProgress: CrawlProgress = {\n type: 'strategy',\n pagesVisited: 0,\n totalPages: maxPages,\n message: `Claude identified ${String(strategy.urls.length)} URLs to crawl: ${strategy.reasoning}`,\n };\n this.emit('progress', strategyCompleteProgress);\n } catch (error) {\n // Fallback to simple mode if Claude fails\n const errorProgress: CrawlProgress = {\n type: 'error',\n pagesVisited: 0,\n totalPages: maxPages,\n message: 'Claude crawl strategy failed, falling back to simple mode',\n error: error instanceof Error ? error : new Error(String(error)),\n };\n this.emit('progress', errorProgress);\n\n yield* this.crawlSimple(seedUrl, extractInstruction, maxPages);\n return;\n }\n\n // Step 3: Crawl each URL from Claude's strategy\n let pagesVisited = 0;\n\n for (const url of strategy.urls) {\n if (this.stopped || pagesVisited >= maxPages) break;\n if (this.visited.has(url)) continue;\n\n try {\n const result = await this.crawlSinglePage(\n url,\n extractInstruction,\n pagesVisited,\n useHeadless\n );\n pagesVisited++;\n yield result;\n } catch (error) {\n const pageErrorProgress: CrawlProgress = {\n type: 'error',\n pagesVisited,\n totalPages: maxPages,\n currentUrl: url,\n error: error instanceof Error ? error : new Error(String(error)),\n };\n this.emit('progress', pageErrorProgress);\n }\n }\n }\n\n /**\n * Simple mode: BFS crawling with depth limit\n */\n private async *crawlSimple(\n seedUrl: string,\n extractInstruction: string | undefined,\n maxPages: number,\n useHeadless: boolean = false\n ): AsyncIterable<CrawlResult> {\n const queue: Array<{ url: string; depth: number }> = [{ url: seedUrl, depth: 0 }];\n const maxDepth = 2; // Default depth limit for simple mode\n let pagesVisited = 0;\n\n while (queue.length > 0 && pagesVisited < maxPages && !this.stopped) {\n const current = queue.shift();\n\n if (!current || this.visited.has(current.url) || current.depth > maxDepth) {\n continue;\n }\n\n try {\n const result = await this.crawlSinglePage(\n current.url,\n extractInstruction,\n pagesVisited,\n useHeadless\n );\n result.depth = current.depth;\n pagesVisited++;\n\n yield result;\n\n // Add links to queue if we haven't reached max depth\n if (current.depth < maxDepth) {\n try {\n const links = await this.extractLinks(current.url, useHeadless);\n\n if (links.length === 0) {\n logger.debug({ url: current.url }, 'No links found - page may be a leaf node');\n } else {\n logger.debug(\n { url: current.url, linkCount: links.length },\n 'Links extracted from page'\n );\n }\n\n for (const link of links) {\n if (!this.visited.has(link) && this.isSameDomain(seedUrl, link)) {\n queue.push({ url: link, depth: current.depth + 1 });\n }\n }\n } catch (error) {\n // Log link extraction failure but continue crawling other pages\n const errorProgress: CrawlProgress = {\n type: 'error',\n pagesVisited,\n totalPages: maxPages,\n currentUrl: current.url,\n message: `Failed to extract links from ${current.url}`,\n error: error instanceof Error ? error : new Error(String(error)),\n };\n this.emit('progress', errorProgress);\n }\n }\n } catch (error) {\n const simpleErrorProgress: CrawlProgress = {\n type: 'error',\n pagesVisited,\n totalPages: maxPages,\n currentUrl: current.url,\n error: error instanceof Error ? error : new Error(String(error)),\n };\n this.emit('progress', simpleErrorProgress);\n }\n }\n }\n\n /**\n * Crawl a single page: fetch, convert to markdown, optionally extract\n */\n private async crawlSinglePage(\n url: string,\n extractInstruction: string | undefined,\n pagesVisited: number,\n useHeadless: boolean = false\n ): Promise<CrawlResult> {\n const pageProgress: CrawlProgress = {\n type: 'page',\n pagesVisited,\n totalPages: 0,\n currentUrl: url,\n };\n this.emit('progress', pageProgress);\n\n // Mark as visited\n this.visited.add(url);\n\n // Fetch HTML\n const html = await this.fetchHtml(url, useHeadless);\n\n // Convert to clean markdown using slurp-ai techniques\n const conversion = await convertHtmlToMarkdown(html, url);\n\n if (!conversion.success) {\n logger.error({ url, error: conversion.error }, 'HTML to markdown conversion failed');\n throw new Error(`Failed to convert HTML: ${conversion.error ?? 'Unknown error'}`);\n }\n\n logger.debug(\n {\n url,\n title: conversion.title,\n markdownLength: conversion.markdown.length,\n },\n 'Article converted to markdown'\n );\n\n let extracted: string | undefined;\n\n // Optional: Extract specific information using Claude\n if (extractInstruction !== undefined && extractInstruction !== '') {\n // Skip extraction if Claude CLI isn't available\n if (!ClaudeClient.isAvailable()) {\n const skipProgress: CrawlProgress = {\n type: 'error',\n pagesVisited,\n totalPages: 0,\n currentUrl: url,\n message: 'Skipping extraction (Claude CLI not available), storing raw markdown',\n error: new Error('Claude CLI not available'),\n };\n this.emit('progress', skipProgress);\n } else {\n try {\n const extractionProgress: CrawlProgress = {\n type: 'extraction',\n pagesVisited,\n totalPages: 0,\n currentUrl: url,\n };\n this.emit('progress', extractionProgress);\n\n extracted = await this.claudeClient.extractContent(\n conversion.markdown,\n extractInstruction\n );\n } catch (error) {\n // If extraction fails, just store raw markdown\n const extractionErrorProgress: CrawlProgress = {\n type: 'error',\n pagesVisited,\n totalPages: 0,\n currentUrl: url,\n message: 'Extraction failed, storing raw markdown',\n error: error instanceof Error ? error : new Error(String(error)),\n };\n this.emit('progress', extractionErrorProgress);\n }\n }\n }\n\n return {\n url,\n ...(conversion.title !== undefined && { title: conversion.title }),\n markdown: conversion.markdown,\n ...(extracted !== undefined && { extracted }),\n };\n }\n\n /**\n * Fetch HTML content from a URL\n */\n private async fetchHtml(url: string, useHeadless: boolean = false): Promise<string> {\n const startTime = Date.now();\n logger.debug({ url, useHeadless }, 'Fetching HTML');\n\n if (useHeadless) {\n try {\n const result = await this.pythonBridge.fetchHeadless(url);\n const durationMs = Date.now() - startTime;\n logger.info(\n {\n url,\n useHeadless: true,\n durationMs,\n ...summarizePayload(result.html, 'raw-html', url),\n },\n 'Raw HTML fetched'\n );\n return result.html;\n } catch (error) {\n // Fallback to axios if headless fails\n logger.warn(\n { url, error: error instanceof Error ? error.message : String(error) },\n 'Headless fetch failed, falling back to axios'\n );\n }\n }\n\n // Original axios implementation for static sites\n try {\n const response = await axios.get<string>(url, {\n timeout: 30000,\n headers: {\n 'User-Agent': 'Mozilla/5.0 (compatible; bluera-knowledge-crawler/1.0)',\n },\n });\n\n const durationMs = Date.now() - startTime;\n logger.info(\n {\n url,\n useHeadless: false,\n durationMs,\n ...summarizePayload(response.data, 'raw-html', url),\n },\n 'Raw HTML fetched'\n );\n\n return response.data;\n } catch (error) {\n logger.error(\n { url, error: error instanceof Error ? error.message : String(error) },\n 'Failed to fetch HTML'\n );\n throw new Error(\n `Failed to fetch ${url}: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n /**\n * Extract links from a page using Python bridge\n */\n private async extractLinks(url: string, useHeadless: boolean = false): Promise<string[]> {\n try {\n // Use headless mode for link extraction if enabled\n if (useHeadless) {\n const result = await this.pythonBridge.fetchHeadless(url);\n // Extract href strings from link objects (crawl4ai returns objects, not strings)\n return result.links.map((link: CrawledLink | string) => {\n if (typeof link === 'string') return link;\n return link.href;\n });\n }\n\n const result = await this.pythonBridge.crawl(url);\n\n // Validate response structure (handle potential runtime type mismatches)\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- TypeScript types claim pages exists but Python bridge may return invalid structure at runtime\n const firstPage = result.pages?.[0];\n if (!firstPage) {\n throw new Error(`Invalid crawl response structure for ${url}: missing pages array`);\n }\n\n return firstPage.links;\n } catch (error: unknown) {\n // Log the error for debugging\n const errorMessage = error instanceof Error ? error.message : String(error);\n logger.error({ url, error: errorMessage }, 'Failed to extract links');\n\n // Re-throw the error instead of silently swallowing it\n throw new Error(`Link extraction failed for ${url}: ${errorMessage}`);\n }\n }\n\n /**\n * Check if two URLs are from the same domain\n */\n private isSameDomain(url1: string, url2: string): boolean {\n try {\n const domain1 = new URL(url1).hostname.toLowerCase();\n const domain2 = new URL(url2).hostname.toLowerCase();\n return (\n domain1 === domain2 || domain1.endsWith(`.${domain2}`) || domain2.endsWith(`.${domain1}`)\n );\n } catch {\n return false;\n }\n }\n\n /**\n * Stop the crawler\n */\n async stop(): Promise<void> {\n this.stopped = true;\n await this.pythonBridge.stop();\n }\n}\n","/**\n * Article converter using @extractus/article-extractor and Turndown\n * Produces clean markdown from HTML using slurp-ai techniques\n */\n\nimport { extractFromHtml } from '@extractus/article-extractor';\nimport TurndownService from 'turndown';\nimport { gfm } from 'turndown-plugin-gfm';\nimport { preprocessHtmlForCodeBlocks, cleanupMarkdown } from './markdown-utils.js';\nimport { createLogger, truncateForLog } from '../logging/index.js';\n\nconst logger = createLogger('article-converter');\n\nexport interface ConversionResult {\n markdown: string;\n title?: string;\n success: boolean;\n error?: string;\n}\n\n/**\n * Convert HTML to clean markdown using best practices from slurp-ai\n *\n * Pipeline:\n * 1. Extract main article content (strips navigation, ads, boilerplate)\n * 2. Preprocess HTML (handle MkDocs code blocks)\n * 3. Convert to markdown with Turndown + GFM\n * 4. Cleanup markdown (regex patterns)\n */\nexport async function convertHtmlToMarkdown(html: string, url: string): Promise<ConversionResult> {\n logger.debug({ url, htmlLength: html.length }, 'Starting HTML conversion');\n\n try {\n // Step 1: Extract main article content\n let articleHtml: string;\n let title: string | undefined;\n\n try {\n const article = await extractFromHtml(html, url);\n if (article?.content !== undefined && article.content !== '') {\n articleHtml = article.content;\n title = article.title !== undefined && article.title !== '' ? article.title : undefined;\n logger.debug(\n {\n url,\n title,\n extractedLength: articleHtml.length,\n usedFullHtml: false,\n },\n 'Article content extracted'\n );\n } else {\n // Fallback to full HTML if extraction fails\n articleHtml = html;\n logger.debug(\n { url, usedFullHtml: true },\n 'Article extraction returned empty, using full HTML'\n );\n }\n } catch (extractError) {\n // Fallback to full HTML if extraction fails\n articleHtml = html;\n logger.debug(\n {\n url,\n usedFullHtml: true,\n error: extractError instanceof Error ? extractError.message : String(extractError),\n },\n 'Article extraction failed, using full HTML'\n );\n }\n\n // Step 2: Preprocess HTML for code blocks\n const preprocessed = preprocessHtmlForCodeBlocks(articleHtml);\n\n // Step 3: Configure Turndown with custom rules\n const turndownService = new TurndownService({\n headingStyle: 'atx', // Use # style headings\n codeBlockStyle: 'fenced', // Use ``` style code blocks\n fence: '```',\n emDelimiter: '*',\n strongDelimiter: '**',\n linkStyle: 'inlined',\n });\n\n // Add GitHub Flavored Markdown support (tables, strikethrough, task lists)\n turndownService.use(gfm);\n\n // Custom rule for headings with anchors (from slurp-ai)\n turndownService.addRule('headingsWithAnchors', {\n filter: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'],\n replacement(content: string, node: HTMLElement): string {\n const level = Number(node.nodeName.charAt(1));\n const hashes = '#'.repeat(level);\n const cleanContent = content\n .replace(/\\[\\]\\([^)]*\\)/g, '') // Remove empty links\n .replace(/\\s+/g, ' ') // Normalize whitespace\n .trim();\n return cleanContent !== '' ? `\\n\\n${hashes} ${cleanContent}\\n\\n` : '';\n },\n });\n\n // Convert to markdown\n const rawMarkdown = turndownService.turndown(preprocessed);\n\n // Step 4: Cleanup markdown with comprehensive regex patterns\n const markdown = cleanupMarkdown(rawMarkdown);\n\n logger.debug(\n {\n url,\n title,\n rawMarkdownLength: rawMarkdown.length,\n finalMarkdownLength: markdown.length,\n },\n 'HTML to markdown conversion complete'\n );\n\n // Log markdown preview at trace level\n logger.trace(\n {\n url,\n markdownPreview: truncateForLog(markdown, 1000),\n },\n 'Markdown content preview'\n );\n\n return {\n markdown,\n ...(title !== undefined && { title }),\n success: true,\n };\n } catch (error) {\n logger.error(\n {\n url,\n error: error instanceof Error ? error.message : String(error),\n },\n 'HTML to markdown conversion failed'\n );\n\n return {\n markdown: '',\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n","/**\n * Markdown conversion utilities ported from slurp-ai\n * Source: https://github.com/ratacat/slurp-ai\n *\n * These utilities handle complex documentation site patterns (MkDocs, Sphinx, etc.)\n * and produce clean, well-formatted markdown.\n */\n\nimport * as cheerio from 'cheerio';\n\n/**\n * Detect language from code element class names.\n * Handles various class naming patterns from different highlighters.\n */\nfunction detectLanguageFromClass(className: string | undefined): string {\n if (className === undefined || className === '') return '';\n\n // Common patterns: \"language-python\", \"lang-js\", \"highlight-python\", \"python\", \"hljs language-python\"\n const patterns = [\n /language-(\\w+)/i,\n /lang-(\\w+)/i,\n /highlight-(\\w+)/i,\n /hljs\\s+(\\w+)/i,\n /^(\\w+)$/i,\n ];\n\n for (const pattern of patterns) {\n const match = className.match(pattern);\n if (match?.[1] !== undefined) {\n const lang = match[1].toLowerCase();\n // Filter out common non-language classes\n if (!['hljs', 'highlight', 'code', 'pre', 'block', 'inline'].includes(lang)) {\n return lang;\n }\n }\n }\n\n return '';\n}\n\n/**\n * Escape HTML special characters for safe embedding in HTML.\n */\nfunction escapeHtml(text: string): string {\n return text\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n\n/**\n * Preprocess HTML to handle MkDocs/Material theme code blocks.\n *\n * MkDocs wraps code in tables for line numbers:\n * <table><tbody><tr><td>line numbers</td><td><pre><code>code</code></pre></td></tr></tbody></table>\n *\n * This function converts them to standard <pre><code> blocks that Turndown handles correctly.\n * Also strips syntax highlighting spans and empty anchors from code.\n */\nexport function preprocessHtmlForCodeBlocks(html: string): string {\n if (!html || typeof html !== 'string') return html;\n\n const $ = cheerio.load(html);\n\n // Handle MkDocs/Material table-wrapped code blocks\n $('table').each((_i, table) => {\n const $table = $(table);\n\n // Check if this table contains a code block\n const $codeCell = $table.find('td pre code, td div pre code');\n\n if ($codeCell.length > 0) {\n // This is a code block table - extract the code\n const $pre = $codeCell.closest('pre');\n const $code = $codeCell.first();\n\n // Get language from class\n let language = detectLanguageFromClass($code.attr('class'));\n if (!language) {\n language = detectLanguageFromClass($pre.attr('class'));\n }\n\n // Get the text content, stripping all inner HTML tags\n const codeText = $code.text();\n\n // Create a clean pre > code block\n const cleanPre = `<pre><code class=\"language-${language}\">${escapeHtml(codeText)}</code></pre>`;\n\n // Replace the entire table with the clean code block\n $table.replaceWith(cleanPre);\n }\n });\n\n // Strip empty anchor tags used for line numbers\n $('pre a, code a').each((_i, anchor) => {\n const $anchor = $(anchor);\n if (!$anchor.text().trim()) {\n $anchor.remove();\n }\n });\n\n // Strip syntax highlighting spans inside code blocks, keeping only text\n $('pre span, code span').each((_i, span) => {\n const $span = $(span);\n $span.replaceWith($span.text());\n });\n\n // Handle standalone pre blocks that might have spans/anchors\n $('pre').each((_i, pre) => {\n const $pre = $(pre);\n // If this pre has a code child, it was already processed\n if ($pre.find('code').length === 0) {\n // Direct pre without code - get text content\n const text = $pre.text();\n const lang = detectLanguageFromClass($pre.attr('class'));\n $pre.html(`<code class=\"language-${lang}\">${escapeHtml(text)}</code>`);\n }\n });\n\n return $.html();\n}\n\n/**\n * Apply comprehensive cleanup rules to markdown content.\n *\n * Formatting rules:\n * - Double newlines between paragraphs and headings\n * - Double newlines before lists when preceded by normal text\n * - Single newlines between list items\n * - No blank lines inside code blocks\n */\nexport function cleanupMarkdown(markdown: string): string {\n if (!markdown) return '';\n\n const trimmed = markdown.trim();\n if (trimmed === '') return '';\n\n let result = trimmed;\n\n // 0. Fix broken headings where ## is on its own line followed by the text\n // Pattern: \"## \\n\\nSome text\" → \"## Some text\"\n result = result.replace(/^(#{1,6})\\s*\\n\\n+(\\S[^\\n]*)/gm, '$1 $2');\n\n // 0.5. Normalize multiple spaces after heading markers to single space\n // Pattern: \"## Subtitle\" → \"## Subtitle\"\n result = result.replace(/(#{1,6})\\s{2,}/g, '$1 ');\n\n // 1. Fix navigation links with excessive whitespace\n result = result.replace(/\\*\\s+\\[\\s*([^\\n]+?)\\s*\\]\\(([^)]+)\\)/g, '* [$1]($2)');\n\n // 2. Handle headings with specific newline requirements\n\n // Text followed by heading should have a single newline between them (no blank line)\n result = result.replace(/([^\\n])\\n\\n+(#\\s)/g, '$1\\n$2');\n\n // Add double newlines between text and next heading\n result = result.replace(/(Some text\\.)\\n(##\\s)/g, '$1\\n\\n$2');\n\n // Double newlines after a heading when followed by text\n result = result.replace(/(#{1,6}\\s[^\\n]+)\\n([^#\\n])/g, '$1\\n\\n$2');\n\n // Double newlines between headings\n result = result.replace(/(#{1,6}\\s[^\\n]+)\\n(#{1,6}\\s)/g, '$1\\n\\n$2');\n\n // 3. Lists - ensure all list items have single newlines only\n result = result.replace(/(\\* Item 1)\\n\\n+(\\* Item 2)\\n\\n+(\\* Item 3)/g, '$1\\n$2\\n$3');\n\n // 3.5. General list item spacing - ensure single newlines between list items\n result = result.replace(/(^\\*\\s[^\\n]+)\\n{2,}(^\\*\\s)/gm, '$1\\n$2');\n\n // 4. Clean up excessive blank lines (3+ newlines → 2 newlines)\n result = result.replace(/\\n{3,}/g, '\\n\\n');\n\n // 5. Code blocks - no blank lines after opening or before closing backticks\n result = result.replace(/(```[^\\n]*)\\n\\n+/g, '$1\\n');\n result = result.replace(/\\n\\n+```/g, '\\n```');\n\n // 6. Remove empty list items\n result = result.replace(/\\*\\s*\\n\\s*\\*/g, '*');\n\n // 7. Strip any remaining HTML tags that leaked through (common in MkDocs/Material)\n // Remove table structure tags\n result = result.replace(/<\\/?table[^>]*>/gi, '');\n result = result.replace(/<\\/?tbody[^>]*>/gi, '');\n result = result.replace(/<\\/?thead[^>]*>/gi, '');\n result = result.replace(/<\\/?tr[^>]*>/gi, '');\n result = result.replace(/<\\/?td[^>]*>/gi, '');\n result = result.replace(/<\\/?th[^>]*>/gi, '');\n\n // Remove empty anchor tags: <a></a> or <a id=\"...\"></a>\n result = result.replace(/<a[^>]*><\\/a>/gi, '');\n\n // Remove span tags (syntax highlighting remnants)\n result = result.replace(/<\\/?span[^>]*>/gi, '');\n\n // Remove div tags\n result = result.replace(/<\\/?div[^>]*>/gi, '');\n\n // Remove pre/code tags that leaked\n result = result.replace(/<\\/?pre[^>]*>/gi, '');\n result = result.replace(/<\\/?code[^>]*>/gi, '');\n\n // 8. Remove empty markdown links: [](url) and []()\n result = result.replace(/\\[\\]\\([^)]*\\)/g, '');\n\n // 9. Remove codelineno references that leaked into content\n // Pattern: [](_file.md#__codelineno-N-M)\n result = result.replace(/\\[\\]\\([^)]*#__codelineno-[^)]+\\)/g, '');\n\n // Also clean inline codelineno patterns\n result = result.replace(/\\[?\\]?\\([^)]*#__codelineno-[^)]*\\)/g, '');\n\n // 10. Clean up any double-escaped HTML entities that might result\n result = result.replace(/&lt;/g, '<');\n result = result.replace(/&gt;/g, '>');\n result = result.replace(/&amp;/g, '&');\n\n // 11. Final cleanup - normalize excessive whitespace from removed tags\n result = result.replace(/\\n{3,}/g, '\\n\\n');\n result = result.replace(/[ \\t]+\\n/g, '\\n');\n\n return result;\n}\n","/**\n * Claude CLI client for intelligent crawling and extraction\n * Uses `claude -p` programmatically to analyze page structure and extract content\n */\n\nimport { spawn, execSync } from 'node:child_process';\n\n/**\n * Schema for crawl strategy response from Claude\n */\nexport interface CrawlStrategy {\n urls: string[];\n reasoning: string;\n}\n\nconst CRAWL_STRATEGY_SCHEMA = {\n type: 'object',\n properties: {\n urls: {\n type: 'array',\n items: { type: 'string' },\n description: 'List of URLs to crawl based on the instruction',\n },\n reasoning: {\n type: 'string',\n description: 'Brief explanation of why these URLs were selected',\n },\n },\n required: ['urls', 'reasoning'],\n};\n\n/**\n * Client for interacting with Claude Code CLI\n */\nexport class ClaudeClient {\n private readonly timeout: number;\n private static availabilityChecked = false;\n private static available = false;\n\n /**\n * Check if Claude CLI is available in PATH\n * Result is cached after first check for performance\n */\n static isAvailable(): boolean {\n if (!ClaudeClient.availabilityChecked) {\n try {\n execSync('which claude', { stdio: 'ignore' });\n ClaudeClient.available = true;\n } catch {\n ClaudeClient.available = false;\n }\n ClaudeClient.availabilityChecked = true;\n }\n return ClaudeClient.available;\n }\n\n /**\n * Reset availability cache (for testing)\n */\n static resetAvailabilityCache(): void {\n ClaudeClient.availabilityChecked = false;\n ClaudeClient.available = false;\n }\n\n constructor(options: { timeout?: number } = {}) {\n this.timeout = options.timeout ?? 30000; // 30s default\n }\n\n /**\n * Determine which URLs to crawl based on natural language instruction\n *\n * @param seedUrl - The URL of the seed page (for resolving relative URLs)\n * @param seedHtml - HTML content of the seed page\n * @param instruction - Natural language crawl instruction (e.g., \"scrape all Getting Started pages\")\n * @returns List of URLs to crawl with reasoning\n */\n async determineCrawlUrls(\n seedUrl: string,\n seedHtml: string,\n instruction: string\n ): Promise<CrawlStrategy> {\n const prompt = `You are analyzing a webpage to determine which pages to crawl based on the user's instruction.\n\nBase URL: ${seedUrl}\n\nInstruction: ${instruction}\n\nWebpage HTML (analyze the navigation structure, links, and content):\n${this.truncateHtml(seedHtml, 50000)}\n\nBased on the instruction, extract and return a list of absolute URLs that should be crawled. When you encounter relative URLs (starting with \"/\" or without a protocol), resolve them against the Base URL. For example, if Base URL is \"https://example.com/docs\" and you see href=\"/docs/hooks\", return \"https://example.com/docs/hooks\".\n\nLook for navigation menus, sidebars, headers, and link structures that match the instruction.\n\nReturn only URLs that are relevant to the instruction. If the instruction mentions specific sections (e.g., \"Getting Started\"), find links in those sections.`;\n\n try {\n const result = await this.callClaude(prompt, CRAWL_STRATEGY_SCHEMA);\n const rawParsed: unknown = JSON.parse(result);\n\n // Claude CLI with --json-schema returns wrapper: {type, result, structured_output: {...}}\n // Extract structured_output if present, otherwise use raw response\n const parsed = this.extractStructuredOutput(rawParsed);\n\n // Validate and narrow type\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n !('urls' in parsed) ||\n !('reasoning' in parsed) ||\n !Array.isArray(parsed.urls) ||\n parsed.urls.length === 0 ||\n typeof parsed.reasoning !== 'string' ||\n !parsed.urls.every((url) => typeof url === 'string')\n ) {\n throw new Error('Claude returned invalid crawl strategy');\n }\n\n // Type is now properly narrowed - urls is string[] after validation\n return { urls: parsed.urls, reasoning: parsed.reasoning };\n } catch (error) {\n throw new Error(\n `Failed to determine crawl strategy: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n /**\n * Extract specific information from markdown content using natural language\n *\n * @param markdown - Page content in markdown format\n * @param instruction - Natural language extraction instruction (e.g., \"extract pricing info\")\n * @returns Extracted information as text\n */\n async extractContent(markdown: string, instruction: string): Promise<string> {\n const prompt = `${instruction}\n\nContent to analyze:\n${this.truncateMarkdown(markdown, 100000)}`;\n\n try {\n const result = await this.callClaude(prompt);\n return result.trim();\n } catch (error) {\n throw new Error(\n `Failed to extract content: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n /**\n * Call Claude CLI with a prompt\n *\n * @param prompt - The prompt to send to Claude\n * @param jsonSchema - Optional JSON schema for structured output\n * @returns Claude's response as a string\n */\n private async callClaude(prompt: string, jsonSchema?: Record<string, unknown>): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n const args = ['-p'];\n\n // Add JSON schema if provided\n if (jsonSchema) {\n args.push('--json-schema', JSON.stringify(jsonSchema));\n args.push('--output-format', 'json');\n }\n\n const proc = spawn('claude', args, {\n stdio: ['pipe', 'pipe', 'pipe'],\n cwd: process.cwd(),\n env: { ...process.env },\n });\n\n let stdout = '';\n let stderr = '';\n let timeoutId: NodeJS.Timeout | undefined;\n\n // Set timeout\n if (this.timeout > 0) {\n timeoutId = setTimeout(() => {\n proc.kill('SIGTERM');\n reject(new Error(`Claude CLI timed out after ${String(this.timeout)}ms`));\n }, this.timeout);\n }\n\n proc.stdout.on('data', (chunk: Buffer) => {\n stdout += chunk.toString();\n });\n\n proc.stderr.on('data', (chunk: Buffer) => {\n stderr += chunk.toString();\n });\n\n proc.on('close', (code: number | null) => {\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n\n if (code === 0) {\n resolve(stdout.trim());\n } else {\n reject(\n new Error(`Claude CLI exited with code ${String(code)}${stderr ? `: ${stderr}` : ''}`)\n );\n }\n });\n\n proc.on('error', (err) => {\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n reject(new Error(`Failed to spawn Claude CLI: ${err.message}`));\n });\n\n // Write prompt to stdin\n proc.stdin.write(prompt);\n proc.stdin.end();\n });\n }\n\n /**\n * Truncate HTML to a maximum length (keep important parts)\n */\n private truncateHtml(html: string, maxLength: number): string {\n if (html.length <= maxLength) return html;\n\n // Try to keep the beginning (usually has navigation)\n return `${html.substring(0, maxLength)}\\n\\n[... HTML truncated ...]`;\n }\n\n /**\n * Truncate markdown to a maximum length\n */\n private truncateMarkdown(markdown: string, maxLength: number): string {\n if (markdown.length <= maxLength) return markdown;\n\n return `${markdown.substring(0, maxLength)}\\n\\n[... content truncated ...]`;\n }\n\n /**\n * Type guard to check if value is a record (plain object)\n */\n private isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n }\n\n /**\n * Extract structured_output from Claude CLI wrapper format if present.\n * Claude CLI with --json-schema returns: {type, result, structured_output: {...}}\n * This method extracts the inner structured_output, or returns the raw value if not wrapped.\n */\n private extractStructuredOutput(rawParsed: unknown): unknown {\n if (this.isRecord(rawParsed) && 'structured_output' in rawParsed) {\n const structuredOutput = rawParsed['structured_output'];\n if (typeof structuredOutput === 'object') {\n return structuredOutput;\n }\n }\n return rawParsed;\n }\n}\n"],"mappings":";;;;;;;;AAKA,SAAS,oBAAoB;AAC7B,OAAO,WAAW;;;ACDlB,SAAS,uBAAuB;AAChC,OAAO,qBAAqB;AAC5B,SAAS,WAAW;;;ACCpB,YAAY,aAAa;AAMzB,SAAS,wBAAwB,WAAuC;AACtE,MAAI,cAAc,UAAa,cAAc,GAAI,QAAO;AAGxD,QAAM,WAAW;AAAA,IACf;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,aAAW,WAAW,UAAU;AAC9B,UAAM,QAAQ,UAA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aAAa,MAAM,GAAG;AAIhD,YAAM,YAAY,OAAO,QAAQ,CAAC;AAClC,UAAI,CAAC,WAAW;AACd,cAAM,IAAI,MAAM,wCAAwC,GAAG,uBAAuB;AAAA,MACpF;AAEA,aAAO,UAAU;AAAA,IACnB,SAAS,OAAgB;AAEvB,YAAM,eAAe,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC1E,MAAAD,QAAO,MAAM,EAAE,KAAK,OAAO,aAAa,GAAG,yBAAyB;AAGpE,YAAM,IAAI,MAAM,8BAA8B,GAAG,KAAK,YAAY,EAAE;AAAA,IACtE;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKQ,aAAa,MAAc,MAAuB;AACxD,QAAI;AACF,YAAM,UAAU,IAAI,IAAI,IAAI,EAAE,SAAS,YAAY;AACnD,YAAM,UAAU,IAAI,IAAI,IAAI,EAAE,SAAS,YAAY;AACnD,aACE,YAAY,WAAW,QAAQ,SAAS,IAAI,OAAO,EAAE,KAAK,QAAQ,SAAS,IAAI,OAAO,EAAE;AAAA,IAE5F,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,OAAsB;AAC1B,SAAK,UAAU;AACf,UAAM,KAAK,aAAa,KAAK;AAAA,EAC/B;AACF;","names":["logger","result"]}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import {
|
|
2
2
|
JobService,
|
|
3
|
+
ProjectRootService,
|
|
3
4
|
createLogger,
|
|
4
5
|
createServices,
|
|
5
6
|
createStoreId,
|
|
6
7
|
summarizePayload
|
|
7
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-UE4ZIJYA.js";
|
|
8
9
|
|
|
9
10
|
// src/mcp/server.ts
|
|
10
11
|
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
@@ -599,10 +600,375 @@ var storeCommands = [
|
|
|
599
600
|
}
|
|
600
601
|
];
|
|
601
602
|
|
|
603
|
+
// src/mcp/commands/sync.commands.ts
|
|
604
|
+
import { z as z7 } from "zod";
|
|
605
|
+
|
|
606
|
+
// src/services/store-definition.service.ts
|
|
607
|
+
import { readFile, writeFile, mkdir, access } from "fs/promises";
|
|
608
|
+
import { dirname, resolve, isAbsolute, join as join2 } from "path";
|
|
609
|
+
|
|
610
|
+
// src/types/store-definition.ts
|
|
611
|
+
import { z as z6 } from "zod";
|
|
612
|
+
var BaseStoreDefinitionSchema = z6.object({
|
|
613
|
+
name: z6.string().min(1, "Store name is required"),
|
|
614
|
+
description: z6.string().optional(),
|
|
615
|
+
tags: z6.array(z6.string()).optional()
|
|
616
|
+
});
|
|
617
|
+
var FileStoreDefinitionSchema = BaseStoreDefinitionSchema.extend({
|
|
618
|
+
type: z6.literal("file"),
|
|
619
|
+
path: z6.string().min(1, "Path is required for file stores")
|
|
620
|
+
});
|
|
621
|
+
var RepoStoreDefinitionSchema = BaseStoreDefinitionSchema.extend({
|
|
622
|
+
type: z6.literal("repo"),
|
|
623
|
+
url: z6.url("Valid URL is required for repo stores"),
|
|
624
|
+
branch: z6.string().optional(),
|
|
625
|
+
depth: z6.number().int().positive("Depth must be a positive integer").optional()
|
|
626
|
+
});
|
|
627
|
+
var WebStoreDefinitionSchema = BaseStoreDefinitionSchema.extend({
|
|
628
|
+
type: z6.literal("web"),
|
|
629
|
+
url: z6.url("Valid URL is required for web stores"),
|
|
630
|
+
depth: z6.number().int().min(0, "Depth must be non-negative").default(1),
|
|
631
|
+
maxPages: z6.number().int().positive("maxPages must be a positive integer").optional(),
|
|
632
|
+
crawlInstructions: z6.string().optional(),
|
|
633
|
+
extractInstructions: z6.string().optional()
|
|
634
|
+
});
|
|
635
|
+
var StoreDefinitionSchema = z6.discriminatedUnion("type", [
|
|
636
|
+
FileStoreDefinitionSchema,
|
|
637
|
+
RepoStoreDefinitionSchema,
|
|
638
|
+
WebStoreDefinitionSchema
|
|
639
|
+
]);
|
|
640
|
+
var StoreDefinitionsConfigSchema = z6.object({
|
|
641
|
+
version: z6.literal(1),
|
|
642
|
+
stores: z6.array(StoreDefinitionSchema)
|
|
643
|
+
});
|
|
644
|
+
function isFileStoreDefinition(def) {
|
|
645
|
+
return def.type === "file";
|
|
646
|
+
}
|
|
647
|
+
function isRepoStoreDefinition(def) {
|
|
648
|
+
return def.type === "repo";
|
|
649
|
+
}
|
|
650
|
+
function isWebStoreDefinition(def) {
|
|
651
|
+
return def.type === "web";
|
|
652
|
+
}
|
|
653
|
+
var DEFAULT_STORE_DEFINITIONS_CONFIG = {
|
|
654
|
+
version: 1,
|
|
655
|
+
stores: []
|
|
656
|
+
};
|
|
657
|
+
|
|
658
|
+
// src/services/store-definition.service.ts
|
|
659
|
+
async function fileExists(path2) {
|
|
660
|
+
try {
|
|
661
|
+
await access(path2);
|
|
662
|
+
return true;
|
|
663
|
+
} catch {
|
|
664
|
+
return false;
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
var StoreDefinitionService = class {
|
|
668
|
+
configPath;
|
|
669
|
+
projectRoot;
|
|
670
|
+
config = null;
|
|
671
|
+
constructor(projectRoot) {
|
|
672
|
+
this.projectRoot = projectRoot ?? ProjectRootService.resolve();
|
|
673
|
+
this.configPath = join2(this.projectRoot, ".bluera/bluera-knowledge/stores.config.json");
|
|
674
|
+
}
|
|
675
|
+
/**
|
|
676
|
+
* Load store definitions from config file.
|
|
677
|
+
* Returns empty config if file doesn't exist.
|
|
678
|
+
* Throws on parse/validation errors (fail fast per CLAUDE.md).
|
|
679
|
+
*/
|
|
680
|
+
async load() {
|
|
681
|
+
if (this.config !== null) {
|
|
682
|
+
return this.config;
|
|
683
|
+
}
|
|
684
|
+
const exists = await fileExists(this.configPath);
|
|
685
|
+
if (!exists) {
|
|
686
|
+
this.config = {
|
|
687
|
+
...DEFAULT_STORE_DEFINITIONS_CONFIG,
|
|
688
|
+
stores: [...DEFAULT_STORE_DEFINITIONS_CONFIG.stores]
|
|
689
|
+
};
|
|
690
|
+
return this.config;
|
|
691
|
+
}
|
|
692
|
+
const content = await readFile(this.configPath, "utf-8");
|
|
693
|
+
let parsed;
|
|
694
|
+
try {
|
|
695
|
+
parsed = JSON.parse(content);
|
|
696
|
+
} catch (error) {
|
|
697
|
+
throw new Error(
|
|
698
|
+
`Failed to parse store definitions at ${this.configPath}: ${error instanceof Error ? error.message : String(error)}`
|
|
699
|
+
);
|
|
700
|
+
}
|
|
701
|
+
const result = StoreDefinitionsConfigSchema.safeParse(parsed);
|
|
702
|
+
if (!result.success) {
|
|
703
|
+
throw new Error(`Invalid store definitions at ${this.configPath}: ${result.error.message}`);
|
|
704
|
+
}
|
|
705
|
+
this.config = result.data;
|
|
706
|
+
return this.config;
|
|
707
|
+
}
|
|
708
|
+
/**
|
|
709
|
+
* Save store definitions to config file.
|
|
710
|
+
*/
|
|
711
|
+
async save(config) {
|
|
712
|
+
await mkdir(dirname(this.configPath), { recursive: true });
|
|
713
|
+
await writeFile(this.configPath, JSON.stringify(config, null, 2));
|
|
714
|
+
this.config = config;
|
|
715
|
+
}
|
|
716
|
+
/**
|
|
717
|
+
* Add a store definition.
|
|
718
|
+
* Throws if a definition with the same name already exists.
|
|
719
|
+
*/
|
|
720
|
+
async addDefinition(definition) {
|
|
721
|
+
const config = await this.load();
|
|
722
|
+
const existing = config.stores.find((s) => s.name === definition.name);
|
|
723
|
+
if (existing !== void 0) {
|
|
724
|
+
throw new Error(`Store definition "${definition.name}" already exists`);
|
|
725
|
+
}
|
|
726
|
+
config.stores.push(definition);
|
|
727
|
+
await this.save(config);
|
|
728
|
+
}
|
|
729
|
+
/**
|
|
730
|
+
* Remove a store definition by name.
|
|
731
|
+
* Returns true if removed, false if not found.
|
|
732
|
+
*/
|
|
733
|
+
async removeDefinition(name) {
|
|
734
|
+
const config = await this.load();
|
|
735
|
+
const index = config.stores.findIndex((s) => s.name === name);
|
|
736
|
+
if (index === -1) {
|
|
737
|
+
return false;
|
|
738
|
+
}
|
|
739
|
+
config.stores.splice(index, 1);
|
|
740
|
+
await this.save(config);
|
|
741
|
+
return true;
|
|
742
|
+
}
|
|
743
|
+
/**
|
|
744
|
+
* Update an existing store definition.
|
|
745
|
+
* Only updates the provided fields, preserving others.
|
|
746
|
+
* Throws if definition not found.
|
|
747
|
+
*/
|
|
748
|
+
async updateDefinition(name, updates) {
|
|
749
|
+
const config = await this.load();
|
|
750
|
+
const index = config.stores.findIndex((s) => s.name === name);
|
|
751
|
+
if (index === -1) {
|
|
752
|
+
throw new Error(`Store definition "${name}" not found`);
|
|
753
|
+
}
|
|
754
|
+
const existing = config.stores[index];
|
|
755
|
+
if (existing === void 0) {
|
|
756
|
+
throw new Error(`Store definition "${name}" not found at index ${String(index)}`);
|
|
757
|
+
}
|
|
758
|
+
if (updates.description !== void 0) {
|
|
759
|
+
existing.description = updates.description;
|
|
760
|
+
}
|
|
761
|
+
if (updates.tags !== void 0) {
|
|
762
|
+
existing.tags = updates.tags;
|
|
763
|
+
}
|
|
764
|
+
await this.save(config);
|
|
765
|
+
}
|
|
766
|
+
/**
|
|
767
|
+
* Get a store definition by name.
|
|
768
|
+
* Returns undefined if not found.
|
|
769
|
+
*/
|
|
770
|
+
async getByName(name) {
|
|
771
|
+
const config = await this.load();
|
|
772
|
+
return config.stores.find((s) => s.name === name);
|
|
773
|
+
}
|
|
774
|
+
/**
|
|
775
|
+
* Check if any definitions exist.
|
|
776
|
+
*/
|
|
777
|
+
async hasDefinitions() {
|
|
778
|
+
const config = await this.load();
|
|
779
|
+
return config.stores.length > 0;
|
|
780
|
+
}
|
|
781
|
+
/**
|
|
782
|
+
* Resolve a file store path relative to project root.
|
|
783
|
+
*/
|
|
784
|
+
resolvePath(path2) {
|
|
785
|
+
if (isAbsolute(path2)) {
|
|
786
|
+
return path2;
|
|
787
|
+
}
|
|
788
|
+
return resolve(this.projectRoot, path2);
|
|
789
|
+
}
|
|
790
|
+
/**
|
|
791
|
+
* Get the config file path.
|
|
792
|
+
*/
|
|
793
|
+
getConfigPath() {
|
|
794
|
+
return this.configPath;
|
|
795
|
+
}
|
|
796
|
+
/**
|
|
797
|
+
* Get the project root.
|
|
798
|
+
*/
|
|
799
|
+
getProjectRoot() {
|
|
800
|
+
return this.projectRoot;
|
|
801
|
+
}
|
|
802
|
+
/**
|
|
803
|
+
* Clear the cached config (useful for testing).
|
|
804
|
+
*/
|
|
805
|
+
clearCache() {
|
|
806
|
+
this.config = null;
|
|
807
|
+
}
|
|
808
|
+
};
|
|
809
|
+
|
|
810
|
+
// src/mcp/commands/sync.commands.ts
|
|
811
|
+
async function handleStoresSync(args, context) {
|
|
812
|
+
const { services, options } = context;
|
|
813
|
+
const projectRoot = options.projectRoot;
|
|
814
|
+
if (projectRoot === void 0) {
|
|
815
|
+
throw new Error("Project root is required for stores:sync");
|
|
816
|
+
}
|
|
817
|
+
const defService = new StoreDefinitionService(projectRoot);
|
|
818
|
+
const config = await defService.load();
|
|
819
|
+
const result = {
|
|
820
|
+
created: [],
|
|
821
|
+
skipped: [],
|
|
822
|
+
failed: [],
|
|
823
|
+
orphans: []
|
|
824
|
+
};
|
|
825
|
+
if (args.dryRun === true) {
|
|
826
|
+
result.dryRun = true;
|
|
827
|
+
result.wouldCreate = [];
|
|
828
|
+
result.wouldPrune = [];
|
|
829
|
+
}
|
|
830
|
+
const existingStores = await services.store.list();
|
|
831
|
+
const existingNames = new Set(existingStores.map((s) => s.name));
|
|
832
|
+
for (const def of config.stores) {
|
|
833
|
+
if (existingNames.has(def.name)) {
|
|
834
|
+
result.skipped.push(def.name);
|
|
835
|
+
continue;
|
|
836
|
+
}
|
|
837
|
+
if (args.dryRun === true) {
|
|
838
|
+
result.wouldCreate?.push(def.name);
|
|
839
|
+
continue;
|
|
840
|
+
}
|
|
841
|
+
const createResult = await createStoreFromDefinition(def, defService, services, context);
|
|
842
|
+
if (createResult.success) {
|
|
843
|
+
result.created.push(def.name);
|
|
844
|
+
} else {
|
|
845
|
+
result.failed.push({ name: def.name, error: createResult.error });
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
const definedNames = new Set(config.stores.map((d) => d.name));
|
|
849
|
+
for (const store of existingStores) {
|
|
850
|
+
if (!definedNames.has(store.name)) {
|
|
851
|
+
result.orphans.push(store.name);
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
if (args.prune === true && result.orphans.length > 0) {
|
|
855
|
+
if (args.dryRun === true) {
|
|
856
|
+
result.wouldPrune = [...result.orphans];
|
|
857
|
+
} else {
|
|
858
|
+
result.pruned = [];
|
|
859
|
+
for (const orphanName of result.orphans) {
|
|
860
|
+
const store = await services.store.getByName(orphanName);
|
|
861
|
+
if (store !== void 0) {
|
|
862
|
+
const deleteResult = await services.store.delete(store.id, { skipDefinitionSync: true });
|
|
863
|
+
if (deleteResult.success) {
|
|
864
|
+
result.pruned.push(orphanName);
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
return {
|
|
871
|
+
content: [
|
|
872
|
+
{
|
|
873
|
+
type: "text",
|
|
874
|
+
text: JSON.stringify(result, null, 2)
|
|
875
|
+
}
|
|
876
|
+
]
|
|
877
|
+
};
|
|
878
|
+
}
|
|
879
|
+
async function createStoreFromDefinition(def, defService, services, _context) {
|
|
880
|
+
try {
|
|
881
|
+
if (isFileStoreDefinition(def)) {
|
|
882
|
+
const resolvedPath = defService.resolvePath(def.path);
|
|
883
|
+
const createResult = await services.store.create(
|
|
884
|
+
{
|
|
885
|
+
name: def.name,
|
|
886
|
+
type: "file",
|
|
887
|
+
path: resolvedPath,
|
|
888
|
+
description: def.description,
|
|
889
|
+
tags: def.tags
|
|
890
|
+
},
|
|
891
|
+
{ skipDefinitionSync: true }
|
|
892
|
+
// Don't re-add to definitions
|
|
893
|
+
);
|
|
894
|
+
if (!createResult.success) {
|
|
895
|
+
return { success: false, error: createResult.error.message };
|
|
896
|
+
}
|
|
897
|
+
return { success: true };
|
|
898
|
+
}
|
|
899
|
+
if (isRepoStoreDefinition(def)) {
|
|
900
|
+
const createResult = await services.store.create(
|
|
901
|
+
{
|
|
902
|
+
name: def.name,
|
|
903
|
+
type: "repo",
|
|
904
|
+
url: def.url,
|
|
905
|
+
branch: def.branch,
|
|
906
|
+
depth: def.depth,
|
|
907
|
+
description: def.description,
|
|
908
|
+
tags: def.tags
|
|
909
|
+
},
|
|
910
|
+
{ skipDefinitionSync: true }
|
|
911
|
+
);
|
|
912
|
+
if (!createResult.success) {
|
|
913
|
+
return { success: false, error: createResult.error.message };
|
|
914
|
+
}
|
|
915
|
+
return { success: true };
|
|
916
|
+
}
|
|
917
|
+
if (isWebStoreDefinition(def)) {
|
|
918
|
+
const createResult = await services.store.create(
|
|
919
|
+
{
|
|
920
|
+
name: def.name,
|
|
921
|
+
type: "web",
|
|
922
|
+
url: def.url,
|
|
923
|
+
depth: def.depth,
|
|
924
|
+
description: def.description,
|
|
925
|
+
tags: def.tags
|
|
926
|
+
},
|
|
927
|
+
{ skipDefinitionSync: true }
|
|
928
|
+
);
|
|
929
|
+
if (!createResult.success) {
|
|
930
|
+
return { success: false, error: createResult.error.message };
|
|
931
|
+
}
|
|
932
|
+
return { success: true };
|
|
933
|
+
}
|
|
934
|
+
return { success: false, error: "Unknown store definition type" };
|
|
935
|
+
} catch (error) {
|
|
936
|
+
return {
|
|
937
|
+
success: false,
|
|
938
|
+
error: error instanceof Error ? error.message : String(error)
|
|
939
|
+
};
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
var syncCommands = [
|
|
943
|
+
{
|
|
944
|
+
name: "stores:sync",
|
|
945
|
+
description: "Sync stores from definitions config (bootstrap on fresh clone)",
|
|
946
|
+
argsSchema: z7.object({
|
|
947
|
+
reindex: z7.boolean().optional().describe("Re-index existing stores after sync"),
|
|
948
|
+
prune: z7.boolean().optional().describe("Remove stores not in definitions"),
|
|
949
|
+
dryRun: z7.boolean().optional().describe("Show what would happen without making changes")
|
|
950
|
+
}),
|
|
951
|
+
handler: (args, context) => {
|
|
952
|
+
const syncArgs = {};
|
|
953
|
+
if (typeof args["reindex"] === "boolean") {
|
|
954
|
+
syncArgs.reindex = args["reindex"];
|
|
955
|
+
}
|
|
956
|
+
if (typeof args["prune"] === "boolean") {
|
|
957
|
+
syncArgs.prune = args["prune"];
|
|
958
|
+
}
|
|
959
|
+
if (typeof args["dryRun"] === "boolean") {
|
|
960
|
+
syncArgs.dryRun = args["dryRun"];
|
|
961
|
+
}
|
|
962
|
+
return handleStoresSync(syncArgs, context);
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
];
|
|
966
|
+
|
|
602
967
|
// src/mcp/commands/index.ts
|
|
603
968
|
commandRegistry.registerAll(storeCommands);
|
|
604
969
|
commandRegistry.registerAll(jobCommands);
|
|
605
970
|
commandRegistry.registerAll(metaCommands);
|
|
971
|
+
commandRegistry.registerAll(syncCommands);
|
|
606
972
|
|
|
607
973
|
// src/mcp/handlers/execute.handler.ts
|
|
608
974
|
var handleExecute = async (args, context) => {
|
|
@@ -1092,7 +1458,11 @@ if (isMCPServerEntry) {
|
|
|
1092
1458
|
}
|
|
1093
1459
|
|
|
1094
1460
|
export {
|
|
1461
|
+
isFileStoreDefinition,
|
|
1462
|
+
isRepoStoreDefinition,
|
|
1463
|
+
isWebStoreDefinition,
|
|
1464
|
+
StoreDefinitionService,
|
|
1095
1465
|
createMCPServer,
|
|
1096
1466
|
runMCPServer
|
|
1097
1467
|
};
|
|
1098
|
-
//# sourceMappingURL=chunk-
|
|
1468
|
+
//# sourceMappingURL=chunk-DP5XBPQV.js.map
|