@ctxo/cli 0.10.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -0
- package/dist/{atomic-write-AQNYJFAG.js → atomic-write-BAFH464Q.js} +3 -2
- package/dist/chunk-5DSKZJNN.js +38 -0
- package/dist/chunk-5DSKZJNN.js.map +1 -0
- package/dist/{chunk-2TVHKCCU.js → chunk-CDGQGCVN.js} +55 -5
- package/dist/chunk-CDGQGCVN.js.map +1 -0
- package/dist/{chunk-I6HLEK4G.js → chunk-HZ4UGA6J.js} +43 -9
- package/dist/chunk-HZ4UGA6J.js.map +1 -0
- package/dist/{chunk-6EKERTJ7.js → chunk-RFEXMBTG.js} +4 -36
- package/dist/chunk-RFEXMBTG.js.map +1 -0
- package/dist/{cli-router-45W4IRYE.js → cli-router-NFAGLJ46.js} +389 -209
- package/dist/cli-router-NFAGLJ46.js.map +1 -0
- package/dist/index.js +7 -6
- package/dist/index.js.map +1 -1
- package/dist/json-index-reader-UYS74USB.js +9 -0
- package/llms-full.txt +2 -1
- package/llms.txt +1 -0
- package/package.json +4 -4
- package/dist/chunk-2TVHKCCU.js.map +0 -1
- package/dist/chunk-6EKERTJ7.js.map +0 -1
- package/dist/chunk-I6HLEK4G.js.map +0 -1
- package/dist/cli-router-45W4IRYE.js.map +0 -1
- package/dist/json-index-reader-XOEE6VMD.js +0 -8
- /package/dist/{atomic-write-AQNYJFAG.js.map → atomic-write-BAFH464Q.js.map} +0 -0
- /package/dist/{json-index-reader-XOEE6VMD.js.map → json-index-reader-UYS74USB.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
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/core/install/run-package-manager.ts","../src/core/detection/detect-java-runtime.ts","../src/adapters/storage/json-index-writer.ts","../src/adapters/storage/schema-manager.ts","../src/adapters/storage/architecture-artifacts-writer.ts","../src/core/overlay/community-detector.ts","../src/core/overlay/community-labeler.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/java-tier-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","../src/cli/graph-loader.ts","../src/cli/update-command.ts","../src/core/update/registry-client.ts","../src/core/update/update-plan.ts","../src/cli/blast-radius-command.ts","../src/cli/gate-hook-command.ts","../src/core/gate/gate-config.ts","../src/core/gate/symbol-locator.ts","../src/core/gate/transcript-scan.ts","../src/adapters/gate/gate-session-store.ts","../src/core/gate/percentile.ts","../src/core/gate/gate-decision.ts","../src/cli/gate-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';\nimport { UpdateCommand } from './update-command.js';\nimport { BlastRadiusCommand } from './blast-radius-command.js';\nimport { GateHookCommand } from './gate-hook-command.js';\nimport { GateCommand } from './gate-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 skipCommunity = args.includes('--skip-community');\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 skipCommunity,\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 === '--full-tier') flagValues['fullTier'] = true;\n else if (a === '--syntax-only') flagValues['syntaxOnly'] = 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 fullTier: flagValues['fullTier'] === true,\n syntaxOnly: flagValues['syntaxOnly'] === 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 'update': {\n const flagValues: Record<string, string | boolean> = {};\n for (let i = 1; i < args.length; i++) {\n const a = args[i]!;\n if (a === '--check') flagValues['check'] = true;\n else if (a === '--print') flagValues['print'] = true;\n else if (a === '--global' || a === '-g') flagValues['global'] = true;\n else if (a === '--json') flagValues['json'] = 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 {\n console.error(`[ctxo] Unknown update flag: ${a}`);\n process.exit(1);\n return;\n }\n }\n await new UpdateCommand(this.projectRoot, {\n setExitCode: (code: number) => { process.exitCode = code; },\n }).run({\n check: flagValues['check'] === true,\n print: flagValues['print'] === true,\n global: flagValues['global'] === true,\n json: flagValues['json'] === true,\n force: flagValues['force'] === true,\n pm: typeof flagValues['pm'] === 'string' ? flagValues['pm'] : undefined,\n });\n break;\n }\n\n case 'gate': {\n if (args.includes('--preview')) {\n new GateCommand(this.projectRoot).preview({ json: args.includes('--json') });\n } else {\n console.error('[ctxo] usage: ctxo gate --preview [--json]');\n process.exit(1);\n }\n break;\n }\n\n case 'gate-hook':\n await new GateHookCommand(this.projectRoot).run();\n break;\n\n case 'blast-radius': {\n const symbolId = args[1];\n if (!symbolId || symbolId.startsWith('--')) {\n console.error('[ctxo] usage: ctxo blast-radius <symbolId> [--json]');\n process.exit(1);\n return;\n }\n new BlastRadiusCommand(this.projectRoot).run({ symbolId, json: args.includes('--json') });\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 index --skip-community Skip Louvain community detection for faster indexing\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 update Check + apply updates for ctxo + plugins\n ctxo update --check Check only, no install\n ctxo update --print Print install command, never execute\n ctxo update --global Force a global install\n ctxo update --json Machine-readable output\n ctxo update --pm <pm> Override package manager (npm|pnpm|yarn|bun)\n ctxo update --force Bypass CI lockfile guard\n ctxo blast-radius <symbolId> Blast radius for one symbol (--json for machine output)\n ctxo gate --preview Preview which symbols the safe-edit guard would block\n ctxo gate --preview --json Same, machine-readable output\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 { JsonIndexReader } from '../adapters/storage/json-index-reader.js';\nimport { SqliteStorageAdapter } from '../adapters/storage/sqlite-storage-adapter.js';\nimport { SchemaManager } from '../adapters/storage/schema-manager.js';\nimport { ArchitectureArtifactsWriter } from '../adapters/storage/architecture-artifacts-writer.js';\nimport { CommunitySnapshotWriter } from '../adapters/storage/community-snapshot-writer.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 { CommunityDetector } from '../core/overlay/community-detector.js';\nimport { DriftDetector } from '../core/overlay/drift-detector.js';\nimport { BoundaryViolationDetector } from '../core/overlay/boundary-violation-detector.js';\nimport { SymbolGraph } from '../core/graph/symbol-graph.js';\nimport { PageRankCalculator } from '../core/importance/pagerank-calculator.js';\nimport type {\n BoundaryViolationsArtifact,\n CommunitySnapshot,\n DriftEventsArtifact,\n EdgeQuality,\n FileIndex,\n SymbolKind,\n} 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\ninterface JavaCompositeLike {\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 skipCommunity?: 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, javaTier } = 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 // Pre-Phase 0: sweep orphan .<pid>.tmp files from a previous interrupted write.\n try {\n const { sweepStaleTmpFiles } = await import('../adapters/storage/atomic-write.js');\n const swept = sweepStaleTmpFiles(join(this.ctxoRoot, 'index'));\n if (swept > 0) {\n console.error(`[ctxo] Cleaned ${swept} orphan .tmp file(s) from previous interrupted run`);\n }\n } catch {\n /* non-fatal */\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 2c: Community detection + snapshot\n //\n // Full indexing: run Louvain over pendingIndices (all indexed files).\n // Incremental (--file): merge the just-updated fileIndex(es) with the rest of the committed\n // JSON index on disk so Louvain sees the *complete* graph. Running it\n // over the 1-file subgraph alone would produce a meaningless\n // N-singleton snapshot (modularity 0).\n // Opt-out (--skip-community): skip entirely. Warn if a stale snapshot exists on disk.\n let communitySnapshot: CommunitySnapshot | undefined;\n\n if (options.skipCommunity && pendingIndices.length > 0) {\n if (existsSync(join(this.ctxoRoot, 'index', 'communities.json'))) {\n console.error(\n `[ctxo] WARN stale communities.json present — --skip-community preserved existing snapshot. Run \\`ctxo index\\` (full) to refresh.`,\n );\n }\n } else if (pendingIndices.length > 0) {\n try {\n const graphIndices = this.buildGraphInputIndices(pendingIndices);\n communitySnapshot = this.buildCommunitySnapshot(\n graphIndices,\n {\n csharpTier,\n goTier,\n javaTier,\n tsCount: graphIndices.filter((idx) => /\\.(ts|tsx|js|jsx)$/.test(idx.file)).length,\n },\n gitAdapter,\n );\n const scope = options.file ? ' (incremental, full-graph recompute)' : '';\n console.error(\n `[ctxo] Community detection${scope}: ${countCommunities(communitySnapshot)} clusters (modularity ${communitySnapshot.modularity.toFixed(3)})`,\n );\n } catch (err) {\n console.error(`[ctxo] Community detection skipped: ${(err as Error).message}`);\n }\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, { allowProductionPath: true });\n try {\n await storage.initEmpty();\n storage.bulkWrite(indices);\n if (communitySnapshot) {\n storage.writeCommunities(communitySnapshot);\n }\n } finally {\n storage.close();\n }\n\n // Phase 2d: Persist derived architectural artifacts (drift events + boundary\n // violations). These are computed AFTER `writeCommunities` so that the\n // freshly-archived previous snapshot is available at history[0]. Consumers:\n // - pages/ctxo-visualizer.html Architecture tab reads these directly.\n // - Future MCP tools can surface the same data without recomputing.\n if (communitySnapshot) {\n this.writeArchitectureArtifacts(indices, communitySnapshot);\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 const javaCount = pendingIndices.filter(e => e.relativePath.endsWith('.java')).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 if (javaCount > 0) console.error(`[ctxo] Java: ${javaCount} files (${javaTier} tier${javaTier === 'syntax' ? ' - JRE 17+ & \"ctxo install java --full-tier\" 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 javaTier: 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 let javaTier = '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 // Duck-type: JavaCompositeAdapter exposes tier info\n const javaCandidate = adapter as unknown as Partial<JavaCompositeLike>;\n if (plugin.id === 'java' && typeof javaCandidate.getTier === 'function') {\n javaTier = javaCandidate.getTier();\n }\n\n const activeTier =\n plugin.id === 'csharp' ? csharpTier :\n plugin.id === 'go' ? goTier :\n plugin.id === 'java' ? javaTier :\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, javaTier };\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 // `git ls-files --cached` still lists files that have been deleted in\n // the working tree but whose removal isn't staged yet. Filter those out\n // so we don't spam ENOENT errors from readFileSync on stale entries.\n .filter((abs) => existsSync(abs));\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 console.error(`[ctxo] STALE: ${relativePath} (content hash differs)`);\n } else {\n // Legacy index: contentHash wasn't populated yet. We cannot tell whether\n // the mtime bump reflects real content change — fail closed, but tell the user why.\n console.error(\n `[ctxo] STALE: ${relativePath} (index predates contentHash — run \\`ctxo index\\` once to enable mtime-tolerant checks)`,\n );\n }\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 /**\n * Produce the FileIndex list used as input to community detection.\n *\n * Full index run: returns pendingIndices as-is — they already cover every file.\n * Incremental `--file` run: pendingIndices holds only the just-updated file(s). We load the\n * rest of the committed JSON index from disk and splice in the fresh in-memory indices so\n * Louvain sees the COMPLETE project graph. Without this, Louvain would run on a 1-file\n * subgraph and emit a meaningless modularity-0 snapshot.\n */\n private buildGraphInputIndices(\n pendingIndices: ReadonlyArray<{ relativePath: string; fileIndex: FileIndex }>,\n ): FileIndex[] {\n const pendingByPath = new Map<string, FileIndex>();\n for (const { fileIndex } of pendingIndices) {\n pendingByPath.set(fileIndex.file, fileIndex);\n }\n\n const reader = new JsonIndexReader(this.ctxoRoot);\n const committed = reader.readAll();\n\n const merged: FileIndex[] = [];\n for (const idx of committed) {\n const override = pendingByPath.get(idx.file);\n if (override) {\n merged.push(override);\n pendingByPath.delete(idx.file);\n } else {\n merged.push(idx);\n }\n }\n // Newly indexed files (no prior committed entry) get appended.\n for (const remaining of pendingByPath.values()) merged.push(remaining);\n return merged;\n }\n\n private buildCommunitySnapshot(\n indices: readonly FileIndex[],\n tiers: { csharpTier: string; goTier: string; javaTier: string; tsCount: number },\n gitAdapter: SimpleGitAdapter,\n ): CommunitySnapshot {\n const graph = new SymbolGraph();\n for (const fileIndex of indices) {\n for (const symbol of fileIndex.symbols) graph.addNode(symbol);\n }\n for (const fileIndex of indices) {\n for (const edge of fileIndex.edges) graph.addEdge(edge);\n }\n\n const pagerank = new PageRankCalculator().calculate(graph, { limit: graph.nodeCount });\n const pagerankMap = new Map<string, number>();\n for (const entry of pagerank.rankings) pagerankMap.set(entry.symbolId, entry.score);\n\n const detector = new CommunityDetector();\n const edgeQuality = pickEdgeQuality(tiers);\n const detectResult = detector.detect(graph, pagerankMap, edgeQuality);\n\n return {\n version: 1,\n computedAt: new Date().toISOString(),\n commitSha: safeHeadSha(gitAdapter),\n modularity: detectResult.modularity,\n communities: detectResult.communities,\n godNodes: detectResult.godNodes,\n edgeQuality: detectResult.edgeQuality,\n crossClusterEdges: detectResult.crossClusterEdges,\n };\n }\n\n /**\n * Writes drift-events.json and boundary-violations.json next to\n * communities.json. Must be called AFTER storage.writeCommunities so the\n * prior snapshot has already been archived into communities.history/ and\n * can serve as history[0] for the detectors.\n */\n private writeArchitectureArtifacts(\n indices: readonly FileIndex[],\n snapshot: CommunitySnapshot,\n ): void {\n try {\n const snapshotWriter = new CommunitySnapshotWriter(this.ctxoRoot, {\n allowProductionPath: true,\n });\n const history = snapshotWriter.listHistory();\n\n const graph = new SymbolGraph();\n for (const fileIndex of indices) {\n for (const symbol of fileIndex.symbols) graph.addNode(symbol);\n }\n for (const fileIndex of indices) {\n for (const edge of fileIndex.edges) graph.addEdge(edge);\n }\n\n const driftResult = new DriftDetector().detect(snapshot, history);\n const violationsResult = new BoundaryViolationDetector().detect(\n graph,\n snapshot,\n history,\n );\n\n const computedAt = new Date().toISOString();\n const driftArtifact: DriftEventsArtifact = {\n version: 1,\n computedAt,\n commitSha: snapshot.commitSha,\n confidence: driftResult.confidence,\n snapshotsAvailable: driftResult.snapshotsAvailable,\n ...(driftResult.hint ? { hint: driftResult.hint } : {}),\n events: driftResult.events,\n };\n const violationsArtifact: BoundaryViolationsArtifact = {\n version: 1,\n computedAt,\n commitSha: snapshot.commitSha,\n confidence: violationsResult.confidence,\n snapshotsAvailable: violationsResult.snapshotsAvailable,\n ...(violationsResult.hint ? { hint: violationsResult.hint } : {}),\n violations: violationsResult.violations,\n };\n\n const writer = new ArchitectureArtifactsWriter(this.ctxoRoot, {\n allowProductionPath: true,\n });\n writer.writeDriftEvents(driftArtifact);\n writer.writeBoundaryViolations(violationsArtifact);\n\n console.error(\n `[ctxo] Architecture artifacts: ${driftResult.events.length} drift events, ` +\n `${violationsResult.violations.length} boundary violations ` +\n `(confidence: drift=${driftResult.confidence}, violations=${violationsResult.confidence})`,\n );\n } catch (err) {\n // Non-fatal: detectors failing must not break the core index.\n console.error(\n `[ctxo] Architecture artifacts skipped: ${(err as Error).message}`,\n );\n }\n }\n}\n\nfunction pickEdgeQuality(tiers: {\n csharpTier: string;\n goTier: string;\n javaTier: string;\n tsCount: number;\n}): EdgeQuality {\n const hasSyntaxOnly = tiers.csharpTier === 'syntax' || tiers.goTier === 'syntax' || tiers.javaTier === 'syntax';\n const hasFull =\n tiers.tsCount > 0 || tiers.csharpTier === 'full' || tiers.goTier === 'full' || tiers.javaTier === 'full';\n if (hasSyntaxOnly && hasFull) return 'mixed';\n if (hasSyntaxOnly) return 'syntax-only';\n return 'full';\n}\n\nfunction safeHeadSha(gitAdapter: SimpleGitAdapter): string {\n try {\n const maybeSha = (gitAdapter as unknown as { getHeadSha?: () => string | undefined }).getHeadSha?.();\n if (maybeSha) return maybeSha.slice(0, 8);\n } catch {\n /* fall through */\n }\n try {\n const out = execFileSync('git', ['rev-parse', '--short', 'HEAD'], { encoding: 'utf-8' });\n return out.trim();\n } catch {\n return 'nocommit';\n }\n}\n\nfunction countCommunities(snapshot: CommunitySnapshot): number {\n const ids = new Set<number>();\n for (const entry of snapshot.communities) ids.add(entry.communityId);\n return ids.size;\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 { createRequire } from 'node:module';\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\ntype ExportsEntry = string | { [condition: string]: ExportsEntry } | null | undefined;\n\nfunction pickEsmEntry(exportsField: unknown): string | undefined {\n if (!exportsField) return undefined;\n if (typeof exportsField === 'string') return exportsField;\n if (typeof exportsField !== 'object') return undefined;\n const table = exportsField as Record<string, ExportsEntry>;\n const dot = '.' in table ? table['.'] : (exportsField as ExportsEntry);\n if (typeof dot === 'string') return dot;\n if (!dot || typeof dot !== 'object') return undefined;\n for (const key of ['import', 'node', 'default'] as const) {\n const nested = (dot as Record<string, ExportsEntry>)[key];\n if (typeof nested === 'string') return nested;\n if (nested && typeof nested === 'object') {\n for (const inner of ['default', 'import', 'node'] as const) {\n const v = (nested as Record<string, ExportsEntry>)[inner];\n if (typeof v === 'string') return v;\n }\n }\n }\n return undefined;\n}\n\nconst cliFallbackRequire = createRequire(import.meta.url);\n\nfunction resolvePluginEntryUrl(\n specifier: string,\n manifestRequire: NodeJS.Require,\n): string {\n // Resolve bare specifiers against the consumer project's node_modules first,\n // not the CLI bundle location. Matters when `ctxo` runs via npx, where plain\n // import() would look in ~/.npm/_npx/<hash>/node_modules. We anchor via\n // `${spec}/package.json` because `require.resolve(spec)` fails for ESM-only\n // packages whose \"exports\" map has no \"require\" condition. Fall back to the\n // CLI's own location so dev/test flows (where the CLI source lives inside\n // the plugin's monorepo) still resolve without a populated node_modules.\n let pkgJsonPath: string;\n try {\n pkgJsonPath = manifestRequire.resolve(`${specifier}/package.json`);\n } catch (primary) {\n try {\n pkgJsonPath = cliFallbackRequire.resolve(`${specifier}/package.json`);\n } catch {\n throw primary;\n }\n }\n const pkgDir = dirname(pkgJsonPath);\n const pkgJson = JSON.parse(readFileSync(pkgJsonPath, 'utf-8')) as {\n main?: string;\n module?: string;\n exports?: unknown;\n };\n const entry = pickEsmEntry(pkgJson.exports) ?? pkgJson.module ?? pkgJson.main ?? 'index.js';\n return pathToFileURL(resolve(pkgDir, entry)).href;\n}\n\nasync function tryLoad(\n specifier: string,\n baseDir: string,\n manifestRequire: NodeJS.Require,\n): Promise<CtxoLanguagePlugin | PluginLoadFailure> {\n try {\n const target = isLocalSpecifier(specifier)\n ? pathToFileURL(resolve(baseDir, specifier)).href\n : resolvePluginEntryUrl(specifier, manifestRequire);\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 const manifestRequire = createRequire(pathToFileURL(manifestPath).href);\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, manifestRequire);\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 { 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 isWorkspaceRoot,\n PACKAGE_MANAGERS,\n type PackageManager,\n type Resolution,\n} from '../core/install/package-manager.js';\nimport { runPackageManager } from '../core/install/run-package-manager.js';\nimport { javaRuntimeAvailable } from '../core/detection/detect-java-runtime.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 readonly fullTier?: boolean;\n readonly syntaxOnly?: boolean;\n}\n\n/** Decide the java package set from JRE availability + flags. Pure + unit-testable. */\nexport function resolveJavaPackages(opts: { jreAvailable: boolean; fullTier?: boolean; syntaxOnly?: boolean }): string[] {\n if (opts.fullTier && opts.syntaxOnly) throw new Error('Cannot combine --full-tier with --syntax-only.');\n const base = ['@ctxo/lang-java'];\n if (opts.syntaxOnly) return base;\n if (opts.fullTier || opts.jreAvailable) return [...base, '@ctxo/lang-java-analyzer'];\n return base;\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: string[] = [];\n for (const lang of resolvedLangs) {\n if (lang === 'java') {\n const jreAvailable = javaRuntimeAvailable();\n if (!jreAvailable && !options.fullTier && !options.syntaxOnly) {\n console.error('[ctxo] JRE 17+ not found; installing Java syntax tier. Install a JRE then run \"ctxo install java --full-tier\" for resolved call/use edges.');\n }\n let javaPkgs: string[];\n try {\n javaPkgs = resolveJavaPackages({ jreAvailable, fullTier: options.fullTier, syntaxOnly: options.syntaxOnly });\n } catch (err) {\n console.error(`[ctxo] ${(err as Error).message}`);\n process.exitCode = 1;\n return;\n }\n for (const pkg of javaPkgs) {\n specifiers.push(options.version ? `${pkg}@${options.version}` : pkg);\n }\n } else {\n specifiers.push(options.version ? `${officialPluginFor(lang)}@${options.version}` : officialPluginFor(lang));\n }\n }\n\n const invocation = buildInstallCommand(resolution.manager, specifiers, {\n global: options.global,\n workspaceRoot: !options.global && isWorkspaceRoot(this.projectRoot),\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 runPackageManager(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\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 * Read every dependency in `projectRoot`'s `package.json` whose version spec\n * starts with `workspace:` (pnpm / yarn workspaces convention, e.g.\n * `workspace:*`, `workspace:^`, `workspace:~`). Returns a Set of package names.\n *\n * Used by `ctxo update` to skip these packages: their source is local, so\n * \"upgrading\" them to a registry version would unlink the workspace and\n * silently downgrade you to whatever npm has published.\n */\nexport function readWorkspaceLinks(projectRoot: string): Set<string> {\n const links = new Set<string>();\n const pkgPath = join(projectRoot, 'package.json');\n if (!existsSync(pkgPath)) return links;\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8')) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n optionalDependencies?: Record<string, string>;\n };\n for (const group of [pkg.dependencies, pkg.devDependencies, pkg.peerDependencies, pkg.optionalDependencies]) {\n if (!group) continue;\n for (const [name, spec] of Object.entries(group)) {\n if (typeof spec === 'string' && spec.startsWith('workspace:')) {\n links.add(name);\n }\n }\n }\n return links;\n } catch {\n return links;\n }\n}\n\n/**\n * True when `projectRoot` is the root of a pnpm workspace. Detects either\n * `pnpm-workspace.yaml` (the explicit pnpm marker) or a `package.json` whose\n * `workspaces` field declares sub-packages. Required so `buildInstallCommand`\n * can append `-w` to pnpm add; pnpm 8+ refuses to install at the workspace\n * root without it (`ERR_PNPM_ADDING_TO_ROOT`).\n */\nexport function isWorkspaceRoot(projectRoot: string): boolean {\n if (existsSync(join(projectRoot, 'pnpm-workspace.yaml'))) return true;\n const pkgPath = join(projectRoot, 'package.json');\n if (!existsSync(pkgPath)) return false;\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8')) as { workspaces?: unknown };\n const ws = pkg.workspaces;\n if (Array.isArray(ws) && ws.length > 0) return true;\n if (ws && typeof ws === 'object' && Array.isArray((ws as { packages?: unknown }).packages)) return true;\n return false;\n } catch {\n return false;\n }\n}\n\nexport interface BuildInstallOptions {\n readonly global?: boolean;\n /**\n * True when the install is targeting the root of a pnpm/npm/yarn/bun\n * workspace. Adds `-w` for pnpm (required) and is a no-op for the others\n * (their CLIs do not error in the same way).\n */\n readonly workspaceRoot?: boolean;\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 * Pass `workspaceRoot: true` when running at the root of a pnpm workspace —\n * pnpm refuses to add to the root without `-w` (ERR_PNPM_ADDING_TO_ROOT).\n */\nexport function buildInstallCommand(\n manager: PackageManager,\n packages: readonly string[],\n options: BuildInstallOptions = {},\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 if (options.global) {\n return { command: 'pnpm', args: ['add', '-g', ...packages] };\n }\n if (options.workspaceRoot) {\n return { command: 'pnpm', args: ['add', '-D', '-w', ...packages] };\n }\n return { command: 'pnpm', args: ['add', '-D', ...packages] };\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 { spawn } from 'node:child_process';\n\n/**\n * Spawn a package manager (npm / pnpm / yarn / bun) with the given args.\n *\n * Windows note: package managers ship as `.cmd` (npm, pnpm, yarn) or `.exe`\n * (bun, and pnpm's native binary) shim files. `spawn('pnpm', args)` with\n * `shell: false` would fail to resolve the .cmd extension via PATHEXT, but\n * `shell: true` is now deprecated when combined with an argv array (DEP0190\n * in Node 22) because args are concatenated unescaped.\n *\n * To avoid the deprecation warning while still resolving the right binary,\n * we append the appropriate extension on Windows and call `spawn` with\n * `shell: false`. The args we pass come from `buildInstallCommand`, which\n * only produces package-manager subcommands and version specifiers — both\n * validated upstream (`isSafeVersionSpecifier` rejects shell metacharacters).\n * No interpolated user input ever reaches this function.\n */\nexport function runPackageManager(command: string, args: readonly string[], cwd: string): Promise<number> {\n const resolved = resolveBinary(command);\n return new Promise((resolve, reject) => {\n const child = spawn(resolved, [...args], { cwd, stdio: 'inherit', shell: false });\n child.on('exit', (code) => resolve(code ?? 0));\n child.on('error', (err) => reject(err));\n });\n}\n\nfunction resolveBinary(command: string): string {\n if (process.platform !== 'win32') return command;\n // bun ships as bun.exe on Windows; npm / pnpm / yarn ship as .cmd shims.\n if (command === 'bun') return 'bun.exe';\n return `${command}.cmd`;\n}\n","import { spawnSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\n\n/** Parse `java -version` text → major (handles 1.8 legacy). Pure/uncached. */\nexport function parseJavaMajor(output: string): number | undefined {\n const m = output.match(/version \"([^\"]+)\"/);\n if (!m) return undefined;\n const parts = m[1]!.split('.');\n const major = parts[0] === '1' && parts[1] ? parseInt(parts[1]!, 10) : parseInt(parts[0]!, 10);\n return Number.isNaN(major) ? undefined : major;\n}\n\n/** Module-level memo: undefined = not yet computed; null = computed as absent */\nlet _javaMajorCache: number | null | undefined = undefined;\n\n/**\n * Spawn `java -version` once (CTXO_JAVA_HOME → JAVA_HOME → PATH), return the\n * parsed major version. Returns undefined when java is not found or the\n * version string cannot be parsed. Always respects a 10 s timeout so\n * a hanging JVM on a broken JAVA_HOME / network mount cannot stall the CLI.\n *\n * Result is memoized at module scope after the first spawn — repeated calls\n * within the same process are free.\n */\nexport function detectJavaMajor(): number | undefined {\n if (_javaMajorCache !== undefined) {\n // null sentinel means \"computed, result was undefined\"\n return _javaMajorCache === null ? undefined : _javaMajorCache;\n }\n\n const home = process.env['CTXO_JAVA_HOME'] || process.env['JAVA_HOME'];\n const bin = home\n ? join(home, 'bin', process.platform === 'win32' ? 'java.exe' : 'java')\n : 'java';\n if (home && !existsSync(bin)) {\n _javaMajorCache = null;\n return undefined;\n }\n const r = spawnSync(bin, ['-version'], {\n encoding: 'utf-8',\n timeout: 10_000,\n windowsHide: true,\n });\n if (r.error || r.status === null) {\n _javaMajorCache = null;\n return undefined;\n }\n // java writes version to stderr; stdout may also carry it in some JVMs\n const major = parseJavaMajor(`${r.stderr ?? ''}${r.stdout ?? ''}`);\n _javaMajorCache = major ?? null;\n return major;\n}\n\n/**\n * Reset the memoized java major cache. Intended for tests only — allows\n * successive test cases to exercise different java-not-found / version\n * scenarios without cross-test contamination.\n */\nexport function resetJavaRuntimeCacheForTests(): void {\n _javaMajorCache = undefined;\n}\n\n/** True if a JRE >= 17 is reachable (CTXO_JAVA_HOME -> JAVA_HOME -> PATH). */\nexport function javaRuntimeAvailable(): boolean {\n return (detectJavaMajor() ?? 0) >= 17;\n}\n","import { mkdirSync, unlinkSync, existsSync } from 'node:fs';\nimport { dirname, join, resolve, sep } from 'node:path';\nimport type { FileIndex, CoChangeMatrix } from '../../core/types.js';\nimport { atomicWrite } from './atomic-write.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 atomicWrite(targetPath, content);\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 { existsSync, mkdirSync, readFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { tmpdir } from 'node:os';\nimport { createLogger } from '../../core/logger.js';\nimport type {\n BoundaryViolationsArtifact,\n DriftEventsArtifact,\n} from '../../core/types.js';\nimport { atomicWrite } from './atomic-write.js';\n\nconst log = createLogger('ctxo:architecture-artifacts');\n\nconst DRIFT_FILE_NAME = 'drift-events.json';\nconst VIOLATIONS_FILE_NAME = 'boundary-violations.json';\n\nexport interface ArchitectureArtifactsWriterOptions {\n /**\n * Acknowledge writes to a production `.ctxo/` root. Mirrors the guard in\n * CommunitySnapshotWriter so tests can't accidentally poison a real project.\n */\n readonly allowProductionPath?: boolean;\n}\n\n/**\n * Persists derived architectural-intelligence artifacts next to the\n * community snapshot. These files exist so the static HTML visualizer\n * (pages/ctxo-visualizer.html) can render the Architecture views without\n * re-running the detectors in the browser.\n *\n * Contracts:\n * - `drift-events.json` is overwritten on every index run.\n * - `boundary-violations.json` is overwritten on every index run.\n * - Both are derived — no history rotation needed (history lives in\n * communities.history/ and the detectors recompute from there).\n */\nexport class ArchitectureArtifactsWriter {\n private readonly indexDir: string;\n\n constructor(ctxoRoot: string, options: ArchitectureArtifactsWriterOptions = {}) {\n this.indexDir = join(ctxoRoot, 'index');\n assertSafeWritePath(ctxoRoot, options.allowProductionPath ?? false);\n }\n\n writeDriftEvents(artifact: DriftEventsArtifact): void {\n mkdirSync(this.indexDir, { recursive: true });\n atomicWrite(join(this.indexDir, DRIFT_FILE_NAME), JSON.stringify(artifact, null, 2));\n }\n\n writeBoundaryViolations(artifact: BoundaryViolationsArtifact): void {\n mkdirSync(this.indexDir, { recursive: true });\n atomicWrite(join(this.indexDir, VIOLATIONS_FILE_NAME), JSON.stringify(artifact, null, 2));\n }\n\n readDriftEvents(): DriftEventsArtifact | undefined {\n const path = join(this.indexDir, DRIFT_FILE_NAME);\n if (!existsSync(path)) return undefined;\n try {\n return JSON.parse(readFileSync(path, 'utf-8')) as DriftEventsArtifact;\n } catch (err) {\n log.warn(`failed to parse ${DRIFT_FILE_NAME}: ${(err as Error).message}`);\n return undefined;\n }\n }\n\n readBoundaryViolations(): BoundaryViolationsArtifact | undefined {\n const path = join(this.indexDir, VIOLATIONS_FILE_NAME);\n if (!existsSync(path)) return undefined;\n try {\n return JSON.parse(readFileSync(path, 'utf-8')) as BoundaryViolationsArtifact;\n } catch (err) {\n log.warn(`failed to parse ${VIOLATIONS_FILE_NAME}: ${(err as Error).message}`);\n return undefined;\n }\n }\n}\n\nfunction assertSafeWritePath(ctxoRoot: string, allowProductionPath: boolean): void {\n const resolvedRoot = resolve(ctxoRoot);\n const resolvedTmp = resolve(tmpdir());\n if (resolvedRoot.startsWith(resolvedTmp)) return;\n if (allowProductionPath) return;\n throw new Error(\n `ArchitectureArtifactsWriter: refusing to write to non-tmp path ${resolvedRoot}. ` +\n `Pass { allowProductionPath: true } for production CLI writes, ` +\n `or target a tmpdir-based path in tests.`,\n );\n}\n","import { UndirectedGraph } from 'graphology';\nimport type { DetailedLouvainOutput, LouvainOptions } from 'graphology-communities-louvain';\nimport louvainModule from 'graphology-communities-louvain';\n\ntype LouvainGraph = UndirectedGraph;\n\ninterface LouvainRunner {\n detailed(graph: LouvainGraph, options?: LouvainOptions): DetailedLouvainOutput;\n}\n\n// graphology-communities-louvain is a CJS module exposed via default export; under\n// Node16 module resolution the TS type is the module namespace, so we normalize here.\nconst louvain: LouvainRunner =\n ((louvainModule as unknown) as { default?: LouvainRunner }).default ??\n (louvainModule as unknown as LouvainRunner);\n\nimport type { SymbolGraph } from '../graph/symbol-graph.js';\nimport type { CommunityEntry, EdgeQuality, GodNode } from '../types.js';\nimport { labelCommunities } from './community-labeler.js';\n\nexport interface CommunityComputeResult {\n readonly communities: CommunityEntry[];\n readonly godNodes: GodNode[];\n readonly modularity: number;\n readonly crossClusterEdges: number;\n readonly edgeQuality: EdgeQuality;\n}\n\nexport interface CommunityDetectorOptions {\n readonly resolution?: number;\n readonly godNodeMinBridged?: number;\n readonly godNodeMaxResults?: number;\n}\n\nconst DEFAULT_RESOLUTION = 1.0;\nconst DEFAULT_GOD_NODE_MIN_BRIDGED = 3;\nconst DEFAULT_GOD_NODE_MAX_RESULTS = 25;\n\nexport class CommunityDetector {\n private readonly resolution: number;\n private readonly godNodeMinBridged: number;\n private readonly godNodeMaxResults: number;\n\n constructor(options: CommunityDetectorOptions = {}) {\n this.resolution = options.resolution ?? DEFAULT_RESOLUTION;\n this.godNodeMinBridged = options.godNodeMinBridged ?? DEFAULT_GOD_NODE_MIN_BRIDGED;\n this.godNodeMaxResults = options.godNodeMaxResults ?? DEFAULT_GOD_NODE_MAX_RESULTS;\n }\n\n detect(\n graph: SymbolGraph,\n pagerank: ReadonlyMap<string, number>,\n edgeQuality: EdgeQuality = 'full',\n ): CommunityComputeResult {\n const nodes = graph.allNodes();\n if (nodes.length === 0) {\n return {\n communities: [],\n godNodes: [],\n modularity: 0,\n crossClusterEdges: 0,\n edgeQuality,\n };\n }\n\n // Sort for determinism. Louvain result depends on node insertion order.\n // Use codepoint comparison (NOT localeCompare) — localeCompare is\n // locale-sensitive and can produce different orders on different machines\n // (e.g., Turkish locale treats dotted/dotless i specially), which would\n // poison snapshot drift comparisons across teammates or CI runners.\n const sortedNodes = [...nodes].sort((a, b) =>\n a.symbolId < b.symbolId ? -1 : a.symbolId > b.symbolId ? 1 : 0,\n );\n\n const gph = new UndirectedGraph();\n for (const node of sortedNodes) {\n gph.addNode(node.symbolId);\n }\n\n // Collapse directed edges to undirected weights. A→B and B→A contribute to same undirected edge.\n const weightByPair = new Map<string, number>();\n for (const edge of graph.allEdges()) {\n if (edge.from === edge.to) continue;\n if (!gph.hasNode(edge.from) || !gph.hasNode(edge.to)) continue;\n const [a, b] = edge.from < edge.to ? [edge.from, edge.to] : [edge.to, edge.from];\n const key = `${a}|${b}`;\n weightByPair.set(key, (weightByPair.get(key) ?? 0) + 1);\n }\n\n for (const [key, weight] of weightByPair) {\n const [from, to] = key.split('|') as [string, string];\n gph.addEdge(from, to, { weight });\n }\n\n if (gph.size === 0) {\n return {\n communities: this.singletonCommunities(sortedNodes),\n godNodes: [],\n modularity: 0,\n crossClusterEdges: 0,\n edgeQuality,\n };\n }\n\n const result = louvain.detailed(gph, {\n resolution: this.resolution,\n randomWalk: false,\n fastLocalMoves: true,\n getEdgeWeight: 'weight',\n });\n\n const rawAssignments = result.communities as Record<string, number>;\n const splitAssignments = this.splitDisconnectedCommunities(gph, rawAssignments);\n const normalizedAssignments = this.normalizeCommunityIds(splitAssignments, sortedNodes);\n\n const memberIndex = this.buildMemberIndex(normalizedAssignments);\n const labels = labelCommunities(memberIndex, pagerank);\n\n const communities: CommunityEntry[] = sortedNodes.map((node) => {\n const communityId = normalizedAssignments.get(node.symbolId) ?? 0;\n return {\n symbolId: node.symbolId,\n communityId,\n communityLabel: labels.get(communityId) ?? `community-${communityId}`,\n };\n });\n\n const crossClusterEdges = this.countCrossClusterEdges(graph, normalizedAssignments);\n const godNodes = this.detectGodNodes(graph, normalizedAssignments, pagerank);\n\n return {\n communities,\n godNodes,\n modularity: result.modularity,\n crossClusterEdges,\n edgeQuality,\n };\n }\n\n private singletonCommunities(nodes: ReadonlyArray<{ symbolId: string }>): CommunityEntry[] {\n return nodes.map((node, i) => ({\n symbolId: node.symbolId,\n communityId: i,\n communityLabel: `isolated-${i}`,\n }));\n }\n\n private splitDisconnectedCommunities(\n gph: LouvainGraph,\n assignments: Record<string, number>,\n ): Map<string, number> {\n const result = new Map<string, number>();\n const membersByCommunity = new Map<number, string[]>();\n for (const [node, communityId] of Object.entries(assignments)) {\n const list = membersByCommunity.get(communityId) ?? [];\n list.push(node);\n membersByCommunity.set(communityId, list);\n }\n\n let nextCommunityId = 0;\n const sortedCommunities = [...membersByCommunity.entries()].sort(([a], [b]) => a - b);\n\n for (const [, members] of sortedCommunities) {\n const visited = new Set<string>();\n for (const start of [...members].sort()) {\n if (visited.has(start)) continue;\n const componentId = nextCommunityId++;\n const queue = [start];\n visited.add(start);\n while (queue.length > 0) {\n const node = queue.shift()!;\n result.set(node, componentId);\n for (const neighbor of gph.neighbors(node)) {\n if (visited.has(neighbor)) continue;\n if (!members.includes(neighbor)) continue;\n visited.add(neighbor);\n queue.push(neighbor);\n }\n }\n }\n }\n\n return result;\n }\n\n private normalizeCommunityIds(\n assignments: Map<string, number>,\n sortedNodes: ReadonlyArray<{ symbolId: string }>,\n ): Map<string, number> {\n const remap = new Map<number, number>();\n const result = new Map<string, number>();\n let nextId = 0;\n for (const node of sortedNodes) {\n const raw = assignments.get(node.symbolId);\n if (raw === undefined) {\n result.set(node.symbolId, nextId);\n remap.set(nextId, nextId);\n nextId++;\n continue;\n }\n let normalized = remap.get(raw);\n if (normalized === undefined) {\n normalized = nextId++;\n remap.set(raw, normalized);\n }\n result.set(node.symbolId, normalized);\n }\n return result;\n }\n\n private buildMemberIndex(assignments: Map<string, number>): Map<number, string[]> {\n const index = new Map<number, string[]>();\n for (const [symbolId, communityId] of assignments) {\n const list = index.get(communityId) ?? [];\n list.push(symbolId);\n index.set(communityId, list);\n }\n for (const list of index.values()) list.sort();\n return index;\n }\n\n private countCrossClusterEdges(\n graph: SymbolGraph,\n assignments: Map<string, number>,\n ): number {\n let count = 0;\n for (const edge of graph.allEdges()) {\n const from = assignments.get(edge.from);\n const to = assignments.get(edge.to);\n if (from === undefined || to === undefined) continue;\n if (from !== to) count++;\n }\n return count;\n }\n\n private detectGodNodes(\n graph: SymbolGraph,\n assignments: Map<string, number>,\n pagerank: ReadonlyMap<string, number>,\n ): GodNode[] {\n const candidates: GodNode[] = [];\n for (const node of graph.allNodes()) {\n const ownCommunity = assignments.get(node.symbolId);\n if (ownCommunity === undefined) continue;\n const bridged = new Set<number>();\n const forward = graph.getForwardEdges(node.symbolId);\n const reverse = graph.getReverseEdges(node.symbolId);\n for (const edge of forward) {\n const other = assignments.get(edge.to);\n if (other !== undefined && other !== ownCommunity) bridged.add(other);\n }\n for (const edge of reverse) {\n const other = assignments.get(edge.from);\n if (other !== undefined && other !== ownCommunity) bridged.add(other);\n }\n if (bridged.size >= this.godNodeMinBridged) {\n const pr = pagerank.get(node.symbolId) ?? 0;\n candidates.push({\n symbolId: node.symbolId,\n bridgedCommunities: [...bridged].sort((a, b) => a - b),\n centralityScore: bridged.size * (pr > 0 ? pr : 1 / graph.nodeCount),\n });\n }\n }\n\n candidates.sort((a, b) => {\n if (b.centralityScore !== a.centralityScore) {\n return b.centralityScore - a.centralityScore;\n }\n return a.symbolId.localeCompare(b.symbolId);\n });\n\n return candidates.slice(0, this.godNodeMaxResults);\n }\n}\n","const MIN_PREFIX_SEGMENTS = 1;\nconst PATH_SEPARATOR = '/';\n\nexport function labelCommunities(\n membersByCommunity: ReadonlyMap<number, readonly string[]>,\n pagerank: ReadonlyMap<string, number>,\n): Map<number, string> {\n const labels = new Map<number, string>();\n const used = new Set<string>();\n\n for (const [communityId, members] of membersByCommunity) {\n const label = pickLabel(members, pagerank, used);\n labels.set(communityId, label);\n used.add(label);\n }\n\n return labels;\n}\n\nfunction pickLabel(\n members: readonly string[],\n pagerank: ReadonlyMap<string, number>,\n used: ReadonlySet<string>,\n): string {\n const files = members.map(extractFilePath).filter((file): file is string => Boolean(file));\n const prefixLabel = longestCommonPathPrefix(files);\n\n if (prefixLabel && !used.has(prefixLabel)) {\n return prefixLabel;\n }\n\n const topSymbol = pickTopByPagerank(members, pagerank);\n if (topSymbol) {\n const name = extractSymbolName(topSymbol);\n if (name) {\n const candidate = `${name} area`;\n if (!used.has(candidate)) return candidate;\n }\n }\n\n if (prefixLabel) {\n return disambiguate(prefixLabel, used);\n }\n\n return disambiguate('cluster', used);\n}\n\nfunction extractFilePath(symbolId: string): string | undefined {\n const parts = symbolId.split('::');\n return parts.length === 3 ? parts[0] : undefined;\n}\n\nfunction extractSymbolName(symbolId: string): string | undefined {\n const parts = symbolId.split('::');\n return parts.length === 3 ? parts[1] : undefined;\n}\n\nfunction longestCommonPathPrefix(files: readonly string[]): string | undefined {\n if (files.length === 0) return undefined;\n const normalized = files.map((file) => file.replace(/\\\\/g, PATH_SEPARATOR));\n const segments = normalized.map((file) => file.split(PATH_SEPARATOR));\n const first = segments[0]!;\n\n let matchLength = first.length;\n for (let i = 1; i < segments.length; i++) {\n const current = segments[i]!;\n matchLength = Math.min(matchLength, current.length);\n for (let j = 0; j < matchLength; j++) {\n if (current[j] !== first[j]) {\n matchLength = j;\n break;\n }\n }\n if (matchLength === 0) break;\n }\n\n // Drop the filename if the common prefix includes it.\n const fullMatch = matchLength === first.length && files.length === 1;\n const keep = fullMatch ? matchLength - 1 : matchLength;\n if (keep < MIN_PREFIX_SEGMENTS) return undefined;\n\n const prefix = first.slice(0, keep).join(PATH_SEPARATOR);\n return prefix.length > 0 ? prefix : undefined;\n}\n\nfunction pickTopByPagerank(\n members: readonly string[],\n pagerank: ReadonlyMap<string, number>,\n): string | undefined {\n let best: string | undefined;\n let bestScore = -1;\n for (const symbolId of members) {\n const score = pagerank.get(symbolId) ?? 0;\n if (score > bestScore || (score === bestScore && best !== undefined && symbolId < best)) {\n bestScore = score;\n best = symbolId;\n }\n }\n return best ?? members[0];\n}\n\nfunction disambiguate(base: string, used: ReadonlySet<string>): string {\n if (!used.has(base)) return base;\n let suffix = 2;\n while (used.has(`${base} (${suffix})`)) suffix++;\n return `${base} (${suffix})`;\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, { allowProductionPath: true });\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, installSkills, ensureClaudeHook } 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(\n stepNum,\n totalSteps,\n `Git Hooks ${pc.yellow('recommended')}`,\n 'Auto-updates index and community snapshots on every commit and pull.\\n Without hooks, architectural drift & boundary violation signals stay empty\\n until you re-run `ctxo index` manually (or start `ctxo watch`).',\n pc,\n ));\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\n if (!installGitHooks) {\n console.error('');\n console.error(pc.yellow(' ⚠ Drift & boundary-violation signals depend on repeated snapshots.'));\n console.error(pc.dim(' Options without hooks:'));\n console.error(pc.dim(' • run `ctxo watch` during development'));\n console.error(pc.dim(' • add `ctxo index --check` to CI'));\n console.error(pc.dim(' • run `ctxo init` again to install hooks later'));\n }\n console.error('');\n }\n\n // ── Guard prompt (claude-code only) ──\n let installGuard = false;\n if (!options.rulesOnly && (selectedTools as string[]).includes('claude-code')) {\n const guard = await clack.confirm({\n message: pc.cyan('Install the safe-edit guard? Blocks edits to high-impact symbols until blast radius is checked.'),\n initialValue: true,\n });\n if (clack.isCancel(guard)) { clack.cancel('Setup cancelled.'); process.exit(0); }\n installGuard = guard as boolean;\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 for (const sk of installSkills(this.projectRoot, toolId)) {\n results.push(`${pc.green('\\u2713')} ${pc.bold(sk.file)} ${pc.dim(sk.action + ' \\u2014 skill')}`);\n }\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 (installGuard) {\n const r = ensureClaudeHook(this.projectRoot);\n if (r.action !== 'skipped') results.push(`${pc.green('\\u2713')} ${pc.bold(r.file)} ${pc.dim(r.action + ' \\u2014 safe-edit guard')}`);\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')} ctxo index ${pc.dim('\\u2500 build codebase index')}`,\n `${pc.cyan('\\u25b6')} 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 for (const sk of installSkills(this.projectRoot, toolId)) {\n console.error(`[ctxo] \\u2713 ${sk.file} \\u2014 ${sk.action} (skill)`);\n }\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 if (!options.rulesOnly && toolIds.includes('claude-code')) {\n const r = ensureClaudeHook(this.projectRoot);\n if (r.action !== 'skipped') console.error(`[ctxo] \\u2713 ${r.file} \\u2014 ${r.action} (safe-edit guard)`);\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 if (!options.rulesOnly && toolIds.includes('claude-code')) {\n console.error(' .claude/settings.json (safe-edit guard hook)');\n console.error(' .claude/skills/ctxo-*/SKILL.md (skills)');\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\n/* ------------------------------------------------------------------ */\n/* Claude Code safe-edit gate hook */\n/* ------------------------------------------------------------------ */\n\nconst CTXO_HOOK_COMMAND = 'ctxo gate-hook';\n\nexport function ensureClaudeHook(projectRoot: string): InstallResult {\n const filePath = join(projectRoot, '.claude', 'settings.json');\n const dir = dirname(filePath);\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true });\n\n const ctxoEntry = { matcher: 'Edit', hooks: [{ type: 'command', command: CTXO_HOOK_COMMAND }] };\n\n if (!existsSync(filePath)) {\n writeFileSync(filePath, JSON.stringify({ hooks: { PreToolUse: [ctxoEntry] } }, null, 2) + '\\n', 'utf-8');\n return { file: '.claude/settings.json', action: 'created' };\n }\n\n let existing: Record<string, unknown>;\n try { existing = JSON.parse(readFileSync(filePath, 'utf-8')); }\n catch {\n writeFileSync(filePath, JSON.stringify({ hooks: { PreToolUse: [ctxoEntry] } }, null, 2) + '\\n', 'utf-8');\n return { file: '.claude/settings.json', action: 'updated' };\n }\n\n const hooks = (existing.hooks ?? {}) as Record<string, unknown>;\n const pre = (hooks.PreToolUse ?? []) as Array<{ hooks?: Array<{ command?: string }> }>;\n if (pre.some((e) => e.hooks?.some((h) => h.command === CTXO_HOOK_COMMAND))) {\n return { file: '.claude/settings.json', action: 'skipped' };\n }\n pre.push(ctxoEntry);\n hooks.PreToolUse = pre;\n existing.hooks = hooks;\n writeFileSync(filePath, JSON.stringify(existing, null, 2) + '\\n', 'utf-8');\n return { file: '.claude/settings.json', action: 'updated' };\n}\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 { id: 'gemini-cli', name: 'Gemini CLI', file: 'GEMINI.md', mode: 'append', detectPaths: ['.gemini/settings.json', 'GEMINI.md'], starred: false },\n { id: 'continue', name: 'Continue', file: '.continue/rules/ctxo.md', mode: 'create', detectPaths: ['.continue'], 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/* Skills */\n/* ------------------------------------------------------------------ */\n\nexport const SKILLS = ['ctxo-understand', 'ctxo-safe-edit', 'ctxo-review-pr'] as const;\n\n/** Platforms with a markdown skill/rule directory we can drop skills into. */\nconst SKILL_TARGET_DIR: Partial<Record<string, (root: string, skill: string) => string>> = {\n 'claude-code': (root, skill) => join(root, '.claude', 'skills', skill, 'SKILL.md'),\n cursor: (root, skill) => join(root, '.cursor', 'rules', `${skill}.mdc`),\n};\n\nfunction skillsSourceDir(): string {\n let dir = import.meta.dirname;\n for (let i = 0; i < 10; i++) {\n const candidate = join(dir, 'skills');\n if (existsSync(join(candidate, 'ctxo-safe-edit', 'SKILL.md'))) return candidate;\n const parent = join(dir, '..');\n if (parent === dir) break;\n dir = parent;\n }\n throw new Error('Could not locate ctxo skills/ directory.');\n}\n\nexport function installSkills(projectRoot: string, platformId: string): InstallResult[] {\n const target = SKILL_TARGET_DIR[platformId];\n if (!target) return [];\n const src = skillsSourceDir();\n const out: InstallResult[] = [];\n for (const skill of SKILLS) {\n const from = join(src, skill, 'SKILL.md');\n const to = target(projectRoot, skill);\n mkdirSync(dirname(to), { recursive: true });\n const existed = existsSync(to);\n writeFileSync(to, readFileSync(from, 'utf-8'), 'utf-8');\n out.push({ file: to, action: existed ? 'updated' : 'created' });\n }\n return out;\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\ngate:\n enabled: true\n sensitivity: balanced # strict | balanced | lenient\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 case 'gemini-cli':\n // Gemini CLI reads MCP servers from .gemini/settings.json (project) or ~/.gemini/settings.json (user).\n targets.set('.gemini/settings.json', { file: '.gemini/settings.json', serverKey: 'mcpServers' });\n break;\n case 'continue':\n // Continue reads each MCP server from a standalone file under .continue/mcpServers/.\n targets.set('.continue/mcpServers/ctxo.json', { file: '.continue/mcpServers/ctxo.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 { execFileSync } from 'node:child_process';\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 { SymbolGraph } from '../core/graph/symbol-graph.js';\nimport { PageRankCalculator } from '../core/importance/pagerank-calculator.js';\nimport { CommunityDetector } from '../core/overlay/community-detector.js';\nimport { loadConfig, watchSnapshotMinFileChanges } from '../core/config/load-config.js';\nimport type { FileIndex, CommitIntent, AntiPattern, CommunitySnapshot } from '../core/types.js';\nimport type { IIncrementalReindex, IncrementalReindexCapable } from '@ctxo/plugin-api';\n\nconst DEBOUNCE_MS = 300;\nconst COMMUNITY_SNAPSHOT_DEBOUNCE_MS = 5000;\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 const keepAliveByExt = new Map<string, IIncrementalReindex>();\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 // Generic feature detection: if the adapter exposes an incremental-reindex capability, use it\n const capable = adapter as unknown as Partial<IncrementalReindexCapable>;\n if (typeof capable.getIncrementalReindex === 'function') {\n const cap = capable.getIncrementalReindex();\n if (cap?.isReady() && (await cap.startKeepAlive())) {\n for (const ext of plugin.extensions) keepAliveByExt.set(ext.toLowerCase(), cap);\n console.error(`[ctxo] ${plugin.id} watch: keep-alive active (full tier, fast incremental re-index)`);\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, { allowProductionPath: true });\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 // Watch-time community snapshots cost ~1s of blocking CPU on 25K-symbol\n // monorepos (full PageRank + Louvain recompute). Only recompute once at\n // least `snapshotMinFileChanges` distinct files have been re-indexed\n // since the last snapshot, so rapid-fire saves don't stall the editor.\n const snapshotThreshold = watchSnapshotMinFileChanges(loadConfig(this.ctxoRoot).config);\n const pathsChangedSinceSnapshot = new Set<string>();\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 // Generic keep-alive path: use capability if registered for this file extension\n const cap = keepAliveByExt.get(extname(filePath).toLowerCase());\n if (cap?.isReady()) {\n const result = await cap.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 (keep-alive): ${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 let communitySnapshotTimer: NodeJS.Timeout | undefined;\n const scheduleCommunitySnapshot = () => {\n // Threshold skip — don't even arm the debounce timer unless enough\n // distinct files changed since the last accepted snapshot.\n if (pathsChangedSinceSnapshot.size < snapshotThreshold) return;\n\n if (communitySnapshotTimer) clearTimeout(communitySnapshotTimer);\n communitySnapshotTimer = setTimeout(() => {\n communitySnapshotTimer = undefined;\n if (pathsChangedSinceSnapshot.size < snapshotThreshold) return;\n const changedCount = pathsChangedSinceSnapshot.size;\n pathsChangedSinceSnapshot.clear();\n try {\n const snapshot = buildWatchCommunitySnapshot(storage);\n if (snapshot) {\n storage.writeCommunities(snapshot);\n console.error(\n `[ctxo] Community snapshot refreshed after ${changedCount} file change(s) (modularity ${snapshot.modularity.toFixed(3)})`,\n );\n }\n } catch (err) {\n console.error(`[ctxo] Community snapshot skipped: ${(err as Error).message}`);\n }\n }, COMMUNITY_SNAPSHOT_DEBOUNCE_MS);\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(async () => {\n pendingFiles.delete(filePath);\n await reindexFile(filePath);\n pathsChangedSinceSnapshot.add(filePath);\n scheduleCommunitySnapshot();\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 if (communitySnapshotTimer) clearTimeout(communitySnapshotTimer);\n // Shutdown all keep-alive capabilities (dedup via Set over Map values)\n const uniques = new Set(keepAliveByExt.values());\n const shutdowns = Promise.all([...uniques].map((c) => c.dispose()));\n shutdowns.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\nfunction buildWatchCommunitySnapshot(storage: SqliteStorageAdapter): CommunitySnapshot | undefined {\n const symbols = storage.getAllSymbols();\n if (symbols.length === 0) return undefined;\n const edges = storage.getAllEdges();\n\n const graph = new SymbolGraph();\n for (const symbol of symbols) graph.addNode(symbol);\n for (const edge of edges) graph.addEdge(edge);\n\n const pagerank = new PageRankCalculator().calculate(graph, { limit: graph.nodeCount });\n const pagerankMap = new Map<string, number>();\n for (const entry of pagerank.rankings) pagerankMap.set(entry.symbolId, entry.score);\n\n const detector = new CommunityDetector();\n const detectResult = detector.detect(graph, pagerankMap, 'full');\n\n return {\n version: 1,\n computedAt: new Date().toISOString(),\n commitSha: readHeadSha(),\n modularity: detectResult.modularity,\n communities: detectResult.communities,\n godNodes: detectResult.godNodes,\n edgeQuality: detectResult.edgeQuality,\n crossClusterEdges: detectResult.crossClusterEdges,\n };\n}\n\nfunction readHeadSha(): string {\n try {\n return execFileSync('git', ['rev-parse', '--short', 'HEAD'], { encoding: 'utf-8' }).trim();\n } catch {\n return 'nocommit';\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 { JavaTierCheck } from '../adapters/diagnostics/checks/java-tier-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 JavaTierCheck(),\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, { quiet: Boolean(options.quiet) });\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 interface HealthCheckerOptions {\n /** Suppress all per-check logger lines. The reporter still prints WARN/FAIL lines, so operators see them without the duplicated `[ctxo:doctor] ...` logger stream. */\n readonly quiet?: boolean;\n}\n\nexport class HealthChecker {\n private readonly checks: IHealthCheck[];\n private readonly quiet: boolean;\n\n constructor(checks: IHealthCheck[], options: HealthCheckerOptions = {}) {\n this.checks = checks;\n this.quiet = options.quiet ?? false;\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 if (!this.quiet) {\n log.info(`${r.id}: ${r.status.toUpperCase()} (${r.message})`);\n }\n return r;\n }\n const message = (outcome.reason as Error)?.message ?? 'Unknown error';\n if (!this.quiet) 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 { createRequire } from 'node:module';\nimport { existsSync, readdirSync } from 'node:fs';\nimport { join, dirname } from 'node:path';\nimport type { IHealthCheck, CheckContext, CheckResult } from '../../../core/diagnostics/types.js';\nimport { detectJavaMajor } from '../../../core/detection/detect-java-runtime.js';\n\nconst require = createRequire(import.meta.url);\n\nexport interface JavaTierInputs {\n hasJava: boolean;\n jreMajor: number | undefined;\n analyzerInstalled: boolean;\n}\n\n/** Pure decision: map (java-present, jre, analyzer) -> CheckResult. */\nexport function evaluateJavaTier(i: JavaTierInputs): CheckResult {\n const id = 'java_tier';\n const title = 'Java analysis tier';\n\n if (!i.hasJava) {\n return { id, title, status: 'pass', message: 'no Java sources detected' };\n }\n\n const jreOk = (i.jreMajor ?? 0) >= 17;\n\n if (jreOk && i.analyzerInstalled) {\n return { id, title, status: 'pass', message: `full tier (JRE ${i.jreMajor}, analyzer installed)` };\n }\n\n if (jreOk && !i.analyzerInstalled) {\n return {\n id,\n title,\n status: 'warn',\n message: `syntax tier (JRE ${i.jreMajor} present, analyzer missing)`,\n fix: 'Run \"ctxo install java --full-tier\" for resolved call/use edges',\n };\n }\n\n if (!jreOk && i.analyzerInstalled) {\n return {\n id,\n title,\n status: 'warn',\n message: 'syntax tier (analyzer installed but no JRE 17+)',\n fix: 'Install a JRE 17+ and ensure it is on PATH (or set JAVA_HOME)',\n };\n }\n\n // No JRE >=17, no analyzer — syntax tier only, no nag\n return {\n id,\n title,\n status: 'pass',\n message: 'syntax tier (install JRE 17+ and run \"ctxo install java --full-tier\" for full tier)',\n };\n}\n\n/**\n * Returns true only when the @ctxo/lang-java-analyzer package is installed\n * AND its actual JAR file (`jar/ctxo-jdt-analyzer.jar`) exists on disk.\n * A package-only install without a built/extracted jar is not sufficient for\n * the full-tier indexer — doctor must reflect that accurately.\n */\nexport function analyzerJarPresent(): boolean {\n try {\n const pkgJson = require.resolve('@ctxo/lang-java-analyzer/package.json');\n const jarPath = join(dirname(pkgJson), 'jar', 'ctxo-jdt-analyzer.jar');\n return existsSync(jarPath);\n } catch {\n return false;\n }\n}\n\n/** Directories that should never be descended into during a Java source scan. */\nconst SKIP_DIRS = new Set([\n 'node_modules', 'target', 'build', 'out', 'bin',\n '.git', '.ctxo', 'dist', 'coverage',\n]);\n\n/**\n * Shallow-bounded recursive search for any `.java` file under `root`.\n * Descends at most `maxDepth` directory levels (root = depth 0), skipping\n * SKIP_DIRS at every level. Stops and returns true as soon as one file is\n * found to keep the work bounded.\n *\n * Uses Dirent entries — no extra stat calls. Symlinked entries (both files\n * and directories) are skipped entirely to avoid following loops.\n */\nexport function findJavaFile(root: string, maxDepth: number): boolean {\n function walk(dir: string, depth: number): boolean {\n let entries: import('node:fs').Dirent[];\n try {\n entries = readdirSync(dir, { withFileTypes: true });\n } catch {\n return false;\n }\n for (const entry of entries) {\n if (entry.isSymbolicLink()) continue; // never follow symlinks\n if (entry.isFile() && entry.name.endsWith('.java')) return true;\n }\n if (depth >= maxDepth) return false;\n for (const entry of entries) {\n if (entry.isSymbolicLink()) continue;\n if (entry.isDirectory() && !SKIP_DIRS.has(entry.name)) {\n if (walk(join(dir, entry.name), depth + 1)) return true;\n }\n }\n return false;\n }\n return walk(root, 0);\n}\n\nfunction projectHasJava(root: string): boolean {\n for (const f of ['pom.xml', 'build.gradle', 'build.gradle.kts']) {\n if (existsSync(join(root, f))) return true;\n }\n return findJavaFile(root, 4);\n}\n\nexport class JavaTierCheck implements IHealthCheck {\n readonly id = 'java_tier';\n readonly title = 'Java analysis tier';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n return evaluateJavaTier({\n hasJava: projectHasJava(ctx.projectRoot),\n jreMajor: detectJavaMajor(),\n analyzerInstalled: analyzerJarPresent(),\n });\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 { ArchitectureArtifactsWriter } from '../adapters/storage/architecture-artifacts-writer.js';\nimport { CommunitySnapshotWriter } from '../adapters/storage/community-snapshot-writer.js';\nimport { loadGraph } from './graph-loader.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 {\n VisCommunityLegend,\n VisualizationPayload,\n VisNode,\n VisEdge,\n VisFileInfo,\n} from '../core/graph/visualization-payload.js';\nimport type { BoundaryViolation, CommunityEntry } from '../core/types.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 and build graph\n const { graph, indices } = loadGraph(this.ctxoRoot);\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 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 // 5b. Load community snapshot + boundary violations produced by `ctxo index`.\n // These are read-only here — the writer guards are opt-in.\n const communityWriter = new CommunitySnapshotWriter(this.ctxoRoot, {\n allowProductionPath: true,\n });\n const currentSnapshot = communityWriter.readCurrent();\n const communityByIdForSymbol = new Map<string, { id: number; label: string }>();\n if (currentSnapshot) {\n for (const entry of currentSnapshot.communities as readonly CommunityEntry[]) {\n communityByIdForSymbol.set(entry.symbolId, {\n id: entry.communityId,\n label: entry.communityLabel,\n });\n }\n }\n const architectureWriter = new ArchitectureArtifactsWriter(this.ctxoRoot, {\n allowProductionPath: true,\n });\n const violationsArtifact = architectureWriter.readBoundaryViolations();\n const violationEdgeSeverity = new Map<string, BoundaryViolation['severity']>();\n if (violationsArtifact) {\n for (const v of violationsArtifact.violations as readonly BoundaryViolation[]) {\n violationEdgeSeverity.set(\n `${v.from.symbolId}|${v.to.symbolId}`,\n v.severity,\n );\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 const community = communityByIdForSymbol.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 communityId: community?.id ?? -1,\n communityLabel: community?.label ?? 'unassigned',\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 => {\n const severity = violationEdgeSeverity.get(`${e.from}|${e.to}`);\n return {\n source: e.from,\n target: e.to,\n kind: e.kind,\n ...(severity ? { violationSeverity: severity } : {}),\n };\n });\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 // Build community legend restricted to communities with visible members.\n const legendCounts = new Map<number, { label: string; count: number }>();\n for (const node of nodes) {\n if (node.communityId < 0) continue;\n const entry = legendCounts.get(node.communityId);\n if (entry) {\n entry.count += 1;\n } else {\n legendCounts.set(node.communityId, { label: node.communityLabel, count: 1 });\n }\n }\n const communities: VisCommunityLegend[] = [...legendCounts.entries()]\n .map(([id, { label, count }]) => ({ id, label, memberCount: count }))\n .sort((a, b) => b.memberCount - a.memberCount);\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 communities,\n modularity: currentSnapshot?.modularity ?? 0,\n violationCount: violationsArtifact?.violations.length ?? 0,\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","import { JsonIndexReader } from '../adapters/storage/json-index-reader.js';\nimport { SymbolGraph } from '../core/graph/symbol-graph.js';\nimport type { FileIndex } from '../core/types.js';\n\nexport interface LoadedGraph {\n readonly graph: SymbolGraph;\n readonly indices: FileIndex[];\n}\n\n/** Build a SymbolGraph from the committed JSON index under `ctxoRoot`. */\nexport function loadGraph(ctxoRoot: string): LoadedGraph {\n const indices = new JsonIndexReader(ctxoRoot).readAll();\n const graph = new SymbolGraph();\n for (const fi of indices) for (const sym of fi.symbols) graph.addNode(sym);\n for (const fi of indices) for (const edge of fi.edges) graph.addEdge(edge);\n return { graph, indices };\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { getVersion } from './cli-router.js';\nimport { discoverPlugins } from '../adapters/language/plugin-discovery.js';\nimport { loadManifestPath } from './plugin-loader.js';\nimport { fetchDistTagsBatch, type HttpsFetcher } from '../core/update/registry-client.js';\nimport {\n computePackageStates,\n detectChannel,\n markWorkspaceLinks,\n selectInstallTargets,\n} from '../core/update/update-plan.js';\nimport {\n resolvePackageManager,\n buildInstallCommand,\n isPackageManager,\n isWorkspaceRoot,\n readWorkspaceLinks,\n} from '../core/install/package-manager.js';\nimport { runPackageManager } from '../core/install/run-package-manager.js';\nimport { createLogger } from '../core/logger.js';\nimport type { PackageManager, Resolution } from '../core/install/package-manager.js';\nimport type { PackageState, Channel } from '../core/update/update-plan.js';\n\nconst log = createLogger('ctxo:update');\nconst CTXO_CLI_PACKAGE = '@ctxo/cli';\n\nexport type UpdateStrategy = 'execute' | 'print' | 'none';\n\nexport interface UpdatePlanShape {\n readonly manager: PackageManager;\n readonly managerSource: Resolution['source'];\n readonly managerDetail?: string;\n readonly global: boolean;\n readonly command: string;\n readonly args: readonly string[];\n}\n\nexport interface UpdateReport {\n readonly ctxo: string;\n readonly channel: Channel;\n readonly packages: readonly PackageState[];\n readonly plan: UpdatePlanShape | null;\n readonly strategy: UpdateStrategy;\n readonly executed: boolean;\n readonly exitCode?: number;\n}\n\nexport function formatText(report: UpdateReport): string {\n const lines: string[] = [];\n lines.push('ctxo update — checking registry for updates...');\n lines.push('');\n\n const updatesExist = report.packages.some((p) => p.status === 'update');\n if (!updatesExist && report.strategy !== 'print') {\n const total = report.packages.length;\n lines.push(`All ${total} package${total === 1 ? '' : 's'} are up to date.`);\n return lines.join('\\n');\n }\n\n const latestCell = (p: PackageState): string => {\n if (p.status === 'workspace') return '(local)';\n return p.latest ?? '(not found)';\n };\n\n const nameCol = Math.max(7, ...report.packages.map((p) => p.name.length));\n const curCol = Math.max(7, ...report.packages.map((p) => p.current.length));\n const latestCol = Math.max(15, ...report.packages.map((p) => latestCell(p).length));\n\n lines.push(\n `${'PACKAGE'.padEnd(nameCol)} ${'CURRENT'.padEnd(curCol)} ${`LATEST (${report.channel})`.padEnd(latestCol)} STATUS`,\n );\n for (const pkg of report.packages) {\n const statusText = renderStatus(pkg, report.channel);\n lines.push(\n `${pkg.name.padEnd(nameCol)} ${pkg.current.padEnd(curCol)} ${latestCell(pkg).padEnd(latestCol)} ${statusText}`,\n );\n }\n\n if (report.plan && report.strategy === 'execute') {\n lines.push('');\n lines.push(`Plan: ${report.plan.command} ${report.plan.args.join(' ')}`);\n lines.push(`Using ${report.plan.manager} (${formatManagerSource(report.plan)})`);\n lines.push('');\n lines.push('Running...');\n } else if (report.plan && report.strategy === 'print') {\n lines.push('');\n lines.push('To update, run:');\n lines.push(` ${report.plan.command} ${report.plan.args.join(' ')}`);\n }\n\n return lines.join('\\n');\n}\n\nfunction renderStatus(pkg: PackageState, reportChannel: Channel): string {\n switch (pkg.status) {\n case 'current': return 'up to date';\n case 'ahead': return 'ahead of registry';\n case 'workspace': return 'workspace link';\n case 'unknown': return pkg.reason === 'registry-404' ? 'skipped' : `error${pkg.reason ? ` (${pkg.reason})` : ''}`;\n case 'update':\n return pkg.channel === reportChannel ? 'update' : `update (${pkg.channel})`;\n }\n}\n\nfunction formatManagerSource(plan: UpdatePlanShape): string {\n return plan.managerDetail ? `${plan.managerSource}: ${plan.managerDetail}` : plan.managerSource;\n}\n\nexport function formatJson(report: UpdateReport): string {\n return JSON.stringify(\n {\n ctxo: report.ctxo,\n channel: report.channel,\n packages: report.packages,\n plan: report.plan,\n executed: report.executed,\n ...(report.exitCode !== undefined ? { exitCode: report.exitCode } : {}),\n },\n null,\n 2,\n );\n}\n\nexport interface UpdateOptions {\n readonly check?: boolean;\n readonly print?: boolean;\n readonly global?: boolean;\n readonly json?: boolean;\n readonly pm?: string;\n readonly force?: boolean;\n}\n\nexport interface UpdateCommandDeps {\n readonly discoverInstalled?: (projectRoot: string) => Promise<ReadonlyArray<{ name: string; version: string }>>;\n readonly fetcher?: HttpsFetcher;\n readonly runner?: (command: string, args: readonly string[], cwd: string) => Promise<number>;\n readonly setExitCode?: (code: number) => void;\n readonly env?: NodeJS.ProcessEnv;\n}\n\nexport class UpdateCommand {\n constructor(\n private readonly projectRoot: string,\n private readonly deps: UpdateCommandDeps = {},\n ) {}\n\n async run(options: UpdateOptions = {}): Promise<void> {\n if (options.pm && !isPackageManager(options.pm)) {\n this.emitError(`Unknown --pm value \"${options.pm}\".`);\n this.deps.setExitCode?.(1);\n return;\n }\n\n const discover = this.deps.discoverInstalled ?? defaultDiscoverInstalled;\n const installed = await discover(this.projectRoot);\n if (installed.length === 0) {\n this.emit(options.json ? '{}\\n' : 'ctxo update — no @ctxo/* packages discovered.\\n');\n return;\n }\n\n const names = installed.map((p) => p.name);\n const results = await fetchDistTagsBatch(names, { fetcher: this.deps.fetcher });\n\n const allMissed = results.every((r) => !('distTags' in r));\n if (allMissed) {\n this.emitError('registry unreachable for every package; aborting.');\n this.deps.setExitCode?.(1);\n return;\n }\n\n const rawStates = computePackageStates(installed, results);\n // Drop workspace-linked packages from the install plan; they live in this\n // repo as `workspace:*` deps, not registry consumers. Keep them visible in\n // the report so users see why they were skipped.\n const states = markWorkspaceLinks(rawStates, readWorkspaceLinks(this.projectRoot));\n const targets = selectInstallTargets(states);\n\n const cliVersion = getVersion();\n const channel = detectChannel(cliVersion);\n const plan = targets.length === 0 ? null : this.buildPlan(targets, options);\n const strategy = this.pickStrategy(targets, options);\n\n const baseReport: UpdateReport = {\n ctxo: cliVersion,\n channel,\n packages: states,\n plan,\n strategy,\n executed: false,\n };\n\n if (options.check) {\n // --check never executes, so render with the print-style block so the user\n // sees the suggested command instead of a misleading \"Running...\" line.\n const checkStrategy: UpdateStrategy = plan ? 'print' : strategy;\n this.emitReport({ ...baseReport, strategy: checkStrategy }, options.json ?? false);\n return;\n }\n\n if (strategy === 'none' || strategy === 'print' || !plan) {\n this.emitReport(baseReport, options.json ?? false);\n return;\n }\n\n if (!options.force && !options.global && isLockedCI(this.deps.env ?? process.env)) {\n this.emitReport({ ...baseReport, strategy: 'print' }, options.json ?? false);\n this.emitError('CI environment with frozen lockfile detected. Refusing to mutate. Use --force or --global.');\n this.deps.setExitCode?.(1);\n return;\n }\n\n if (!options.json) this.emitReport(baseReport, false);\n const run = this.deps.runner ?? runPackageManager;\n const code = await run(plan.command, plan.args, this.projectRoot);\n const finalReport: UpdateReport = { ...baseReport, executed: true, exitCode: code };\n if (options.json) this.emit(formatJson(finalReport) + '\\n');\n if (code !== 0) this.deps.setExitCode?.(code);\n }\n\n private buildPlan(\n targets: ReadonlyArray<{ name: string; version: string }>,\n options: UpdateOptions,\n ): UpdatePlanShape {\n const resolution = resolvePackageManager({\n flag: options.pm,\n projectRoot: this.projectRoot,\n env: this.deps.env,\n });\n const specifiers = targets.map((t) => `${t.name}@${t.version}`);\n const useGlobal = options.global || !this.projectHasCtxoDep();\n const invocation = buildInstallCommand(resolution.manager, specifiers, {\n global: useGlobal,\n workspaceRoot: !useGlobal && isWorkspaceRoot(this.projectRoot),\n });\n return {\n manager: resolution.manager,\n managerSource: resolution.source,\n managerDetail: resolution.detail,\n global: useGlobal,\n command: invocation.command,\n args: invocation.args,\n };\n }\n\n private pickStrategy(\n targets: ReadonlyArray<{ name: string; version: string }>,\n options: UpdateOptions,\n ): UpdateStrategy {\n if (targets.length === 0) return 'none';\n if (options.print) return 'print';\n if (options.global) return 'execute';\n return this.projectHasCtxoDep() ? 'execute' : 'print';\n }\n\n private projectHasCtxoDep(): boolean {\n const pkg = join(this.projectRoot, 'package.json');\n if (!existsSync(pkg)) return false;\n try {\n const json = JSON.parse(readFileSync(pkg, 'utf-8')) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n const merged = { ...(json.dependencies ?? {}), ...(json.devDependencies ?? {}) };\n return Object.keys(merged).some(\n (name) => name === CTXO_CLI_PACKAGE || name.startsWith('@ctxo/lang-') || name.startsWith('ctxo-lang-'),\n );\n } catch (err) {\n log.error(`failed to read project package.json: ${(err as Error).message}`);\n return false;\n }\n }\n\n private emit(text: string): void { process.stdout.write(text); }\n private emitError(text: string): void { process.stderr.write(`[ctxo] ${text}\\n`); }\n\n private emitReport(report: UpdateReport, json: boolean): void {\n if (json) this.emit(formatJson(report) + '\\n');\n else this.emit(formatText(report) + '\\n');\n }\n}\n\nasync function defaultDiscoverInstalled(projectRoot: string): Promise<ReadonlyArray<{ name: string; version: string }>> {\n const out: Array<{ name: string; version: string }> = [{ name: CTXO_CLI_PACKAGE, version: getVersion() }];\n const manifestPath = loadManifestPath(projectRoot);\n if (!manifestPath) return out;\n const { plugins } = await discoverPlugins({ manifestPath });\n for (const p of plugins) out.push({ name: p.specifier, version: p.plugin.version });\n return out;\n}\n\nfunction isLockedCI(env: NodeJS.ProcessEnv): boolean {\n return env['CI'] === 'true' || env['CI'] === '1';\n}\n","import { request } from 'node:https';\nimport { createLogger } from '../logger.js';\n\nconst log = createLogger('ctxo:update:registry');\n\nexport interface RegistryDistTags {\n readonly [tag: string]: string;\n}\n\nexport interface RegistryHit {\n readonly name: string;\n readonly distTags: RegistryDistTags;\n}\n\nexport interface RegistryMiss {\n readonly name: string;\n readonly reason: 'registry-404' | 'registry-error' | 'timeout' | 'network';\n readonly status?: number;\n readonly message?: string;\n}\n\nexport type RegistryResult = RegistryHit | RegistryMiss;\n\nexport interface FetchOptions {\n readonly timeoutMs?: number;\n readonly fetcher?: HttpsFetcher;\n}\n\nexport type HttpsFetcher = (url: string, timeoutMs: number) => Promise<{ status: number; body: string }>;\n\nconst DEFAULT_TIMEOUT_MS = 5_000;\n\nexport async function fetchDistTags(\n packageName: string,\n options: FetchOptions = {},\n): Promise<RegistryResult> {\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const fetcher = options.fetcher ?? defaultHttpsFetcher;\n const url = `https://registry.npmjs.org/${encodeURIComponent(packageName)}`;\n\n let response: { status: number; body: string };\n try {\n response = await fetcher(url, timeoutMs);\n } catch (err) {\n return classifyFetchError(packageName, err);\n }\n\n if (response.status === 404) {\n return { name: packageName, reason: 'registry-404', status: 404 };\n }\n if (response.status < 200 || response.status >= 300) {\n return { name: packageName, reason: 'registry-error', status: response.status };\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(response.body);\n } catch {\n return { name: packageName, reason: 'registry-error', status: response.status, message: 'invalid JSON' };\n }\n const distTags = (parsed as { 'dist-tags'?: unknown })['dist-tags'];\n if (!distTags || typeof distTags !== 'object') {\n return { name: packageName, reason: 'registry-error', status: response.status, message: 'missing dist-tags' };\n }\n return { name: packageName, distTags: distTags as RegistryDistTags };\n}\n\nexport async function fetchDistTagsBatch(\n packageNames: readonly string[],\n options: FetchOptions = {},\n): Promise<RegistryResult[]> {\n return Promise.all(packageNames.map((name) => fetchDistTags(name, options)));\n}\n\nfunction classifyFetchError(name: string, err: unknown): RegistryMiss {\n const code = (err as NodeJS.ErrnoException)?.code;\n const message = (err as Error)?.message ?? String(err);\n if (code === 'ETIMEDOUT' || /timeout/i.test(message)) {\n return { name, reason: 'timeout', message };\n }\n if (code === 'ECONNREFUSED' || code === 'ECONNRESET' || code === 'ENOTFOUND' || code === 'EAI_AGAIN') {\n return { name, reason: 'network', message };\n }\n log.error(`unexpected fetch error for ${name}: ${message}`);\n return { name, reason: 'network', message };\n}\n\nconst defaultHttpsFetcher: HttpsFetcher = (url, timeoutMs) => new Promise((resolve, reject) => {\n const req = request(url, { method: 'GET', headers: { 'user-agent': 'ctxo-update', accept: 'application/json' } }, (res) => {\n const chunks: Buffer[] = [];\n res.on('data', (chunk: Buffer) => chunks.push(chunk));\n res.on('end', () => resolve({ status: res.statusCode ?? 0, body: Buffer.concat(chunks).toString('utf-8') }));\n res.on('error', reject);\n });\n req.setTimeout(timeoutMs, () => {\n req.destroy(Object.assign(new Error(`timeout after ${timeoutMs}ms`), { code: 'ETIMEDOUT' }));\n });\n req.on('error', reject);\n req.end();\n});\n","import type { RegistryResult } from './registry-client.js';\n\nexport type Channel = 'latest' | 'alpha' | 'beta' | 'rc' | 'next' | string;\n\nconst SEMVER_RE = /^(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z.-]+))?(?:\\+[0-9A-Za-z.-]+)?$/;\n\ninterface ParsedSemver {\n major: number;\n minor: number;\n patch: number;\n prerelease: string[]; // empty array means release\n}\n\nfunction parseSemver(version: string): ParsedSemver | null {\n const match = SEMVER_RE.exec(version.trim());\n if (!match) return null;\n const prereleaseRaw = match[4] ?? '';\n return {\n major: Number(match[1]),\n minor: Number(match[2]),\n patch: Number(match[3]),\n prerelease: prereleaseRaw ? prereleaseRaw.split('.') : [],\n };\n}\n\nexport function detectChannel(version: string): Channel {\n const parsed = parseSemver(version);\n if (!parsed || parsed.prerelease.length === 0) return 'latest';\n const first = parsed.prerelease[0]!;\n if (/^\\d+$/.test(first)) return 'latest';\n return first;\n}\n\nexport function compareSemver(a: string, b: string): -1 | 0 | 1 {\n const pa = parseSemver(a);\n const pb = parseSemver(b);\n if (!pa && !pb) return 0;\n if (!pa) return -1;\n if (!pb) return 1;\n\n if (pa.major !== pb.major) return pa.major < pb.major ? -1 : 1;\n if (pa.minor !== pb.minor) return pa.minor < pb.minor ? -1 : 1;\n if (pa.patch !== pb.patch) return pa.patch < pb.patch ? -1 : 1;\n\n // Prerelease ordering per semver section 11.\n if (pa.prerelease.length === 0 && pb.prerelease.length === 0) return 0;\n if (pa.prerelease.length === 0) return 1; // release > prerelease\n if (pb.prerelease.length === 0) return -1;\n\n const len = Math.max(pa.prerelease.length, pb.prerelease.length);\n for (let i = 0; i < len; i++) {\n const ai = pa.prerelease[i];\n const bi = pb.prerelease[i];\n if (ai === undefined) return -1;\n if (bi === undefined) return 1;\n const aNum = /^\\d+$/.test(ai);\n const bNum = /^\\d+$/.test(bi);\n if (aNum && bNum) {\n const an = Number(ai);\n const bn = Number(bi);\n if (an !== bn) return an < bn ? -1 : 1;\n } else if (aNum && !bNum) {\n return -1; // numeric < non-numeric\n } else if (!aNum && bNum) {\n return 1;\n } else if (ai !== bi) {\n return ai < bi ? -1 : 1;\n }\n }\n return 0;\n}\n\nexport type PackageStatus = 'current' | 'update' | 'ahead' | 'unknown' | 'workspace';\n\nexport interface PackageState {\n readonly name: string;\n readonly current: string;\n readonly latest: string | null;\n readonly channel: Channel;\n readonly status: PackageStatus;\n readonly reason?: 'registry-404' | 'registry-error' | 'timeout' | 'network';\n}\n\nexport interface InstalledPackage {\n readonly name: string;\n readonly version: string;\n}\n\nexport function computePackageStates(\n installed: readonly InstalledPackage[],\n results: readonly RegistryResult[],\n): PackageState[] {\n const byName = new Map<string, RegistryResult>();\n for (const r of results) byName.set(r.name, r);\n\n return installed.map((pkg) => {\n const installedChannel = detectChannel(pkg.version);\n const result = byName.get(pkg.name);\n\n if (!result) {\n return { name: pkg.name, current: pkg.version, latest: null, channel: installedChannel, status: 'unknown' as const };\n }\n if (!('distTags' in result)) {\n return { name: pkg.name, current: pkg.version, latest: null, channel: installedChannel, status: 'unknown' as const, reason: result.reason };\n }\n\n // Pick the channel we actually have a version for. If the installed channel\n // is not published, fall back to \"latest\" so the row reports the real source.\n const hasInstalledChannel = typeof result.distTags[installedChannel] === 'string';\n const targetChannel: Channel = hasInstalledChannel ? installedChannel : 'latest';\n const target = result.distTags[targetChannel] ?? null;\n if (!target) {\n return { name: pkg.name, current: pkg.version, latest: null, channel: installedChannel, status: 'unknown' as const };\n }\n const cmp = compareSemver(pkg.version, target);\n const status: PackageStatus = cmp === 0 ? 'current' : cmp < 0 ? 'update' : 'ahead';\n return { name: pkg.name, current: pkg.version, latest: target, channel: targetChannel, status };\n });\n}\n\nexport function selectInstallTargets(states: readonly PackageState[]): ReadonlyArray<{ name: string; version: string }> {\n return states\n .filter((s): s is PackageState & { latest: string } => s.status === 'update' && typeof s.latest === 'string')\n .filter((s) => isSafeVersionSpecifier(s.latest))\n .map((s) => ({ name: s.name, version: s.latest }));\n}\n\n/**\n * Override the status of any package whose name appears in `workspaceLinkNames`\n * to `'workspace'`. Workspace-linked packages (pnpm `workspace:*` / yarn\n * `workspace:^`) are local source, not registry consumers — they must never\n * appear in the install plan or be \"upgraded\" to a registry version. They are\n * still shown in the report table so users see why a row is being skipped.\n */\nexport function markWorkspaceLinks(\n states: readonly PackageState[],\n workspaceLinkNames: ReadonlySet<string>,\n): PackageState[] {\n return states.map((s) =>\n workspaceLinkNames.has(s.name)\n ? { ...s, status: 'workspace' as const, latest: null }\n : s,\n );\n}\n\n// Strict semver-ish regex: digits, letters, dots, plus, minus only. Matches the\n// SEMVER_RE prefix without anchoring full structure (safe enough to feed to a\n// shell when shell:true is in effect on Windows).\nconst SAFE_SPECIFIER_RE = /^[0-9A-Za-z.+-]+$/;\n\nexport function isSafeVersionSpecifier(version: string): boolean {\n return SAFE_SPECIFIER_RE.test(version);\n}\n","import { join } from 'node:path';\nimport { loadGraph } from './graph-loader.js';\nimport { BlastRadiusCalculator } from '../core/blast-radius/blast-radius-calculator.js';\n\nexport interface BlastRadiusOptions {\n symbolId: string;\n json?: boolean;\n}\n\nexport class BlastRadiusCommand {\n private readonly ctxoRoot: string;\n constructor(projectRoot: string) {\n this.ctxoRoot = join(projectRoot, '.ctxo');\n }\n\n run(options: BlastRadiusOptions): void {\n const { graph } = loadGraph(this.ctxoRoot);\n if (!graph.hasNode(options.symbolId)) {\n process.stdout.write(JSON.stringify({ found: false, symbolId: options.symbolId }) + '\\n');\n return;\n }\n const result = new BlastRadiusCalculator().calculate(graph, options.symbolId);\n const payload = {\n found: true,\n symbolId: options.symbolId,\n directDependentsCount: result.directDependentsCount,\n confirmedCount: result.confirmedCount,\n likelyCount: result.likelyCount,\n potentialCount: result.potentialCount,\n overallRiskScore: result.overallRiskScore,\n impactedSymbols: result.impactedSymbols.map((s) => ({\n symbolId: s.symbolId, confidence: s.confidence, depth: s.depth,\n })),\n };\n process.stdout.write(JSON.stringify(payload) + '\\n');\n }\n}\n","import { join, relative, sep } from 'node:path';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { loadConfig } from '../core/config/load-config.js';\nimport { resolveGateThresholds } from '../core/gate/gate-config.js';\nimport { loadGraph } from './graph-loader.js';\nimport { JsonIndexReader } from '../adapters/storage/json-index-reader.js';\nimport { lineOfSnippet, locateSymbolAtLine } from '../core/gate/symbol-locator.js';\nimport { transcriptHasBlastCheck } from '../core/gate/transcript-scan.js';\nimport { GateSessionStore } from '../adapters/gate/gate-session-store.js';\nimport { BlastRadiusCalculator } from '../core/blast-radius/blast-radius-calculator.js';\nimport { PageRankCalculator } from '../core/importance/pagerank-calculator.js';\nimport { percentileCutoff } from '../core/gate/percentile.js';\nimport { shouldBlock, formatBlockReason } from '../core/gate/gate-decision.js';\nimport { createLogger } from '../core/logger.js';\n\nconst log = createLogger('ctxo:gate-hook');\n\nconst RANK_ALL = 100_000; // effectively unbounded: rank every node\n\nexport interface HookPayload {\n session_id: string;\n transcript_path: string;\n tool_name: string;\n tool_input: { file_path?: string; old_string?: string; new_string?: string };\n}\n\nexport interface HookDecision { block: boolean; reason?: string; }\n\nexport class GateHookCommand {\n private readonly ctxoRoot: string;\n private readonly cacheDir: string;\n constructor(private readonly projectRoot: string) {\n this.ctxoRoot = join(projectRoot, '.ctxo');\n this.cacheDir = join(this.ctxoRoot, '.cache');\n }\n\n /** Pure-ish decision: never throws (fail-open). */\n evaluate(payload: HookPayload): HookDecision {\n try {\n if (payload.tool_name !== 'Edit') return { block: false };\n const filePath = payload.tool_input?.file_path;\n const oldString = payload.tool_input?.old_string;\n if (!filePath || !oldString) return { block: false };\n\n // loadConfig takes ctxoRoot (.ctxo directory) and returns LoadedConfig wrapper\n const loaded = loadConfig(this.ctxoRoot);\n const thresholds = resolveGateThresholds(loaded.config.gate);\n if (!thresholds.enabled) return { block: false };\n\n const relPath = relative(this.projectRoot, filePath).split(sep).join('/');\n const indexFile = join(this.ctxoRoot, 'index', `${relPath}.json`);\n if (!existsSync(indexFile)) return { block: false };\n\n const fileIndex = new JsonIndexReader(this.ctxoRoot).readSingle(indexFile);\n if (!fileIndex) return { block: false };\n\n if (!existsSync(filePath)) return { block: false };\n const source = readFileSync(filePath, 'utf-8');\n const line = lineOfSnippet(source, oldString);\n if (line === null) return { block: false };\n\n const symbolId = locateSymbolAtLine(fileIndex, line);\n if (!symbolId) return { block: false };\n\n const store = new GateSessionStore(this.cacheDir);\n if (store.hasWarned(payload.session_id, symbolId)) return { block: false };\n if (payload.transcript_path && existsSync(payload.transcript_path)) {\n const lines = readFileSync(payload.transcript_path, 'utf-8').split('\\n').filter(Boolean);\n if (transcriptHasBlastCheck(lines, symbolId)) return { block: false };\n }\n\n const { graph } = loadGraph(this.ctxoRoot);\n if (!graph.hasNode(symbolId)) return { block: false };\n const blast = new BlastRadiusCalculator().calculate(graph, symbolId);\n const riskCount = blast.confirmedCount + blast.likelyCount;\n\n const pr = new PageRankCalculator().calculate(graph, { limit: RANK_ALL });\n const prMap = new Map(pr.rankings.map((r) => [r.symbolId, r.score]));\n const cutoff = percentileCutoff([...prMap.values()], thresholds.percentile);\n const importanceScore = prMap.get(symbolId) ?? 0;\n\n const block = shouldBlock({ riskCount, importanceScore, importanceCutoff: cutoff }, thresholds);\n if (!block) return { block: false };\n\n store.recordWarned(payload.session_id, symbolId);\n const name = symbolId.split('::')[1] ?? symbolId;\n const top = blast.impactedSymbols\n .filter((s) => s.confidence !== 'potential')\n .map((s) => s.symbolId);\n return { block: true, reason: formatBlockReason(name, riskCount, top) };\n } catch (err) {\n log.error(`${(err as Error).message}`);\n return { block: false };\n }\n }\n\n async run(): Promise<void> {\n try {\n const payload = await this.readStdin();\n if (payload) {\n const decision = this.evaluate(payload);\n if (decision.block) this.emitBlock(decision.reason ?? 'ctxo guard');\n }\n } catch (err) {\n log.error(`${(err as Error).message}`);\n }\n process.exit(0);\n }\n\n /** PreToolUse block contract (verified): exit 0 + stdout JSON deny. */\n private emitBlock(reason: string): void {\n process.stdout.write(JSON.stringify({\n hookSpecificOutput: {\n hookEventName: 'PreToolUse',\n permissionDecision: 'deny',\n permissionDecisionReason: reason,\n },\n }) + '\\n');\n process.exit(0);\n }\n\n private readStdin(): Promise<HookPayload | null> {\n return new Promise((resolve) => {\n let data = '';\n process.stdin.setEncoding('utf-8');\n process.stdin.on('data', (c) => { data += c; });\n process.stdin.on('end', () => {\n try { resolve(JSON.parse(data) as HookPayload); } catch { resolve(null); }\n });\n process.stdin.on('error', () => resolve(null));\n });\n }\n}\n","import type { GateConfig } from '../config/config-schema.js';\n\nexport interface ResolvedGate {\n readonly enabled: boolean;\n readonly percentile: number;\n readonly minDependents: number;\n}\n\nconst DIAL: Record<NonNullable<GateConfig['sensitivity']>, { percentile: number; minDependents: number }> = {\n strict: { percentile: 30, minDependents: 2 },\n balanced: { percentile: 15, minDependents: 3 },\n lenient: { percentile: 5, minDependents: 5 },\n};\n\nexport function resolveGateThresholds(gate: GateConfig | undefined): ResolvedGate {\n const dial = DIAL[gate?.sensitivity ?? 'balanced'];\n return {\n enabled: gate?.enabled ?? true,\n percentile: gate?.percentile ?? dial.percentile,\n minDependents: gate?.minDependents ?? dial.minDependents,\n };\n}\n","import type { FileIndex } from '../types.js';\n\n/**\n * 0-based line where `snippet` begins in `source`, or null if not found.\n * 0-based to match the ctxo index, whose `startLine`/`endLine` are stored as\n * `getStartLineNumber() - 1` by the language adapters (see ts-morph-adapter.ts).\n */\nexport function lineOfSnippet(source: string, snippet: string): number | null {\n const idx = source.indexOf(snippet);\n if (idx === -1) return null;\n let line = 0;\n for (let i = 0; i < idx; i++) {\n if (source.codePointAt(i) === 10 /* \\n */) line++;\n }\n return line;\n}\n\n/** symbolId of the innermost symbol whose [startLine,endLine] contains `line` (all 0-based). */\nexport function locateSymbolAtLine(fileIndex: FileIndex, line: number): string | null {\n let best: { id: string; span: number } | null = null;\n for (const s of fileIndex.symbols) {\n if (line >= s.startLine && line <= s.endLine) {\n const span = s.endLine - s.startLine;\n if (best === null || span < best.span) best = { id: s.symbolId, span };\n }\n }\n return best?.id ?? null;\n}\n","function fileAndName(symbolId: string): string {\n const [file, name] = symbolId.split('::');\n return `${file}::${name}`;\n}\n\n/**\n * True if any transcript line records a get_blast_radius tool call whose\n * symbolId argument matches `symbolId` by file::name (kind-insensitive).\n */\nexport function transcriptHasBlastCheck(lines: readonly string[], symbolId: string): boolean {\n const target = fileAndName(symbolId);\n for (const line of lines) {\n if (!line.includes('get_blast_radius')) continue;\n let entry: unknown;\n try { entry = JSON.parse(line); } catch { continue; }\n const content = (entry as { message?: { content?: unknown[] } })?.message?.content;\n if (!Array.isArray(content)) continue;\n for (const block of content) {\n const b = block as { type?: string; name?: string; input?: { symbolId?: string } };\n if (b?.type === 'tool_use' && typeof b.name === 'string' && b.name.includes('get_blast_radius')) {\n const id = b.input?.symbolId;\n if (typeof id === 'string' && fileAndName(id) === target) return true;\n }\n }\n }\n return false;\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { createLogger } from '../../core/logger.js';\n\nconst log = createLogger('ctxo:gate-store');\n\n/** Tracks which symbols the gate has already warned about, per session. */\nexport class GateSessionStore {\n constructor(private readonly cacheDir: string) {}\n\n private file(sessionId: string): string {\n const safe = sessionId.replace(/[^a-zA-Z0-9_-]/g, '_');\n return join(this.cacheDir, 'gate', `${safe}.json`);\n }\n\n private read(sessionId: string): Set<string> {\n const f = this.file(sessionId);\n if (!existsSync(f)) return new Set();\n try {\n return new Set(JSON.parse(readFileSync(f, 'utf-8')) as string[]);\n } catch (err) {\n log.error(`${(err as Error).message}`);\n return new Set();\n }\n }\n\n hasWarned(sessionId: string, symbolId: string): boolean {\n return this.read(sessionId).has(symbolId);\n }\n\n recordWarned(sessionId: string, symbolId: string): void {\n try {\n const set = this.read(sessionId);\n set.add(symbolId);\n const f = this.file(sessionId);\n mkdirSync(join(this.cacheDir, 'gate'), { recursive: true });\n writeFileSync(f, JSON.stringify([...set]), 'utf-8');\n } catch (err) {\n log.error(`${(err as Error).message}`);\n }\n }\n}\n","/**\n * The score value at the top-`topPercent`% boundary. A score >= the returned\n * cutoff is in the top `topPercent`% of the distribution. Empty input returns\n * Infinity so that \"in top P%\" is always false (nothing to gate on).\n */\nexport function percentileCutoff(scores: readonly number[], topPercent: number): number {\n if (scores.length === 0) return Infinity;\n const sorted = [...scores].sort((a, b) => a - b);\n const rank = Math.ceil(((100 - topPercent) / 100) * sorted.length);\n const idx = Math.min(Math.max(rank, 0), sorted.length - 1);\n return sorted[idx]!;\n}\n","import type { ResolvedGate } from './gate-config.js';\n\nconst MAX_TOP_DEPENDENTS = 8;\n\nexport interface GateInput {\n /** confirmed + likely dependents of the edited symbol (primary risk signal). */\n readonly riskCount: number;\n /** PageRank of the edited symbol. */\n readonly importanceScore: number;\n /** PageRank value at the top-percentile boundary for this repo. */\n readonly importanceCutoff: number;\n}\n\nexport function shouldBlock(input: GateInput, t: ResolvedGate): boolean {\n if (!t.enabled) return false;\n return input.riskCount >= t.minDependents && input.importanceScore >= input.importanceCutoff;\n}\n\n/** One-time guard message injected into the block reason. */\nexport function formatBlockReason(\n symbolName: string,\n riskCount: number,\n topDependents: readonly string[],\n): string {\n const list = topDependents.slice(0, MAX_TOP_DEPENDENTS).map((d) => ` - ${d}`).join('\\n');\n return [\n `⚠ ctxo guard: \"${symbolName}\" is a high-impact symbol - ${riskCount} confirmed/likely dependents may break.`,\n topDependents.length > 0 ? `Top dependents:\\n${list}` : '',\n `Call get_blast_radius / get_why_context before editing. This guard fires once per symbol per session - re-issue the edit to proceed.`,\n ].filter(Boolean).join('\\n');\n}\n","import { join } from 'node:path';\nimport { loadConfig } from '../core/config/load-config.js';\nimport { resolveGateThresholds } from '../core/gate/gate-config.js';\nimport { loadGraph } from './graph-loader.js';\nimport { BlastRadiusCalculator } from '../core/blast-radius/blast-radius-calculator.js';\nimport { PageRankCalculator } from '../core/importance/pagerank-calculator.js';\nimport { percentileCutoff } from '../core/gate/percentile.js';\nimport { shouldBlock } from '../core/gate/gate-decision.js';\n\nconst RANK_ALL = 100_000;\n\nexport interface GatePreviewOptions { json?: boolean; }\n\nexport class GateCommand {\n private readonly ctxoRoot: string;\n constructor(projectRoot: string) {\n this.ctxoRoot = join(projectRoot, '.ctxo');\n }\n\n preview(options: GatePreviewOptions = {}): void {\n const gate = loadConfig(this.ctxoRoot).config.gate;\n const thresholds = resolveGateThresholds(gate);\n const { graph } = loadGraph(this.ctxoRoot);\n const pr = new PageRankCalculator().calculate(graph, { limit: RANK_ALL });\n const prMap = new Map(pr.rankings.map((r) => [r.symbolId, r.score]));\n const cutoff = percentileCutoff([...prMap.values()], thresholds.percentile);\n\n const calc = new BlastRadiusCalculator();\n const firing: Array<{ symbolId: string; riskCount: number; importance: number }> = [];\n for (const [symbolId, importance] of prMap) {\n if (importance < cutoff) continue;\n const blast = calc.calculate(graph, symbolId);\n const riskCount = blast.confirmedCount + blast.likelyCount;\n if (shouldBlock({ riskCount, importanceScore: importance, importanceCutoff: cutoff }, thresholds)) {\n firing.push({ symbolId, riskCount, importance: Math.round(importance * 1e4) / 1e4 });\n }\n }\n firing.sort((a, b) => b.riskCount - a.riskCount);\n\n const payload = {\n sensitivity: gate?.sensitivity ?? 'balanced',\n thresholds,\n totalSymbols: graph.nodeCount,\n wouldFireCount: firing.length,\n symbols: firing.slice(0, 50),\n };\n if (options.json) { process.stdout.write(JSON.stringify(payload, null, 2) + '\\n'); return; }\n console.error(`[ctxo] gate preview (${payload.sensitivity}): ${firing.length}/${graph.nodeCount} symbols would gate.`);\n for (const f of firing.slice(0, 25)) console.error(` ${f.riskCount} dep ${f.symbolId}`);\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,cAAY,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,SAA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AAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAuCP,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","createRequire","join","existsSync","extname","join","existsSync","readFileSync","dirname","join","resolve","existsSync","join","existsSync","join","createRequire","existsSync","dirname","join","resolve","join","dirname","existsSync","resolve","readFileSync","existsSync","mkdirSync","join","dirname","existsSync","mkdirSync","readFileSync","join","resolve","log","join","mkdirSync","existsSync","readFileSync","resolve","createRequire","join","readFileSync","existsSync","execFileSync","readdirSync","extname","writeFileSync","join","join","join","existsSync","execFileSync","join","existsSync","execFileSync","join","tmpdir","join","tmpdir","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","execFileSync","join","relative","extname","commits","intent","antiPatterns","source","readFileSync","fileIndex","execFileSync","join","existsSync","readFileSync","join","existsSync","readFileSync","writeFileSync","join","existsSync","log","createRequire","require","SUPPORTED_API_VERSION","SUPPORTED_API_VERSION","createRequire","require","createRequire","createRequire","existsSync","readdirSync","join","dirname","require","createRequire","join","dirname","existsSync","readdirSync","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","existsSync","readFileSync","join","log","resolve","log","formatJson","isLockedCI","run","join","existsSync","readFileSync","join","join","join","relative","sep","existsSync","readFileSync","existsSync","mkdirSync","readFileSync","writeFileSync","join","log","join","existsSync","readFileSync","mkdirSync","writeFileSync","log","join","relative","sep","existsSync","readFileSync","resolve","join","RANK_ALL","join","join","existsSync","readFileSync","dirname"]}
|