@ctxo/cli 0.7.2 → 0.8.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.
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/cli/cli-router.ts","../src/cli/index-command.ts","../src/core/staleness/content-hasher.ts","../src/adapters/language/language-adapter-registry.ts","../src/cli/plugin-loader.ts","../src/adapters/language/plugin-discovery.ts","../src/cli/install-command.ts","../src/core/detection/detect-languages.ts","../src/core/install/package-manager.ts","../src/adapters/storage/json-index-writer.ts","../src/adapters/storage/schema-manager.ts","../src/cli/sync-command.ts","../src/cli/status-command.ts","../src/cli/verify-command.ts","../src/cli/init-command.ts","../src/cli/ai-rules.ts","../src/cli/watch-command.ts","../src/adapters/watcher/chokidar-watcher-adapter.ts","../src/cli/stats-command.ts","../src/cli/doctor-command.ts","../src/adapters/diagnostics/health-checker.ts","../src/adapters/diagnostics/doctor-reporter.ts","../src/adapters/diagnostics/checks/runtime-check.ts","../src/cli/version-command.ts","../src/adapters/diagnostics/checks/versions-check.ts","../src/adapters/diagnostics/checks/language-coverage-check.ts","../src/adapters/diagnostics/checks/git-check.ts","../src/adapters/diagnostics/checks/index-check.ts","../src/adapters/diagnostics/checks/storage-check.ts","../src/adapters/diagnostics/checks/config-check.ts","../src/adapters/diagnostics/checks/disk-check.ts","../src/cli/doctor-fix.ts","../src/cli/visualize-command.ts"],"sourcesContent":["import { readFileSync, existsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { IndexCommand } from './index-command.js';\nimport { SyncCommand } from './sync-command.js';\nimport { StatusCommand } from './status-command.js';\nimport { VerifyCommand } from './verify-command.js';\nimport { InitCommand } from './init-command.js';\nimport { WatchCommand } from './watch-command.js';\nimport { StatsCommand } from './stats-command.js';\nimport { DoctorCommand } from './doctor-command.js';\nimport { VisualizeCommand } from './visualize-command.js';\nimport { VersionCommand } from './version-command.js';\nimport { InstallCommand } from './install-command.js';\n\nexport function getVersion(): string {\n let dir = import.meta.dirname;\n for (let i = 0; i < 10; i++) {\n const pkg = join(dir, 'package.json');\n if (existsSync(pkg)) {\n try {\n const json = JSON.parse(readFileSync(pkg, 'utf-8'));\n return json.version ?? 'unknown';\n } catch { break; }\n }\n const parent = join(dir, '..');\n if (parent === dir) break;\n dir = parent;\n }\n return 'unknown';\n}\n\n/**\n * Walk up from `startDir` (capped at 12 levels) looking for a directory that\n * contains `.git`. First hit wins. Matches how git itself resolves the working\n * tree and keeps every subcommand consistent when the user runs ctxo from a\n * subdirectory or when pnpm --filter sets cwd to a monorepo package.\n */\nexport function locateGitRoot(startDir: string): string | null {\n let dir = startDir;\n for (let i = 0; i < 12; i++) {\n if (existsSync(join(dir, '.git'))) return dir;\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\nexport class CliRouter {\n private readonly projectRoot: string;\n\n constructor(projectRoot: string) {\n // If cwd is a subdirectory of a git repo (common in monorepos and when\n // users run ctxo from anywhere below the repo root), use the repo root so\n // every subcommand consistently operates on the same project.\n this.projectRoot = locateGitRoot(projectRoot) ?? projectRoot;\n }\n\n async route(args: string[]): Promise<void> {\n const command = args[0];\n\n if (command === '--version' || command === '-v' || command === '-V') {\n const verbose = args.includes('--verbose');\n const json = args.includes('--json');\n await new VersionCommand(this.projectRoot).run({ verbose, json });\n return;\n }\n\n if (command === 'version') {\n const json = args.includes('--json');\n const short = args.includes('--short');\n await new VersionCommand(this.projectRoot).run({\n verbose: !json && !short,\n json,\n });\n return;\n }\n\n if (!command || command === '--help' || command === '-h') {\n this.printHelp();\n return;\n }\n\n switch (command) {\n case 'index': {\n const fileIdx = args.indexOf('--file');\n const fileArg = fileIdx !== -1 ? args[fileIdx + 1] : undefined;\n if (fileIdx !== -1 && (!fileArg || fileArg.startsWith('--'))) {\n console.error('[ctxo] --file requires a path argument');\n process.exit(1);\n return;\n }\n const checkArg = args.includes('--check');\n const skipHistory = args.includes('--skip-history');\n const installMissing = args.includes('--install-missing');\n const maxHistoryIdx = args.indexOf('--max-history');\n const maxHistoryArg = maxHistoryIdx !== -1 ? Number(args[maxHistoryIdx + 1]) : undefined;\n if (maxHistoryIdx !== -1 && (!maxHistoryArg || isNaN(maxHistoryArg) || maxHistoryArg < 1)) {\n console.error('[ctxo] --max-history requires a positive integer');\n process.exit(1);\n return;\n }\n await new IndexCommand(this.projectRoot).run({\n file: fileArg,\n check: checkArg,\n skipHistory,\n maxHistory: maxHistoryArg,\n installMissing,\n });\n break;\n }\n\n case 'sync':\n await new SyncCommand(this.projectRoot).run();\n break;\n\n case 'watch':\n await new WatchCommand(this.projectRoot).run();\n break;\n\n case 'verify-index':\n await new VerifyCommand(this.projectRoot).run();\n break;\n\n case 'status':\n new StatusCommand(this.projectRoot).run();\n break;\n\n case 'init': {\n const toolsIdx = args.indexOf('--tools');\n const toolsArg = toolsIdx !== -1 ? args[toolsIdx + 1] : undefined;\n const yesArg = args.includes('--yes') || args.includes('-y');\n const rulesOnly = args.includes('--rules');\n const dryRun = args.includes('--dry-run');\n const noInstall = args.includes('--no-install');\n const tools = toolsArg ? toolsArg.split(',').map(t => t.trim()) : undefined;\n await new InitCommand(this.projectRoot).run({ tools, yes: yesArg, rulesOnly, dryRun, noInstall });\n break;\n }\n\n case 'stats': {\n const daysIdx = args.indexOf('--days');\n const daysArg = daysIdx !== -1 ? Number(args[daysIdx + 1]) : undefined;\n const jsonArg = args.includes('--json');\n const clearArg = args.includes('--clear');\n await new StatsCommand(this.projectRoot).run({ days: daysArg, json: jsonArg, clear: clearArg });\n break;\n }\n\n case 'doctor': {\n const jsonArg = args.includes('--json');\n const quietArg = args.includes('--quiet');\n const fixArg = args.includes('--fix');\n const dryRunArg = args.includes('--dry-run');\n const yesArg = args.includes('--yes') || args.includes('-y');\n await new DoctorCommand(this.projectRoot).run({\n json: jsonArg,\n quiet: quietArg,\n fix: fixArg,\n dryRun: dryRunArg,\n yes: yesArg,\n });\n break;\n }\n\n case 'install': {\n const languages: string[] = [];\n const flagValues: Record<string, string | boolean> = {};\n for (let i = 1; i < args.length; i++) {\n const a = args[i]!;\n if (a === '--yes' || a === '-y') flagValues['yes'] = true;\n else if (a === '--global' || a === '-g') flagValues['global'] = true;\n else if (a === '--dry-run') flagValues['dryRun'] = true;\n else if (a === '--force') flagValues['force'] = true;\n else if (a === '--pm') {\n const next = args[++i];\n if (!next) { console.error('[ctxo] --pm requires a value'); process.exit(1); return; }\n flagValues['pm'] = next;\n } else if (a === '--version') {\n const next = args[++i];\n if (!next) { console.error('[ctxo] --version requires a value'); process.exit(1); return; }\n flagValues['version'] = next;\n } else if (a.startsWith('--')) {\n console.error(`[ctxo] Unknown install flag: ${a}`);\n process.exit(1);\n return;\n } else {\n languages.push(a);\n }\n }\n await new InstallCommand(this.projectRoot).run({\n languages,\n yes: flagValues['yes'] === true,\n global: flagValues['global'] === true,\n dryRun: flagValues['dryRun'] === true,\n force: flagValues['force'] === true,\n pm: typeof flagValues['pm'] === 'string' ? flagValues['pm'] : undefined,\n version: typeof flagValues['version'] === 'string' ? flagValues['version'] : undefined,\n });\n break;\n }\n\n case 'visualize': {\n const outputIdx = args.indexOf('--output');\n const outputArg = outputIdx !== -1 ? args[outputIdx + 1] : undefined;\n const maxNodesIdx = args.indexOf('--max-nodes');\n const maxNodesArg = maxNodesIdx !== -1 ? Number(args[maxNodesIdx + 1]) : undefined;\n const noBrowser = args.includes('--no-browser');\n if (maxNodesIdx !== -1 && (!maxNodesArg || isNaN(maxNodesArg) || maxNodesArg < 1)) {\n console.error('[ctxo] --max-nodes requires a positive integer');\n process.exit(1);\n return;\n }\n await new VisualizeCommand(this.projectRoot).run({ output: outputArg, maxNodes: maxNodesArg, noBrowser });\n break;\n }\n\n default:\n console.error(`[ctxo] Unknown command: \"${command}\". Run \"ctxo --help\" for usage.`);\n process.exit(1);\n return;\n }\n }\n\n private printHelp(): void {\n const v = getVersion();\n console.error(`\nctxo v${v} — MCP server for dependency-aware codebase context\n\nUsage:\n ctxo Start MCP server (stdio transport)\n ctxo index Build full codebase index (--max-history N, default 20)\n ctxo sync Rebuild SQLite cache from committed JSON index\n ctxo watch Start file watcher for incremental re-indexing\n ctxo verify-index CI gate: fail if index is stale\n ctxo status Show index manifest\n ctxo init Interactive setup (tools, rules, hooks)\n ctxo init --rules Regenerate AI tool rules only\n ctxo init --tools a,b -y Non-interactive (claude-code,cursor,...)\n ctxo init --dry-run Preview what would be created\n ctxo stats Show usage statistics (--json, --days N, --clear)\n ctxo doctor Health check all subsystems (--json, --quiet)\n ctxo visualize Generate interactive dependency graph HTML\n ctxo visualize --max-nodes N Limit to top N symbols by PageRank\n ctxo visualize --output PATH Write HTML to custom path\n ctxo visualize --no-browser Skip auto-opening browser\n ctxo install [<lang>...] Install language plugins (detects if omitted)\n ctxo install python -y Batch install, no prompt\n ctxo install ts --global Install globally\n ctxo install py --dry-run Show command without running\n ctxo --version Print core version\n ctxo --version --verbose Print core + plugins + runtime\n ctxo --version --json Machine-readable version payload\n ctxo version Subcommand — verbose by default\n ctxo --help Show this help message\n`.trim());\n }\n}\n","import { execFileSync } from 'node:child_process';\nimport { readFileSync, writeFileSync, existsSync, statSync, readdirSync } from 'node:fs';\nimport { join, relative, extname } from 'node:path';\nimport { createRequire } from 'node:module';\nimport { ContentHasher } from '../core/staleness/content-hasher.js';\nimport { LanguageAdapterRegistry } from '../adapters/language/language-adapter-registry.js';\nimport { loadPlugins } from './plugin-loader.js';\nimport { InstallCommand } from './install-command.js';\nimport {\n loadConfig,\n indexIgnorePatterns,\n indexIgnoreProjectPatterns,\n makeGlobMatcher,\n} from '../core/config/load-config.js';\nimport {\n detectLanguages,\n decideNeededLanguages,\n officialPluginFor,\n EXTENSION_LANGUAGE,\n type KnownLanguage,\n} from '../core/detection/detect-languages.js';\n\nconst requireCjs = createRequire(import.meta.url);\nimport { JsonIndexWriter } from '../adapters/storage/json-index-writer.js';\nimport { SqliteStorageAdapter } from '../adapters/storage/sqlite-storage-adapter.js';\nimport { SchemaManager } from '../adapters/storage/schema-manager.js';\nimport { SimpleGitAdapter } from '../adapters/git/simple-git-adapter.js';\nimport { RevertDetector } from '../core/why-context/revert-detector.js';\nimport { aggregateCoChanges } from '../core/co-change/co-change-analyzer.js';\nimport type { FileIndex, SymbolKind } from '../core/types.js';\n\ninterface TsMorphLike {\n loadProjectSources(sources: Map<string, string>): void;\n clearProjectSources(): void;\n}\n\ninterface RoslynLike {\n isReady(): boolean;\n batchIndex(): Promise<void>;\n startKeepAlive(): Promise<boolean>;\n reindexFile(relativePath: string): Promise<{\n symbols: Array<{ symbolId: string; name: string; kind: string; startLine: number; endLine: number }>;\n edges: Array<{ from: string; to: string; kind: string }>;\n complexity: Array<{ symbolId: string; cyclomatic: number }>;\n } | null>;\n dispose(): Promise<void>;\n}\n\ninterface CSharpCompositeLike {\n getRoslynDelegate(): RoslynLike | null;\n getTier(): 'full' | 'syntax' | 'unavailable';\n}\n\ninterface GoCompositeLike {\n getTier(): 'full' | 'syntax' | 'unavailable';\n}\n\nexport class IndexCommand {\n private readonly projectRoot: string;\n ctxoRoot: string;\n private supportedExtensions: Set<string>;\n\n constructor(projectRoot: string, ctxoRoot?: string) {\n this.projectRoot = projectRoot;\n this.ctxoRoot = ctxoRoot ?? join(projectRoot, '.ctxo');\n this.supportedExtensions = new Set(['.ts', '.tsx', '.js', '.jsx', '.go', '.cs']);\n }\n\n private loadIgnoreConfig(): {\n ignoreFile: (p: string) => boolean;\n ignoreProject: (p: string) => boolean;\n ignoreProjectPatterns: string[];\n } {\n const { config } = loadConfig(this.ctxoRoot);\n const filePatterns = indexIgnorePatterns(config);\n const projectPatterns = indexIgnoreProjectPatterns(config);\n if (filePatterns.length > 0) {\n console.error(`[ctxo] index.ignore: ${filePatterns.length} pattern(s) active`);\n }\n if (projectPatterns.length > 0) {\n console.error(`[ctxo] index.ignoreProjects: ${projectPatterns.length} pattern(s) active`);\n }\n return {\n ignoreFile: makeGlobMatcher(filePatterns),\n ignoreProject: makeGlobMatcher(projectPatterns),\n ignoreProjectPatterns: projectPatterns,\n };\n }\n\n async run(options: {\n file?: string;\n check?: boolean;\n skipSideEffects?: boolean;\n skipHistory?: boolean;\n maxHistory?: number;\n installMissing?: boolean;\n } = {}): Promise<void> {\n if (options.check) {\n // Delegate to verify logic: hash-based freshness check\n return this.runCheck();\n }\n\n // Pre-index: detect missing plugins and optionally auto-install\n if (options.installMissing) {\n await this.autoInstallMissingPlugins();\n }\n\n const ignore = this.loadIgnoreConfig();\n\n // Set up adapters via plugin discovery (TS, Go, C# all plugin-backed)\n const registry = new LanguageAdapterRegistry();\n const { tsMorphLike, roslynAdapter, csharpTier, goTier } = await this.registerDiscoveredPlugins(registry, ignore.ignoreProjectPatterns);\n this.supportedExtensions = registry.getSupportedExtensions();\n\n // Emit a language-aware pre-scan so users see the plan before the work runs\n this.printLanguagePreview();\n\n const writer = new JsonIndexWriter(this.ctxoRoot);\n const schemaManager = new SchemaManager(this.ctxoRoot);\n const hasher = new ContentHasher();\n const gitAdapter = new SimpleGitAdapter(this.projectRoot);\n const revertDetector = new RevertDetector();\n\n // Discover files (single file, monorepo workspaces, or full project)\n let files: string[];\n if (options.file) {\n const fullPath = join(this.projectRoot, options.file);\n files = [fullPath];\n console.error(`[ctxo] Incremental re-index: ${options.file}`);\n } else {\n // Check for monorepo workspaces — discover files across all roots\n const workspaces = this.discoverWorkspaces(ignore.ignoreProject);\n files = [];\n for (const ws of workspaces) {\n const wsFiles = this.discoverFilesIn(ws, ignore.ignoreFile);\n files.push(...wsFiles);\n }\n console.error(`[ctxo] Building codebase index... Found ${files.length} source files`);\n }\n\n // Phase 0: Roslyn batch index (if available, pre-caches all C# results)\n if (roslynAdapter?.isReady()) {\n const hasCsFiles = files.some(f => f.endsWith('.cs'));\n if (hasCsFiles) {\n await roslynAdapter.batchIndex();\n }\n }\n\n // Phase 1a: Extract symbols (CPU-bound, builds symbol registry for edge resolution)\n const symbolRegistry = new Map<string, SymbolKind>();\n const pendingIndices: Array<{\n relativePath: string;\n source: string;\n fileIndex: FileIndex;\n }> = [];\n let processed = 0;\n\n for (const filePath of files) {\n const adapter = registry.getAdapter(filePath);\n if (!adapter) continue;\n\n const relativePath = relative(this.projectRoot, filePath).replace(/\\\\/g, '/');\n\n try {\n const source = readFileSync(filePath, 'utf-8');\n const lastModified = Math.floor(Date.now() / 1000);\n\n const symbols = await adapter.extractSymbols(relativePath, source);\n const complexity = await adapter.extractComplexity(relativePath, source);\n\n // Build symbol registry for accurate edge resolution\n for (const sym of symbols) {\n symbolRegistry.set(sym.symbolId, sym.kind);\n }\n\n pendingIndices.push({\n relativePath,\n source,\n fileIndex: {\n file: relativePath,\n lastModified,\n contentHash: hasher.hash(source),\n symbols,\n edges: [],\n complexity,\n intent: [],\n antiPatterns: [],\n },\n });\n\n processed++;\n if (processed % 50 === 0) {\n console.error(`[ctxo] Processed ${processed}/${files.length} files (symbols)`);\n }\n } catch (err) {\n console.error(`[ctxo] Skipped ${relativePath}: ${(err as Error).message}`);\n }\n }\n\n // Pre-load all sources into ts-morph for cross-file resolution\n const allSources = new Map<string, string>();\n for (const entry of pendingIndices) {\n allSources.set(entry.relativePath, entry.source);\n }\n tsMorphLike?.loadProjectSources(allSources);\n\n // Phase 1b: Extract edges (uses symbol registry for correct kind resolution)\n for (const entry of pendingIndices) {\n const adapter = registry.getAdapter(entry.relativePath);\n if (!adapter) continue;\n\n try {\n adapter.setSymbolRegistry?.(symbolRegistry);\n entry.fileIndex.edges = await adapter.extractEdges(entry.relativePath, entry.source);\n } catch (err) {\n console.error(`[ctxo] Edge extraction failed for ${entry.relativePath}: ${(err as Error).message}`);\n }\n }\n\n // Clean up pre-loaded sources\n tsMorphLike?.clearProjectSources();\n\n // Phase 2: Batch git history (single git call for all files)\n if (!options.skipHistory && pendingIndices.length > 0) {\n const maxHistory = options.maxHistory ?? 20;\n const batchHistory = await gitAdapter.getBatchHistory?.(maxHistory) ?? new Map<string, import('../core/types.js').CommitRecord[]>();\n\n for (const { relativePath, fileIndex } of pendingIndices) {\n const commits = batchHistory.get(relativePath) ?? [];\n fileIndex.intent = commits.map((c) => ({\n hash: c.hash,\n message: c.message,\n date: c.date,\n kind: 'commit' as const,\n }));\n fileIndex.antiPatterns = revertDetector.detect(commits);\n }\n }\n\n // Phase 2b: Aggregate co-change data from git history\n if (!options.skipHistory && pendingIndices.length > 0) {\n const fileIndices = pendingIndices.map(e => e.fileIndex);\n const coChangeMatrix = aggregateCoChanges(fileIndices);\n writer.writeCoChanges(coChangeMatrix);\n console.error(`[ctxo] Co-change analysis: ${coChangeMatrix.entries.length} file pairs detected`);\n }\n\n // Phase 3: Write all indices\n const indices: FileIndex[] = [];\n for (const { fileIndex } of pendingIndices) {\n writer.write(fileIndex);\n indices.push(fileIndex);\n }\n\n // Write schema version\n schemaManager.writeVersion();\n\n // Populate SQLite cache (skip rebuildFromJson since we just wrote the JSON)\n const storage = new SqliteStorageAdapter(this.ctxoRoot);\n try {\n await storage.initEmpty();\n storage.bulkWrite(indices);\n } finally {\n storage.close();\n }\n\n // Ensure .ctxo/.cache/ is in .gitignore (skip during verify runs)\n if (!options.skipSideEffects) {\n this.ensureGitignore();\n }\n\n // Tier summary\n const csCount = pendingIndices.filter(e => e.relativePath.endsWith('.cs')).length;\n const tsCount = pendingIndices.filter(e => /\\.(ts|tsx|js|jsx)$/.test(e.relativePath)).length;\n const goCount = pendingIndices.filter(e => e.relativePath.endsWith('.go')).length;\n console.error(`[ctxo] Index complete: ${processed} files indexed`);\n if (tsCount > 0) console.error(`[ctxo] TypeScript/JS: ${tsCount} files (full tier)`);\n if (csCount > 0) console.error(`[ctxo] C#: ${csCount} files (${csharpTier} tier${csharpTier === 'syntax' ? ' - .NET SDK 8+ for full analysis' : ''})`);\n if (goCount > 0) console.error(`[ctxo] Go: ${goCount} files (${goTier} tier${goTier === 'syntax' ? ' - Go 1.22+ for full analysis' : ''})`);\n\n // Dispose Roslyn adapter\n if (roslynAdapter) await roslynAdapter.dispose();\n }\n\n private async autoInstallMissingPlugins(): Promise<void> {\n const detection = detectLanguages(this.projectRoot);\n const needed = decideNeededLanguages(detection);\n const missing: KnownLanguage[] = [];\n for (const lang of needed) {\n try {\n requireCjs.resolve(`${officialPluginFor(lang)}/package.json`);\n } catch {\n missing.push(lang);\n }\n }\n if (missing.length === 0) return;\n console.error(`[ctxo] --install-missing: installing ${missing.join(', ')}`);\n await new InstallCommand(this.projectRoot).run({ languages: missing, yes: true });\n }\n\n private printLanguagePreview(): void {\n const detection = detectLanguages(this.projectRoot);\n const lines: string[] = [];\n for (const [lang, count] of Object.entries(detection.byExtension)) {\n const hasPlugin = this.supportedExtensions.size > 0 && Object.entries(EXTENSION_LANGUAGE)\n .some(([ext, id]) => id === lang && this.supportedExtensions.has(ext));\n const status = hasPlugin ? 'plugin available' : 'no plugin — skipped';\n lines.push(` ${lang.padEnd(10)} ${String(count).padStart(5)} files (${status})`);\n }\n if (lines.length === 0) return;\n console.error('[ctxo] Language scan:');\n for (const line of lines) console.error(line);\n }\n\n private async registerDiscoveredPlugins(\n registry: LanguageAdapterRegistry,\n ignoreProjectPatterns: string[] = [],\n ): Promise<{\n tsMorphLike: TsMorphLike | undefined;\n roslynAdapter: RoslynLike | null;\n csharpTier: string;\n goTier: string;\n }> {\n const loaded = await loadPlugins(this.projectRoot, { ignoreProjects: ignoreProjectPatterns });\n let tsMorphLike: TsMorphLike | undefined;\n let roslynAdapter: RoslynLike | null = null;\n let csharpTier = 'unavailable';\n let goTier = 'unavailable';\n\n for (const { plugin, adapter } of loaded) {\n // Plugins that expose an initialize() lifecycle need it called before register\n if (typeof adapter.initialize === 'function') {\n try {\n await adapter.initialize(this.projectRoot);\n } catch (err) {\n console.error(`[ctxo] Plugin ${plugin.id} initialize failed: ${(err as Error).message}`);\n continue;\n }\n }\n\n registry.register(plugin.extensions, adapter);\n\n // Duck-type: TsMorphAdapter exposes project-wide preload hooks\n const tsCandidate = adapter as unknown as Partial<TsMorphLike>;\n if (\n typeof tsCandidate.loadProjectSources === 'function' &&\n typeof tsCandidate.clearProjectSources === 'function'\n ) {\n tsMorphLike = tsCandidate as TsMorphLike;\n }\n\n // Duck-type: CSharpCompositeAdapter exposes Roslyn delegate + tier info\n const csCandidate = adapter as unknown as Partial<CSharpCompositeLike>;\n if (\n plugin.id === 'csharp' &&\n typeof csCandidate.getRoslynDelegate === 'function' &&\n typeof csCandidate.getTier === 'function'\n ) {\n csharpTier = csCandidate.getTier();\n roslynAdapter = csCandidate.getRoslynDelegate() ?? null;\n }\n\n // Duck-type: GoCompositeAdapter exposes tier info\n const goCandidate = adapter as unknown as Partial<GoCompositeLike>;\n if (plugin.id === 'go' && typeof goCandidate.getTier === 'function') {\n goTier = goCandidate.getTier();\n }\n\n const activeTier =\n plugin.id === 'csharp' ? csharpTier :\n plugin.id === 'go' ? goTier :\n plugin.tier;\n const tierSuffix = activeTier !== plugin.tier ? ` (active: ${activeTier})` : '';\n console.error(`[ctxo] Plugin ${plugin.id}@${plugin.version} (${plugin.tier} tier${tierSuffix}) — ${plugin.extensions.join(', ')}`);\n }\n\n return { tsMorphLike, roslynAdapter, csharpTier, goTier };\n }\n\n private discoverFilesIn(root: string, ignoreFile: (p: string) => boolean = () => false): string[] {\n try {\n const output = execFileSync('git', ['ls-files', '--cached', '--others', '--exclude-standard'], {\n cwd: root,\n encoding: 'utf-8',\n maxBuffer: 10 * 1024 * 1024,\n });\n\n return output\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .filter((line) => this.isSupportedExtension(line))\n .map((line) => join(root, line))\n .filter((abs) => {\n const rel = relative(this.projectRoot, abs).replace(/\\\\/g, '/');\n return !ignoreFile(rel);\n });\n } catch {\n console.error(`[ctxo] git ls-files failed for ${root}`);\n return [];\n }\n }\n\n private discoverWorkspaces(ignoreProject: (p: string) => boolean = () => false): string[] {\n const pkgPath = join(this.projectRoot, 'package.json');\n if (!existsSync(pkgPath)) return [this.projectRoot];\n\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));\n const workspaces: string[] | undefined = Array.isArray(pkg.workspaces)\n ? pkg.workspaces\n : pkg.workspaces?.packages;\n\n if (!workspaces || workspaces.length === 0) return [this.projectRoot];\n\n // Resolve workspace patterns (supports simple globs like packages/*)\n const resolved: string[] = [];\n for (const ws of workspaces) {\n if (ws.endsWith('/*') || ws.endsWith('\\\\*')) {\n // Glob: packages/* → list subdirectories of packages/\n const parentDir = join(this.projectRoot, ws.slice(0, -2));\n if (existsSync(parentDir)) {\n for (const entry of readdirSync(parentDir, { withFileTypes: true })) {\n if (entry.isDirectory()) {\n resolved.push(join(parentDir, entry.name));\n }\n }\n }\n } else {\n // Literal path\n const wsPath = join(this.projectRoot, ws);\n if (existsSync(wsPath)) {\n resolved.push(wsPath);\n }\n }\n }\n\n if (resolved.length === 0) return [this.projectRoot];\n\n const filtered = resolved.filter((wsAbs) => {\n const rel = relative(this.projectRoot, wsAbs).replace(/\\\\/g, '/');\n if (ignoreProject(rel)) {\n console.error(`[ctxo] index.ignoreProjects: skipping ${rel}`);\n return false;\n }\n return true;\n });\n\n if (filtered.length === 0) return [this.projectRoot];\n\n console.error(`[ctxo] Monorepo detected: ${filtered.length} workspace(s)`);\n return filtered;\n } catch {\n return [this.projectRoot];\n }\n }\n\n private isSupportedExtension(filePath: string): boolean {\n const ext = extname(filePath).toLowerCase();\n return this.supportedExtensions.has(ext);\n }\n\n private async runCheck(): Promise<void> {\n console.error('[ctxo] Checking index freshness...');\n\n // Register adapters so supportedExtensions includes discovered extensions\n const registry = new LanguageAdapterRegistry();\n const { roslynAdapter: _roslyn } = await this.registerDiscoveredPlugins(registry);\n this.supportedExtensions = registry.getSupportedExtensions();\n if (_roslyn) await _roslyn.dispose();\n\n const hasher = new ContentHasher();\n const files = this.discoverFilesIn(this.projectRoot);\n const reader = new (await import('../adapters/storage/json-index-reader.js')).JsonIndexReader(this.ctxoRoot);\n const indices = reader.readAll();\n const indexedMap = new Map(indices.map((i) => [i.file, i]));\n\n let staleCount = 0;\n\n for (const filePath of files) {\n if (!this.isSupportedExtension(filePath)) continue;\n\n const relativePath = relative(this.projectRoot, filePath).replace(/\\\\/g, '/');\n const indexed = indexedMap.get(relativePath);\n\n if (!indexed) {\n console.error(`[ctxo] NOT INDEXED: ${relativePath}`);\n staleCount++;\n continue;\n }\n\n // Guard: file may be deleted from disk but still tracked by git\n if (!existsSync(filePath)) {\n console.error(`[ctxo] DELETED: ${relativePath}`);\n staleCount++;\n continue;\n }\n\n // Fast path: mtime check (skip hash if mtime hasn't changed)\n const mtime = Math.floor(statSync(filePath).mtimeMs / 1000);\n if (mtime <= indexed.lastModified) continue;\n\n // Slow path: hash-based verification (handles git checkout, cp -p, CI)\n if (indexed.contentHash) {\n const source = readFileSync(filePath, 'utf-8');\n const currentHash = hasher.hash(source);\n if (currentHash === indexed.contentHash) continue;\n }\n\n console.error(`[ctxo] STALE: ${relativePath}`);\n staleCount++;\n }\n\n if (staleCount > 0) {\n console.error(`[ctxo] ${staleCount} file(s) need re-indexing. Run \"ctxo index\"`);\n process.exit(1);\n }\n\n console.error('[ctxo] Index is up to date');\n }\n\n private ensureGitignore(): void {\n const gitignorePath = join(this.projectRoot, '.gitignore');\n const cachePattern = '.ctxo/.cache/';\n const suffix = `\\n# Ctxo local cache (never committed)\\n${cachePattern}\\n`;\n\n // Read-modify-write atomically to avoid TOCTOU race\n const existing = existsSync(gitignorePath) ? readFileSync(gitignorePath, 'utf-8') : '';\n if (existing.includes(cachePattern)) return;\n\n writeFileSync(gitignorePath, existing + suffix, 'utf-8');\n console.error('[ctxo] Added .ctxo/.cache/ to .gitignore');\n }\n}\n","import { createHash } from 'node:crypto';\n\nexport class ContentHasher {\n hash(content: string): string {\n return createHash('sha256').update(content, 'utf-8').digest('hex');\n }\n}\n","import { extname } from 'node:path';\nimport type { ILanguageAdapter } from '@ctxo/plugin-api';\n\nexport class LanguageAdapterRegistry {\n private readonly adaptersByExtension = new Map<string, ILanguageAdapter>();\n\n register(extensions: readonly string[], adapter: ILanguageAdapter): void {\n for (const ext of extensions) {\n this.adaptersByExtension.set(ext.toLowerCase(), adapter);\n }\n }\n\n getSupportedExtensions(): Set<string> {\n return new Set(this.adaptersByExtension.keys());\n }\n\n getAdapter(filePath: string): ILanguageAdapter | undefined {\n if (!filePath) return undefined;\n\n const ext = extname(filePath).toLowerCase();\n if (!ext) return undefined;\n\n return this.adaptersByExtension.get(ext);\n }\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport type { CtxoLanguagePlugin, PluginContext, ILanguageAdapter, IWorkspace } from '@ctxo/plugin-api';\nimport { discoverPlugins, type DiscoveredPlugin } from '../adapters/language/plugin-discovery.js';\nimport { detectWorkspace } from '../adapters/workspace/single-package-workspace.js';\nimport { createLogger } from '../core/logger.js';\nimport { makeGlobMatcher } from '../core/config/load-config.js';\n\nconst log = createLogger('ctxo:plugin-loader');\n\nexport interface LoadedPlugin {\n readonly plugin: CtxoLanguagePlugin;\n readonly adapter: ILanguageAdapter;\n readonly specifier: string;\n}\n\nfunction manifestHasPlugins(path: string): boolean {\n try {\n const raw = JSON.parse(readFileSync(path, 'utf-8')) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n };\n const all = { ...raw.dependencies, ...raw.devDependencies, ...raw.peerDependencies };\n return Object.keys(all).some((n) => n.startsWith('@ctxo/lang-') || n.startsWith('ctxo-lang-'));\n } catch {\n return false;\n }\n}\n\n/**\n * Resolve the package.json that should be scanned for plugin deps.\n * Preference order:\n * 1. projectRoot/package.json (user's project)\n * 2. cli install location (walk up from __dirname until package.json)\n */\nexport function loadManifestPath(projectRoot: string): string | null {\n return resolveManifestPath(projectRoot);\n}\n\nfunction resolveManifestPath(projectRoot: string): string | null {\n const projectManifest = join(projectRoot, 'package.json');\n if (existsSync(projectManifest) && manifestHasPlugins(projectManifest)) {\n return projectManifest;\n }\n\n let dir = import.meta.dirname;\n for (let i = 0; i < 12; i++) {\n const candidate = join(dir, 'package.json');\n if (existsSync(candidate) && manifestHasPlugins(candidate)) return candidate;\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n\n // Last resort: return projectManifest even if empty so discovery reports absence.\n return existsSync(projectManifest) ? projectManifest : null;\n}\n\nfunction buildContext(projectRoot: string, workspace: IWorkspace, pluginId: string): PluginContext {\n const pluginLog = createLogger(`ctxo:plugin:${pluginId}`);\n return {\n logger: {\n debug: (msg, ...args) => pluginLog.info(String(msg), ...args),\n info: (msg, ...args) => pluginLog.info(String(msg), ...args),\n warn: (msg, ...args) => pluginLog.warn(String(msg), ...args),\n error: (msg, ...args) => pluginLog.error(String(msg), ...args),\n },\n projectRoot,\n workspace,\n config: {},\n };\n}\n\nexport interface LoadPluginsOptions {\n /**\n * Glob patterns (matched against workspace paths relative to projectRoot)\n * for workspaces whose plugin deps should be ignored during discovery.\n * Sourced from `.ctxo/config.yaml#index.ignoreProjects`.\n */\n readonly ignoreProjects?: readonly string[];\n}\n\nexport async function loadPlugins(\n projectRoot: string,\n options: LoadPluginsOptions = {},\n): Promise<LoadedPlugin[]> {\n const manifestPath = resolveManifestPath(projectRoot);\n if (!manifestPath) {\n log.info('No package.json found for plugin discovery');\n return [];\n }\n\n const workspace = detectWorkspace(projectRoot);\n const ignoreProjectPatterns = options.ignoreProjects ?? [];\n const shouldSkipSpecifier = ignoreProjectPatterns.length === 0\n ? undefined\n : makeGlobMatcher(ignoreProjectPatterns.slice());\n const result = await discoverPlugins({ manifestPath, shouldSkipSpecifier });\n\n const loaded: LoadedPlugin[] = [];\n for (const { plugin, specifier } of result.plugins as readonly DiscoveredPlugin[]) {\n try {\n const ctx = buildContext(projectRoot, workspace, plugin.id);\n const adapter = plugin.createAdapter(ctx);\n loaded.push({ plugin, adapter, specifier });\n } catch (err) {\n log.warn(`Plugin ${plugin.id} createAdapter failed: ${(err as Error).message}`);\n }\n }\n return loaded;\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { dirname, isAbsolute, resolve } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { CtxoLanguagePlugin } from '@ctxo/plugin-api';\nimport { SUPPORTED_API_VERSION } from '@ctxo/plugin-api';\nimport { createLogger } from '../../core/logger.js';\n\nconst log = createLogger('ctxo:plugin-discovery');\n\nconst OFFICIAL_PREFIX = '@ctxo/lang-';\nconst COMMUNITY_PREFIX = 'ctxo-lang-';\n\nexport interface DiscoverOptions {\n /** Absolute path to the package.json used for dependency scanning. */\n readonly manifestPath: string;\n /**\n * Explicit plugin list. When provided, suppresses auto-discovery and loads\n * only these packages/paths. Strings starting with '.' or '/' are treated\n * as local paths resolved against the manifest directory.\n */\n readonly explicit?: readonly string[];\n /**\n * Predicate that returns true for plugin specifiers that should be skipped\n * entirely (never imported). Used by the CLI to short-circuit loading of\n * plugins whose backing workspace was excluded via\n * `.ctxo/config.yaml#index.ignoreProjects`.\n */\n readonly shouldSkipSpecifier?: (specifier: string) => boolean;\n}\n\nexport interface DiscoveredPlugin {\n readonly plugin: CtxoLanguagePlugin;\n readonly specifier: string;\n}\n\nexport interface PluginLoadFailure {\n readonly specifier: string;\n readonly reason: string;\n}\n\nexport interface DiscoveryResult {\n readonly plugins: readonly DiscoveredPlugin[];\n readonly failures: readonly PluginLoadFailure[];\n}\n\nfunction readManifestDeps(manifestPath: string): string[] {\n try {\n const raw = readFileSync(manifestPath, 'utf-8');\n const manifest = JSON.parse(raw) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n };\n const all = {\n ...manifest.dependencies,\n ...manifest.devDependencies,\n ...manifest.peerDependencies,\n };\n return Object.keys(all).filter(\n (name) => name.startsWith(OFFICIAL_PREFIX) || name.startsWith(COMMUNITY_PREFIX),\n );\n } catch (err) {\n log.warn(`Failed to read manifest ${manifestPath}: ${(err as Error).message}`);\n return [];\n }\n}\n\nfunction isLocalSpecifier(spec: string): boolean {\n return spec.startsWith('.') || spec.startsWith('/') || isAbsolute(spec);\n}\n\nasync function tryLoad(\n specifier: string,\n baseDir: string,\n): Promise<CtxoLanguagePlugin | PluginLoadFailure> {\n try {\n const target = isLocalSpecifier(specifier)\n ? pathToFileURL(resolve(baseDir, specifier)).href\n : specifier;\n\n const mod = (await import(target)) as {\n default?: unknown;\n plugin?: unknown;\n };\n const candidate = (mod.default ?? mod.plugin ?? mod) as Partial<CtxoLanguagePlugin>;\n\n if (!candidate || typeof candidate !== 'object') {\n return { specifier, reason: 'module export is not an object' };\n }\n if (candidate.apiVersion !== SUPPORTED_API_VERSION) {\n return {\n specifier,\n reason: `unsupported apiVersion ${String(candidate.apiVersion)} (want '${SUPPORTED_API_VERSION}')`,\n };\n }\n if (typeof candidate.createAdapter !== 'function') {\n return { specifier, reason: 'missing createAdapter()' };\n }\n if (typeof candidate.id !== 'string' || candidate.id.length === 0) {\n return { specifier, reason: 'missing or empty id' };\n }\n if (!Array.isArray(candidate.extensions)) {\n return { specifier, reason: 'extensions must be an array' };\n }\n if (candidate.tier !== 'syntax' && candidate.tier !== 'full') {\n return { specifier, reason: `invalid tier ${String(candidate.tier)}` };\n }\n\n return candidate as CtxoLanguagePlugin;\n } catch (err) {\n return { specifier, reason: (err as Error).message };\n }\n}\n\nexport async function discoverPlugins(options: DiscoverOptions): Promise<DiscoveryResult> {\n const { manifestPath } = options;\n if (!existsSync(manifestPath)) {\n log.info(`Manifest not found at ${manifestPath} — no plugins discovered`);\n return { plugins: [], failures: [] };\n }\n\n const baseDir = dirname(manifestPath);\n const specifiers = options.explicit ?? readManifestDeps(manifestPath);\n\n const plugins: DiscoveredPlugin[] = [];\n const failures: PluginLoadFailure[] = [];\n\n for (const spec of specifiers) {\n if (options.shouldSkipSpecifier?.(spec)) {\n log.info(`Skipping plugin ${spec} (matched ignoreProjects)`);\n continue;\n }\n const result = await tryLoad(spec, baseDir);\n if ('apiVersion' in result) {\n plugins.push({ plugin: result, specifier: spec });\n } else {\n failures.push(result);\n log.warn(`Skipped plugin ${spec}: ${result.reason}`);\n }\n }\n\n return { plugins, failures };\n}\n","import { existsSync } from 'node:fs';\nimport { spawn } from 'node:child_process';\nimport { createRequire } from 'node:module';\nimport { join } from 'node:path';\nimport {\n KNOWN_LANGUAGES,\n officialPluginFor,\n detectLanguages,\n decideNeededLanguages,\n type KnownLanguage,\n} from '../core/detection/detect-languages.js';\nimport {\n resolvePackageManager,\n buildInstallCommand,\n isPackageManager,\n PACKAGE_MANAGERS,\n type PackageManager,\n type Resolution,\n} from '../core/install/package-manager.js';\n\nexport interface InstallOptions {\n readonly languages?: readonly string[];\n readonly yes?: boolean;\n readonly global?: boolean;\n readonly dryRun?: boolean;\n readonly pm?: string;\n readonly version?: string;\n readonly force?: boolean;\n}\n\nexport interface InstallPlan {\n readonly languages: readonly KnownLanguage[];\n readonly packages: readonly string[];\n readonly manager: PackageManager;\n readonly managerSource: Resolution['source'];\n readonly global: boolean;\n readonly command: string;\n readonly args: readonly string[];\n}\n\nexport class InstallCommand {\n constructor(private readonly projectRoot: string) {}\n\n async run(options: InstallOptions = {}): Promise<void> {\n const resolvedLangs = this.resolveLanguages(options);\n if (resolvedLangs.length === 0) {\n console.error('[ctxo] Nothing to install. Specify a language (e.g. \"ctxo install python\") or add one to your project.');\n process.exitCode = 0;\n return;\n }\n\n let resolution: Resolution;\n try {\n resolution = resolvePackageManager({\n flag: options.pm,\n projectRoot: this.projectRoot,\n });\n } catch (err) {\n console.error(`[ctxo] ${(err as Error).message}`);\n process.exitCode = 1;\n return;\n }\n\n if (!options.global && !existsSync(join(this.projectRoot, 'package.json'))) {\n console.error('[ctxo] No package.json in the current project. Re-run with --global or create a package.json first.');\n process.exitCode = 1;\n return;\n }\n\n if (!options.force && !options.global && isLockedCI(process.env)) {\n console.error('[ctxo] CI environment detected with a frozen lockfile. Refusing to mutate dependencies. Use --force or switch to --global.');\n process.exitCode = 1;\n return;\n }\n\n const specifiers = resolvedLangs.map((lang) =>\n options.version ? `${officialPluginFor(lang)}@${options.version}` : officialPluginFor(lang),\n );\n\n const invocation = buildInstallCommand(resolution.manager, specifiers, {\n global: options.global,\n });\n\n const plan: InstallPlan = {\n languages: resolvedLangs,\n packages: specifiers,\n manager: resolution.manager,\n managerSource: resolution.source,\n global: options.global ?? false,\n command: invocation.command,\n args: [...invocation.args],\n };\n\n console.error(`[ctxo] Plan: install ${plan.packages.join(', ')}`);\n console.error(`[ctxo] Using ${plan.manager} (${plan.managerSource}${resolution.detail ? `: ${resolution.detail}` : ''})${plan.global ? ', global' : ''}`);\n console.error(`[ctxo] Command: ${plan.command} ${plan.args.join(' ')}`);\n\n if (options.dryRun) {\n console.error('[ctxo] --dry-run set; not executing.');\n return;\n }\n\n const code = await spawnInstall(plan.command, plan.args, this.projectRoot);\n if (code !== 0) {\n console.error(`[ctxo] ${plan.command} exited with code ${code}`);\n process.exitCode = code;\n return;\n }\n\n console.error(`[ctxo] Installed ${plan.packages.join(', ')}`);\n }\n\n private resolveLanguages(options: InstallOptions): KnownLanguage[] {\n const requested = options.languages ?? [];\n if (requested.length > 0) {\n const out: KnownLanguage[] = [];\n for (const raw of requested) {\n const lang = normalizeLanguage(raw);\n if (!lang) {\n console.error(\n `[ctxo] Unknown language \"${raw}\". Known: ${KNOWN_LANGUAGES.join(', ')}. Community plugins: see the ctxo-lang-template scaffolding guide.`,\n );\n process.exitCode = 1;\n return [];\n }\n if (!out.includes(lang)) out.push(lang);\n }\n return out;\n }\n\n // No explicit languages — detect missing.\n const detection = detectLanguages(this.projectRoot);\n const needed = decideNeededLanguages(detection);\n if (needed.length === 0) return [];\n const missing = needed.filter((lang) => !isPluginInstalled(lang));\n if (missing.length === 0) {\n console.error('[ctxo] All detected languages already have plugins installed.');\n return [];\n }\n console.error(`[ctxo] Detected missing plugins for: ${missing.join(', ')}`);\n return missing;\n }\n}\n\nfunction normalizeLanguage(input: string): KnownLanguage | null {\n const lowered = input.toLowerCase();\n if ((KNOWN_LANGUAGES as readonly string[]).includes(lowered)) {\n return lowered as KnownLanguage;\n }\n // Accept common aliases.\n const aliases: Record<string, KnownLanguage> = {\n ts: 'typescript',\n js: 'javascript',\n py: 'python',\n 'c#': 'csharp',\n 'cs': 'csharp',\n 'net': 'csharp',\n golang: 'go',\n kt: 'kotlin',\n rb: 'ruby',\n rs: 'rust',\n };\n return aliases[lowered] ?? null;\n}\n\nconst installRequire = createRequire(import.meta.url);\n\nfunction isPluginInstalled(lang: KnownLanguage): boolean {\n try {\n installRequire.resolve(`${officialPluginFor(lang)}/package.json`);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction isLockedCI(env: NodeJS.ProcessEnv): boolean {\n if (env['CI'] !== 'true' && env['CI'] !== '1') return false;\n // npm ci / pnpm --frozen-lockfile / yarn install --frozen-lockfile run in CI and must not mutate.\n return true;\n}\n\nfunction spawnInstall(command: string, args: readonly string[], cwd: string): Promise<number> {\n return new Promise((resolve, reject) => {\n const child = spawn(command, [...args], { cwd, stdio: 'inherit', shell: process.platform === 'win32' });\n child.on('exit', (code) => resolve(code ?? 0));\n child.on('error', (err) => reject(err));\n });\n}\n\nexport { isPackageManager, PACKAGE_MANAGERS };\n","import { execFileSync } from 'node:child_process';\nimport { existsSync, readdirSync } from 'node:fs';\nimport { extname, join } from 'node:path';\n\n/**\n * Canonical short language ids. Plugins use these same ids (e.g. `@ctxo/lang-typescript`\n * declares id: 'typescript'). Keep in sync with plugin id fields.\n */\nexport const KNOWN_LANGUAGES = [\n 'typescript',\n 'javascript',\n 'go',\n 'csharp',\n 'python',\n 'java',\n 'rust',\n 'ruby',\n 'kotlin',\n] as const;\n\nexport type KnownLanguage = (typeof KNOWN_LANGUAGES)[number];\n\n/**\n * Extension → canonical language id. Multiple extensions may map to the same\n * language (e.g. .ts + .tsx → typescript).\n */\nexport const EXTENSION_LANGUAGE: Readonly<Record<string, KnownLanguage>> = {\n '.ts': 'typescript',\n '.tsx': 'typescript',\n '.js': 'javascript',\n '.jsx': 'javascript',\n '.go': 'go',\n '.cs': 'csharp',\n '.py': 'python',\n '.pyi': 'python',\n '.java': 'java',\n '.kt': 'kotlin',\n '.kts': 'kotlin',\n '.rs': 'rust',\n '.rb': 'ruby',\n};\n\nexport interface DetectionResult {\n /** Language id → manifest filename that surfaced it. */\n byManifest: Record<string, string>;\n /** Language id → source file count (from git ls-files). */\n byExtension: Record<string, number>;\n /** Total source files counted (sum of byExtension). */\n totalFiles: number;\n /** Extensions seen that don't map to a known language id. */\n unknownExtensions: Record<string, number>;\n}\n\ninterface ManifestProbe {\n readonly id: KnownLanguage;\n readonly check: (root: string) => string | null;\n}\n\nconst MANIFEST_PROBES: readonly ManifestProbe[] = [\n {\n id: 'typescript',\n check: (root) => (existsSync(join(root, 'tsconfig.json')) ? 'tsconfig.json' : null),\n },\n {\n id: 'python',\n check: (root) => {\n if (existsSync(join(root, 'pyproject.toml'))) return 'pyproject.toml';\n if (existsSync(join(root, 'setup.py'))) return 'setup.py';\n if (existsSync(join(root, 'requirements.txt'))) return 'requirements.txt';\n return null;\n },\n },\n {\n id: 'java',\n check: (root) => {\n if (existsSync(join(root, 'pom.xml'))) return 'pom.xml';\n if (existsSync(join(root, 'build.gradle'))) return 'build.gradle';\n if (existsSync(join(root, 'build.gradle.kts'))) return 'build.gradle.kts';\n return null;\n },\n },\n {\n id: 'go',\n check: (root) => (existsSync(join(root, 'go.mod')) ? 'go.mod' : null),\n },\n {\n id: 'csharp',\n check: (root) => {\n try {\n for (const entry of readdirSync(root, { withFileTypes: true })) {\n if (entry.isFile() && (entry.name.endsWith('.csproj') || entry.name.endsWith('.sln'))) {\n return entry.name;\n }\n }\n } catch {\n // ignore\n }\n return null;\n },\n },\n {\n id: 'rust',\n check: (root) => (existsSync(join(root, 'Cargo.toml')) ? 'Cargo.toml' : null),\n },\n {\n id: 'ruby',\n check: (root) => (existsSync(join(root, 'Gemfile')) ? 'Gemfile' : null),\n },\n];\n\nfunction listGitFiles(root: string): string[] {\n try {\n const out = execFileSync(\n 'git',\n ['ls-files', '--cached', '--others', '--exclude-standard'],\n { cwd: root, encoding: 'utf-8', maxBuffer: 64 * 1024 * 1024 },\n );\n return out.split('\\n').filter(Boolean);\n } catch {\n return [];\n }\n}\n\n/**\n * Detect languages present in a project root.\n *\n * - Manifest signals: presence of language-specific build files (pyproject.toml, pom.xml, go.mod, ...)\n * - Extension counts: derived from `git ls-files` (falls back to empty when not a git repo)\n *\n * Pure I/O: no network, bounded by git output. Safe to call repeatedly.\n */\nexport function detectLanguages(root: string): DetectionResult {\n const byManifest: Record<string, string> = {};\n for (const probe of MANIFEST_PROBES) {\n const manifest = probe.check(root);\n if (manifest) byManifest[probe.id] = manifest;\n }\n\n const byExtension: Record<string, number> = {};\n const unknownExtensions: Record<string, number> = {};\n let totalFiles = 0;\n\n for (const file of listGitFiles(root)) {\n const ext = extname(file).toLowerCase();\n if (!ext) continue;\n totalFiles += 1;\n const lang = EXTENSION_LANGUAGE[ext];\n if (lang) {\n byExtension[lang] = (byExtension[lang] ?? 0) + 1;\n } else {\n unknownExtensions[ext] = (unknownExtensions[ext] ?? 0) + 1;\n }\n }\n\n return { byManifest, byExtension, totalFiles, unknownExtensions };\n}\n\nexport interface LanguageNeedsOptions {\n /** Minimum source files needed to flag an extension-only language. Default 5. */\n minFiles?: number;\n /** Minimum ratio (0..1) of total files needed for extension-only detection. Default 0.02. */\n minRatio?: number;\n}\n\n/**\n * Decide which languages the project needs plugins for.\n *\n * Rules (from PRD §4.6):\n * - Manifest-backed language → always in `needed`\n * - Extension-only language → needed if count >= minFiles AND ratio >= minRatio\n */\nexport function decideNeededLanguages(\n result: DetectionResult,\n options: LanguageNeedsOptions = {},\n): KnownLanguage[] {\n const minFiles = options.minFiles ?? 5;\n const minRatio = options.minRatio ?? 0.02;\n const needed = new Set<KnownLanguage>();\n\n for (const id of Object.keys(result.byManifest)) {\n needed.add(id as KnownLanguage);\n }\n\n for (const [id, count] of Object.entries(result.byExtension)) {\n if (result.byManifest[id]) continue;\n const ratio = result.totalFiles > 0 ? count / result.totalFiles : 0;\n if (count >= minFiles && ratio >= minRatio) {\n needed.add(id as KnownLanguage);\n }\n }\n\n return [...needed];\n}\n\n/** Map a language id to its canonical official npm plugin package name. */\nexport function officialPluginFor(language: KnownLanguage): string {\n return `@ctxo/lang-${language}`;\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\n\nexport type PackageManager = 'npm' | 'pnpm' | 'yarn' | 'bun';\n\nexport const PACKAGE_MANAGERS: readonly PackageManager[] = ['npm', 'pnpm', 'yarn', 'bun'];\n\nexport function isPackageManager(value: string): value is PackageManager {\n return (PACKAGE_MANAGERS as readonly string[]).includes(value);\n}\n\nexport interface ResolveOptions {\n /** CLI flag value (highest priority). */\n readonly flag?: string;\n /** process.env lookup (can inject for tests). */\n readonly env?: NodeJS.ProcessEnv;\n /** Project root where package.json, lockfiles, and .ctxo live. */\n readonly projectRoot: string;\n}\n\nexport interface Resolution {\n readonly manager: PackageManager;\n readonly source: 'flag' | 'env' | 'config' | 'lockfile' | 'default';\n readonly detail?: string;\n}\n\n/**\n * Resolve the package manager to use for install operations.\n *\n * Order (PRD §5.4 D3.6):\n * 1. `--pm` flag\n * 2. `CTXO_PM` env var\n * 3. `.ctxo/config.yaml` packageManager field\n * 4. Lockfile detection: bun.lockb > pnpm-lock.yaml > yarn.lock > package-lock.json\n * 5. Default: npm\n */\nexport function resolvePackageManager(options: ResolveOptions): Resolution {\n const env = options.env ?? process.env;\n\n if (options.flag) {\n if (!isPackageManager(options.flag)) {\n throw new Error(\n `Unknown --pm value \"${options.flag}\". Supported: ${PACKAGE_MANAGERS.join(', ')}`,\n );\n }\n return { manager: options.flag, source: 'flag' };\n }\n\n const envValue = env['CTXO_PM'];\n if (envValue) {\n if (!isPackageManager(envValue)) {\n throw new Error(\n `CTXO_PM=\"${envValue}\" is not a supported package manager. Expected one of: ${PACKAGE_MANAGERS.join(', ')}`,\n );\n }\n return { manager: envValue, source: 'env' };\n }\n\n const configured = readConfigPackageManager(options.projectRoot);\n if (configured) return { manager: configured, source: 'config' };\n\n const corepack = readPackageManagerField(options.projectRoot);\n if (corepack) return { manager: corepack.manager, source: 'config', detail: corepack.detail };\n\n const lockHit = detectFromLockfileWalkUp(options.projectRoot);\n if (lockHit) return { manager: lockHit.manager, source: 'lockfile', detail: lockHit.detail };\n\n return { manager: 'npm', source: 'default' };\n}\n\n/**\n * Honor the corepack `packageManager` field in the nearest package.json walking\n * up from projectRoot. Format: \"pnpm@10.9.0\" | \"yarn@4.0.0\" | \"npm@10.0.0\".\n */\nfunction readPackageManagerField(startDir: string): LockHit | null {\n let dir = startDir;\n for (let i = 0; i < 12; i++) {\n const pkg = join(dir, 'package.json');\n if (existsSync(pkg)) {\n try {\n const parsed = JSON.parse(readFileSync(pkg, 'utf-8')) as { packageManager?: string };\n const value = parsed.packageManager;\n if (typeof value === 'string') {\n const [nameRaw] = value.split('@');\n const name = (nameRaw ?? '').trim();\n if (isPackageManager(name)) {\n return { manager: name, detail: `packageManager: ${value}` };\n }\n }\n } catch {\n // ignore malformed manifests; try parent\n }\n }\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\nfunction readConfigPackageManager(projectRoot: string): PackageManager | null {\n const path = join(projectRoot, '.ctxo', 'config.yaml');\n if (!existsSync(path)) return null;\n try {\n const raw = readFileSync(path, 'utf-8');\n // Minimal parse — single top-level `packageManager: <value>` line.\n const match = raw.match(/^packageManager:\\s*(\\S+)\\s*$/m);\n if (!match) return null;\n const value = match[1]!;\n return isPackageManager(value) ? value : null;\n } catch {\n return null;\n }\n}\n\ninterface LockHit {\n manager: PackageManager;\n detail: string;\n}\n\n/**\n * Look for a lockfile at `projectRoot` or any ancestor (monorepo-aware).\n * pnpm-workspace.yaml is also a strong pnpm signal even when the lockfile\n * lives only at the workspace root.\n */\nfunction detectFromLockfileWalkUp(startDir: string): LockHit | null {\n const probes: Array<{ file: string; manager: PackageManager }> = [\n { file: 'bun.lockb', manager: 'bun' },\n { file: 'pnpm-lock.yaml', manager: 'pnpm' },\n { file: 'pnpm-workspace.yaml', manager: 'pnpm' },\n { file: 'yarn.lock', manager: 'yarn' },\n { file: 'package-lock.json', manager: 'npm' },\n ];\n let dir = startDir;\n for (let i = 0; i < 12; i++) {\n for (const probe of probes) {\n const path = join(dir, probe.file);\n if (existsSync(path)) {\n return { manager: probe.manager, detail: probe.file };\n }\n }\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\nexport interface InstallInvocation {\n readonly command: string;\n readonly args: readonly string[];\n}\n\n/**\n * Build the install invocation for a chosen package manager. `global` produces\n * a globally-scoped install; otherwise the install targets devDependencies.\n */\nexport function buildInstallCommand(\n manager: PackageManager,\n packages: readonly string[],\n options: { global?: boolean } = {},\n): InstallInvocation {\n if (packages.length === 0) {\n throw new Error('buildInstallCommand requires at least one package');\n }\n switch (manager) {\n case 'npm':\n return {\n command: 'npm',\n args: options.global ? ['install', '-g', ...packages] : ['install', '-D', ...packages],\n };\n case 'pnpm':\n return {\n command: 'pnpm',\n args: options.global ? ['add', '-g', ...packages] : ['add', '-D', ...packages],\n };\n case 'yarn':\n return {\n command: 'yarn',\n args: options.global\n ? ['global', 'add', ...packages]\n : ['add', '--dev', ...packages],\n };\n case 'bun':\n return {\n command: 'bun',\n args: options.global ? ['add', '-g', ...packages] : ['add', '-d', ...packages],\n };\n }\n}\n","import { writeFileSync, renameSync, mkdirSync, unlinkSync, existsSync } from 'node:fs';\nimport { dirname, join, resolve, sep } from 'node:path';\nimport type { FileIndex, CoChangeMatrix } from '../../core/types.js';\n\nexport class JsonIndexWriter {\n private readonly indexDir: string;\n\n constructor(ctxoRoot: string) {\n this.indexDir = join(ctxoRoot, 'index');\n }\n\n write(fileIndex: FileIndex): void {\n if (!fileIndex.file) {\n throw new Error('FileIndex.file must not be empty');\n }\n\n const targetPath = this.resolveIndexPath(fileIndex.file);\n mkdirSync(dirname(targetPath), { recursive: true });\n\n const sorted = this.sortKeys(fileIndex);\n const json = JSON.stringify(sorted, null, 2);\n this.atomicWrite(targetPath, json);\n }\n\n writeCoChanges(matrix: CoChangeMatrix): void {\n mkdirSync(this.indexDir, { recursive: true });\n const targetPath = join(this.indexDir, 'co-changes.json');\n this.atomicWrite(targetPath, JSON.stringify(matrix, null, 2));\n }\n\n private atomicWrite(targetPath: string, content: string): void {\n const tmpPath = `${targetPath}.${process.pid}.tmp`;\n writeFileSync(tmpPath, content, 'utf-8');\n renameSync(tmpPath, targetPath);\n }\n\n delete(relativePath: string): void {\n const targetPath = this.resolveIndexPath(relativePath);\n if (existsSync(targetPath)) {\n unlinkSync(targetPath);\n }\n }\n\n private resolveIndexPath(relativePath: string): string {\n const resolved = resolve(this.indexDir, `${relativePath}.json`);\n const normalizedDir = resolve(this.indexDir) + sep;\n if (!resolved.startsWith(normalizedDir)) {\n throw new Error(`Path traversal detected: ${relativePath}`);\n }\n return resolved;\n }\n\n private sortKeys(obj: unknown): unknown {\n if (Array.isArray(obj)) {\n return obj.map((item) => this.sortKeys(item));\n }\n if (obj !== null && typeof obj === 'object') {\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(obj).sort()) {\n sorted[key] = this.sortKeys((obj as Record<string, unknown>)[key]);\n }\n return sorted;\n }\n return obj;\n }\n}\n","import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';\nimport { join, dirname } from 'node:path';\n\nconst CURRENT_SCHEMA_VERSION = '1.0.0';\n\nexport class SchemaManager {\n private readonly versionFilePath: string;\n\n constructor(ctxoRoot: string) {\n this.versionFilePath = join(ctxoRoot, 'index', 'schema-version');\n }\n\n currentVersion(): string {\n return CURRENT_SCHEMA_VERSION;\n }\n\n readStoredVersion(): string | undefined {\n if (!existsSync(this.versionFilePath)) {\n return undefined;\n }\n return readFileSync(this.versionFilePath, 'utf-8').trim();\n }\n\n writeVersion(): void {\n mkdirSync(dirname(this.versionFilePath), { recursive: true });\n writeFileSync(this.versionFilePath, CURRENT_SCHEMA_VERSION, 'utf-8');\n }\n\n isCompatible(): boolean {\n const stored = this.readStoredVersion();\n if (!stored) return false;\n return stored === CURRENT_SCHEMA_VERSION;\n }\n}\n","import { join } from 'node:path';\nimport { SqliteStorageAdapter } from '../adapters/storage/sqlite-storage-adapter.js';\n\nexport class SyncCommand {\n private readonly ctxoRoot: string;\n\n constructor(projectRoot: string) {\n this.ctxoRoot = join(projectRoot, '.ctxo');\n }\n\n async run(): Promise<void> {\n console.error('[ctxo] Rebuilding SQLite cache from committed JSON index...');\n\n const storage = new SqliteStorageAdapter(this.ctxoRoot);\n try {\n await storage.init();\n } finally {\n storage.close();\n }\n\n console.error('[ctxo] Sync complete');\n }\n}\n","import { join } from 'node:path';\nimport { existsSync } from 'node:fs';\nimport { execFileSync } from 'node:child_process';\nimport { JsonIndexReader } from '../adapters/storage/json-index-reader.js';\nimport { SchemaManager } from '../adapters/storage/schema-manager.js';\n\nexport class StatusCommand {\n private readonly projectRoot: string;\n private readonly ctxoRoot: string;\n\n constructor(projectRoot: string) {\n this.projectRoot = projectRoot;\n this.ctxoRoot = join(projectRoot, '.ctxo');\n }\n\n run(): void {\n const indexDir = join(this.ctxoRoot, 'index');\n\n if (!existsSync(indexDir)) {\n console.error('[ctxo] No index found. Run \"ctxo index\" first.');\n return;\n }\n\n const schemaManager = new SchemaManager(this.ctxoRoot);\n const version = schemaManager.readStoredVersion() ?? 'unknown';\n\n const reader = new JsonIndexReader(this.ctxoRoot);\n const indices = reader.readAll();\n\n const totalSymbols = indices.reduce((sum, idx) => sum + idx.symbols.length, 0);\n const totalEdges = indices.reduce((sum, idx) => sum + idx.edges.length, 0);\n\n console.error(`[ctxo] Index Status`);\n console.error(` Schema version: ${version}`);\n console.error(` Indexed files: ${indices.length}`);\n console.error(` Total symbols: ${totalSymbols}`);\n console.error(` Total edges: ${totalEdges}`);\n\n const cacheExists = existsSync(join(this.ctxoRoot, '.cache', 'symbols.db'));\n console.error(` SQLite cache: ${cacheExists ? 'present' : 'missing (run ctxo sync)'}`);\n\n // Per-file listing with timestamps\n if (indices.length > 0) {\n console.error('');\n console.error(' Files:');\n\n // Get source files to detect orphans\n const sourceFiles = this.getSourceFiles();\n\n for (const idx of indices.sort((a, b) => a.file.localeCompare(b.file))) {\n const ts = new Date(idx.lastModified * 1000).toISOString();\n const isOrphaned = sourceFiles.size > 0 && !sourceFiles.has(idx.file);\n const badge = isOrphaned ? ' [orphaned]' : '';\n console.error(` ${idx.file} ${ts} (${idx.symbols.length} symbols, ${idx.edges.length} edges)${badge}`);\n }\n }\n }\n\n private getSourceFiles(): Set<string> {\n try {\n const output = execFileSync('git', ['ls-files', '--cached', '--others', '--exclude-standard'], {\n cwd: this.projectRoot,\n encoding: 'utf-8',\n });\n return new Set(output.split('\\n').map((l) => l.trim()).filter((l) => l.length > 0));\n } catch {\n return new Set();\n }\n }\n}\n","import { mkdtempSync, rmSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { tmpdir } from 'node:os';\nimport { IndexCommand } from './index-command.js';\nimport { JsonIndexReader } from '../adapters/storage/json-index-reader.js';\n\nexport class VerifyCommand {\n private readonly projectRoot: string;\n\n constructor(projectRoot: string) {\n this.projectRoot = projectRoot;\n }\n\n async run(): Promise<void> {\n console.error('[ctxo] Verifying index freshness...');\n\n // Build index into a temp directory to avoid overwriting committed index\n const tempDir = mkdtempSync(join(tmpdir(), 'ctxo-verify-'));\n\n try {\n const tempCtxo = join(tempDir, '.ctxo');\n\n // Run index into temp .ctxo (does not touch committed index)\n const indexCmd = new IndexCommand(this.projectRoot, tempCtxo);\n await indexCmd.run({ skipSideEffects: true });\n\n // Compare temp index with committed index\n const committedReader = new JsonIndexReader(join(this.projectRoot, '.ctxo'));\n const freshReader = new JsonIndexReader(tempCtxo);\n\n const committedIndices = committedReader.readAll();\n const freshIndices = freshReader.readAll();\n\n // Compare full index: symbols + edges + intent + antiPatterns\n const serialize = (i: { symbols: unknown; edges: unknown; intent: unknown; antiPatterns: unknown }) =>\n JSON.stringify({ symbols: i.symbols, edges: i.edges, intent: i.intent, antiPatterns: i.antiPatterns });\n\n const committedMap = new Map(committedIndices.map((i) => [i.file, serialize(i)]));\n const freshMap = new Map(freshIndices.map((i) => [i.file, serialize(i)]));\n\n let stale = false;\n\n // Check for files that changed or were added\n for (const [file, freshData] of freshMap) {\n const committed = committedMap.get(file);\n if (committed !== freshData) {\n console.error(`[ctxo] STALE: ${file}`);\n stale = true;\n }\n }\n\n // Check for files that were removed\n for (const file of committedMap.keys()) {\n if (!freshMap.has(file)) {\n console.error(`[ctxo] REMOVED: ${file}`);\n stale = true;\n }\n }\n\n if (stale) {\n console.error('[ctxo] Index is STALE — run \"ctxo index\" and commit .ctxo/index/');\n process.exit(1);\n }\n\n console.error('[ctxo] Index is up to date');\n } finally {\n rmSync(tempDir, { recursive: true, force: true });\n }\n }\n}\n","import { join } from 'node:path';\nimport { existsSync, readFileSync, writeFileSync, mkdirSync, chmodSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { PLATFORMS, detectPlatforms, installRules, ensureGitignore, ensureConfig, getMcpConfigTargets, ensureMcpConfig } from './ai-rules.js';\nimport {\n detectLanguages,\n decideNeededLanguages,\n officialPluginFor,\n type KnownLanguage,\n} from '../core/detection/detect-languages.js';\nimport { InstallCommand } from './install-command.js';\n\nconst requireCjs = createRequire(import.meta.url);\n\nfunction resolveInstalledPlugins(needed: readonly KnownLanguage[]): {\n installed: KnownLanguage[];\n missing: KnownLanguage[];\n} {\n const installed: KnownLanguage[] = [];\n const missing: KnownLanguage[] = [];\n for (const lang of needed) {\n try {\n requireCjs.resolve(`${officialPluginFor(lang)}/package.json`);\n installed.push(lang);\n } catch {\n missing.push(lang);\n }\n }\n return { installed, missing };\n}\n\n/* ------------------------------------------------------------------ */\n/* Git hook content */\n/* ------------------------------------------------------------------ */\n\nconst CTXO_START = '# ctxo-start';\nconst CTXO_END = '# ctxo-end';\n\nconst POST_COMMIT_CONTENT = `\n${CTXO_START}\n# Incremental re-index on commit (only changed files)\nif command -v ctxo >/dev/null 2>&1; then\n for file in $(git diff --name-only HEAD~1 HEAD 2>/dev/null); do\n ctxo index --file \"$file\" 2>/dev/null || true\n done\nfi\n${CTXO_END}\n`.trim();\n\nconst POST_MERGE_CONTENT = `\n${CTXO_START}\n# Rebuild SQLite cache after merge (index updated via git pull)\nif command -v ctxo >/dev/null 2>&1; then\n ctxo sync 2>/dev/null || true\nfi\n${CTXO_END}\n`.trim();\n\n/* ------------------------------------------------------------------ */\n/* Options */\n/* ------------------------------------------------------------------ */\n\nexport interface InitOptions {\n tools?: string[];\n yes?: boolean;\n rulesOnly?: boolean;\n dryRun?: boolean;\n /** Skip language detection prompt + any install invocation. */\n noInstall?: boolean;\n}\n\n/* ------------------------------------------------------------------ */\n/* Terminal UI helpers (zero dependency — picocolors only) */\n/* ------------------------------------------------------------------ */\n\nimport type picocolorsType from 'picocolors';\ntype PC = typeof picocolorsType;\n\nconst STRIP_ANSI = /\\u001b\\[[0-9;]*m/g;\nconst strip = (s: string) => s.replace(STRIP_ANSI, '');\n\nfunction box(lines: string[], opts: { title?: string; border?: (s: string) => string; width?: number }, pc: PC): string {\n const border = opts.border ?? pc.dim;\n const w = opts.width ?? Math.max(...lines.map(l => strip(l).length), strip(opts.title ?? '').length + 4, 48);\n const pad = (s: string) => s + ' '.repeat(Math.max(0, w - strip(s).length));\n\n const hr = '\\u2500'.repeat(w + 2);\n let top: string;\n if (opts.title) {\n const tLen = strip(opts.title).length;\n top = border('\\u256d\\u2500 ') + opts.title + border(` ${ '\\u2500'.repeat(Math.max(0, w - tLen - 2))}\\u256e`);\n } else {\n top = border(`\\u256d${hr}\\u256e`);\n }\n const bot = border(`\\u2570${hr}\\u256f`);\n const body = lines.map(l => `${border('\\u2502')} ${pad(l)} ${border('\\u2502')}`).join('\\n');\n return `${top}\\n${body}\\n${bot}`;\n}\n\nfunction stepHeader(step: number, total: number, title: string, desc: string, pc: PC): string {\n const stepLabel = pc.bold(pc.cyan(`${step}/${total}`));\n const titleStr = pc.bold(title);\n return box(\n [`${pc.dim(desc)}`],\n { title: `${stepLabel} ${titleStr}`, border: pc.cyan },\n pc,\n );\n}\n\n/* ------------------------------------------------------------------ */\n/* ASCII banner with faux gradient */\n/* ------------------------------------------------------------------ */\n\nfunction renderBanner(_version: string | undefined, pc: PC): string {\n const art = [\n ' \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2557\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2557\\u2588\\u2588\\u2557 \\u2588\\u2588\\u2557 \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2557 ',\n ' \\u2588\\u2588\\u2554\\u2550\\u2550\\u2550\\u255d\\u255a\\u2550\\u2550\\u2588\\u2588\\u2554\\u2550\\u2550\\u255d\\u255a\\u2588\\u2588\\u2557\\u2588\\u2588\\u2554\\u255d\\u2588\\u2588\\u2554\\u2550\\u2550\\u2550\\u2588\\u2588\\u2557',\n ' \\u2588\\u2588\\u2551 \\u2588\\u2588\\u2551 \\u255a\\u2588\\u2588\\u2588\\u2554\\u255d \\u2588\\u2588\\u2551 \\u2588\\u2588\\u2551',\n ' \\u2588\\u2588\\u2551 \\u2588\\u2588\\u2551 \\u2588\\u2588\\u2554\\u2588\\u2588\\u2557 \\u2588\\u2588\\u2551 \\u2588\\u2588\\u2551',\n ' \\u255a\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2557 \\u2588\\u2588\\u2551 \\u2588\\u2588\\u2554\\u255d\\u255a\\u2588\\u2588\\u2557\\u255a\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2554\\u255d',\n ' \\u255a\\u2550\\u2550\\u2550\\u2550\\u2550\\u255d \\u255a\\u2550\\u255d \\u255a\\u2550\\u255d \\u255a\\u2550\\u255d \\u255a\\u2550\\u2550\\u2550\\u2550\\u2550\\u255d ',\n ];\n\n // Faux vertical gradient: cyan → blueBright → magentaBright\n const colors = [pc.cyan, pc.cyan, pc.blueBright, pc.blueBright, pc.magentaBright, pc.magentaBright] as const;\n const coloredArt = art.map((line, i) => colors[i]!(line));\n\n const tagline1 = pc.bold(pc.white(' Code intelligence for AI agents.'));\n const tagline2 = pc.dim(' One call instead of hundreds.');\n\n const inner = [\n '',\n ...coloredArt,\n '',\n tagline1,\n tagline2,\n '',\n ];\n\n return box(inner, { border: pc.dim }, pc);\n}\n\n/* ------------------------------------------------------------------ */\n/* InitCommand */\n/* ------------------------------------------------------------------ */\n\nexport class InitCommand {\n private readonly projectRoot: string;\n\n constructor(projectRoot: string) {\n // Router now resolves this; kept as a defensive copy for direct construction.\n this.projectRoot = projectRoot;\n }\n\n installHooks(): void {\n const hooksDir = join(this.projectRoot, '.git', 'hooks');\n mkdirSync(hooksDir, { recursive: true });\n this.installHook(hooksDir, 'post-commit', POST_COMMIT_CONTENT);\n this.installHook(hooksDir, 'post-merge', POST_MERGE_CONTENT);\n }\n\n async run(options: InitOptions = {}): Promise<void> {\n if (!existsSync(join(this.projectRoot, '.git'))) {\n console.error('[ctxo] Not a git repository. Run \"git init\" first.');\n process.exit(1);\n }\n\n if (options.dryRun) return this.dryRun(options);\n if (options.yes || options.tools) return await this.runNonInteractive(options);\n return this.runInteractive(options);\n }\n\n /* ---------------------------------------------------------------- */\n /* Interactive flow */\n /* ---------------------------------------------------------------- */\n\n private async runInteractive(options: InitOptions): Promise<void> {\n const clack = await import('@clack/prompts');\n const pc = (await import('picocolors')).default;\n\n const version = await this.getVersion();\n const totalSteps = options.rulesOnly ? 1 : 3;\n\n // ── Banner ──\n console.error('');\n console.error(renderBanner(version, pc));\n console.error('');\n\n // ── Step 1: Index directory ──\n let stepNum = 0;\n if (!options.rulesOnly) {\n stepNum++;\n console.error(stepHeader(stepNum, totalSteps, 'Index Directory', 'Where ctxo stores the symbol graph and metadata.', pc));\n console.error('');\n\n const indexDir = await clack.text({\n message: pc.cyan('Directory path'),\n placeholder: '.ctxo/index',\n initialValue: '.ctxo/index',\n validate: (val) => {\n if (!val?.trim()) return 'Directory path is required';\n return undefined;\n },\n });\n\n if (clack.isCancel(indexDir)) { clack.cancel('Setup cancelled.'); process.exit(0); }\n\n const fullPath = join(this.projectRoot, indexDir as string);\n if (!existsSync(fullPath)) mkdirSync(fullPath, { recursive: true });\n console.error('');\n }\n\n // ── Step 2: AI tool selection ──\n stepNum++;\n const detected = detectPlatforms(this.projectRoot);\n const detectedCount = detected.size;\n const detectedHint = detectedCount > 0 ? pc.green(` ${detectedCount} detected`) : '';\n\n console.error(stepHeader(stepNum, totalSteps, `AI Tools${detectedHint}`, 'Select your tools. Generates MCP usage rules for each.', pc));\n console.error('');\n\n const toolChoices = PLATFORMS.map(p => {\n const isDetected = detected.has(p.id);\n const star = p.starred ? pc.yellow(' \\u2605') : '';\n const detect = isDetected ? pc.green(' (detected)') : '';\n return {\n value: p.id,\n label: `${p.name}${star}${detect}`,\n hint: isDetected ? undefined : pc.dim(p.file),\n };\n });\n\n const selectedTools = await clack.multiselect({\n message: pc.cyan('Select tools'),\n options: toolChoices,\n initialValues: [...detected],\n required: false,\n });\n\n if (clack.isCancel(selectedTools)) { clack.cancel('Setup cancelled.'); process.exit(0); }\n console.error('');\n\n // ── Step 2.5: Language plugins (skipped in --rules / --no-install) ──\n let pluginsToInstall: KnownLanguage[] = [];\n if (!options.rulesOnly && !options.noInstall) {\n const detection = detectLanguages(this.projectRoot);\n const needed = decideNeededLanguages(detection);\n const { missing } = resolveInstalledPlugins(needed);\n if (missing.length > 0) {\n console.error(stepHeader(\n stepNum + 1,\n totalSteps + 1,\n `Language Plugins ${pc.yellow('missing')}`,\n `Detected: ${missing.join(', ')} — ctxo needs a plugin per language to index it.`,\n pc,\n ));\n console.error('');\n const confirm = await clack.confirm({\n message: pc.cyan(`Install ${missing.map(officialPluginFor).join(' ')}?`),\n initialValue: true,\n });\n if (clack.isCancel(confirm)) { clack.cancel('Setup cancelled.'); process.exit(0); }\n if (confirm) {\n pluginsToInstall = missing;\n stepNum++;\n }\n console.error('');\n }\n }\n\n // ── Step 3: Git hooks ──\n let installGitHooks = false;\n if (!options.rulesOnly) {\n stepNum++;\n console.error(stepHeader(stepNum, totalSteps, `Git Hooks ${pc.yellow('recommended')}`, 'Auto-updates index on every commit and pull.', pc));\n console.error('');\n\n const hooks = await clack.confirm({\n message: pc.cyan('Install hooks?'),\n initialValue: true,\n });\n\n if (clack.isCancel(hooks)) { clack.cancel('Setup cancelled.'); process.exit(0); }\n installGitHooks = hooks as boolean;\n console.error('');\n }\n\n // ── Execute with spinner ──\n const s = clack.spinner();\n s.start(pc.dim('Configuring...'));\n\n const results: string[] = [];\n\n // Automatic scaffolding (always runs, no prompt needed)\n const gitignoreResult = ensureGitignore(this.projectRoot);\n const configResult = ensureConfig(this.projectRoot);\n\n if (!options.rulesOnly) {\n results.push(`${pc.green('\\u2713')} ${pc.bold('.ctxo/index/')} ${pc.dim('index directory')}`);\n }\n\n if (configResult.action !== 'skipped') {\n results.push(`${pc.green('\\u2713')} ${pc.bold(configResult.file)} ${pc.dim(configResult.action)}`);\n }\n\n if (gitignoreResult.action !== 'skipped') {\n results.push(`${pc.green('\\u2713')} ${pc.bold(gitignoreResult.file)} ${pc.dim(gitignoreResult.action)}`);\n }\n\n for (const toolId of (selectedTools as string[])) {\n const result = installRules(this.projectRoot, toolId);\n results.push(`${pc.green('\\u2713')} ${pc.bold(result.file)} ${pc.dim(result.action)}`);\n }\n\n // MCP server registration (automatic based on selected tools)\n const mcpTargets = getMcpConfigTargets(selectedTools as string[]);\n for (const target of mcpTargets) {\n const result = ensureMcpConfig(this.projectRoot, target);\n if (result.action !== 'skipped') {\n results.push(`${pc.green('\\u2713')} ${pc.bold(result.file)} ${pc.dim(result.action + ' \\u2014 MCP server registered')}`);\n }\n }\n\n if (installGitHooks) {\n this.installHooks();\n results.push(`${pc.green('\\u2713')} ${pc.bold('post-commit, post-merge')} ${pc.dim('hooks installed')}`);\n }\n\n if (pluginsToInstall.length > 0) {\n s.stop(pc.dim('Installing language plugins...'));\n const installer = new InstallCommand(this.projectRoot);\n await installer.run({ languages: pluginsToInstall, yes: true });\n results.push(`${pc.green('\\u2713')} ${pc.bold(pluginsToInstall.map(officialPluginFor).join(', '))} ${pc.dim('language plugins installed')}`);\n s.start(pc.dim('Finalizing...'));\n }\n\n s.stop(pc.green('Done!'));\n\n // ── Summary box ──\n if (results.length > 0) {\n console.error('');\n console.error(box(results, { title: pc.green('\\u2713 Created'), border: pc.green }, pc));\n }\n\n // ── Next steps box ──\n const hasWork = (selectedTools as string[]).length > 0 || installGitHooks;\n if (hasWork) {\n const steps = [\n `${pc.cyan('\\u25b6')} npx ctxo index ${pc.dim('\\u2500 build codebase index')}`,\n `${pc.cyan('\\u25b6')} npx ctxo doctor ${pc.dim('\\u2500 verify everything works')}`,\n ];\n console.error('');\n console.error(box(steps, { title: pc.cyan('\\u2192 Next steps'), border: pc.cyan }, pc));\n }\n\n console.error('');\n console.error(` ${pc.dim('Happy coding!')} ${pc.magentaBright('\\u2764')}`);\n console.error('');\n }\n\n /* ---------------------------------------------------------------- */\n /* Non-interactive flow */\n /* ---------------------------------------------------------------- */\n\n private async runNonInteractive(options: InitOptions): Promise<void> {\n const toolIds = options.tools ?? [];\n\n for (const id of toolIds) {\n if (!PLATFORMS.find(p => p.id === id)) {\n console.error(`[ctxo] Unknown tool: \"${id}\". Valid: ${PLATFORMS.map(p => p.id).join(', ')}`);\n process.exit(1);\n }\n }\n\n // Automatic scaffolding\n const gitignoreResult = ensureGitignore(this.projectRoot);\n const configResult = ensureConfig(this.projectRoot);\n\n if (!options.rulesOnly) {\n const indexDir = join(this.projectRoot, '.ctxo', 'index');\n if (!existsSync(indexDir)) mkdirSync(indexDir, { recursive: true });\n console.error('[ctxo] \\u2713 .ctxo/index/ ready');\n }\n\n if (configResult.action !== 'skipped') {\n console.error(`[ctxo] \\u2713 ${configResult.file} \\u2014 ${configResult.action}`);\n }\n if (gitignoreResult.action !== 'skipped') {\n console.error(`[ctxo] \\u2713 ${gitignoreResult.file} \\u2014 ${gitignoreResult.action}`);\n }\n\n for (const toolId of toolIds) {\n const result = installRules(this.projectRoot, toolId);\n console.error(`[ctxo] \\u2713 ${result.file} \\u2014 ${result.action}`);\n }\n\n // MCP server registration\n const mcpTargets = getMcpConfigTargets(toolIds);\n for (const target of mcpTargets) {\n const result = ensureMcpConfig(this.projectRoot, target);\n if (result.action !== 'skipped') {\n console.error(`[ctxo] \\u2713 ${result.file} \\u2014 ${result.action} (MCP server registered)`);\n }\n }\n\n if (!options.rulesOnly) {\n this.installHooks();\n console.error('[ctxo] \\u2713 Git hooks installed');\n }\n\n // Language detection + plugin install (skipped under --no-install or --rules)\n if (!options.rulesOnly && !options.noInstall) {\n const detection = detectLanguages(this.projectRoot);\n const needed = decideNeededLanguages(detection);\n const { missing } = resolveInstalledPlugins(needed);\n if (missing.length > 0) {\n if (options.yes) {\n console.error(`[ctxo] Installing missing plugins: ${missing.join(', ')}`);\n await new InstallCommand(this.projectRoot).run({ languages: missing, yes: true });\n } else {\n console.error(\n `[ctxo] Detected missing plugins: ${missing.join(', ')}. Run \"ctxo install ${missing.join(' ')}\" to install.`,\n );\n }\n }\n }\n }\n\n /* ---------------------------------------------------------------- */\n /* Dry run */\n /* ---------------------------------------------------------------- */\n\n private dryRun(options: InitOptions): void {\n const toolIds = options.tools ?? PLATFORMS.map(p => p.id);\n\n console.error('[ctxo] Dry run \\u2014 the following files would be created/updated:\\n');\n\n if (!options.rulesOnly) {\n console.error(' .ctxo/index/ (index directory)');\n }\n\n for (const id of toolIds) {\n const platform = PLATFORMS.find(p => p.id === id);\n if (platform) {\n const exists = existsSync(join(this.projectRoot, platform.file));\n const action = platform.mode === 'append' && exists ? 'append section' : 'create';\n console.error(` ${platform.file.padEnd(42)} (${action})`);\n }\n }\n\n if (!options.rulesOnly) {\n console.error(' .git/hooks/post-commit (git hook)');\n console.error(' .git/hooks/post-merge (git hook)');\n }\n }\n\n /* ---------------------------------------------------------------- */\n /* Helpers */\n /* ---------------------------------------------------------------- */\n\n private async getVersion(): Promise<string | undefined> {\n try {\n const pkgPath = join(this.projectRoot, 'node_modules', '@ctxo', 'cli', 'package.json');\n if (existsSync(pkgPath)) {\n return JSON.parse(readFileSync(pkgPath, 'utf-8')).version;\n }\n const { createRequire } = await import('node:module');\n const require = createRequire(import.meta.url);\n return require('../../package.json').version;\n } catch {\n return undefined;\n }\n }\n\n private installHook(hooksDir: string, hookName: string, hookContent: string): void {\n const hookPath = join(hooksDir, hookName);\n\n let existing = '';\n if (existsSync(hookPath)) {\n existing = readFileSync(hookPath, 'utf-8');\n if (existing.includes(CTXO_START)) return;\n } else {\n existing = '#!/bin/sh\\n';\n }\n\n const updated = existing.endsWith('\\n')\n ? existing + '\\n' + hookContent + '\\n'\n : existing + '\\n\\n' + hookContent + '\\n';\n\n writeFileSync(hookPath, updated, 'utf-8');\n chmodSync(hookPath, 0o755);\n }\n}\n","/**\n * Platform configurations and MCP tool usage rule generator.\n *\n * Each platform entry defines where the AI coding assistant reads its\n * project-level instructions and how ctxo should write them.\n */\n\nimport { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';\nimport { join, dirname } from 'node:path';\n\nexport interface Platform {\n id: string;\n name: string;\n file: string;\n /** 'append' inserts a marked section into an existing file; 'create' writes from scratch */\n mode: 'append' | 'create';\n /** Paths to check for auto-detection (relative to project root) */\n detectPaths: string[];\n /** Show a star next to this platform name */\n starred: boolean;\n}\n\nexport const PLATFORMS: Platform[] = [\n { id: 'claude-code', name: 'Claude Code', file: 'CLAUDE.md', mode: 'append', detectPaths: ['CLAUDE.md', '.claude'], starred: true },\n { id: 'cursor', name: 'Cursor', file: '.cursor/rules/ctxo.mdc', mode: 'create', detectPaths: ['.cursor', '.cursorrules'], starred: false },\n { id: 'github-copilot', name: 'GitHub Copilot', file: '.github/copilot-instructions.md', mode: 'create', detectPaths: ['.github', '.vscode'], starred: false },\n { id: 'windsurf', name: 'Windsurf', file: '.windsurfrules', mode: 'create', detectPaths: ['.windsurfrules', '.windsurf'], starred: false },\n { id: 'antigravity', name: 'Google Antigravity', file: 'AGENTS.md', mode: 'create', detectPaths: ['AGENTS.md', 'GEMINI.md', '.gemini'], starred: false },\n { id: 'augment', name: 'Augment Code', file: 'augment-guidelines.md', mode: 'create', detectPaths: ['augment-guidelines.md', '.augment'], starred: false },\n { id: 'amazonq', name: 'Amazon Q', file: '.amazonq/rules/ctxo.md', mode: 'create', detectPaths: ['.amazonq'], starred: false },\n];\n\nexport function detectPlatforms(projectRoot: string): Set<string> {\n const detected = new Set<string>();\n for (const p of PLATFORMS) {\n if (p.detectPaths.some(d => existsSync(join(projectRoot, d)))) {\n detected.add(p.id);\n }\n }\n return detected;\n}\n\nconst SECTION_START = '<!-- ctxo-rules-start -->';\nconst SECTION_END = '<!-- ctxo-rules-end -->';\n\n/* ------------------------------------------------------------------ */\n/* Rule content */\n/* ------------------------------------------------------------------ */\n\nfunction ruleBody(): string {\n return `## ctxo MCP Tool Usage (MANDATORY)\n\n**ALWAYS use ctxo MCP tools before reading source files or making code changes.** The ctxo index contains dependency graphs, git intent, anti-patterns, and change health that cannot be derived from reading files alone. Skipping these tools leads to blind edits and broken dependencies.\n\n### Before ANY Code Modification\n1. Call \\`get_blast_radius\\` for the symbol you are about to change — understand what breaks\n2. Call \\`get_why_context\\` for the same symbol — check for revert history or anti-patterns\n3. Only then read and edit source files\n\n### Before Starting a Task\n| Task Type | REQUIRED First Call |\n|---|---|\n| Fixing a bug | \\`get_context_for_task(taskType: \"fix\")\\` |\n| Adding/extending a feature | \\`get_context_for_task(taskType: \"extend\")\\` |\n| Refactoring | \\`get_context_for_task(taskType: \"refactor\")\\` |\n| Understanding code | \\`get_context_for_task(taskType: \"understand\")\\` |\n\n### Before Reviewing a PR or Diff\n- Call \\`get_pr_impact\\` — single call gives full risk assessment with co-change analysis\n\n### When Exploring or Searching Code\n- Use \\`search_symbols\\` for name/regex lookup — DO NOT grep source files for symbol discovery\n- Use \\`get_ranked_context\\` for natural language queries — DO NOT manually browse directories\n\n### Orientation in Unfamiliar Areas\n- Call \\`get_architectural_overlay\\` to understand layer boundaries\n- Call \\`get_symbol_importance\\` to identify critical symbols\n\n### NEVER Do These\n- NEVER edit a function without first calling \\`get_blast_radius\\` on it\n- NEVER skip \\`get_why_context\\` — reverted code and anti-patterns are invisible without it\n- NEVER grep source files to find symbols when \\`search_symbols\\` exists\n- NEVER manually trace imports when \\`find_importers\\` gives the full reverse dependency graph`;\n}\n\n/* ------------------------------------------------------------------ */\n/* Per-platform rendering */\n/* ------------------------------------------------------------------ */\n\nfunction cursorFrontmatter(): string {\n return `---\ndescription: ctxo MCP tool usage rules — always applied\nglobs:\nalwaysApply: true\n---\n\n`;\n}\n\nexport function generateRules(platformId: string): string {\n const body = ruleBody();\n\n if (platformId === 'cursor') {\n return cursorFrontmatter() + body + '\\n';\n }\n\n return body + '\\n';\n}\n\n/* ------------------------------------------------------------------ */\n/* File operations */\n/* ------------------------------------------------------------------ */\n\nexport interface InstallResult {\n file: string;\n action: 'created' | 'updated' | 'skipped';\n}\n\nexport function installRules(projectRoot: string, platformId: string): InstallResult {\n const platform = PLATFORMS.find(p => p.id === platformId);\n if (!platform) throw new Error(`Unknown platform: ${platformId}`);\n\n const filePath = join(projectRoot, platform.file);\n const content = generateRules(platformId);\n\n // Ensure parent directory exists\n const dir = dirname(filePath);\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true });\n\n if (platform.mode === 'create') {\n // For 'create' mode: write or replace entire file\n writeFileSync(filePath, content, 'utf-8');\n return { file: platform.file, action: existsSync(filePath) ? 'updated' : 'created' };\n }\n\n // 'append' mode: insert marked section into existing file\n if (!existsSync(filePath)) {\n writeFileSync(filePath, content, 'utf-8');\n return { file: platform.file, action: 'created' };\n }\n\n const existing = readFileSync(filePath, 'utf-8');\n\n // Already has ctxo rules section — replace it\n if (existing.includes(SECTION_START)) {\n const re = new RegExp(`${escapeRegExp(SECTION_START)}[\\\\s\\\\S]*?${escapeRegExp(SECTION_END)}`, 'm');\n const updated = existing.replace(re, `${SECTION_START}\\n${content}${SECTION_END}`);\n writeFileSync(filePath, updated, 'utf-8');\n return { file: platform.file, action: 'updated' };\n }\n\n // Append new section\n const separator = existing.endsWith('\\n') ? '\\n' : '\\n\\n';\n const updated = existing + separator + `${SECTION_START}\\n${content}${SECTION_END}\\n`;\n writeFileSync(filePath, updated, 'utf-8');\n return { file: platform.file, action: 'updated' };\n}\n\nfunction escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/* ------------------------------------------------------------------ */\n/* Project scaffolding (automatic, not prompted) */\n/* ------------------------------------------------------------------ */\n\nconst GITIGNORE_ENTRY = '.ctxo/.cache/';\n\nexport function ensureGitignore(projectRoot: string): InstallResult {\n const filePath = join(projectRoot, '.gitignore');\n\n if (!existsSync(filePath)) {\n writeFileSync(filePath, `# Ctxo local cache (auto-rebuilt, never committed)\\n${GITIGNORE_ENTRY}\\n`, 'utf-8');\n return { file: '.gitignore', action: 'created' };\n }\n\n const existing = readFileSync(filePath, 'utf-8');\n if (existing.includes(GITIGNORE_ENTRY)) {\n return { file: '.gitignore', action: 'skipped' };\n }\n\n const separator = existing.endsWith('\\n') ? '\\n' : '\\n\\n';\n const updated = existing + `${separator}# Ctxo local cache (auto-rebuilt, never committed)\\n${GITIGNORE_ENTRY}\\n`;\n writeFileSync(filePath, updated, 'utf-8');\n return { file: '.gitignore', action: 'updated' };\n}\n\nconst DEFAULT_CONFIG = `# ctxo project configuration\n# Docs: https://github.com/alperhankendi/Ctxo\nversion: \"1.0\"\n\n# Exclude files and workspaces from indexing.\n# Uncomment and edit to activate — both fields accept picomatch globs\n# (forward-slash paths relative to repo root).\nindex:\n # Per-file filter applied after \\`git ls-files\\`.\n ignore: []\n # - \"packages/**/fixtures/**\"\n # - \"tools/legacy-*/**\"\n\n # Workspace filter — matching workspaces are skipped entirely\n # (no plugin load, no file enumeration).\n ignoreProjects: []\n # - \"packages/experimental-*\"\n # - \"examples/*\"\n`;\n\nexport function ensureConfig(projectRoot: string): InstallResult {\n const filePath = join(projectRoot, '.ctxo', 'config.yaml');\n const dir = dirname(filePath);\n\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true });\n\n if (existsSync(filePath)) {\n return { file: '.ctxo/config.yaml', action: 'skipped' };\n }\n\n writeFileSync(filePath, DEFAULT_CONFIG, 'utf-8');\n return { file: '.ctxo/config.yaml', action: 'created' };\n}\n\n/* ------------------------------------------------------------------ */\n/* MCP server registration */\n/* ------------------------------------------------------------------ */\n\nconst CTXO_MCP_ENTRY = { command: 'npx', args: ['-y', '@ctxo/cli'] };\n\ninterface McpConfigTarget {\n file: string;\n /** JSON key that holds server map */\n serverKey: 'mcpServers' | 'servers';\n /** Extra fields per server entry */\n extraFields?: Record<string, string>;\n}\n\n/**\n * Returns which MCP config files to create/update based on selected platforms.\n * Multiple platforms may map to the same config file (deduplicated).\n */\nexport function getMcpConfigTargets(selectedPlatformIds: string[]): McpConfigTarget[] {\n const targets = new Map<string, McpConfigTarget>();\n\n for (const id of selectedPlatformIds) {\n switch (id) {\n case 'claude-code':\n case 'cursor':\n case 'windsurf':\n case 'augment':\n case 'antigravity':\n // .mcp.json is the universal project-level MCP config\n targets.set('.mcp.json', { file: '.mcp.json', serverKey: 'mcpServers' });\n break;\n case 'github-copilot':\n targets.set('.vscode/mcp.json', { file: '.vscode/mcp.json', serverKey: 'servers', extraFields: { type: 'stdio' } });\n break;\n case 'amazonq':\n targets.set('.amazonq/mcp.json', { file: '.amazonq/mcp.json', serverKey: 'mcpServers' });\n break;\n }\n }\n\n return [...targets.values()];\n}\n\nexport function ensureMcpConfig(projectRoot: string, target: McpConfigTarget): InstallResult {\n const filePath = join(projectRoot, target.file);\n const dir = dirname(filePath);\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true });\n\n const entry = target.extraFields\n ? { ...target.extraFields, ...CTXO_MCP_ENTRY }\n : { ...CTXO_MCP_ENTRY };\n\n if (!existsSync(filePath)) {\n const config = { [target.serverKey]: { ctxo: entry } };\n writeFileSync(filePath, JSON.stringify(config, null, 2) + '\\n', 'utf-8');\n return { file: target.file, action: 'created' };\n }\n\n // Merge into existing config\n let existing: Record<string, unknown>;\n try {\n existing = JSON.parse(readFileSync(filePath, 'utf-8'));\n } catch {\n // Corrupt JSON — overwrite\n const config = { [target.serverKey]: { ctxo: entry } };\n writeFileSync(filePath, JSON.stringify(config, null, 2) + '\\n', 'utf-8');\n return { file: target.file, action: 'updated' };\n }\n\n const servers = (existing[target.serverKey] ?? {}) as Record<string, unknown>;\n if (servers['ctxo']) {\n return { file: target.file, action: 'skipped' };\n }\n\n servers['ctxo'] = entry;\n existing[target.serverKey] = servers;\n writeFileSync(filePath, JSON.stringify(existing, null, 2) + '\\n', 'utf-8');\n return { file: target.file, action: 'updated' };\n}\n","import { join, extname, relative } from 'node:path';\nimport { readFileSync } from 'node:fs';\nimport { LanguageAdapterRegistry } from '../adapters/language/language-adapter-registry.js';\nimport { loadPlugins } from './plugin-loader.js';\nimport { JsonIndexWriter } from '../adapters/storage/json-index-writer.js';\nimport { SqliteStorageAdapter } from '../adapters/storage/sqlite-storage-adapter.js';\nimport { ChokidarWatcherAdapter } from '../adapters/watcher/chokidar-watcher-adapter.js';\nimport { ContentHasher } from '../core/staleness/content-hasher.js';\nimport { SimpleGitAdapter } from '../adapters/git/simple-git-adapter.js';\nimport { RevertDetector } from '../core/why-context/revert-detector.js';\nimport type { FileIndex, CommitIntent, AntiPattern } from '../core/types.js';\n\nconst DEBOUNCE_MS = 300;\n\ninterface RoslynLike {\n isReady(): boolean;\n startKeepAlive(): Promise<boolean>;\n reindexFile(relativePath: string): Promise<{\n symbols: Array<{ symbolId: string; name: string; kind: string; startLine: number; endLine: number }>;\n edges: Array<{ from: string; to: string; kind: string }>;\n complexity: Array<{ symbolId: string; cyclomatic: number }>;\n } | null>;\n dispose(): Promise<void>;\n}\n\ninterface CSharpCompositeLike {\n getRoslynDelegate(): RoslynLike | null;\n}\n\nexport class WatchCommand {\n private readonly projectRoot: string;\n private readonly ctxoRoot: string;\n\n constructor(projectRoot: string) {\n this.projectRoot = projectRoot;\n this.ctxoRoot = join(projectRoot, '.ctxo');\n }\n\n async run(): Promise<void> {\n console.error('[ctxo] Starting file watcher...');\n\n const registry = new LanguageAdapterRegistry();\n\n // Plugins via discovery\n let roslynAdapter: RoslynLike | null = null;\n for (const { plugin, adapter } of await loadPlugins(this.projectRoot)) {\n if (typeof adapter.initialize === 'function') {\n try {\n await adapter.initialize(this.projectRoot);\n } catch (err) {\n console.error(`[ctxo] Plugin ${plugin.id} initialize failed: ${(err as Error).message}`);\n continue;\n }\n }\n\n registry.register(plugin.extensions, adapter);\n\n // If the plugin exposes a Roslyn delegate, attempt keep-alive for fast re-index\n const csCandidate = adapter as unknown as Partial<CSharpCompositeLike>;\n if (typeof csCandidate.getRoslynDelegate === 'function') {\n const roslyn = csCandidate.getRoslynDelegate();\n if (roslyn?.isReady()) {\n const started = await roslyn.startKeepAlive();\n if (started) {\n roslynAdapter = roslyn;\n console.error('[ctxo] C# watch: Roslyn keep-alive active (full tier, <100ms per change)');\n }\n }\n }\n\n console.error(`[ctxo] Plugin ${plugin.id}@${plugin.version} (${plugin.tier} tier)`);\n }\n\n const supportedExtensions = registry.getSupportedExtensions();\n const writer = new JsonIndexWriter(this.ctxoRoot);\n const storage = new SqliteStorageAdapter(this.ctxoRoot);\n await storage.init();\n const hasher = new ContentHasher();\n\n const gitAdapter = new SimpleGitAdapter(this.projectRoot);\n const revertDetector = new RevertDetector();\n const watcher = new ChokidarWatcherAdapter(this.projectRoot);\n const pendingFiles = new Map<string, NodeJS.Timeout>();\n\n const reindexFile = async (filePath: string) => {\n const adapter = registry.getAdapter(filePath);\n if (!adapter) return;\n\n const relativePath = relative(this.projectRoot, filePath).replace(/\\\\/g, '/');\n\n try {\n // For .cs files with Roslyn keep-alive: use incremental re-index\n if (roslynAdapter?.isReady() && filePath.endsWith('.cs')) {\n const result = await roslynAdapter.reindexFile(relativePath);\n if (result) {\n const commits = await gitAdapter.getCommitHistory(relativePath);\n const intent: CommitIntent[] = commits.map((c) => ({\n hash: c.hash, message: c.message, date: c.date, kind: 'commit' as const,\n }));\n const antiPatterns: AntiPattern[] = revertDetector.detect(commits);\n const source = readFileSync(filePath, 'utf-8');\n\n const fileIndex: FileIndex = {\n file: relativePath,\n lastModified: Math.floor(Date.now() / 1000),\n contentHash: hasher.hash(source),\n symbols: result.symbols.map(s => ({\n symbolId: s.symbolId, name: s.name,\n kind: s.kind as FileIndex['symbols'][0]['kind'],\n startLine: s.startLine, endLine: s.endLine,\n })),\n edges: result.edges\n .filter(e => !e.to.startsWith('ns:'))\n .map(e => ({\n from: e.from, to: e.to,\n kind: e.kind as FileIndex['edges'][0]['kind'],\n })),\n complexity: result.complexity.map(c => ({\n symbolId: c.symbolId, cyclomatic: c.cyclomatic,\n })),\n intent,\n antiPatterns,\n };\n\n writer.write(fileIndex);\n storage.writeSymbolFile(fileIndex);\n console.error(`[ctxo] Re-indexed (Roslyn): ${relativePath}`);\n return;\n }\n }\n\n // Default path: use adapter from registry (tree-sitter or ts-morph)\n const source = readFileSync(filePath, 'utf-8');\n const lastModified = Math.floor(Date.now() / 1000);\n\n const symbols = await adapter.extractSymbols(relativePath, source);\n const edges = await adapter.extractEdges(relativePath, source);\n const complexity = await adapter.extractComplexity(relativePath, source);\n\n const commits = await gitAdapter.getCommitHistory(relativePath);\n const intent: CommitIntent[] = commits.map((c) => ({\n hash: c.hash, message: c.message, date: c.date, kind: 'commit' as const,\n }));\n const antiPatterns: AntiPattern[] = revertDetector.detect(commits);\n\n const fileIndex: FileIndex = {\n file: relativePath,\n lastModified,\n contentHash: hasher.hash(source),\n symbols,\n edges,\n complexity,\n intent,\n antiPatterns,\n };\n\n writer.write(fileIndex);\n storage.writeSymbolFile(fileIndex);\n console.error(`[ctxo] Re-indexed: ${relativePath}`);\n } catch (err) {\n console.error(`[ctxo] Failed to re-index ${relativePath}: ${(err as Error).message}`);\n }\n };\n\n const debouncedReindex = (filePath: string) => {\n const existing = pendingFiles.get(filePath);\n if (existing) clearTimeout(existing);\n\n pendingFiles.set(\n filePath,\n setTimeout(() => {\n pendingFiles.delete(filePath);\n reindexFile(filePath);\n }, DEBOUNCE_MS),\n );\n };\n\n watcher.start((event, filePath) => {\n if (event === 'unlink') {\n const ext = extname(filePath).toLowerCase();\n if (!supportedExtensions.has(ext)) return;\n\n const relativePath = relative(this.projectRoot, filePath).replace(/\\\\/g, '/');\n writer.delete(relativePath);\n storage.deleteSymbolFile(relativePath);\n console.error(`[ctxo] Removed from index: ${relativePath}`);\n } else {\n debouncedReindex(filePath);\n }\n });\n\n console.error('[ctxo] Watching for file changes... (Ctrl+C to stop)');\n\n const cleanup = () => {\n console.error('\\n[ctxo] Stopping watcher...');\n for (const timeout of pendingFiles.values()) {\n clearTimeout(timeout);\n }\n // Shutdown Roslyn keep-alive\n const roslynShutdown = roslynAdapter ? roslynAdapter.dispose() : Promise.resolve();\n roslynShutdown.then(() => {\n watcher.stop().then(() => {\n storage.close();\n console.error('[ctxo] Watcher stopped');\n process.exit(0);\n });\n });\n };\n\n process.on('SIGINT', cleanup);\n process.on('SIGTERM', cleanup);\n }\n\n}\n","import { watch, type FSWatcher } from 'chokidar';\nimport type { IWatcherPort, FileChangeHandler } from '../../ports/i-watcher-port.js';\n\nconst DEFAULT_IGNORED = [\n '**/node_modules/**',\n '**/.git/**',\n '**/.ctxo/**',\n '**/dist/**',\n '**/coverage/**',\n];\n\nexport class ChokidarWatcherAdapter implements IWatcherPort {\n private readonly projectRoot: string;\n private readonly ignored: string[];\n private watcher: FSWatcher | undefined;\n\n constructor(projectRoot: string, ignored?: string[]) {\n this.projectRoot = projectRoot;\n this.ignored = ignored ?? DEFAULT_IGNORED;\n }\n\n start(handler: FileChangeHandler): void {\n if (this.watcher) {\n throw new Error('Watcher already started. Call stop() before starting again.');\n }\n\n this.watcher = watch(this.projectRoot, {\n ignored: this.ignored,\n persistent: true,\n ignoreInitial: true,\n });\n\n this.watcher.on('add', (path) => handler('add', path));\n this.watcher.on('change', (path) => handler('change', path));\n this.watcher.on('unlink', (path) => handler('unlink', path));\n }\n\n async stop(): Promise<void> {\n if (this.watcher) {\n await this.watcher.close();\n this.watcher = undefined;\n }\n }\n}\n","import { join } from 'node:path';\nimport { existsSync, readFileSync } from 'node:fs';\nimport initSqlJs from 'sql.js';\nimport { SessionRecorderAdapter } from '../adapters/stats/session-recorder-adapter.js';\nimport type { AggregatedStats } from '../ports/i-session-recorder-port.js';\nimport type { StatsReport } from '../core/stats/stats-types.js';\n\nexport class StatsCommand {\n private readonly ctxoRoot: string;\n\n constructor(projectRoot: string) {\n this.ctxoRoot = join(projectRoot, '.ctxo');\n }\n\n async run(options: { days?: number; json?: boolean; clear?: boolean }): Promise<void> {\n // Check if stats are enabled\n if (!this.isStatsEnabled()) {\n console.error('[ctxo] Stats collection is disabled in .ctxo/config.yaml');\n return;\n }\n\n const dbPath = join(this.ctxoRoot, '.cache', 'symbols.db');\n if (!existsSync(dbPath)) {\n if (options.json) {\n process.stdout.write(JSON.stringify(this.emptyReport(options.days)) + '\\n');\n } else {\n console.error('[ctxo] No usage data yet. Start using Ctxo MCP tools to collect stats.');\n }\n return;\n }\n\n // Open DB\n const SQL = await initSqlJs();\n const buffer = readFileSync(dbPath);\n const db = new SQL.Database(buffer);\n const recorder = new SessionRecorderAdapter(db);\n\n try {\n if (options.clear) {\n recorder.clear();\n // Persist cleared DB\n const data = db.export();\n const { writeFileSync } = await import('node:fs');\n writeFileSync(dbPath, Buffer.from(data));\n console.error('[ctxo] Session data cleared.');\n return;\n }\n\n // Validate --days\n if (options.days != null) {\n if (!Number.isInteger(options.days) || options.days <= 0) {\n console.error('[ctxo] --days must be a positive integer');\n process.exit(1);\n return;\n }\n }\n\n const stats = recorder.queryStats(options.days);\n\n if (stats.totalCalls === 0) {\n if (options.json) {\n process.stdout.write(JSON.stringify(this.emptyReport(options.days)) + '\\n');\n } else {\n console.error('[ctxo] No usage data yet. Start using Ctxo MCP tools to collect stats.');\n }\n return;\n }\n\n if (options.json) {\n process.stdout.write(JSON.stringify(this.buildReport(stats, options.days), null, 2) + '\\n');\n } else {\n this.printHumanReadable(stats, options.days);\n }\n } finally {\n db.close();\n }\n }\n\n private isStatsEnabled(): boolean {\n const configPath = join(this.ctxoRoot, 'config.yaml');\n if (!existsSync(configPath)) return true;\n\n try {\n const raw = readFileSync(configPath, 'utf-8');\n const match = raw.match(/stats:\\s*\\n\\s*enabled:\\s*(true|false)/);\n if (match) return match[1] !== 'false';\n return true;\n } catch {\n return true;\n }\n }\n\n private buildReport(stats: AggregatedStats, days?: number): StatsReport {\n const now = new Date().toISOString();\n const from = days != null\n ? new Date(Date.now() - days * 86400000).toISOString()\n : null;\n\n return {\n timeRange: { from, to: now, daysFilter: days ?? null },\n summary: {\n totalCalls: stats.totalCalls,\n totalTokensServed: stats.totalTokensServed,\n },\n topTools: stats.topTools,\n topSymbols: stats.topSymbols,\n detailLevelDistribution: stats.detailLevelDistribution.map((d) => ({\n level: d.level,\n count: d.count,\n percentage: d.percentage,\n })),\n };\n }\n\n private emptyReport(days?: number): StatsReport {\n return this.buildReport({\n totalCalls: 0,\n totalTokensServed: 0,\n topTools: [],\n topSymbols: [],\n detailLevelDistribution: [],\n }, days);\n }\n\n private printHumanReadable(stats: AggregatedStats, days?: number): void {\n const header = days != null ? `last ${days} days` : 'all time';\n\n console.error('');\n console.error(` Usage Summary (${header})`);\n console.error(' ────────────────────────────────────────');\n console.error(` Total tool calls: ${this.formatNumber(stats.totalCalls)}`);\n console.error(` Total tokens served: ${this.formatTokens(stats.totalTokensServed)}`);\n\n if (stats.topTools.length > 0) {\n console.error('');\n console.error(' Top Tools');\n console.error(' ────────────────────────────────────────');\n for (const t of stats.topTools) {\n const name = t.tool.padEnd(24);\n const calls = `${this.formatNumber(t.calls)} calls`.padEnd(14);\n console.error(` ${name}${calls}avg ${this.formatNumber(t.avgTokens)} tokens`);\n }\n }\n\n if (stats.topSymbols.length > 0) {\n console.error('');\n console.error(' Top Queried Symbols');\n console.error(' ────────────────────────────────────────');\n for (const s of stats.topSymbols) {\n const name = s.name.padEnd(32);\n console.error(` ${name}${this.formatNumber(s.queries)} queries`);\n }\n }\n\n if (stats.detailLevelDistribution.length > 0) {\n console.error('');\n console.error(' Detail Level Distribution');\n console.error(' ────────────────────────────────────────');\n for (const d of stats.detailLevelDistribution) {\n const bar = this.renderBar(d.percentage);\n const pct = `${d.percentage}%`.padStart(4);\n console.error(` ${d.level}: ${bar} ${pct}`);\n }\n }\n\n console.error('');\n }\n\n private renderBar(percentage: number): string {\n const filled = Math.round(percentage / 10);\n const empty = 10 - filled;\n return '█'.repeat(filled) + '░'.repeat(empty);\n }\n\n private formatNumber(n: number): string {\n return n.toLocaleString('en-US');\n }\n\n private formatTokens(n: number): string {\n if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;\n if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`;\n return String(n);\n }\n}\n","import { join } from 'node:path';\nimport { existsSync } from 'node:fs';\nimport type { IHealthCheck } from '../core/diagnostics/types.js';\nimport { JsonIndexReader } from '../adapters/storage/json-index-reader.js';\nimport { HealthChecker } from '../adapters/diagnostics/health-checker.js';\nimport { DoctorReporter } from '../adapters/diagnostics/doctor-reporter.js';\nimport { NodeVersionCheck, TsMorphCheck, TreeSitterCheck } from '../adapters/diagnostics/checks/runtime-check.js';\nimport { VersionsCheck } from '../adapters/diagnostics/checks/versions-check.js';\nimport { LanguageCoverageCheck } from '../adapters/diagnostics/checks/language-coverage-check.js';\nimport { GitBinaryCheck, GitRepoCheck } from '../adapters/diagnostics/checks/git-check.js';\nimport {\n IndexDirectoryCheck,\n IndexFreshnessCheck,\n SymbolCountCheck,\n EdgeCountCheck,\n OrphanedFilesCheck,\n CoChangesCacheCheck,\n SchemaVersionCheck,\n} from '../adapters/diagnostics/checks/index-check.js';\nimport { SqliteCacheCheck } from '../adapters/diagnostics/checks/storage-check.js';\nimport { ConfigFileCheck } from '../adapters/diagnostics/checks/config-check.js';\nimport { DiskUsageCheck } from '../adapters/diagnostics/checks/disk-check.js';\nimport { applyFixes, formatFixReport } from './doctor-fix.js';\n\nexport interface DoctorOptions {\n json?: boolean;\n quiet?: boolean;\n fix?: boolean;\n dryRun?: boolean;\n yes?: boolean;\n}\n\nexport class DoctorCommand {\n private readonly projectRoot: string;\n private readonly ctxoRoot: string;\n\n constructor(projectRoot: string) {\n this.projectRoot = projectRoot;\n this.ctxoRoot = join(projectRoot, '.ctxo');\n }\n\n async run(options: DoctorOptions = {}): Promise<void> {\n const { getVersion } = await import('./cli-router.js');\n console.error(`ctxo v${getVersion()} — health check\\n`);\n\n const checks: IHealthCheck[] = [\n new VersionsCheck(),\n new NodeVersionCheck(),\n new GitBinaryCheck(),\n new GitRepoCheck(),\n new IndexDirectoryCheck(),\n new IndexFreshnessCheck(),\n new SqliteCacheCheck(),\n new ConfigFileCheck(),\n new TsMorphCheck(),\n new TreeSitterCheck(),\n new LanguageCoverageCheck(),\n new DiskUsageCheck(),\n new SymbolCountCheck(),\n new EdgeCountCheck(),\n new OrphanedFilesCheck(),\n new CoChangesCacheCheck(),\n new SchemaVersionCheck(),\n ];\n\n // Pre-load index once — shared by all index-related checks (avoids 5x redundant readAll)\n const indexDir = join(this.ctxoRoot, 'index');\n const indices = existsSync(indexDir)\n ? new JsonIndexReader(this.ctxoRoot).readAll()\n : [];\n\n const checker = new HealthChecker(checks);\n const report = await checker.runAll({\n projectRoot: this.projectRoot,\n ctxoRoot: this.ctxoRoot,\n indices,\n });\n\n const reporter = new DoctorReporter();\n let output: string;\n\n if (options.json) {\n output = reporter.formatJson(report);\n process.stdout.write(output + '\\n');\n } else if (options.quiet) {\n output = reporter.formatQuiet(report);\n console.error(output);\n } else {\n output = reporter.formatHuman(report);\n console.error(output);\n }\n\n if (options.fix) {\n console.error('');\n console.error(options.dryRun ? '[ctxo] --fix --dry-run: planned actions' : '[ctxo] --fix: applying remediation');\n const fixReport = await applyFixes(report, {\n projectRoot: this.projectRoot,\n ctxoRoot: this.ctxoRoot,\n yes: options.yes,\n dryRun: options.dryRun,\n });\n console.error(formatFixReport(fixReport));\n if (fixReport.halted) {\n process.exitCode = 2;\n }\n return;\n }\n\n if (report.exitCode !== 0) {\n process.exitCode = 1;\n }\n }\n}\n","import { createLogger } from '../../core/logger.js';\nimport type { IHealthCheck, CheckContext, CheckResult, DoctorReport } from '../../core/diagnostics/types.js';\n\nconst log = createLogger('ctxo:doctor');\n\nexport class HealthChecker {\n private readonly checks: IHealthCheck[];\n\n constructor(checks: IHealthCheck[]) {\n this.checks = checks;\n }\n\n async runAll(ctx: CheckContext): Promise<DoctorReport> {\n const settled = await Promise.allSettled(\n this.checks.map(check => check.run(ctx)),\n );\n\n const results: CheckResult[] = settled.map((outcome, i) => {\n const check = this.checks[i]!;\n if (outcome.status === 'fulfilled') {\n const r = outcome.value;\n log.info(`${r.id}: ${r.status.toUpperCase()} (${r.message})`);\n return r;\n }\n const message = (outcome.reason as Error)?.message ?? 'Unknown error';\n log.error(`${check.id}: FAIL (${message})`);\n return {\n id: check.id,\n title: check.title,\n status: 'fail' as const,\n message: `Check crashed: ${message}`,\n };\n });\n\n const summary = {\n pass: results.filter(r => r.status === 'pass').length,\n warn: results.filter(r => r.status === 'warn').length,\n fail: results.filter(r => r.status === 'fail').length,\n };\n\n const exitCode = summary.fail > 0 ? 1 as const : 0 as const;\n\n return { checks: results, summary, exitCode };\n }\n}\n","import type { DoctorReport, CheckResult } from '../../core/diagnostics/types.js';\n\nconst ICONS: Record<string, string> = {\n pass: '✓',\n warn: '⚠',\n fail: '✗',\n};\n\nexport class DoctorReporter {\n formatHuman(report: DoctorReport): string {\n const lines: string[] = ['ctxo doctor — Health Check', ''];\n\n for (const check of report.checks) {\n lines.push(this.formatCheckLine(check));\n }\n\n lines.push('');\n lines.push(` Summary: ${report.summary.pass} passed, ${report.summary.warn} warnings, ${report.summary.fail} failures`);\n\n return lines.join('\\n');\n }\n\n formatQuiet(report: DoctorReport): string {\n const lines: string[] = [];\n\n for (const check of report.checks) {\n if (check.status === 'warn' || check.status === 'fail') {\n lines.push(this.formatCheckLine(check));\n }\n }\n\n if (lines.length > 0) lines.push('');\n lines.push(` Summary: ${report.summary.pass} passed, ${report.summary.warn} warnings, ${report.summary.fail} failures`);\n\n return lines.join('\\n');\n }\n\n formatJson(report: DoctorReport): string {\n return JSON.stringify({\n checks: report.checks.map(c => ({\n name: c.id,\n status: c.status,\n value: c.value ?? null,\n message: c.message,\n ...(c.fix ? { fix: c.fix } : {}),\n })),\n summary: report.summary,\n exitCode: report.exitCode,\n }, null, 2);\n }\n\n private formatCheckLine(check: CheckResult): string {\n const icon = ICONS[check.status] ?? '?';\n const title = check.title.padEnd(24);\n const suffix = check.fix ? ` (${check.fix})` : '';\n return ` ${icon} ${title} ${check.message}${suffix}`;\n }\n}\n","import { createRequire } from 'node:module';\nimport type { IHealthCheck, CheckResult, CheckContext } from '../../../core/diagnostics/types.js';\n\nconst require = createRequire(import.meta.url);\n\nfunction pass(id: string, title: string, message: string): CheckResult {\n return { id, title, status: 'pass', message };\n}\nfunction warn(id: string, title: string, message: string, fix: string): CheckResult {\n return { id, title, status: 'warn', message, fix };\n}\n\nexport function checkNodeVersion(version: string): CheckResult {\n const id = 'node_version';\n const title = 'Node.js version';\n const major = parseInt(version.slice(1).split('.')[0] ?? '0', 10);\n if (major >= 20) return { id, title, status: 'pass', message: `Node.js ${version} (required: ≥20)`, value: version };\n if (major >= 18) return { id, title, status: 'warn', message: `Node.js ${version} — v20+ recommended`, fix: 'Upgrade to Node.js 20 or later', value: version };\n return { id, title, status: 'fail', message: `Node.js ${version} — v20+ required`, fix: 'Upgrade to Node.js 20 or later', value: version };\n}\n\nexport class NodeVersionCheck implements IHealthCheck {\n readonly id = 'node_version';\n readonly title = 'Node.js version';\n\n async run(_ctx: CheckContext): Promise<CheckResult> {\n return checkNodeVersion(process.version);\n }\n}\n\nexport class TsMorphCheck implements IHealthCheck {\n readonly id = 'ts_morph';\n readonly title = 'TypeScript plugin (@ctxo/lang-typescript)';\n\n async run(_ctx: CheckContext): Promise<CheckResult> {\n if (tryResolve('@ctxo/lang-typescript')) {\n return pass(this.id, this.title, 'available');\n }\n return warn(\n this.id,\n this.title,\n '@ctxo/lang-typescript not installed — TypeScript/JavaScript indexing disabled',\n 'Run \"npm install @ctxo/lang-typescript\" (or \"ctxo install typescript\")',\n );\n }\n}\n\nexport class TreeSitterCheck implements IHealthCheck {\n readonly id = 'tree_sitter';\n readonly title = 'Go / C# plugins (@ctxo/lang-go, @ctxo/lang-csharp)';\n\n async run(_ctx: CheckContext): Promise<CheckResult> {\n const goOk = tryResolve('@ctxo/lang-go');\n const csOk = tryResolve('@ctxo/lang-csharp');\n if (goOk && csOk) return pass(this.id, this.title, 'both plugins available');\n if (goOk || csOk) {\n const missing = goOk ? '@ctxo/lang-csharp' : '@ctxo/lang-go';\n return warn(\n this.id,\n this.title,\n `${missing} not installed`,\n `Run \"npm install ${missing}\" (or \"ctxo install ${missing === '@ctxo/lang-go' ? 'go' : 'csharp'}\")`,\n );\n }\n return warn(\n this.id,\n this.title,\n 'No Go/C# plugin installed — extended language indexing disabled',\n 'Run \"npm install @ctxo/lang-go @ctxo/lang-csharp\"',\n );\n }\n}\n\nfunction tryResolve(packageName: string): boolean {\n try {\n // Resolve package.json instead of the entry so \"exports: import-only\"\n // packages (all @ctxo/lang-* plugins) still register as installed.\n require.resolve(`${packageName}/package.json`);\n return true;\n } catch {\n return false;\n }\n}\n","import { SUPPORTED_API_VERSION } from '@ctxo/plugin-api';\nimport type { CtxoLanguagePlugin } from '@ctxo/plugin-api';\nimport { getVersion } from './cli-router.js';\nimport { discoverPlugins, type DiscoveredPlugin } from '../adapters/language/plugin-discovery.js';\nimport { loadManifestPath } from './plugin-loader.js';\n\nexport interface PluginVersionInfo {\n /** npm package name, e.g. \"@ctxo/lang-typescript\" or community \"ctxo-lang-kotlin\" */\n name: string;\n /** Plugin id from the runtime declaration, e.g. \"typescript\" */\n id: string;\n /** Runtime-declared plugin version */\n version: string;\n /** Plugin protocol version declared by the plugin */\n apiVersion: string;\n /** True when apiVersion matches the core's SUPPORTED_API_VERSION */\n compatible: boolean;\n}\n\nexport interface RuntimeInfo {\n node: string;\n platform: NodeJS.Platform;\n arch: string;\n}\n\nexport interface VersionInfo {\n ctxo: string;\n pluginApiVersion: string;\n plugins: PluginVersionInfo[];\n runtime: RuntimeInfo;\n}\n\n/**\n * Produce VersionInfo from already-discovered plugins. Pure function; safe to\n * call without I/O once plugins are in hand. Used by both CLI printers and tests.\n */\nexport function gatherVersionInfo(discovered: readonly DiscoveredPlugin[]): VersionInfo {\n const plugins: PluginVersionInfo[] = discovered.map(({ plugin, specifier }) => ({\n name: specifier,\n id: plugin.id,\n version: plugin.version,\n apiVersion: plugin.apiVersion,\n compatible: plugin.apiVersion === SUPPORTED_API_VERSION,\n }));\n\n return {\n ctxo: getVersion(),\n pluginApiVersion: SUPPORTED_API_VERSION,\n plugins,\n runtime: {\n node: process.version,\n platform: process.platform,\n arch: process.arch,\n },\n };\n}\n\nexport function formatShort(info: VersionInfo): string {\n return `ctxo ${info.ctxo}`;\n}\n\nexport function formatVerbose(info: VersionInfo): string {\n const lines: string[] = [];\n lines.push(`ctxo ${info.ctxo}`);\n lines.push(`Plugin API: ${info.pluginApiVersion}`);\n lines.push(`Runtime: Node ${info.runtime.node} on ${info.runtime.platform}/${info.runtime.arch}`);\n lines.push('');\n if (info.plugins.length === 0) {\n lines.push('Plugins: (none installed)');\n lines.push('');\n lines.push('Install a language plugin, e.g. \"npm i -D @ctxo/lang-typescript\"');\n return lines.join('\\n');\n }\n\n const nameCol = Math.max(7, ...info.plugins.map((p) => p.name.length));\n const verCol = Math.max(7, ...info.plugins.map((p) => p.version.length));\n const apiCol = Math.max(3, ...info.plugins.map((p) => p.apiVersion.length));\n\n lines.push(`Plugins: ${info.plugins.length} installed`);\n lines.push(\n ` ${'NAME'.padEnd(nameCol)} ${'VERSION'.padEnd(verCol)} ${'API'.padEnd(apiCol)} STATUS`,\n );\n for (const p of info.plugins) {\n const status = p.compatible ? 'OK' : `incompatible (core wants ${info.pluginApiVersion})`;\n lines.push(\n ` ${p.name.padEnd(nameCol)} ${p.version.padEnd(verCol)} ${p.apiVersion.padEnd(apiCol)} ${status}`,\n );\n }\n\n return lines.join('\\n');\n}\n\nexport function formatJson(info: VersionInfo): string {\n return JSON.stringify(info, null, 2);\n}\n\nexport interface VersionOptions {\n verbose?: boolean;\n json?: boolean;\n}\n\n/**\n * CLI entry. Keeps I/O scoped to plugin-discovery metadata reads; no adapter\n * instantiation, no network. Verbose and JSON modes target sub-200ms even with\n * several plugins installed because discovery only reads package.json plus a\n * single dynamic import() per plugin module (no createAdapter call).\n */\nexport class VersionCommand {\n constructor(private readonly projectRoot: string) {}\n\n async run(options: VersionOptions = {}): Promise<void> {\n const info = await this.collect();\n if (options.json) {\n process.stdout.write(formatJson(info) + '\\n');\n return;\n }\n if (options.verbose) {\n process.stdout.write(formatVerbose(info) + '\\n');\n return;\n }\n process.stdout.write(formatShort(info) + '\\n');\n }\n\n private async collect(): Promise<VersionInfo> {\n const manifestPath = loadManifestPath(this.projectRoot);\n if (!manifestPath) {\n return gatherVersionInfo([]);\n }\n const { plugins } = await discoverPlugins({ manifestPath });\n return gatherVersionInfo(plugins);\n }\n}\n\n/**\n * Treat a CtxoLanguagePlugin-shaped object directly (escape hatch for callers\n * that have plugins in memory, e.g. indexCommand after wiring the registry).\n */\nexport function gatherFromLivePlugins(\n live: ReadonlyArray<{ plugin: CtxoLanguagePlugin; specifier: string }>,\n): VersionInfo {\n return gatherVersionInfo(live);\n}\n","import type { IHealthCheck, CheckContext, CheckResult } from '../../../core/diagnostics/types.js';\nimport {\n gatherVersionInfo,\n formatVerbose,\n type VersionInfo,\n} from '../../../cli/version-command.js';\nimport { discoverPlugins } from '../../language/plugin-discovery.js';\nimport { loadManifestPath } from '../../../cli/plugin-loader.js';\n\n/**\n * Surfaces ctxo + plugin + runtime versions in `ctxo doctor` output. Warns when\n * a plugin declares an apiVersion the core does not support. Purely informational\n * in the pass-case; the doctor report summary already treats warn as non-zero.\n */\nexport class VersionsCheck implements IHealthCheck {\n readonly id = 'versions';\n readonly title = 'Versions';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n const info = await collectInfo(ctx);\n\n const incompatible = info.plugins.filter((p) => !p.compatible);\n const message = buildSummary(info);\n\n if (incompatible.length > 0) {\n return {\n id: this.id,\n title: this.title,\n status: 'warn',\n message,\n fix: `Upgrade or replace plugins with apiVersion != ${info.pluginApiVersion}: ${incompatible.map((p) => p.name).join(', ')}`,\n value: formatVerbose(info),\n };\n }\n\n return {\n id: this.id,\n title: this.title,\n status: 'pass',\n message,\n value: formatVerbose(info),\n };\n }\n}\n\nasync function collectInfo(ctx: CheckContext): Promise<VersionInfo> {\n const manifestPath = loadManifestPath(ctx.projectRoot);\n if (!manifestPath) return gatherVersionInfo([]);\n const { plugins } = await discoverPlugins({ manifestPath });\n return gatherVersionInfo(plugins);\n}\n\nfunction buildSummary(info: VersionInfo): string {\n const pluginCount = info.plugins.length;\n const pluginLabel = pluginCount === 0 ? 'no plugins' : `${pluginCount} plugin${pluginCount === 1 ? '' : 's'}`;\n return `ctxo ${info.ctxo} (API ${info.pluginApiVersion}) — ${pluginLabel}, Node ${info.runtime.node}`;\n}\n","import { createRequire } from 'node:module';\nimport type { IHealthCheck, CheckContext, CheckResult } from '../../../core/diagnostics/types.js';\nimport {\n decideNeededLanguages,\n detectLanguages,\n officialPluginFor,\n type KnownLanguage,\n} from '../../../core/detection/detect-languages.js';\n\nconst require = createRequire(import.meta.url);\n\n/**\n * Reports which detected languages lack an installed plugin. Warns (never fails)\n * so mixed-language projects can still run ctxo for the subset with plugins.\n */\nexport class LanguageCoverageCheck implements IHealthCheck {\n readonly id = 'language_coverage';\n readonly title = 'Language coverage';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n const detection = detectLanguages(ctx.projectRoot);\n const needed = decideNeededLanguages(detection);\n\n if (needed.length === 0) {\n return {\n id: this.id,\n title: this.title,\n status: 'pass',\n message: 'no source languages detected',\n };\n }\n\n const missing: KnownLanguage[] = [];\n for (const lang of needed) {\n if (!pluginResolves(officialPluginFor(lang))) {\n missing.push(lang);\n }\n }\n\n if (missing.length === 0) {\n const summary = needed.map((l) => `${l}`).join(', ');\n return {\n id: this.id,\n title: this.title,\n status: 'pass',\n message: `plugins installed for: ${summary}`,\n };\n }\n\n const packages = missing.map(officialPluginFor).join(' ');\n const shortList = missing.join(', ');\n return {\n id: this.id,\n title: this.title,\n status: 'warn',\n message: `missing plugins for: ${shortList}`,\n fix: `Run \"ctxo install ${missing.join(' ')}\" or \"npm install -D ${packages}\"`,\n };\n }\n}\n\nfunction pluginResolves(packageName: string): boolean {\n try {\n // Resolve package.json instead of the entry point so we don't trip over\n // ESM `exports` fields that refuse CJS require (our own plugins do this).\n require.resolve(`${packageName}/package.json`);\n return true;\n } catch {\n return false;\n }\n}\n","import { execFileSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { IHealthCheck, CheckResult, CheckContext } from '../../../core/diagnostics/types.js';\n\nexport class GitBinaryCheck implements IHealthCheck {\n readonly id = 'git_binary';\n readonly title = 'Git available';\n\n async run(_ctx: CheckContext): Promise<CheckResult> {\n try {\n const version = execFileSync('git', ['--version'], { encoding: 'utf-8' }).trim();\n return { id: this.id, title: this.title, status: 'pass', message: version, value: version };\n } catch {\n return { id: this.id, title: this.title, status: 'fail', message: 'git not found in PATH', fix: 'Install git and ensure it is in your PATH' };\n }\n }\n}\n\nexport class GitRepoCheck implements IHealthCheck {\n readonly id = 'git_repo';\n readonly title = 'Git repository';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n if (existsSync(join(ctx.projectRoot, '.git'))) {\n return { id: this.id, title: this.title, status: 'pass', message: ctx.projectRoot, value: ctx.projectRoot };\n }\n return { id: this.id, title: this.title, status: 'fail', message: 'Not a git repository', fix: 'Run \"git init\" or clone a repository' };\n }\n}\n","import { existsSync } from 'node:fs';\nimport { execFileSync } from 'node:child_process';\nimport { join } from 'node:path';\nimport type { IHealthCheck, CheckResult, CheckContext } from '../../../core/diagnostics/types.js';\nimport type { FileIndex } from '../../../core/types.js';\nimport { JsonIndexReader } from '../../storage/json-index-reader.js';\nimport { StalenessDetector } from '../../../core/staleness/staleness-detector.js';\nimport { SchemaManager } from '../../storage/schema-manager.js';\n\nfunction pass(id: string, title: string, message: string, value?: string): CheckResult {\n return { id, title, status: 'pass', message, value };\n}\nfunction warn(id: string, title: string, message: string, fix?: string, value?: string): CheckResult {\n return { id, title, status: 'warn', message, fix, value };\n}\nfunction fail(id: string, title: string, message: string, fix?: string, value?: string): CheckResult {\n return { id, title, status: 'fail', message, fix, value };\n}\n\n/** Use pre-loaded indices from context, or fall back to reading from disk */\nfunction getIndices(ctx: CheckContext): readonly FileIndex[] {\n return ctx.indices ?? new JsonIndexReader(ctx.ctxoRoot).readAll();\n}\n\nexport class IndexDirectoryCheck implements IHealthCheck {\n readonly id = 'index_directory';\n readonly title = 'Index directory';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n const indexDir = join(ctx.ctxoRoot, 'index');\n if (!existsSync(indexDir)) {\n return fail(this.id, this.title, 'No index directory', 'Run \"ctxo index\"');\n }\n const indices = getIndices(ctx);\n if (indices.length === 0) {\n return fail(this.id, this.title, 'Index directory empty', 'Run \"ctxo index\"');\n }\n return pass(this.id, this.title, `${indices.length} files indexed`, String(indices.length));\n }\n}\n\nexport class IndexFreshnessCheck implements IHealthCheck {\n readonly id = 'index_freshness';\n readonly title = 'Index freshness';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n const indices = getIndices(ctx);\n if (indices.length === 0) {\n return fail(this.id, this.title, 'No indexed files to check', 'Run \"ctxo index\"');\n }\n\n const indexedFiles = indices.map(idx => idx.file);\n const staleness = new StalenessDetector(ctx.projectRoot, ctx.ctxoRoot);\n const warning = staleness.check(indexedFiles);\n\n if (!warning) {\n return pass(this.id, this.title, `All ${indices.length} files fresh`, `0/${indices.length} stale`);\n }\n\n const staleCount = warning.staleFiles.length;\n const pct = staleCount / indices.length;\n const value = `${staleCount}/${indices.length} stale`;\n\n if (pct <= 0.1) {\n return warn(this.id, this.title, `${staleCount} of ${indices.length} files stale`, 'Run \"ctxo index\"', value);\n }\n return fail(this.id, this.title, `${staleCount} of ${indices.length} files stale (${Math.round(pct * 100)}%)`, 'Run \"ctxo index\"', value);\n }\n}\n\nexport class SymbolCountCheck implements IHealthCheck {\n readonly id = 'symbol_count';\n readonly title = 'Symbol count';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n const indices = getIndices(ctx);\n const total = indices.reduce((sum, idx) => sum + idx.symbols.length, 0);\n if (total > 0) {\n return pass(this.id, this.title, `${total.toLocaleString()} symbols`, String(total));\n }\n return fail(this.id, this.title, '0 symbols (index empty)', 'Run \"ctxo index\"', '0');\n }\n}\n\nexport class EdgeCountCheck implements IHealthCheck {\n readonly id = 'edge_count';\n readonly title = 'Edge count';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n const indices = getIndices(ctx);\n const total = indices.reduce((sum, idx) => sum + idx.edges.length, 0);\n if (total > 0) {\n return pass(this.id, this.title, `${total.toLocaleString()} edges`, String(total));\n }\n return warn(this.id, this.title, '0 edges (possible isolated files)', undefined, '0');\n }\n}\n\nexport class OrphanedFilesCheck implements IHealthCheck {\n readonly id = 'orphaned_files';\n readonly title = 'Orphaned index files';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n const indices = getIndices(ctx);\n if (indices.length === 0) {\n return pass(this.id, this.title, 'no index files to check');\n }\n\n const sourceFiles = this.getSourceFiles(ctx.projectRoot);\n if (sourceFiles.size === 0) {\n return pass(this.id, this.title, 'none (git ls-files unavailable)');\n }\n\n const orphaned = indices.filter(idx => !sourceFiles.has(idx.file));\n if (orphaned.length === 0) {\n return pass(this.id, this.title, 'none', '0');\n }\n if (orphaned.length <= 5) {\n return warn(this.id, this.title, `${orphaned.length} orphaned index files`, 'Delete orphaned files from .ctxo/index/', String(orphaned.length));\n }\n return fail(this.id, this.title, `${orphaned.length} orphaned index files`, 'Delete orphaned files from .ctxo/index/', String(orphaned.length));\n }\n\n private getSourceFiles(projectRoot: string): Set<string> {\n try {\n const output = execFileSync('git', ['ls-files', '--cached', '--others', '--exclude-standard'], {\n cwd: projectRoot,\n encoding: 'utf-8',\n });\n return new Set(output.split('\\n').map(l => l.trim()).filter(l => l.length > 0));\n } catch {\n return new Set();\n }\n }\n}\n\nexport class CoChangesCacheCheck implements IHealthCheck {\n readonly id = 'co_changes_cache';\n readonly title = 'Co-changes cache';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n const coChangesPath = join(ctx.ctxoRoot, 'index', 'co-changes.json');\n if (existsSync(coChangesPath)) {\n return pass(this.id, this.title, 'present');\n }\n return warn(this.id, this.title, 'missing (co-change analysis disabled)', 'Run \"ctxo index\" with git history');\n }\n}\n\nexport class SchemaVersionCheck implements IHealthCheck {\n readonly id = 'schema_version';\n readonly title = 'Schema version';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n const manager = new SchemaManager(ctx.ctxoRoot);\n const stored = manager.readStoredVersion();\n const current = manager.currentVersion();\n\n if (!stored) {\n return fail(this.id, this.title, 'No schema version found', 'Run \"ctxo index\"');\n }\n if (manager.isCompatible()) {\n return pass(this.id, this.title, `${stored} (current)`, stored);\n }\n return fail(this.id, this.title, `${stored} (expected ${current})`, 'Run \"ctxo index\" to re-index with current schema', stored);\n }\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { IHealthCheck, CheckResult, CheckContext } from '../../../core/diagnostics/types.js';\n\nexport class SqliteCacheCheck implements IHealthCheck {\n readonly id = 'sqlite_cache';\n readonly title = 'SQLite cache';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n const dbPath = join(ctx.ctxoRoot, '.cache', 'symbols.db');\n if (!existsSync(dbPath)) {\n return { id: this.id, title: this.title, status: 'warn', message: 'SQLite cache missing', fix: 'Run \"ctxo sync\" to rebuild' };\n }\n\n try {\n const { default: initSqlJs } = await import('sql.js');\n const SQL = await initSqlJs();\n const buffer = readFileSync(dbPath);\n const db = new SQL.Database(new Uint8Array(buffer));\n const result = db.exec('PRAGMA integrity_check');\n db.close();\n\n const firstRow = result[0]?.values[0];\n if (firstRow && firstRow[0] === 'ok') {\n return { id: this.id, title: this.title, status: 'pass', message: 'integrity_check passed' };\n }\n return { id: this.id, title: this.title, status: 'fail', message: `SQLite corrupt: ${String(firstRow?.[0])}`, fix: 'Run \"ctxo sync\" to rebuild' };\n } catch (err) {\n return { id: this.id, title: this.title, status: 'fail', message: `SQLite unreadable: ${(err as Error).message}`, fix: 'Run \"ctxo sync\" to rebuild' };\n }\n }\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { IHealthCheck, CheckResult, CheckContext } from '../../../core/diagnostics/types.js';\nimport { loadConfig } from '../../../core/config/load-config.js';\n\nexport class ConfigFileCheck implements IHealthCheck {\n readonly id = 'config_file';\n readonly title = 'Config file';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n const configPath = join(ctx.ctxoRoot, 'config.yaml');\n if (!existsSync(configPath)) {\n return { id: this.id, title: this.title, status: 'warn', message: 'No config.yaml (using defaults)' };\n }\n\n try {\n const content = readFileSync(configPath, 'utf-8');\n if (content.trim().length === 0) {\n return { id: this.id, title: this.title, status: 'warn', message: 'config.yaml is empty (using defaults)' };\n }\n // Basic YAML structure check — tabs are invalid in YAML\n if (content.includes('\\t')) {\n return { id: this.id, title: this.title, status: 'fail', message: 'Invalid config.yaml: tabs are not allowed in YAML', fix: 'Replace tabs with spaces in .ctxo/config.yaml' };\n }\n\n const loaded = loadConfig(ctx.ctxoRoot);\n if (loaded.errors.length > 0) {\n return {\n id: this.id,\n title: this.title,\n status: 'fail',\n message: `Invalid config.yaml: ${loaded.errors[0]}${loaded.errors.length > 1 ? ` (+${loaded.errors.length - 1} more)` : ''}`,\n fix: 'Fix schema violations in .ctxo/config.yaml (see docs for the full schema)',\n };\n }\n if (loaded.invalidGlobs.length > 0) {\n return {\n id: this.id,\n title: this.title,\n status: 'warn',\n message: `config.yaml has ${loaded.invalidGlobs.length} invalid glob pattern(s): ${loaded.invalidGlobs.join('; ')}`,\n fix: 'Fix the listed glob patterns under index.ignore / index.ignoreProjects',\n };\n }\n return { id: this.id, title: this.title, status: 'pass', message: '.ctxo/config.yaml valid' };\n } catch (err) {\n return { id: this.id, title: this.title, status: 'fail', message: `Cannot read config.yaml: ${(err as Error).message}`, fix: 'Check file permissions for .ctxo/config.yaml' };\n }\n }\n}\n","import { existsSync, readdirSync, statSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { IHealthCheck, CheckResult, CheckContext } from '../../../core/diagnostics/types.js';\n\nexport interface DiskThresholds {\n readonly warnMb: number;\n readonly failMb: number;\n}\n\nconst DEFAULT_THRESHOLDS: DiskThresholds = { warnMb: 100, failMb: 500 };\n\nexport class DiskUsageCheck implements IHealthCheck {\n readonly id = 'disk_usage';\n readonly title = 'Disk usage';\n private readonly thresholds: DiskThresholds;\n\n constructor(thresholds: DiskThresholds = DEFAULT_THRESHOLDS) {\n this.thresholds = thresholds;\n }\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n if (!existsSync(ctx.ctxoRoot)) {\n return { id: this.id, title: this.title, status: 'pass', message: 'no .ctxo/ directory', value: '0' };\n }\n\n const bytes = this.getDirSize(ctx.ctxoRoot);\n const mb = bytes / (1024 * 1024);\n const formatted = mb < 1 ? `${Math.round(bytes / 1024)} KB` : `${mb.toFixed(1)} MB`;\n\n if (mb < this.thresholds.warnMb) {\n return { id: this.id, title: this.title, status: 'pass', message: formatted, value: formatted };\n }\n if (mb < this.thresholds.failMb) {\n return { id: this.id, title: this.title, status: 'warn', message: `${formatted} — consider pruning orphaned index files`, value: formatted };\n }\n return { id: this.id, title: this.title, status: 'fail', message: `${formatted} — unusually large`, fix: 'Check for stale data in .ctxo/', value: formatted };\n }\n\n private getDirSize(dirPath: string): number {\n let total = 0;\n try {\n const entries = readdirSync(dirPath, { withFileTypes: true, recursive: true });\n for (const entry of entries) {\n if (entry.isFile()) {\n try {\n // parentPath available in Node 20.12+, path in earlier Node 20.x\n const parent = (entry as unknown as { parentPath?: string; path?: string }).parentPath\n ?? (entry as unknown as { path?: string }).path\n ?? dirPath;\n total += statSync(join(parent, entry.name)).size;\n } catch {\n // skip unreadable files\n }\n }\n }\n } catch {\n // skip unreadable directories\n }\n return total;\n }\n}\n","import { execFileSync } from 'node:child_process';\nimport { appendFileSync, existsSync, mkdirSync, rmSync, unlinkSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, join } from 'node:path';\nimport { JsonIndexReader } from '../adapters/storage/json-index-reader.js';\nimport type { DoctorReport } from '../core/diagnostics/types.js';\nimport {\n detectLanguages,\n decideNeededLanguages,\n officialPluginFor,\n type KnownLanguage,\n} from '../core/detection/detect-languages.js';\nimport { ensureConfig } from './ai-rules.js';\nimport { InstallCommand } from './install-command.js';\nimport { InitCommand } from './init-command.js';\nimport { IndexCommand } from './index-command.js';\nimport { SyncCommand } from './sync-command.js';\n\nexport interface FixOptions {\n readonly projectRoot: string;\n readonly ctxoRoot: string;\n readonly yes?: boolean;\n readonly dryRun?: boolean;\n}\n\nexport interface FixAttempt {\n readonly name: string;\n readonly action: string;\n readonly status: 'success' | 'skipped' | 'failed' | 'planned';\n readonly durationMs?: number;\n readonly error?: string;\n}\n\nexport interface FixReport {\n readonly attempts: readonly FixAttempt[];\n readonly halted: boolean;\n readonly reason?: string;\n}\n\n/**\n * Apply ordered fixes derived from a doctor report.\n *\n * Order (PRD §5.2 D4.4):\n * 1. Config (bootstraps defaults other steps may need)\n * 2. Git hooks (cheap; depends on .git existing)\n * 3. Language coverage (install missing plugins)\n * 4. Index (requires adapters — so run AFTER plugin install)\n * 5. SQLite cache (last; rebuild from index JSONs)\n *\n * Error handling (D4.6 \"dependency-aware continue\"):\n * - Config failure -> skip all dependent steps\n * - Plugin install failure -> skip index (can't rebuild adapters) but DO rebuild cache\n *\n * Never fixable here: runtime, git repo, disk. Those remain as CheckResult\n * output for the user to address manually.\n *\n * All attempts are appended to `.ctxo/doctor-fix.log` for forensics.\n */\nexport async function applyFixes(report: DoctorReport, options: FixOptions): Promise<FixReport> {\n if (isCI(process.env) && !options.yes && !options.dryRun) {\n return {\n attempts: [],\n halted: true,\n reason: 'CI environment detected; refuse to mutate without --yes',\n };\n }\n\n const attempts: FixAttempt[] = [];\n const fixableIds = new Set(report.checks.filter((c) => c.status !== 'pass').map((c) => c.id));\n\n let configOk = true;\n if (fixableIds.has('config_file')) {\n const attempt = await run(\n 'Config',\n 'create from template',\n () => fixConfig(options.projectRoot),\n options,\n );\n attempts.push(attempt);\n configOk = attempt.status === 'success' || attempt.status === 'skipped' || attempt.status === 'planned';\n }\n\n if (!configOk) {\n return finish(attempts, options, true, 'Config fix failed; halting before hooks/plugins/index');\n }\n\n if (fixableIds.has('git_hooks') || fixableIds.has('hooks')) {\n attempts.push(\n await run(\n 'Git hooks',\n 're-install ctxo git hooks',\n () => fixHooks(options.projectRoot),\n options,\n ),\n );\n }\n\n let pluginsOk = true;\n if (fixableIds.has('language_coverage') || hasMissingPlugins(options.projectRoot)) {\n const attempt = await run(\n 'Language plugins',\n 'install missing @ctxo/lang-* packages',\n () => fixLanguageCoverage(options.projectRoot, options.dryRun ?? false),\n options,\n );\n attempts.push(attempt);\n pluginsOk = attempt.status === 'success' || attempt.status === 'skipped' || attempt.status === 'planned';\n }\n\n if (pluginsOk) {\n if (\n fixableIds.has('index_directory') ||\n fixableIds.has('index_freshness') ||\n fixableIds.has('symbol_count')\n ) {\n attempts.push(\n await run(\n 'Index',\n 'rebuild JSON index',\n () => fixIndex(options.projectRoot, options.dryRun ?? false),\n options,\n ),\n );\n }\n if (fixableIds.has('orphaned_files')) {\n attempts.push(\n await run(\n 'Orphaned index files',\n 'delete index entries without a matching source file',\n () => pruneOrphans(options.projectRoot, options.ctxoRoot, options.dryRun ?? false),\n options,\n ),\n );\n }\n } else {\n attempts.push({ name: 'Index', action: 'rebuild JSON index', status: 'skipped', error: 'plugin install failed' });\n }\n\n if (\n fixableIds.has('sqlite_cache') ||\n fixableIds.has('schema_version') ||\n fixableIds.has('co_changes_cache')\n ) {\n attempts.push(\n await run(\n 'SQLite cache',\n 'delete .ctxo/.cache and resync',\n () => fixSqliteCache(options.projectRoot, options.ctxoRoot, options.dryRun ?? false),\n options,\n ),\n );\n }\n\n return finish(attempts, options, false);\n}\n\nfunction finish(\n attempts: FixAttempt[],\n options: FixOptions,\n halted: boolean,\n reason?: string,\n): FixReport {\n writeLog(options.ctxoRoot, attempts, halted, reason);\n return reason ? { attempts, halted, reason } : { attempts, halted };\n}\n\nasync function run(\n name: string,\n action: string,\n body: () => Promise<void>,\n options: FixOptions,\n): Promise<FixAttempt> {\n if (options.dryRun) {\n return { name, action, status: 'planned' };\n }\n const start = Date.now();\n try {\n await body();\n return { name, action, status: 'success', durationMs: Date.now() - start };\n } catch (err) {\n return {\n name,\n action,\n status: 'failed',\n durationMs: Date.now() - start,\n error: (err as Error).message,\n };\n }\n}\n\nasync function fixConfig(projectRoot: string): Promise<void> {\n const result = ensureConfig(projectRoot);\n if (result.action === 'skipped') {\n // Already present — nothing to do\n return;\n }\n}\n\nasync function fixHooks(projectRoot: string): Promise<void> {\n new InitCommand(projectRoot).installHooks();\n}\n\nfunction hasMissingPlugins(projectRoot: string): boolean {\n const detection = detectLanguages(projectRoot);\n const needed = decideNeededLanguages(detection);\n for (const lang of needed) {\n if (!canResolvePlugin(lang)) return true;\n }\n return false;\n}\n\nasync function fixLanguageCoverage(projectRoot: string, dryRun: boolean): Promise<void> {\n const detection = detectLanguages(projectRoot);\n const needed = decideNeededLanguages(detection);\n const missing = needed.filter((lang) => !canResolvePlugin(lang));\n if (missing.length === 0) return;\n if (dryRun) return;\n await new InstallCommand(projectRoot).run({ languages: missing, yes: true });\n}\n\nasync function fixIndex(projectRoot: string, dryRun: boolean): Promise<void> {\n if (dryRun) return;\n await new IndexCommand(projectRoot).run({});\n}\n\nasync function pruneOrphans(projectRoot: string, ctxoRoot: string, dryRun: boolean): Promise<void> {\n if (dryRun) return;\n const indexDir = join(ctxoRoot, 'index');\n if (!existsSync(indexDir)) return;\n\n const sourceFiles = listGitFiles(projectRoot);\n if (sourceFiles.size === 0) return; // no signal; refuse to mass-delete\n\n const reader = new JsonIndexReader(ctxoRoot);\n const indices = reader.readAll();\n let removed = 0;\n for (const idx of indices) {\n if (sourceFiles.has(idx.file)) continue;\n const jsonPath = join(indexDir, `${idx.file}.json`);\n try {\n if (existsSync(jsonPath)) {\n unlinkSync(jsonPath);\n removed += 1;\n pruneEmptyParents(jsonPath, indexDir);\n }\n } catch {\n // best-effort; leave stragglers for next run\n }\n }\n if (removed === 0) return;\n}\n\nfunction pruneEmptyParents(filePath: string, stopAt: string): void {\n let dir = dirname(filePath);\n while (dir !== stopAt && dir.startsWith(stopAt)) {\n try {\n rmSync(dir, { recursive: false });\n } catch {\n return; // not empty or permission issue — stop climbing\n }\n dir = dirname(dir);\n }\n}\n\nfunction listGitFiles(projectRoot: string): Set<string> {\n try {\n const out = execFileSync(\n 'git',\n ['ls-files', '--cached', '--others', '--exclude-standard'],\n { cwd: projectRoot, encoding: 'utf-8', maxBuffer: 64 * 1024 * 1024 },\n );\n return new Set(out.split('\\n').filter(Boolean));\n } catch {\n return new Set();\n }\n}\n\nasync function fixSqliteCache(projectRoot: string, ctxoRoot: string, dryRun: boolean): Promise<void> {\n const cacheDir = join(ctxoRoot, '.cache');\n if (dryRun) return;\n if (existsSync(cacheDir)) rmSync(cacheDir, { recursive: true, force: true });\n // Trigger a sync to rebuild from .ctxo/index/*.json (in-process; no npx round-trip)\n await new SyncCommand(projectRoot).run();\n}\n\nconst doctorRequire = createRequire(import.meta.url);\n\nfunction canResolvePlugin(lang: KnownLanguage): boolean {\n try {\n doctorRequire.resolve(`${officialPluginFor(lang)}/package.json`);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction isCI(env: NodeJS.ProcessEnv): boolean {\n return env['CI'] === 'true' || env['CI'] === '1';\n}\n\nfunction writeLog(\n ctxoRoot: string,\n attempts: readonly FixAttempt[],\n halted: boolean,\n reason?: string,\n): void {\n try {\n if (!existsSync(ctxoRoot)) mkdirSync(ctxoRoot, { recursive: true });\n const path = join(ctxoRoot, 'doctor-fix.log');\n const ts = new Date().toISOString();\n const lines: string[] = [`# ${ts} doctor --fix${halted ? ' (halted: ' + reason + ')' : ''}`];\n for (const a of attempts) {\n const dur = a.durationMs != null ? ` (${a.durationMs}ms)` : '';\n const err = a.error ? ` — ${a.error}` : '';\n lines.push(`- [${a.status}] ${a.name}: ${a.action}${dur}${err}`);\n }\n lines.push('');\n appendFileSync(path, lines.join('\\n'));\n } catch {\n // best-effort logging; never fail the fix because of logging\n }\n}\n\n/** Consumer-friendly formatter for CLI output. */\nexport function formatFixReport(report: FixReport): string {\n const lines: string[] = [];\n for (const a of report.attempts) {\n const icon = a.status === 'success' ? '✓' : a.status === 'planned' ? '·' : a.status === 'skipped' ? '-' : '✗';\n const dur = a.durationMs != null ? ` (${a.durationMs}ms)` : '';\n const err = a.error ? ` — ${a.error}` : '';\n lines.push(` ${icon} ${a.name}: ${a.action}${dur}${err}`);\n }\n if (report.halted && report.reason) {\n lines.push(` ! halted: ${report.reason}`);\n }\n return lines.join('\\n');\n}\n","import { readFileSync, writeFileSync, existsSync } from 'node:fs';\nimport { join, basename } from 'node:path';\nimport { execFile } from 'node:child_process';\nimport { JsonIndexReader } from '../adapters/storage/json-index-reader.js';\nimport { SymbolGraph } from '../core/graph/symbol-graph.js';\nimport { PageRankCalculator } from '../core/importance/pagerank-calculator.js';\nimport { DeadCodeDetector } from '../core/dead-code/dead-code-detector.js';\nimport { ArchitecturalOverlay } from '../core/overlay/architectural-overlay.js';\nimport type { VisualizationPayload, VisNode, VisEdge, VisFileInfo } from '../core/graph/visualization-payload.js';\n\nexport interface VisualizeOptions {\n output?: string;\n maxNodes?: number;\n noBrowser?: boolean;\n}\n\nexport class VisualizeCommand {\n private readonly ctxoRoot: string;\n\n constructor(private readonly projectRoot: string) {\n this.ctxoRoot = join(projectRoot, '.ctxo');\n }\n\n async run(options: VisualizeOptions = {}): Promise<void> {\n // 1. Read index\n const reader = new JsonIndexReader(this.ctxoRoot);\n const indices = reader.readAll();\n\n if (indices.length === 0) {\n console.error('[ctxo] No index found. Run \"ctxo index\" first.');\n process.exit(1);\n return;\n }\n\n console.error(`[ctxo] Building graph from ${indices.length} files...`);\n\n // 2. Build SymbolGraph\n const graph = new SymbolGraph();\n for (const fileIndex of indices) {\n for (const sym of fileIndex.symbols) {\n graph.addNode(sym);\n }\n }\n for (const fileIndex of indices) {\n for (const edge of fileIndex.edges) {\n graph.addEdge(edge);\n }\n }\n\n console.error(`[ctxo] Graph: ${graph.nodeCount} symbols, ${graph.edgeCount} edges`);\n\n // 3. Compute PageRank\n const pageRank = new PageRankCalculator();\n const prResult = pageRank.calculate(graph, { limit: 100_000 });\n const prMap = new Map<string, number>();\n for (const entry of prResult.rankings) {\n prMap.set(entry.symbolId, entry.score);\n }\n\n // 4. Detect dead code\n const deadDetector = new DeadCodeDetector();\n const deadResult = deadDetector.detect(graph);\n const deadMap = new Map<string, { confidence: number; reason: string }>();\n for (const d of deadResult.deadSymbols) {\n deadMap.set(d.symbolId, { confidence: d.confidence, reason: d.reason });\n }\n\n // 4b. Build complexity map from index data\n const complexityMap = new Map<string, number>();\n for (const fileIndex of indices) {\n if (fileIndex.complexity) {\n for (const c of fileIndex.complexity) {\n complexityMap.set(c.symbolId, c.cyclomatic);\n }\n }\n }\n\n // 4c. Build anti-pattern set (files with anti-patterns)\n const antiPatternFiles = new Set<string>();\n for (const fileIndex of indices) {\n if (fileIndex.antiPatterns.length > 0) {\n antiPatternFiles.add(fileIndex.file);\n }\n }\n\n // 5. Classify architectural layers\n const filePaths = [...new Set(indices.map(i => i.file))];\n const overlay = new ArchitecturalOverlay();\n const overlayResult = overlay.classify(filePaths);\n\n // Build file -> layer lookup\n const fileLayerMap = new Map<string, string>();\n for (const [layer, files] of Object.entries(overlayResult.layers)) {\n for (const file of files) {\n fileLayerMap.set(file, layer);\n }\n }\n\n // 6. Build payload\n const totalSymbols = graph.nodeCount;\n let nodes: VisNode[] = graph.allNodes().map(sym => {\n const file = sym.symbolId.split('::')[0] ?? '';\n const dead = deadMap.get(sym.symbolId);\n return {\n id: sym.symbolId,\n name: sym.name,\n kind: sym.kind,\n file,\n startLine: sym.startLine,\n layer: fileLayerMap.get(file) ?? 'Unknown',\n pageRank: prMap.get(sym.symbolId) ?? 0,\n isDead: dead !== undefined,\n ...(dead ? { deadConfidence: dead.confidence, deadReason: dead.reason } : {}),\n cyclomatic: complexityMap.get(sym.symbolId),\n hasAntiPattern: antiPatternFiles.has(file),\n inDegree: graph.getReverseEdges(sym.symbolId).length,\n outDegree: graph.getForwardEdges(sym.symbolId).length,\n };\n });\n\n // 7. Apply --max-nodes filtering\n if (options.maxNodes && nodes.length > options.maxNodes) {\n nodes.sort((a, b) => b.pageRank - a.pageRank);\n nodes = nodes.slice(0, options.maxNodes);\n }\n\n const nodeIds = new Set(nodes.map(n => n.id));\n const edges: VisEdge[] = graph.allEdges()\n .filter(e => nodeIds.has(e.from) && nodeIds.has(e.to))\n .map(e => ({ source: e.from, target: e.to, kind: e.kind }));\n\n // Build per-file info (intent + anti-patterns)\n const filesInfo: VisFileInfo[] = indices\n .filter(fi => nodeIds.has(fi.symbols[0]?.symbolId ?? '___') || fi.symbols.some(s => nodeIds.has(s.symbolId)))\n .map(fi => ({\n file: fi.file,\n intent: fi.intent.map(i => ({ hash: i.hash, message: i.message, date: i.date })),\n antiPatterns: fi.antiPatterns.map(a => ({ hash: a.hash, message: a.message, date: a.date })),\n }));\n\n const payload: VisualizationPayload = {\n projectName: basename(this.projectRoot),\n generatedAt: new Date().toISOString().split('T')[0]!,\n totalSymbols,\n shownSymbols: nodes.length,\n nodes,\n edges,\n layers: overlayResult.layers,\n files: filesInfo,\n };\n\n // 8. Inject into template\n const templatePath = this.getTemplatePath();\n const template = readFileSync(templatePath, 'utf-8');\n const html = template.replace('/*__CTXO_DATA__*/null', JSON.stringify(payload));\n\n // 9. Write output\n const outputPath = options.output ?? join(this.ctxoRoot, 'visualize.html');\n writeFileSync(outputPath, html, 'utf-8');\n console.error(`[ctxo] Wrote visualization to ${outputPath}`);\n console.error(`[ctxo] ${nodes.length} symbols, ${edges.length} edges, ${deadResult.deadSymbols.length} dead`);\n\n // 10. Open in browser\n if (!options.noBrowser) {\n this.openInBrowser(outputPath);\n }\n }\n\n private getTemplatePath(): string {\n let dir = import.meta.dirname;\n for (let i = 0; i < 10; i++) {\n const candidate = join(dir, 'pages', 'visualize-template.html');\n if (existsSync(candidate)) return candidate;\n const parent = join(dir, '..');\n if (parent === dir) break;\n dir = parent;\n }\n throw new Error('Could not find visualize-template.html. Ensure the pages/ directory exists.');\n }\n\n private openInBrowser(filePath: string): void {\n // Use execFile (not exec) for safety - no shell interpretation\n const onError = (err: Error | null) => {\n if (err) {\n console.error(`[ctxo] Could not open browser: ${err.message}`);\n console.error(`[ctxo] Open manually: ${filePath}`);\n }\n };\n\n if (process.platform === 'win32') {\n execFile('cmd.exe', ['/c', 'start', '', filePath], onError);\n } else if (process.platform === 'darwin') {\n execFile('open', [filePath], onError);\n } else {\n execFile('xdg-open', [filePath], onError);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAAA,gBAAc,cAAAC,oBAAkB;AACzC,SAAS,WAAAC,UAAS,QAAAC,cAAY;;;ACD9B,SAAS,gBAAAC,qBAAoB;AAC7B,SAAS,gBAAAC,eAAc,iBAAAC,gBAAe,cAAAC,aAAY,UAAU,eAAAC,oBAAmB;AAC/E,SAAS,QAAAC,OAAM,UAAU,WAAAC,gBAAe;AACxC,SAAS,iBAAAC,sBAAqB;;;ACH9B,SAAS,kBAAkB;AAEpB,IAAM,gBAAN,MAAoB;AAAA,EACzB,KAAK,SAAyB;AAC5B,WAAO,WAAW,QAAQ,EAAE,OAAO,SAAS,OAAO,EAAE,OAAO,KAAK;AA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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA4BP,KAAK,CAAC;AAAA,EACN;AACF;","names":["readFileSync","existsSync","dirname","join","execFileSync","readFileSync","writeFileSync","existsSync","readdirSync","join","extname","createRequire","existsSync","readFileSync","dirname","log","readFileSync","existsSync","dirname","existsSync","join","existsSync","extname","join","existsSync","readFileSync","dirname","join","existsSync","join","resolve","existsSync","dirname","join","resolve","readFileSync","writeFileSync","existsSync","mkdirSync","join","dirname","createRequire","join","readFileSync","execFileSync","existsSync","readdirSync","extname","writeFileSync","join","join","join","existsSync","execFileSync","join","existsSync","execFileSync","join","join","join","existsSync","readFileSync","writeFileSync","mkdirSync","createRequire","existsSync","readFileSync","writeFileSync","mkdirSync","join","dirname","updated","requireCjs","createRequire","join","mkdirSync","existsSync","readFileSync","require","writeFileSync","join","extname","relative","readFileSync","join","relative","commits","intent","antiPatterns","source","readFileSync","fileIndex","extname","join","existsSync","readFileSync","join","existsSync","readFileSync","writeFileSync","join","existsSync","log","createRequire","require","SUPPORTED_API_VERSION","SUPPORTED_API_VERSION","createRequire","require","createRequire","execFileSync","existsSync","join","existsSync","execFileSync","join","pass","warn","join","existsSync","execFileSync","existsSync","readFileSync","join","initSqlJs","existsSync","readFileSync","join","join","existsSync","readFileSync","existsSync","readdirSync","statSync","join","execFileSync","existsSync","mkdirSync","rmSync","unlinkSync","createRequire","dirname","join","join","existsSync","listGitFiles","unlinkSync","dirname","rmSync","execFileSync","createRequire","mkdirSync","join","getVersion","existsSync","readFileSync","writeFileSync","existsSync","join","join","readFileSync","writeFileSync","existsSync","join","existsSync","readFileSync","dirname"]}