codecortex-ai 0.3.2 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cli/index.ts","../../src/cli/commands/init.ts","../../src/core/discovery.ts","../../src/extraction/parser.ts","../../src/core/constitution.ts","../../src/git/history.ts","../../src/git/temporal.ts","../../src/extraction/symbols.ts","../../src/extraction/imports.ts","../../src/extraction/calls.ts","../../src/core/module-gen.ts","../../src/cli/commands/serve.ts","../../src/cli/commands/update.ts","../../src/git/diff.ts","../../src/cli/commands/status.ts","../../src/cli/commands/symbols.ts","../../src/cli/commands/search.ts","../../src/cli/commands/modules.ts","../../src/cli/commands/hotspots.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { createRequire } from 'node:module'\nimport { Command } from 'commander'\nimport { initCommand } from './commands/init.js'\nimport { serveCommand } from './commands/serve.js'\nimport { updateCommand } from './commands/update.js'\nimport { statusCommand } from './commands/status.js'\nimport { symbolsCommand } from './commands/symbols.js'\nimport { searchCommand } from './commands/search.js'\nimport { modulesCommand } from './commands/modules.js'\nimport { hotspotsCommand } from './commands/hotspots.js'\n\nconst require = createRequire(import.meta.url)\nconst { version } = require('../../package.json') as { version: string }\n\nconst program = new Command()\n\nprogram\n .name('codecortex')\n .description('Persistent, AI-powered codebase knowledge layer')\n .version(version)\n\nprogram\n .command('init')\n .description('Initialize codebase knowledge: discover files, extract symbols, analyze git history')\n .option('-r, --root <path>', 'Project root directory', process.cwd())\n .option('-d, --days <number>', 'Days of git history to analyze', '90')\n .action(initCommand)\n\nprogram\n .command('serve')\n .description('Start MCP server (stdio transport) for AI agent access')\n .option('-r, --root <path>', 'Project root directory', process.cwd())\n .action(serveCommand)\n\nprogram\n .command('update')\n .description('Update knowledge for changed files since last session')\n .option('-r, --root <path>', 'Project root directory', process.cwd())\n .option('-d, --days <number>', 'Days of git history to re-analyze', '90')\n .action(updateCommand)\n\nprogram\n .command('status')\n .description('Show knowledge freshness, stale modules, and symbol counts')\n .option('-r, --root <path>', 'Project root directory', process.cwd())\n .action(statusCommand)\n\nprogram\n .command('symbols [query]')\n .description('Browse and filter the symbol index')\n .option('-r, --root <path>', 'Project root directory', process.cwd())\n .option('-k, --kind <kind>', 'Filter by kind: function, class, interface, type, const, enum, method, property, variable')\n .option('-f, --file <path>', 'Filter by file path (partial match)')\n .option('-e, --exported', 'Show only exported symbols')\n .option('-l, --limit <number>', 'Max results', '30')\n .action((query, opts) => symbolsCommand(query, opts))\n\nprogram\n .command('search <query>')\n .description('Search across all CodeCortex knowledge files')\n .option('-r, --root <path>', 'Project root directory', process.cwd())\n .option('-l, --limit <number>', 'Max results', '20')\n .action((query, opts) => searchCommand(query, opts))\n\nprogram\n .command('modules [name]')\n .description('List modules or deep-dive into a specific module')\n .option('-r, --root <path>', 'Project root directory', process.cwd())\n .action((name, opts) => modulesCommand(name, opts))\n\nprogram\n .command('hotspots')\n .description('Show files ranked by risk: churn + coupling + bug history')\n .option('-r, --root <path>', 'Project root directory', process.cwd())\n .option('-l, --limit <number>', 'Number of files to show', '15')\n .action(hotspotsCommand)\n\nprogram.parse()\n","import { resolve } from 'node:path'\nimport { discoverProject } from '../../core/discovery.js'\nimport { createManifest, writeManifest } from '../../core/manifest.js'\nimport { buildGraph, writeGraph } from '../../core/graph.js'\nimport { generateConstitution } from '../../core/constitution.js'\nimport { analyzeTemporalData } from '../../git/temporal.js'\nimport { isGitRepo, getHeadCommit } from '../../git/history.js'\nimport { enrichCouplingWithImports } from '../../core/graph.js'\nimport { initParser, parseFile, languageFromPath } from '../../extraction/parser.js'\nimport { extractSymbols } from '../../extraction/symbols.js'\nimport { extractImports } from '../../extraction/imports.js'\nimport { extractCalls } from '../../extraction/calls.js'\nimport { writeFile, writeJsonStream, ensureDir, cortexPath } from '../../utils/files.js'\nimport { readFile } from 'node:fs/promises'\nimport { generateStructuralModuleDocs } from '../../core/module-gen.js'\nimport type { SymbolRecord, ImportEdge, CallEdge, ModuleNode, SymbolIndex, ProjectInfo } from '../../types/index.js'\n\nexport async function initCommand(opts: { root: string; days: string }): Promise<void> {\n const root = resolve(opts.root)\n const days = parseInt(opts.days, 10)\n\n console.log(`CodeCortex init — analyzing ${root}`)\n console.log('')\n\n // Step 1: Discover project\n console.log('Step 1/6: Discovering project structure...')\n const project = await discoverProject(root)\n console.log(` Found ${project.files.length} files in ${project.modules.length} modules`)\n console.log(` Languages: ${project.languages.join(', ')}`)\n console.log(` Type: ${project.type}`)\n console.log('')\n\n // Step 2: Initialize tree-sitter and extract symbols\n console.log('Step 2/6: Extracting symbols with tree-sitter...')\n await initParser()\n\n const allSymbols: SymbolRecord[] = []\n const allImports: ImportEdge[] = []\n const allCalls: CallEdge[] = []\n let extractionErrors = 0\n\n let parsed = 0\n const parseable = project.files.filter(f => languageFromPath(f.path)).length\n const showProgress = parseable > 500\n\n for (const file of project.files) {\n const lang = languageFromPath(file.path)\n if (!lang) continue\n\n try {\n const tree = await parseFile(file.absolutePath, lang)\n const source = await readFile(file.absolutePath, 'utf-8')\n\n const symbols = extractSymbols(tree, file.path, lang, source)\n const imports = extractImports(tree, file.path, lang)\n const calls = extractCalls(tree, file.path, lang)\n\n allSymbols.push(...symbols)\n allImports.push(...imports)\n allCalls.push(...calls)\n } catch {\n extractionErrors++\n }\n parsed++\n if (showProgress && parsed % 5000 === 0) {\n process.stdout.write(`\\r Progress: ${parsed}/${parseable} files (${allSymbols.length} symbols)`)\n }\n }\n if (showProgress) process.stdout.write('\\r' + ' '.repeat(70) + '\\r')\n\n console.log(` Extracted ${allSymbols.length} symbols, ${allImports.length} imports, ${allCalls.length} call edges`)\n if (extractionErrors > 0) {\n console.log(` (${extractionErrors} files skipped due to parse errors)`)\n }\n console.log('')\n\n // Step 3: Build dependency graph\n console.log('Step 3/6: Building dependency graph...')\n const MODULE_ROOTS = new Set(['src', 'lib', 'pkg', 'packages', 'apps', 'extensions', 'crates', 'internal', 'cmd', 'scripts', 'tools', 'rust'])\n const moduleNodes: ModuleNode[] = project.modules.map(modName => {\n const modFiles = project.files.filter(f => {\n const parts = f.path.split('/')\n const topDir = parts[0] ?? ''\n return (MODULE_ROOTS.has(topDir) && parts[1] === modName) ||\n (parts[0] === modName)\n })\n const topDir = modFiles[0]?.path.split('/')[0] ?? 'src'\n return {\n path: `${topDir}/${modName}`,\n name: modName,\n files: modFiles.map(f => f.path),\n language: modFiles[0]?.language || 'unknown',\n lines: modFiles.reduce((sum, f) => sum + f.lines, 0),\n symbols: allSymbols.filter(s => modFiles.some(f => f.path === s.file)).length,\n }\n })\n\n // Detect external dependencies\n const externalDeps: Record<string, string[]> = {}\n for (const file of project.files) {\n try {\n const content = await readFile(file.absolutePath, 'utf-8')\n const importMatches = content.matchAll(/from\\s+['\"]([^.\\/][^'\"]*)['\"]/g)\n for (const match of importMatches) {\n const raw = match[1]\n if (!raw) continue\n const pkg = raw.startsWith('@') ? raw.split('/').slice(0, 2).join('/') : raw.split('/')[0] ?? raw\n if (!externalDeps[pkg]) externalDeps[pkg] = []\n externalDeps[pkg]!.push(file.path)\n }\n } catch { /* skip */ }\n }\n\n const graph = buildGraph({\n modules: moduleNodes,\n imports: allImports,\n calls: allCalls,\n entryPoints: project.entryPoints,\n externalDeps,\n })\n\n console.log(` ${moduleNodes.length} modules, ${Object.keys(externalDeps).length} external deps`)\n console.log('')\n\n // Step 4: Temporal analysis (git history)\n console.log('Step 4/6: Analyzing git history...')\n let temporalData = null\n const hasGit = await isGitRepo(root)\n if (hasGit) {\n temporalData = await analyzeTemporalData(root, days)\n // Enrich coupling with import graph\n enrichCouplingWithImports(graph, temporalData.coupling)\n console.log(` ${temporalData.totalCommits} commits analyzed over ${days} days`)\n console.log(` ${temporalData.hotspots.length} hotspots, ${temporalData.coupling.length} coupling pairs, ${temporalData.bugHistory.length} bug records`)\n } else {\n console.log(' No git repository found, skipping temporal analysis')\n }\n console.log('')\n\n // Step 5: Write knowledge files\n console.log('Step 5/6: Writing knowledge files...')\n await ensureDir(cortexPath(root))\n await ensureDir(cortexPath(root, 'modules'))\n await ensureDir(cortexPath(root, 'decisions'))\n await ensureDir(cortexPath(root, 'sessions'))\n\n // Write symbols.json\n const symbolIndex: SymbolIndex = {\n generated: new Date().toISOString(),\n total: allSymbols.length,\n symbols: allSymbols,\n }\n await writeJsonStream(cortexPath(root, 'symbols.json'), symbolIndex, 'symbols')\n\n // Write graph.json\n await writeGraph(root, graph)\n\n // Write temporal.json\n if (temporalData) {\n await writeFile(cortexPath(root, 'temporal.json'), JSON.stringify(temporalData, null, 2))\n }\n\n // Write overview.md\n const overview = generateOverview(project)\n await writeFile(cortexPath(root, 'overview.md'), overview)\n\n // Write manifest\n const manifest = createManifest({\n project: project.name,\n root,\n languages: project.languages,\n totalFiles: project.files.length,\n totalSymbols: allSymbols.length,\n totalModules: project.modules.length,\n })\n await writeManifest(root, manifest)\n\n // Write patterns.md (empty template)\n await writeFile(cortexPath(root, 'patterns.md'), '# Coding Patterns\\n\\nNo patterns recorded yet. Use `update_patterns` to add patterns.\\n')\n\n // Generate structural module docs\n const moduleDocsGenerated = await generateStructuralModuleDocs(root, {\n graph,\n symbols: allSymbols,\n temporal: temporalData,\n })\n\n console.log(` Written: cortex.yaml, symbols.json, graph.json, temporal.json, overview.md, patterns.md, ${moduleDocsGenerated} module docs`)\n console.log('')\n\n // Step 6: Generate constitution\n console.log('Step 6/6: Generating constitution...')\n await generateConstitution(root, {\n modules: moduleNodes,\n entryPoints: project.entryPoints,\n externalDeps,\n temporal: temporalData,\n })\n console.log(' Written: constitution.md')\n console.log('')\n\n // Summary\n const head = await getHeadCommit(root)\n console.log('─'.repeat(50))\n console.log('CodeCortex initialized successfully!')\n console.log('')\n console.log(` Project: ${project.name}`)\n console.log(` Files: ${project.files.length}`)\n console.log(` Symbols: ${allSymbols.length}`)\n console.log(` Modules: ${project.modules.length}`)\n if (temporalData) {\n console.log(` Commits: ${temporalData.totalCommits} (last ${days} days)`)\n const hidden = temporalData.coupling.filter(c => !c.hasImport && c.strength >= 0.5)\n if (hidden.length > 0) {\n console.log(` Hidden deps: ${hidden.length} (files that co-change but don't import each other)`)\n }\n }\n if (head) {\n console.log(` Git HEAD: ${head.slice(0, 7)}`)\n }\n console.log('')\n console.log(`Knowledge stored in: ${cortexPath(root)}`)\n console.log('Run `codecortex serve` to start the MCP server.')\n}\n\nfunction generateOverview(project: ProjectInfo): string {\n const lines = [\n `# ${project.name} — Overview`,\n '',\n `**Type:** ${project.type}`,\n `**Languages:** ${project.languages.join(', ')}`,\n `**Files:** ${project.files.length}`,\n '',\n `## Entry Points`,\n ...project.entryPoints.map(e => `- \\`${e}\\``),\n '',\n `## Modules`,\n ...project.modules.map(m => `- **${m}**`),\n '',\n `## File Map`,\n ]\n\n // Group files by directory\n const dirs = new Map<string, string[]>()\n for (const file of project.files) {\n const parts = file.path.split('/')\n const dir = parts.length > 1 ? parts.slice(0, -1).join('/') : '.'\n const existing = dirs.get(dir) || []\n const fileName = parts[parts.length - 1]\n if (fileName) existing.push(fileName)\n dirs.set(dir, existing)\n }\n\n for (const [dir, files] of [...dirs.entries()].sort()) {\n lines.push(`\\n### ${dir}/`)\n for (const file of files.sort()) {\n lines.push(`- ${file}`)\n }\n }\n\n return lines.join('\\n') + '\\n'\n}\n","import { execSync } from 'node:child_process'\nimport { readFile as fsRead, stat } from 'node:fs/promises'\nimport { join, relative, dirname, basename, extname } from 'node:path'\nimport { existsSync } from 'node:fs'\nimport type { DiscoveredFile, ProjectInfo } from '../types/index.js'\nimport { EXTENSION_MAP } from '../extraction/parser.js'\n\nconst IGNORED_DIRS = new Set([\n 'node_modules', '.git', 'dist', 'build', 'out', '.next', '.nuxt',\n '.output', 'coverage', '__pycache__', '.mypy_cache', '.pytest_cache',\n 'vendor', 'target', '.codecortex',\n])\n\nconst IGNORED_FILES = new Set([\n 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml',\n '.DS_Store', 'Thumbs.db',\n])\n\nexport async function discoverProject(root: string): Promise<ProjectInfo> {\n const name = detectProjectName(root)\n const type = detectProjectType(root)\n const files = await discoverFiles(root)\n const modules = detectModules(root, files)\n const entryPoints = detectEntryPoints(root, files, type)\n const languages = [...new Set(files.map(f => f.language).filter(Boolean))]\n\n return { name, root, type, files, modules, entryPoints, languages }\n}\n\nfunction detectProjectName(root: string): string {\n // Try package.json\n const pkgPath = join(root, 'package.json')\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(execSync(`cat \"${pkgPath}\"`, { encoding: 'utf-8' }))\n if (pkg.name) return pkg.name\n } catch { /* ignore */ }\n }\n\n // Try Cargo.toml\n const cargoPath = join(root, 'Cargo.toml')\n if (existsSync(cargoPath)) {\n try {\n const cargo = execSync(`cat \"${cargoPath}\"`, { encoding: 'utf-8' })\n const match = cargo.match(/name\\s*=\\s*\"(.+?)\"/)\n if (match?.[1]) return match[1]\n } catch { /* ignore */ }\n }\n\n // Fallback to directory name\n return basename(root)\n}\n\nfunction detectProjectType(root: string): ProjectInfo['type'] {\n if (existsSync(join(root, 'package.json'))) return 'node'\n if (existsSync(join(root, 'pyproject.toml')) || existsSync(join(root, 'setup.py')) || existsSync(join(root, 'requirements.txt'))) return 'python'\n if (existsSync(join(root, 'go.mod'))) return 'go'\n if (existsSync(join(root, 'Cargo.toml'))) return 'rust'\n return 'unknown'\n}\n\nasync function discoverFiles(root: string): Promise<DiscoveredFile[]> {\n const files: DiscoveredFile[] = []\n\n // Use git ls-files if in a git repo (respects .gitignore)\n let filePaths: string[]\n try {\n const output = execSync('git ls-files --cached --others --exclude-standard', {\n cwd: root,\n encoding: 'utf-8',\n maxBuffer: 10 * 1024 * 1024,\n })\n filePaths = output.trim().split('\\n').filter(Boolean)\n } catch {\n // Fallback: walk manually\n filePaths = await walkDirectory(root, root)\n }\n\n for (const relPath of filePaths) {\n const ext = extname(relPath)\n const language = EXTENSION_MAP[ext]\n if (!language) continue\n\n // Skip ignored dirs and files\n const parts = relPath.split('/')\n if (parts.some(p => IGNORED_DIRS.has(p))) continue\n if (IGNORED_FILES.has(basename(relPath))) continue\n\n const absPath = join(root, relPath)\n try {\n const s = await stat(absPath)\n const content = await fsRead(absPath, 'utf-8')\n const lines = content.split('\\n').length\n\n files.push({\n path: relPath,\n absolutePath: absPath,\n language,\n lines,\n bytes: s.size,\n })\n } catch {\n // Skip files that can't be read\n }\n }\n\n return files\n}\n\nasync function walkDirectory(root: string, baseRoot: string): Promise<string[]> {\n const { readdir } = await import('node:fs/promises')\n const paths: string[] = []\n\n const entries = await readdir(root, { withFileTypes: true })\n for (const entry of entries) {\n if (IGNORED_DIRS.has(entry.name)) continue\n if (IGNORED_FILES.has(entry.name)) continue\n\n const fullPath = join(root, entry.name)\n if (entry.isDirectory()) {\n const sub = await walkDirectory(fullPath, baseRoot)\n paths.push(...sub)\n } else if (entry.isFile()) {\n paths.push(relative(baseRoot, fullPath))\n }\n }\n\n return paths\n}\n\nfunction detectModules(root: string, files: DiscoveredFile[]): string[] {\n // Detect top-level directories under src/ (or equivalent)\n const MODULE_ROOTS = new Set(['src', 'lib', 'pkg', 'packages', 'apps', 'extensions', 'crates', 'internal', 'cmd', 'scripts', 'tools', 'rust'])\n const srcDirs = new Set<string>()\n\n for (const file of files) {\n const parts = file.path.split('/')\n if (parts.length >= 3) {\n const topDir = parts[0]\n const dir = parts[1]\n if (!topDir || !dir) continue\n\n if (MODULE_ROOTS.has(topDir)) {\n srcDirs.add(dir)\n }\n }\n }\n\n return [...srcDirs].sort()\n}\n\nfunction detectEntryPoints(root: string, files: DiscoveredFile[], type: ProjectInfo['type']): string[] {\n const entryPoints: string[] = []\n\n // Check package.json for main/bin entries\n if (type === 'node') {\n const pkgPath = join(root, 'package.json')\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(execSync(`cat \"${pkgPath}\"`, { encoding: 'utf-8' }))\n if (pkg.main) entryPoints.push(pkg.main)\n if (pkg.bin) {\n const bins = typeof pkg.bin === 'string' ? [pkg.bin] : Object.values(pkg.bin)\n entryPoints.push(...(bins as string[]))\n }\n } catch { /* ignore */ }\n }\n }\n\n // Common entry point file names\n const commonEntries = ['src/index.ts', 'src/main.ts', 'src/app.ts', 'index.ts', 'main.ts', 'main.go', 'src/main.rs', 'src/lib.rs']\n for (const entry of commonEntries) {\n if (files.some(f => f.path === entry)) {\n if (!entryPoints.includes(entry)) entryPoints.push(entry)\n }\n }\n\n return entryPoints\n}\n","import { createRequire } from 'node:module'\nimport { readFile as fsRead } from 'node:fs/promises'\n\nconst require = createRequire(import.meta.url)\nconst Parser = require('tree-sitter') as typeof import('tree-sitter')\n\n// Re-export types for consumers\nexport type Tree = import('tree-sitter').Tree\nexport type SyntaxNode = import('tree-sitter').SyntaxNode\n\nconst parser = new Parser()\n\n// Lazy grammar loaders — each grammar is require()'d on first use\ntype LanguageLoader = () => unknown\n\nconst LANGUAGE_LOADERS: Record<string, LanguageLoader> = {\n // TypeScript / JavaScript\n typescript: () => require('tree-sitter-typescript').typescript,\n tsx: () => require('tree-sitter-typescript').tsx,\n javascript: () => require('tree-sitter-javascript'),\n // Python\n python: () => require('tree-sitter-python'),\n // Go\n go: () => require('tree-sitter-go'),\n // Rust\n rust: () => require('tree-sitter-rust'),\n // Systems\n c: () => require('tree-sitter-c'),\n cpp: () => require('tree-sitter-cpp'),\n objc: () => require('tree-sitter-objc'),\n zig: () => require('tree-sitter-zig'),\n // JVM\n java: () => require('tree-sitter-java'),\n kotlin: () => require('tree-sitter-kotlin'),\n scala: () => require('tree-sitter-scala'),\n // .NET\n c_sharp: () => require('tree-sitter-c-sharp'),\n // Mobile\n swift: () => require('tree-sitter-swift'),\n dart: () => require('tree-sitter-dart'),\n // Scripting\n ruby: () => require('tree-sitter-ruby'),\n php: () => require('tree-sitter-php').php,\n lua: () => require('tree-sitter-lua'),\n bash: () => require('tree-sitter-bash'),\n elixir: () => require('tree-sitter-elixir'),\n // Functional\n ocaml: () => require('tree-sitter-ocaml').ocaml,\n elm: () => require('tree-sitter-elm'),\n elisp: () => require('tree-sitter-elisp'),\n // Web / Templating\n vue: () => require('tree-sitter-vue'),\n liquid: () => require('tree-sitter-liquid'),\n // Web3 / Other\n solidity: () => require('tree-sitter-solidity'),\n ql: () => require('tree-sitter-ql'),\n}\n\nexport const EXTENSION_MAP: Record<string, string> = {\n // TypeScript / JavaScript\n '.ts': 'typescript',\n '.tsx': 'tsx',\n '.js': 'javascript',\n '.jsx': 'javascript',\n '.mjs': 'javascript',\n '.cjs': 'javascript',\n // Python\n '.py': 'python',\n '.pyw': 'python',\n '.pyi': 'python',\n // Go\n '.go': 'go',\n // Rust\n '.rs': 'rust',\n // C / C++\n '.c': 'c',\n '.h': 'c',\n '.cpp': 'cpp',\n '.cc': 'cpp',\n '.cxx': 'cpp',\n '.hpp': 'cpp',\n '.hxx': 'cpp',\n '.hh': 'cpp',\n // Objective-C\n '.m': 'objc',\n '.mm': 'objc',\n // Zig\n '.zig': 'zig',\n // Java\n '.java': 'java',\n // Kotlin\n '.kt': 'kotlin',\n '.kts': 'kotlin',\n // Scala\n '.scala': 'scala',\n '.sc': 'scala',\n // C#\n '.cs': 'c_sharp',\n // Swift\n '.swift': 'swift',\n // Dart\n '.dart': 'dart',\n // Ruby\n '.rb': 'ruby',\n '.rake': 'ruby',\n // PHP\n '.php': 'php',\n // Lua\n '.lua': 'lua',\n // Bash / Shell\n '.sh': 'bash',\n '.bash': 'bash',\n // Elixir\n '.ex': 'elixir',\n '.exs': 'elixir',\n // OCaml\n '.ml': 'ocaml',\n '.mli': 'ocaml',\n // Elm\n '.elm': 'elm',\n // Emacs Lisp\n '.el': 'elisp',\n // Solidity\n '.sol': 'solidity',\n // Vue\n '.vue': 'vue',\n // Liquid\n '.liquid': 'liquid',\n // CodeQL\n '.ql': 'ql',\n}\n\nconst languageCache = new Map<string, unknown>()\n\nfunction loadLanguage(lang: string): unknown {\n const cached = languageCache.get(lang)\n if (cached) return cached\n\n const loader = LANGUAGE_LOADERS[lang]\n if (!loader) throw new Error(`Unsupported language: ${lang}`)\n\n const language = loader()\n languageCache.set(lang, language)\n return language\n}\n\n/** No-op — kept for backward compatibility with call sites. Native bindings need no async init. */\nexport async function initParser(): Promise<void> {}\n\nexport async function parseFile(filePath: string, language: string): Promise<Tree> {\n const lang = loadLanguage(language)\n parser.setLanguage(lang as Parameters<typeof parser.setLanguage>[0])\n const source = await fsRead(filePath, 'utf-8')\n return parser.parse(source)\n}\n\nexport function parseSource(source: string, language: string): Tree {\n const lang = loadLanguage(language)\n parser.setLanguage(lang as Parameters<typeof parser.setLanguage>[0])\n return parser.parse(source)\n}\n\nexport function languageFromPath(filePath: string): string | null {\n const ext = filePath.substring(filePath.lastIndexOf('.'))\n return EXTENSION_MAP[ext] || null\n}\n\nexport function supportedLanguages(): string[] {\n return Object.keys(LANGUAGE_LOADERS)\n}\n","import type { CortexManifest, TemporalData, ModuleNode } from '../types/index.js'\nimport { readFile, writeFile, cortexPath } from '../utils/files.js'\nimport { readManifest } from './manifest.js'\nimport { listModuleDocs } from './modules.js'\nimport { listDecisions } from './decisions.js'\n\nexport interface ConstitutionData {\n modules?: ModuleNode[]\n entryPoints?: string[]\n externalDeps?: Record<string, string[]>\n temporal?: TemporalData | null\n}\n\nexport async function generateConstitution(projectRoot: string, data?: ConstitutionData): Promise<string> {\n const manifest = await readManifest(projectRoot)\n const modules = await listModuleDocs(projectRoot)\n const decisions = await listDecisions(projectRoot)\n\n // Use passed-in data or read from disk (for small repos / standalone calls)\n let graphModules = data?.modules\n let entryPoints = data?.entryPoints\n let externalDeps = data?.externalDeps\n let temporal = data?.temporal ?? null\n\n if (!graphModules) {\n const graphContent = await readFile(cortexPath(projectRoot, 'graph.json'))\n if (graphContent) {\n try {\n const graph = JSON.parse(graphContent)\n graphModules = graph.modules\n entryPoints = graph.entryPoints\n externalDeps = graph.externalDeps\n } catch { /* graph too large to parse, skip */ }\n }\n }\n\n if (temporal === null && !data) {\n const temporalContent = await readFile(cortexPath(projectRoot, 'temporal.json'))\n if (temporalContent) {\n try { temporal = JSON.parse(temporalContent) as TemporalData } catch { /* skip */ }\n }\n }\n\n const lines: string[] = [\n `# ${manifest?.project || 'Project'} — Constitution`,\n '',\n `> Auto-generated by CodeCortex. This is the AI's starting knowledge for this codebase.`,\n '',\n ]\n\n // Project overview\n if (manifest) {\n lines.push(\n `## Project`,\n `- **Name:** ${manifest.project}`,\n `- **Languages:** ${manifest.languages.join(', ')}`,\n `- **Files:** ${manifest.totalFiles}`,\n `- **Symbols:** ${manifest.totalSymbols}`,\n `- **Modules:** ${manifest.totalModules}`,\n `- **Last updated:** ${manifest.lastUpdated}`,\n '',\n )\n }\n\n // Architecture\n if (graphModules) {\n lines.push(`## Architecture`, '')\n\n if (entryPoints && entryPoints.length > 0) {\n lines.push(`**Entry points:** ${entryPoints.map(e => `\\`${e}\\``).join(', ')}`, '')\n }\n\n lines.push(`**Modules:**`)\n for (const mod of graphModules) {\n lines.push(`- **${mod.name}** (${mod.files.length} files, ${mod.lines} lines) — ${mod.language}`)\n }\n lines.push('')\n\n // Key dependencies\n if (externalDeps) {\n const extDeps = Object.keys(externalDeps)\n if (extDeps.length > 0) {\n lines.push(`**External dependencies:** ${extDeps.map(d => `\\`${d}\\``).join(', ')}`, '')\n }\n }\n }\n\n // Temporal signals\n if (temporal) {\n lines.push(`## Risk Map`, '')\n\n // Top hotspots\n const topHotspots = temporal.hotspots.slice(0, 5)\n if (topHotspots.length > 0) {\n lines.push(`**Hottest files (most changes):**`)\n for (const h of topHotspots) {\n lines.push(`- \\`${h.file}\\` — ${h.changes} changes, ${h.stability.toUpperCase()}`)\n }\n lines.push('')\n }\n\n // Hidden couplings\n const hiddenCouplings = temporal.coupling.filter(c => !c.hasImport && c.strength >= 0.5)\n if (hiddenCouplings.length > 0) {\n lines.push(`**Hidden dependencies (co-change but no import):**`)\n for (const c of hiddenCouplings.slice(0, 5)) {\n lines.push(`- \\`${c.fileA}\\` ↔ \\`${c.fileB}\\` — ${c.cochanges} co-changes (${Math.round(c.strength * 100)}%)`)\n }\n lines.push('')\n }\n\n // Bug-prone files\n const buggy = temporal.bugHistory.filter(b => b.fixCommits >= 2)\n if (buggy.length > 0) {\n lines.push(`**Bug-prone files:**`)\n for (const b of buggy.slice(0, 5)) {\n lines.push(`- \\`${b.file}\\` — ${b.fixCommits} fix commits`)\n for (const lesson of b.lessons.slice(0, 3)) {\n lines.push(` - ${lesson}`)\n }\n }\n lines.push('')\n }\n }\n\n // Knowledge available\n lines.push(`## Available Knowledge`, '')\n if (modules.length > 0) {\n lines.push(`**Module docs:** ${modules.map(m => `\\`${m}\\``).join(', ')}`)\n }\n if (decisions.length > 0) {\n lines.push(`**Decision records:** ${decisions.length}`)\n }\n lines.push(\n ``,\n `Use \\`get_module_context\\` to deep-dive into any module.`,\n `Use \\`get_change_coupling\\` before editing a file to check what else must change.`,\n `Use \\`lookup_symbol\\` to find any function, type, or class.`,\n )\n\n const content = lines.join('\\n') + '\\n'\n await writeFile(cortexPath(projectRoot, 'constitution.md'), content)\n return content\n}\n","import simpleGit from 'simple-git'\n\nexport interface CommitInfo {\n hash: string\n date: string\n message: string\n author: string\n filesChanged: string[]\n}\n\nexport async function getCommitHistory(root: string, days: number = 90): Promise<CommitInfo[]> {\n const git = simpleGit(root)\n const since = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString().split('T')[0]\n\n const log = await git.log({\n '--since': since,\n '--stat': null,\n maxCount: 500,\n })\n\n return log.all.map(commit => ({\n hash: commit.hash,\n date: commit.date,\n message: commit.message,\n author: commit.author_name,\n filesChanged: parseStatFiles(commit.diff),\n }))\n}\n\nfunction parseStatFiles(diff: { files?: { file: string }[] } | null | undefined): string[] {\n if (!diff || !diff.files) return []\n return diff.files.map((f) => f.file)\n}\n\nexport async function getLastCommitDate(root: string, file: string): Promise<string | null> {\n const git = simpleGit(root)\n try {\n const log = await git.log({ file, maxCount: 1 })\n return log.latest?.date || null\n } catch {\n return null\n }\n}\n\nexport async function isGitRepo(root: string): Promise<boolean> {\n const git = simpleGit(root)\n try {\n await git.status()\n return true\n } catch {\n return false\n }\n}\n\nexport async function getHeadCommit(root: string): Promise<string | null> {\n const git = simpleGit(root)\n try {\n const log = await git.log({ maxCount: 1 })\n return log.latest?.hash || null\n } catch {\n return null\n }\n}\n","import type { ChangeCoupling, Hotspot, BugRecord, TemporalData } from '../types/index.js'\nimport type { CommitInfo } from './history.js'\nimport { getCommitHistory } from './history.js'\n\n// Files that pollute temporal metrics (changed every release, not real code risk)\nconst TEMPORAL_NOISE_FILES = new Set([\n 'CHANGELOG.md', 'CHANGES.md', 'HISTORY.md', 'NEWS.md',\n 'package.json', 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml',\n 'Cargo.lock', 'go.sum', 'poetry.lock', 'Pipfile.lock',\n])\n\nfunction isTemporalNoise(file: string): boolean {\n const basename = file.split('/').pop() ?? ''\n return TEMPORAL_NOISE_FILES.has(basename)\n}\n\nexport async function analyzeTemporalData(root: string, days: number = 90): Promise<TemporalData> {\n const commits = await getCommitHistory(root, days)\n\n const hotspots = getHotspots(commits, days)\n const coupling = getChangeCoupling(commits)\n const bugHistory = getBugArchaeology(commits)\n\n return {\n generated: new Date().toISOString(),\n periodDays: days,\n totalCommits: commits.length,\n hotspots,\n coupling,\n bugHistory,\n }\n}\n\nexport function getHotspots(commits: CommitInfo[], days: number): Hotspot[] {\n const fileChanges = new Map<string, { count: number; lastDate: string }>()\n\n for (const commit of commits) {\n for (const file of commit.filesChanged) {\n if (isTemporalNoise(file)) continue\n const existing = fileChanges.get(file) || { count: 0, lastDate: '' }\n existing.count++\n if (commit.date > existing.lastDate) {\n existing.lastDate = commit.date\n }\n fileChanges.set(file, existing)\n }\n }\n\n const now = new Date()\n const results: Hotspot[] = []\n\n for (const [file, data] of fileChanges) {\n const lastChanged = new Date(data.lastDate)\n const daysSinceChange = Math.floor((now.getTime() - lastChanged.getTime()) / (1000 * 60 * 60 * 24))\n\n let stability: Hotspot['stability']\n if (data.count >= 8 && daysSinceChange < 7) stability = 'volatile'\n else if (data.count >= 5 && daysSinceChange < 14) stability = 'stabilizing'\n else if (data.count >= 3) stability = 'moderate'\n else if (daysSinceChange > 30) stability = 'very_stable'\n else stability = 'stable'\n\n results.push({\n file,\n changes: data.count,\n stability,\n lastChanged: data.lastDate,\n daysSinceChange,\n })\n }\n\n // Sort by change frequency (descending)\n return results.sort((a, b) => b.changes - a.changes)\n}\n\nexport function getChangeCoupling(commits: CommitInfo[]): ChangeCoupling[] {\n const pairCounts = new Map<string, number>()\n const fileCounts = new Map<string, number>()\n\n for (const commit of commits) {\n const files = commit.filesChanged.filter(f =>\n !f.endsWith('.md') && !f.endsWith('.json') && !f.endsWith('.lock') && !f.endsWith('.yaml') && !f.endsWith('.yml')\n )\n\n // Count individual file changes\n for (const file of files) {\n fileCounts.set(file, (fileCounts.get(file) || 0) + 1)\n }\n\n // Skip mega-commits for pairing (refactors/renames create noise, not real coupling)\n if (files.length > 50) continue\n\n // Count pair co-changes\n for (let i = 0; i < files.length; i++) {\n for (let j = i + 1; j < files.length; j++) {\n const key = [files[i], files[j]].sort().join('|')\n pairCounts.set(key, (pairCounts.get(key) || 0) + 1)\n }\n }\n }\n\n const results: ChangeCoupling[] = []\n\n for (const [key, cochanges] of pairCounts) {\n if (cochanges < 3) continue // Filter noise\n\n const parts = key.split('|')\n const fileA = parts[0] ?? ''\n const fileB = parts[1] ?? ''\n const maxChanges = Math.max(fileCounts.get(fileA) || 0, fileCounts.get(fileB) || 0)\n const strength = maxChanges > 0 ? cochanges / maxChanges : 0\n\n const coupling: ChangeCoupling = {\n fileA,\n fileB,\n cochanges,\n strength: Math.round(strength * 100) / 100,\n hasImport: false, // Will be enriched by graph analysis\n }\n\n if (strength >= 0.7 && !coupling.hasImport) {\n coupling.warning = `HIDDEN DEPENDENCY — ${Math.round(strength * 100)}% co-change rate`\n }\n\n results.push(coupling)\n }\n\n // Sort by co-change frequency (descending)\n return results.sort((a, b) => b.cochanges - a.cochanges)\n}\n\nexport function getBugArchaeology(commits: CommitInfo[]): BugRecord[] {\n const bugPatterns = /^(fix|bug|hotfix|patch)[\\s:(]/i\n const fileRecords = new Map<string, { fixCommits: number; lessons: Set<string> }>()\n\n for (const commit of commits) {\n if (!bugPatterns.test(commit.message)) continue\n\n // Extract lesson from commit message\n const lesson = commit.message\n .replace(/^(fix|bug|hotfix|patch)[\\s:(]+/i, '')\n .replace(/\\s*\\(#\\d+\\)$/, '') // Remove PR number\n .trim()\n\n for (const file of commit.filesChanged) {\n if (isTemporalNoise(file)) continue\n const existing = fileRecords.get(file) || { fixCommits: 0, lessons: new Set<string>() }\n existing.fixCommits++\n if (lesson) existing.lessons.add(lesson)\n fileRecords.set(file, existing)\n }\n }\n\n const results: BugRecord[] = []\n for (const [file, data] of fileRecords) {\n results.push({\n file,\n fixCommits: data.fixCommits,\n lessons: [...data.lessons],\n })\n }\n\n return results.sort((a, b) => b.fixCommits - a.fixCommits)\n}\n\nexport function getStabilitySignals(commits: CommitInfo[]): Map<string, { daysSinceChange: number; velocity: number }> {\n const now = new Date()\n const fileData = new Map<string, { lastDate: string; changes: number; firstDate: string }>()\n\n for (const commit of commits) {\n for (const file of commit.filesChanged) {\n const existing = fileData.get(file) || { lastDate: '', changes: 0, firstDate: commit.date }\n existing.changes++\n if (commit.date > existing.lastDate) existing.lastDate = commit.date\n if (commit.date < existing.firstDate) existing.firstDate = commit.date\n fileData.set(file, existing)\n }\n }\n\n const signals = new Map<string, { daysSinceChange: number; velocity: number }>()\n\n for (const [file, data] of fileData) {\n const last = new Date(data.lastDate)\n const first = new Date(data.firstDate)\n const daysSinceChange = Math.floor((now.getTime() - last.getTime()) / (1000 * 60 * 60 * 24))\n const spanDays = Math.max(1, Math.floor((last.getTime() - first.getTime()) / (1000 * 60 * 60 * 24)))\n const velocity = data.changes / spanDays * 30 // changes per 30 days\n\n signals.set(file, { daysSinceChange, velocity: Math.round(velocity * 100) / 100 })\n }\n\n return signals\n}\n\nexport function getEvolutionEvents(commits: CommitInfo[]): { date: string; type: string; description: string; filesAffected: number }[] {\n const events: { date: string; type: string; description: string; filesAffected: number }[] = []\n\n const featPattern = /^feat[\\s:(]/i\n const refactorPattern = /^refactor[\\s:(]/i\n\n for (const commit of commits) {\n const fileCount = commit.filesChanged.length\n\n if (refactorPattern.test(commit.message) && fileCount >= 3) {\n events.push({\n date: commit.date,\n type: 'refactor',\n description: commit.message,\n filesAffected: fileCount,\n })\n } else if (featPattern.test(commit.message) && fileCount >= 5) {\n events.push({\n date: commit.date,\n type: 'feature',\n description: commit.message,\n filesAffected: fileCount,\n })\n } else if (fileCount >= 10) {\n events.push({\n date: commit.date,\n type: 'major_change',\n description: commit.message,\n filesAffected: fileCount,\n })\n }\n }\n\n return events\n}\n","import type Parser from 'tree-sitter'\ntype TSNode = Parser.SyntaxNode\ntype Tree = Parser.Tree\nimport type { SymbolRecord } from '../types/index.js'\n\ninterface SymbolQuery {\n nodeTypes: Set<string>\n getKind: (type: string) => SymbolRecord['kind']\n getName: (node: TSNode) => string | null\n getSignature: (node: TSNode, source: string) => string | undefined\n isExported: (node: TSNode) => boolean\n}\n\nconst TS_JS_QUERY: SymbolQuery = {\n nodeTypes: new Set([\n 'function_declaration',\n 'class_declaration',\n 'interface_declaration',\n 'type_alias_declaration',\n 'enum_declaration',\n 'lexical_declaration',\n 'variable_declaration',\n 'method_definition',\n 'public_field_definition',\n 'export_statement',\n ]),\n getKind(type) {\n const map: Record<string, SymbolRecord['kind']> = {\n function_declaration: 'function',\n class_declaration: 'class',\n interface_declaration: 'interface',\n type_alias_declaration: 'type',\n enum_declaration: 'enum',\n lexical_declaration: 'const',\n variable_declaration: 'variable',\n method_definition: 'method',\n public_field_definition: 'property',\n }\n return map[type] || 'variable'\n },\n getName(node: TSNode) {\n const nameNode = node.childForFieldName('name')\n if (nameNode) return nameNode.text\n\n // For lexical_declaration, dig into declarators\n if (node.type === 'lexical_declaration' || node.type === 'variable_declaration') {\n const declarator = (node.namedChildren as TSNode[]).find((c: TSNode) =>\n c.type === 'variable_declarator'\n )\n if (declarator) {\n const name = declarator.childForFieldName('name')\n return name?.text || null\n }\n }\n return null\n },\n getSignature(node: TSNode, source: string) {\n const startLine = node.startPosition.row\n const lines = source.split('\\n')\n const line = lines[startLine]\n if (!line) return undefined\n const sig = line.trim()\n return sig.length > 200 ? sig.slice(0, 200) + '...' : sig\n },\n isExported(node: TSNode) {\n const parent = node.parent\n if (!parent) return false\n if (parent.type === 'export_statement') return true\n if (node.type === 'lexical_declaration') {\n return parent.type === 'export_statement'\n }\n return false\n },\n}\n\nconst PYTHON_QUERY: SymbolQuery = {\n nodeTypes: new Set([\n 'function_definition',\n 'class_definition',\n 'assignment',\n ]),\n getKind(type) {\n const map: Record<string, SymbolRecord['kind']> = {\n function_definition: 'function',\n class_definition: 'class',\n assignment: 'variable',\n }\n return map[type] || 'variable'\n },\n getName(node: TSNode) {\n const nameNode = node.childForFieldName('name')\n if (nameNode) return nameNode.text\n if (node.type === 'assignment') {\n const left = node.childForFieldName('left')\n return left?.text || null\n }\n return null\n },\n getSignature(node: TSNode, source: string) {\n const startLine = node.startPosition.row\n const lines = source.split('\\n')\n return lines[startLine]?.trim()\n },\n isExported(node: TSNode) {\n const name = PYTHON_QUERY.getName(node)\n return name ? !name.startsWith('_') : false\n },\n}\n\nconst GO_QUERY: SymbolQuery = {\n nodeTypes: new Set([\n 'function_declaration',\n 'method_declaration',\n 'type_declaration',\n 'const_declaration',\n 'var_declaration',\n ]),\n getKind(type) {\n const map: Record<string, SymbolRecord['kind']> = {\n function_declaration: 'function',\n method_declaration: 'method',\n type_declaration: 'type',\n const_declaration: 'const',\n var_declaration: 'variable',\n }\n return map[type] || 'variable'\n },\n getName(node: TSNode) {\n const nameNode = node.childForFieldName('name')\n if (nameNode) return nameNode.text\n\n // Go wraps declarations: type_declaration→type_spec, const_declaration→const_spec, var_declaration→var_spec\n // The name field is on the _spec child, not the _declaration itself\n if (node.type === 'type_declaration' || node.type === 'const_declaration' || node.type === 'var_declaration') {\n for (const child of node.namedChildren as TSNode[]) {\n if (child.type === 'type_spec' || child.type === 'const_spec' || child.type === 'var_spec') {\n const specName = child.childForFieldName('name')\n if (specName) return specName.text\n }\n }\n }\n\n return null\n },\n getSignature(node: TSNode, source: string) {\n const startLine = node.startPosition.row\n const lines = source.split('\\n')\n return lines[startLine]?.trim()\n },\n isExported(node: TSNode) {\n const name = GO_QUERY.getName(node)\n return name ? /^[A-Z]/.test(name) : false\n },\n}\n\nconst RUST_QUERY: SymbolQuery = {\n nodeTypes: new Set([\n 'function_item',\n 'struct_item',\n 'enum_item',\n 'impl_item',\n 'trait_item',\n 'type_item',\n 'const_item',\n 'static_item',\n ]),\n getKind(type) {\n const map: Record<string, SymbolRecord['kind']> = {\n function_item: 'function',\n struct_item: 'class',\n enum_item: 'enum',\n impl_item: 'class',\n trait_item: 'interface',\n type_item: 'type',\n const_item: 'const',\n static_item: 'variable',\n }\n return map[type] || 'variable'\n },\n getName(node: TSNode) {\n const nameNode = node.childForFieldName('name')\n return nameNode?.text || null\n },\n getSignature(node: TSNode, source: string) {\n const startLine = node.startPosition.row\n const lines = source.split('\\n')\n return lines[startLine]?.trim()\n },\n isExported(node: TSNode) {\n const text = node.text\n return text.startsWith('pub ')\n },\n}\n\nconst C_CPP_QUERY: SymbolQuery = {\n nodeTypes: new Set([\n 'function_definition',\n 'declaration',\n 'struct_specifier',\n 'enum_specifier',\n 'union_specifier',\n 'type_definition',\n 'preproc_function_def',\n // C++ additions\n 'class_specifier',\n 'namespace_definition',\n ]),\n getKind(type) {\n const map: Record<string, SymbolRecord['kind']> = {\n function_definition: 'function',\n declaration: 'variable',\n struct_specifier: 'class',\n enum_specifier: 'enum',\n union_specifier: 'class',\n type_definition: 'type',\n preproc_function_def: 'function',\n class_specifier: 'class',\n namespace_definition: 'class',\n }\n return map[type] || 'variable'\n },\n getName(node: TSNode) {\n // Try 'name' field (struct, enum, class, namespace, macro)\n const nameNode = node.childForFieldName('name')\n if (nameNode) return nameNode.text\n\n // For function_definition and declaration: dig through declarator chain\n let declarator = node.childForFieldName('declarator')\n while (declarator) {\n if (declarator.type === 'identifier' || declarator.type === 'type_identifier' || declarator.type === 'field_identifier') {\n return declarator.text\n }\n const inner = declarator.childForFieldName('declarator')\n if (inner) {\n declarator = inner\n continue\n }\n const declName = declarator.childForFieldName('name')\n if (declName) return declName.text\n break\n }\n\n return null\n },\n getSignature(node: TSNode, source: string) {\n const startLine = node.startPosition.row\n const lines = source.split('\\n')\n const line = lines[startLine]\n if (!line) return undefined\n const sig = line.trim()\n return sig.length > 200 ? sig.slice(0, 200) + '...' : sig\n },\n isExported(node: TSNode) {\n // C: static means file-private, everything else at top level is exported\n if (node.text.startsWith('static ')) return false\n if (node.text.startsWith('public ')) return true\n return node.parent?.type === 'translation_unit' || false\n },\n}\n\nconst JAVA_QUERY: SymbolQuery = {\n nodeTypes: new Set([\n 'class_declaration',\n 'interface_declaration',\n 'enum_declaration',\n 'method_declaration',\n 'constructor_declaration',\n 'field_declaration',\n 'annotation_type_declaration',\n // Kotlin\n 'function_declaration',\n 'object_declaration',\n ]),\n getKind(type) {\n const map: Record<string, SymbolRecord['kind']> = {\n class_declaration: 'class',\n interface_declaration: 'interface',\n enum_declaration: 'enum',\n method_declaration: 'method',\n constructor_declaration: 'method',\n field_declaration: 'property',\n annotation_type_declaration: 'interface',\n function_declaration: 'function',\n object_declaration: 'class',\n }\n return map[type] || 'variable'\n },\n getName(node: TSNode) {\n const nameNode = node.childForFieldName('name')\n if (nameNode) return nameNode.text\n // For field_declaration: dig into declarators\n for (const child of node.namedChildren as TSNode[]) {\n if (child.type === 'variable_declarator') {\n const name = child.childForFieldName('name')\n if (name) return name.text\n }\n }\n return null\n },\n getSignature(node: TSNode, source: string) {\n const startLine = node.startPosition.row\n const lines = source.split('\\n')\n const line = lines[startLine]\n if (!line) return undefined\n const sig = line.trim()\n return sig.length > 200 ? sig.slice(0, 200) + '...' : sig\n },\n isExported(node: TSNode) {\n return node.text.startsWith('public ') || node.text.startsWith('protected ')\n },\n}\n\nconst GENERIC_QUERY: SymbolQuery = {\n nodeTypes: new Set([\n // Functions\n 'function_declaration', 'function_definition', 'function_item',\n 'method_declaration', 'method_definition', 'method',\n // Classes / structs\n 'class_declaration', 'class_definition', 'class_specifier',\n 'struct_specifier', 'struct_item', 'struct_declaration',\n 'module_definition', 'module',\n // Interfaces / traits / protocols\n 'interface_declaration', 'trait_item', 'protocol_declaration',\n // Enums\n 'enum_declaration', 'enum_item', 'enum_specifier', 'enum_definition',\n // Types\n 'type_declaration', 'type_alias_declaration', 'type_item', 'type_definition',\n // Constants\n 'const_declaration', 'const_item',\n ]),\n getKind(type) {\n if (type.includes('function') || type.includes('method')) return 'function'\n if (type.includes('class') || type.includes('struct') || type.includes('module')) return 'class'\n if (type.includes('interface') || type.includes('trait') || type.includes('protocol')) return 'interface'\n if (type.includes('enum')) return 'enum'\n if (type.includes('type')) return 'type'\n if (type.includes('const')) return 'const'\n return 'variable'\n },\n getName(node: TSNode) {\n // Try standard 'name' field (most languages)\n const nameNode = node.childForFieldName('name')\n if (nameNode) return nameNode.text\n\n // Try 'declarator' chain (C-family)\n let declarator = node.childForFieldName('declarator')\n while (declarator) {\n if (declarator.type === 'identifier' || declarator.type === 'type_identifier') return declarator.text\n const inner = declarator.childForFieldName('declarator') || declarator.childForFieldName('name')\n if (inner) {\n if (inner.type === 'identifier' || inner.type === 'type_identifier') return inner.text\n declarator = inner\n continue\n }\n break\n }\n\n // Last resort: first identifier child\n for (const child of node.namedChildren as TSNode[]) {\n if (child.type === 'identifier' || child.type === 'type_identifier') return child.text\n }\n\n return null\n },\n getSignature(node: TSNode, source: string) {\n const startLine = node.startPosition.row\n const lines = source.split('\\n')\n const line = lines[startLine]\n if (!line) return undefined\n const sig = line.trim()\n return sig.length > 200 ? sig.slice(0, 200) + '...' : sig\n },\n isExported(node: TSNode) {\n const text = node.text\n if (text.startsWith('pub ') || text.startsWith('public ') || text.startsWith('export ')) return true\n const parent = node.parent\n if (parent?.type === 'export_statement') return true\n return false\n },\n}\n\nfunction getQuery(language: string): SymbolQuery {\n switch (language) {\n case 'typescript':\n case 'tsx':\n case 'javascript':\n return TS_JS_QUERY\n case 'python':\n return PYTHON_QUERY\n case 'go':\n return GO_QUERY\n case 'rust':\n return RUST_QUERY\n case 'c':\n case 'cpp':\n case 'objc':\n return C_CPP_QUERY\n case 'java':\n case 'kotlin':\n case 'c_sharp':\n case 'scala':\n case 'dart':\n return JAVA_QUERY\n default:\n return GENERIC_QUERY\n }\n}\n\nexport function extractSymbols(tree: Tree, file: string, language: string, source: string): SymbolRecord[] {\n const query = getQuery(language)\n const symbols: SymbolRecord[] = []\n\n function walk(node: TSNode, parentName?: string) {\n if (query.nodeTypes.has(node.type)) {\n if (node.type === 'export_statement') {\n const declaration = (node.namedChildren as TSNode[]).find((c: TSNode) => query.nodeTypes.has(c.type))\n if (declaration) {\n const name = query.getName(declaration)\n if (name) {\n symbols.push({\n name,\n kind: query.getKind(declaration.type),\n file,\n startLine: declaration.startPosition.row + 1,\n endLine: declaration.endPosition.row + 1,\n signature: query.getSignature(declaration, source),\n exported: true,\n parentName,\n })\n }\n for (const child of declaration.namedChildren as TSNode[]) {\n walk(child, name || parentName)\n }\n return\n }\n return\n }\n\n const name = query.getName(node)\n if (name) {\n symbols.push({\n name,\n kind: query.getKind(node.type),\n file,\n startLine: node.startPosition.row + 1,\n endLine: node.endPosition.row + 1,\n signature: query.getSignature(node, source),\n exported: query.isExported(node),\n parentName,\n })\n }\n\n for (const child of node.namedChildren as TSNode[]) {\n walk(child, name || parentName)\n }\n return\n }\n\n for (const child of node.namedChildren as TSNode[]) {\n walk(child, parentName)\n }\n }\n\n walk(tree.rootNode)\n return symbols\n}\n","import type Parser from 'tree-sitter'\ntype TSNode = Parser.SyntaxNode\ntype Tree = Parser.Tree\nimport type { ImportEdge } from '../types/index.js'\nimport { dirname, join } from 'node:path'\nimport { existsSync } from 'node:fs'\n\nexport function extractImports(tree: Tree, file: string, language: string): ImportEdge[] {\n switch (language) {\n case 'typescript':\n case 'tsx':\n case 'javascript':\n return extractTsImports(tree, file)\n case 'python':\n return extractPythonImports(tree, file)\n case 'go':\n return extractGoImports(tree, file)\n case 'rust':\n return extractRustImports(tree, file)\n case 'c':\n case 'cpp':\n case 'objc':\n return extractCIncludes(tree, file)\n case 'java':\n case 'kotlin':\n case 'c_sharp':\n case 'scala':\n case 'dart':\n return extractJavaImports(tree, file)\n default:\n return extractGenericImports(tree, file)\n }\n}\n\nfunction extractTsImports(tree: Tree, file: string): ImportEdge[] {\n const imports: ImportEdge[] = []\n\n function walk(node: TSNode) {\n if (node.type === 'import_statement') {\n const sourceNode = node.childForFieldName('source')\n if (!sourceNode) {\n for (const child of node.namedChildren as TSNode[]) {\n walk(child)\n }\n return\n }\n\n const rawPath = sourceNode.text.replace(/['\"]/g, '')\n\n if (!rawPath.startsWith('.')) {\n return\n }\n\n const resolved = resolveImportPath(file, rawPath)\n const specifiers = extractSpecifiers(node)\n\n imports.push({\n source: file,\n target: resolved,\n specifiers,\n })\n return\n }\n\n for (const child of node.namedChildren as TSNode[]) {\n walk(child)\n }\n }\n\n walk(tree.rootNode)\n return imports\n}\n\nfunction extractSpecifiers(importNode: TSNode): string[] {\n const specifiers: string[] = []\n\n function walk(node: TSNode) {\n if (node.type === 'import_specifier') {\n const name = node.childForFieldName('name')\n if (name) specifiers.push(name.text)\n } else if (node.type === 'namespace_import') {\n specifiers.push('*')\n } else if (node.type === 'identifier' && node.parent?.type === 'import_clause') {\n specifiers.push(node.text)\n }\n\n for (const child of node.namedChildren as TSNode[]) {\n walk(child)\n }\n }\n\n walk(importNode)\n return specifiers\n}\n\nfunction resolveImportPath(fromFile: string, importPath: string): string {\n const dir = dirname(fromFile)\n let resolved = join(dir, importPath)\n\n resolved = resolved.replace(/\\.(js|ts|tsx|jsx|mjs)$/, '')\n\n const extensions = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '/index.ts', '/index.js']\n for (const ext of extensions) {\n if (existsSync(resolved + ext)) {\n return resolved + ext\n }\n }\n\n return resolved + '.ts'\n}\n\nfunction extractPythonImports(tree: Tree, file: string): ImportEdge[] {\n const imports: ImportEdge[] = []\n\n function walk(node: TSNode) {\n if (node.type === 'import_from_statement') {\n const moduleNode = node.childForFieldName('module_name')\n if (moduleNode) {\n const modulePath = moduleNode.text\n if (modulePath.startsWith('.')) {\n const specifiers: string[] = []\n for (const child of node.namedChildren as TSNode[]) {\n if (child.type === 'dotted_name' && child !== moduleNode) {\n specifiers.push(child.text)\n }\n }\n imports.push({\n source: file,\n target: resolvePythonImport(file, modulePath),\n specifiers,\n })\n }\n }\n }\n\n for (const child of node.namedChildren as TSNode[]) {\n walk(child)\n }\n }\n\n walk(tree.rootNode)\n return imports\n}\n\nfunction resolvePythonImport(fromFile: string, importPath: string): string {\n const dir = dirname(fromFile)\n const parts = importPath.replace(/^\\.+/, '')\n const dots = importPath.match(/^\\.+/)?.[0].length || 1\n let base = dir\n for (let i = 1; i < dots; i++) base = dirname(base)\n return join(base, parts.replace(/\\./g, '/') + '.py')\n}\n\nfunction extractGoImports(tree: Tree, file: string): ImportEdge[] {\n const imports: ImportEdge[] = []\n\n function walk(node: TSNode) {\n if (node.type === 'import_spec') {\n const pathNode = node.childForFieldName('path')\n if (pathNode) {\n imports.push({\n source: file,\n target: pathNode.text.replace(/\"/g, ''),\n specifiers: ['*'],\n })\n }\n }\n\n for (const child of node.namedChildren as TSNode[]) {\n walk(child)\n }\n }\n\n walk(tree.rootNode)\n return imports\n}\n\nfunction extractRustImports(tree: Tree, file: string): ImportEdge[] {\n const imports: ImportEdge[] = []\n\n function walk(node: TSNode) {\n if (node.type === 'use_declaration') {\n const path = (node.namedChildren as TSNode[]).find((c: TSNode) => c.type === 'scoped_identifier' || c.type === 'use_wildcard' || c.type === 'use_list')\n if (path) {\n imports.push({\n source: file,\n target: path.text,\n specifiers: ['*'],\n })\n }\n }\n\n for (const child of node.namedChildren as TSNode[]) {\n walk(child)\n }\n }\n\n walk(tree.rootNode)\n return imports\n}\n\nfunction extractCIncludes(tree: Tree, file: string): ImportEdge[] {\n const imports: ImportEdge[] = []\n\n function walk(node: TSNode) {\n if (node.type === 'preproc_include') {\n const pathNode = node.childForFieldName('path')\n if (pathNode) {\n const raw = pathNode.text.replace(/['\"<>]/g, '')\n imports.push({ source: file, target: raw, specifiers: ['*'] })\n }\n }\n for (const child of node.namedChildren as TSNode[]) walk(child)\n }\n\n walk(tree.rootNode)\n return imports\n}\n\nfunction extractJavaImports(tree: Tree, file: string): ImportEdge[] {\n const imports: ImportEdge[] = []\n\n function walk(node: TSNode) {\n if (node.type === 'import_declaration') {\n // Java imports are like: import java.util.List;\n // The child is a scoped_identifier chain\n for (const child of node.namedChildren as TSNode[]) {\n if (child.type === 'scoped_identifier' || child.type === 'identifier') {\n imports.push({ source: file, target: child.text, specifiers: ['*'] })\n break\n }\n }\n }\n for (const child of node.namedChildren as TSNode[]) walk(child)\n }\n\n walk(tree.rootNode)\n return imports\n}\n\nfunction extractGenericImports(tree: Tree, file: string): ImportEdge[] {\n const imports: ImportEdge[] = []\n const importNodeTypes = new Set([\n 'preproc_include', 'import_declaration', 'import_statement',\n 'import_from_statement', 'use_declaration', 'namespace_use_declaration',\n ])\n\n function walk(node: TSNode) {\n if (importNodeTypes.has(node.type)) {\n const pathNode = node.childForFieldName('path') ||\n node.childForFieldName('source') ||\n node.childForFieldName('module_name')\n\n if (pathNode) {\n const raw = pathNode.text.replace(/['\"<>]/g, '')\n imports.push({ source: file, target: raw, specifiers: ['*'] })\n } else {\n // Fallback: first named child that looks like a path\n for (const child of node.namedChildren as TSNode[]) {\n if (child.type === 'scoped_identifier' || child.type === 'dotted_name' ||\n child.type === 'string_literal' || child.type === 'string') {\n imports.push({ source: file, target: child.text.replace(/['\"]/g, ''), specifiers: ['*'] })\n break\n }\n }\n }\n return\n }\n for (const child of node.namedChildren as TSNode[]) walk(child)\n }\n\n walk(tree.rootNode)\n return imports\n}\n","import type Parser from 'tree-sitter'\ntype TSNode = Parser.SyntaxNode\ntype Tree = Parser.Tree\nimport type { CallEdge } from '../types/index.js'\n\nexport function extractCalls(tree: Tree, file: string, language: string): CallEdge[] {\n switch (language) {\n case 'typescript':\n case 'tsx':\n case 'javascript':\n return extractTsCalls(tree, file)\n case 'python':\n return extractPythonCalls(tree, file)\n case 'go':\n return extractGoCalls(tree, file)\n case 'rust':\n return extractRustCalls(tree, file)\n default:\n return extractGenericCalls(tree, file)\n }\n}\n\nfunction extractTsCalls(tree: Tree, file: string): CallEdge[] {\n const calls: CallEdge[] = []\n const seen = new Set<string>()\n\n function findEnclosingFunction(node: TSNode): string {\n let current = node.parent\n while (current) {\n if (\n current.type === 'function_declaration' ||\n current.type === 'method_definition' ||\n current.type === 'arrow_function'\n ) {\n const name = current.childForFieldName('name')\n if (name) return name.text\n if (current.parent?.type === 'variable_declarator') {\n const varName = current.parent.childForFieldName('name')\n if (varName) return varName.text\n }\n return '<anonymous>'\n }\n current = current.parent\n }\n return '<module>'\n }\n\n function walk(node: TSNode) {\n if (node.type === 'call_expression') {\n const funcNode = node.childForFieldName('function')\n if (funcNode) {\n let callee: string\n if (funcNode.type === 'member_expression') {\n const prop = funcNode.childForFieldName('property')\n callee = prop?.text || funcNode.text\n } else {\n callee = funcNode.text\n }\n\n const caller = findEnclosingFunction(node)\n const key = `${caller}:${callee}:${node.startPosition.row}`\n if (!seen.has(key)) {\n seen.add(key)\n calls.push({\n caller: `${file}:${caller}`,\n callee,\n file,\n line: node.startPosition.row + 1,\n })\n }\n }\n }\n\n for (const child of node.namedChildren as TSNode[]) {\n walk(child)\n }\n }\n\n walk(tree.rootNode)\n return calls\n}\n\nfunction extractPythonCalls(tree: Tree, file: string): CallEdge[] {\n const calls: CallEdge[] = []\n const seen = new Set<string>()\n\n function findEnclosing(node: TSNode): string {\n let current = node.parent\n while (current) {\n if (current.type === 'function_definition') {\n const name = current.childForFieldName('name')\n if (name) return name.text\n }\n current = current.parent\n }\n return '<module>'\n }\n\n function walk(node: TSNode) {\n if (node.type === 'call') {\n const funcNode = node.childForFieldName('function')\n if (funcNode) {\n const callee = funcNode.type === 'attribute'\n ? funcNode.childForFieldName('attribute')?.text || funcNode.text\n : funcNode.text\n const caller = findEnclosing(node)\n const key = `${caller}:${callee}:${node.startPosition.row}`\n if (!seen.has(key)) {\n seen.add(key)\n calls.push({ caller: `${file}:${caller}`, callee, file, line: node.startPosition.row + 1 })\n }\n }\n }\n for (const child of node.namedChildren as TSNode[]) walk(child)\n }\n\n walk(tree.rootNode)\n return calls\n}\n\nfunction extractGoCalls(tree: Tree, file: string): CallEdge[] {\n const calls: CallEdge[] = []\n const seen = new Set<string>()\n\n function findEnclosing(node: TSNode): string {\n let current = node.parent\n while (current) {\n if (current.type === 'function_declaration' || current.type === 'method_declaration') {\n const name = current.childForFieldName('name')\n if (name) return name.text\n }\n current = current.parent\n }\n return '<module>'\n }\n\n function walk(node: TSNode) {\n if (node.type === 'call_expression') {\n const funcNode = node.childForFieldName('function')\n if (funcNode) {\n const callee = funcNode.type === 'selector_expression'\n ? funcNode.childForFieldName('field')?.text || funcNode.text\n : funcNode.text\n const caller = findEnclosing(node)\n const key = `${caller}:${callee}:${node.startPosition.row}`\n if (!seen.has(key)) {\n seen.add(key)\n calls.push({ caller: `${file}:${caller}`, callee, file, line: node.startPosition.row + 1 })\n }\n }\n }\n for (const child of node.namedChildren as TSNode[]) walk(child)\n }\n\n walk(tree.rootNode)\n return calls\n}\n\nfunction extractRustCalls(tree: Tree, file: string): CallEdge[] {\n const calls: CallEdge[] = []\n const seen = new Set<string>()\n\n function findEnclosing(node: TSNode): string {\n let current = node.parent\n while (current) {\n if (current.type === 'function_item') {\n const name = current.childForFieldName('name')\n if (name) return name.text\n }\n current = current.parent\n }\n return '<module>'\n }\n\n function walk(node: TSNode) {\n if (node.type === 'call_expression') {\n const funcNode = node.childForFieldName('function')\n if (funcNode) {\n const callee = funcNode.text.split('::').pop() || funcNode.text\n const caller = findEnclosing(node)\n const key = `${caller}:${callee}:${node.startPosition.row}`\n if (!seen.has(key)) {\n seen.add(key)\n calls.push({ caller: `${file}:${caller}`, callee, file, line: node.startPosition.row + 1 })\n }\n }\n }\n for (const child of node.namedChildren as TSNode[]) walk(child)\n }\n\n walk(tree.rootNode)\n return calls\n}\n\nfunction extractGenericCalls(tree: Tree, file: string): CallEdge[] {\n const calls: CallEdge[] = []\n const seen = new Set<string>()\n\n function findEnclosing(node: TSNode): string {\n let current = node.parent\n while (current) {\n if (current.type.includes('function') || current.type.includes('method')) {\n const name = current.childForFieldName('name')\n if (name) return name.text\n }\n current = current.parent\n }\n return '<module>'\n }\n\n function walk(node: TSNode) {\n if (node.type === 'call_expression' || node.type === 'call') {\n const funcNode = node.childForFieldName('function') || node.childForFieldName('method')\n if (funcNode) {\n let callee: string\n if (funcNode.type.includes('member') || funcNode.type.includes('selector') || funcNode.type === 'attribute') {\n const prop = funcNode.childForFieldName('property') ||\n funcNode.childForFieldName('field') ||\n funcNode.childForFieldName('attribute')\n callee = prop?.text || funcNode.text\n } else {\n callee = funcNode.text\n }\n\n const caller = findEnclosing(node)\n const key = `${caller}:${callee}:${node.startPosition.row}`\n if (!seen.has(key)) {\n seen.add(key)\n calls.push({ caller: `${file}:${caller}`, callee, file, line: node.startPosition.row + 1 })\n }\n }\n }\n for (const child of node.namedChildren as TSNode[]) walk(child)\n }\n\n walk(tree.rootNode)\n return calls\n}\n","import { existsSync } from 'node:fs'\nimport { cortexPath } from '../utils/files.js'\nimport { writeModuleDoc } from './modules.js'\nimport { getModuleDependencies } from './graph.js'\nimport type { DependencyGraph, SymbolRecord, TemporalData, ModuleAnalysis } from '../types/index.js'\n\nexport interface StructuralModuleData {\n graph: DependencyGraph\n symbols: SymbolRecord[]\n temporal: TemporalData | null\n}\n\nexport async function generateStructuralModuleDocs(\n projectRoot: string,\n data: StructuralModuleData,\n): Promise<number> {\n let generated = 0\n\n for (const mod of data.graph.modules) {\n // Never overwrite existing (possibly LLM-generated) docs\n const docPath = cortexPath(projectRoot, 'modules', `${mod.name}.md`)\n if (existsSync(docPath)) continue\n\n // Exported symbols in this module\n const moduleFiles = new Set(mod.files)\n const exported = data.symbols\n .filter(s => moduleFiles.has(s.file) && s.exported)\n .map(s => {\n const loc = s.endLine > s.startLine\n ? `${s.file}:${s.startLine}-${s.endLine}`\n : `${s.file}:${s.startLine}`\n return `${s.name} (${s.kind}, ${loc})`\n })\n\n // Dependencies\n const deps = getModuleDependencies(data.graph, mod.name)\n const importsFromModules = new Set<string>()\n const importedByModules = new Set<string>()\n\n for (const edge of deps.imports) {\n for (const other of data.graph.modules) {\n if (other.name !== mod.name && other.files.includes(edge.target)) {\n importsFromModules.add(other.name)\n }\n }\n }\n for (const edge of deps.importedBy) {\n for (const other of data.graph.modules) {\n if (other.name !== mod.name && other.files.includes(edge.source)) {\n importedByModules.add(other.name)\n }\n }\n }\n\n const depLines: string[] = []\n if (importsFromModules.size > 0) depLines.push(`Imports from: ${[...importsFromModules].join(', ')}`)\n if (importedByModules.size > 0) depLines.push(`Imported by: ${[...importedByModules].join(', ')}`)\n\n // Temporal signals\n let temporalSignals: ModuleAnalysis['temporalSignals']\n if (data.temporal) {\n const hotspots = data.temporal.hotspots.filter(h => moduleFiles.has(h.file))\n const topHotspot = hotspots[0]\n\n const couplings = data.temporal.coupling.filter(c =>\n moduleFiles.has(c.fileA) || moduleFiles.has(c.fileB)\n )\n const coupledWith = couplings.map(c => {\n const other = moduleFiles.has(c.fileA) ? c.fileB : c.fileA\n return `${other} (${c.cochanges} co-changes, ${Math.round(c.strength * 100)}%)`\n })\n\n const bugs = data.temporal.bugHistory.filter(b => moduleFiles.has(b.file))\n\n temporalSignals = {\n churn: topHotspot ? `${topHotspot.changes} changes (${topHotspot.stability})` : 'no hotspot data',\n coupledWith,\n stability: topHotspot?.stability ?? 'unknown',\n bugHistory: bugs.flatMap(b => b.lessons),\n lastChanged: topHotspot?.lastChanged ?? 'unknown',\n }\n }\n\n const analysis: ModuleAnalysis = {\n name: mod.name,\n purpose: `${mod.files.length} files, ${mod.lines} lines (${mod.language}). Auto-generated from code structure — use \\`analyze_module\\` MCP tool for semantic analysis.`,\n dataFlow: `Files: ${mod.files.join(', ')}`,\n publicApi: exported,\n gotchas: [],\n dependencies: depLines,\n temporalSignals,\n }\n\n await writeModuleDoc(projectRoot, analysis)\n generated++\n }\n\n return generated\n}\n","import { resolve } from 'node:path'\nimport { existsSync } from 'node:fs'\nimport { cortexPath } from '../../utils/files.js'\nimport { startServer } from '../../mcp/server.js'\n\nexport async function serveCommand(opts: { root: string }): Promise<void> {\n const root = resolve(opts.root)\n\n // Check if .codecortex/ exists\n if (!existsSync(cortexPath(root, 'cortex.yaml'))) {\n console.error('Error: No CodeCortex knowledge found.')\n console.error(`Run 'codecortex init' first to analyze the codebase.`)\n console.error(`Expected: ${cortexPath(root, 'cortex.yaml')}`)\n process.exit(1)\n }\n\n await startServer(root)\n}\n","import { resolve } from 'node:path'\nimport { existsSync } from 'node:fs'\nimport { cortexPath, readFile, writeFile, writeJsonStream } from '../../utils/files.js'\nimport { readManifest, updateManifest } from '../../core/manifest.js'\nimport { discoverProject } from '../../core/discovery.js'\nimport { analyzeTemporalData } from '../../git/temporal.js'\nimport { isGitRepo } from '../../git/history.js'\nimport { getUncommittedDiff } from '../../git/diff.js'\nimport { mapFilesToModules } from '../../git/diff.js'\nimport { initParser, parseFile, languageFromPath } from '../../extraction/parser.js'\nimport { extractSymbols } from '../../extraction/symbols.js'\nimport { extractImports } from '../../extraction/imports.js'\nimport { extractCalls } from '../../extraction/calls.js'\nimport { buildGraph, writeGraph, enrichCouplingWithImports } from '../../core/graph.js'\nimport { generateConstitution } from '../../core/constitution.js'\nimport { createSession, writeSession, getLatestSession } from '../../core/sessions.js'\nimport { readFile as fsRead } from 'node:fs/promises'\nimport { generateStructuralModuleDocs } from '../../core/module-gen.js'\nimport type { SymbolRecord, ImportEdge, CallEdge, SymbolIndex } from '../../types/index.js'\n\nexport async function updateCommand(opts: { root: string; days: string }): Promise<void> {\n const root = resolve(opts.root)\n const days = parseInt(opts.days, 10)\n\n if (!existsSync(cortexPath(root, 'cortex.yaml'))) {\n console.error('Error: No CodeCortex knowledge found. Run `codecortex init` first.')\n process.exit(1)\n }\n\n console.log('CodeCortex update — refreshing knowledge...')\n console.log('')\n\n // Discover current state\n console.log('Discovering changes...')\n const project = await discoverProject(root)\n\n // Re-extract all symbols (full refresh for now, incremental in v2)\n console.log('Re-extracting symbols...')\n await initParser()\n\n const allSymbols: SymbolRecord[] = []\n const allImports: ImportEdge[] = []\n const allCalls: CallEdge[] = []\n\n for (const file of project.files) {\n const lang = languageFromPath(file.path)\n if (!lang) continue\n try {\n const tree = await parseFile(file.absolutePath, lang)\n const source = await fsRead(file.absolutePath, 'utf-8')\n allSymbols.push(...extractSymbols(tree, file.path, lang, source))\n allImports.push(...extractImports(tree, file.path, lang))\n allCalls.push(...extractCalls(tree, file.path, lang))\n } catch { /* skip */ }\n }\n\n // Rebuild graph\n console.log('Rebuilding dependency graph...')\n const MODULE_ROOTS = new Set(['src', 'lib', 'pkg', 'packages', 'apps', 'extensions', 'crates', 'internal', 'cmd', 'scripts', 'tools', 'rust'])\n const moduleNodes = project.modules.map(modName => {\n const modFiles = project.files.filter(f => {\n const parts = f.path.split('/')\n const topDir = parts[0] ?? ''\n return (MODULE_ROOTS.has(topDir) && parts[1] === modName) ||\n (parts[0] === modName)\n })\n const topDir = modFiles[0]?.path.split('/')[0] ?? 'src'\n return {\n path: `${topDir}/${modName}`,\n name: modName,\n files: modFiles.map(f => f.path),\n language: modFiles[0]?.language || 'unknown',\n lines: modFiles.reduce((sum, f) => sum + f.lines, 0),\n symbols: allSymbols.filter(s => modFiles.some(f => f.path === s.file)).length,\n }\n })\n\n const externalDeps: Record<string, string[]> = {}\n for (const file of project.files) {\n try {\n const content = await fsRead(file.absolutePath, 'utf-8')\n const importMatches = content.matchAll(/from\\s+['\"]([^.\\/][^'\"]*)['\"]/g)\n for (const match of importMatches) {\n const raw = match[1]\n if (!raw) continue\n const pkg = raw.startsWith('@') ? raw.split('/').slice(0, 2).join('/') : raw.split('/')[0] ?? raw\n if (!externalDeps[pkg]) externalDeps[pkg] = []\n externalDeps[pkg]!.push(file.path)\n }\n } catch { /* skip */ }\n }\n\n const graph = buildGraph({\n modules: moduleNodes,\n imports: allImports,\n calls: allCalls,\n entryPoints: project.entryPoints,\n externalDeps,\n })\n\n // Re-analyze temporal data\n console.log('Re-analyzing git history...')\n let temporalData = null\n if (await isGitRepo(root)) {\n temporalData = await analyzeTemporalData(root, days)\n enrichCouplingWithImports(graph, temporalData.coupling)\n }\n\n // Write updated files\n console.log('Writing updated knowledge...')\n const symbolIndex: SymbolIndex = {\n generated: new Date().toISOString(),\n total: allSymbols.length,\n symbols: allSymbols,\n }\n await writeJsonStream(cortexPath(root, 'symbols.json'), symbolIndex, 'symbols')\n await writeGraph(root, graph)\n if (temporalData) {\n await writeFile(cortexPath(root, 'temporal.json'), JSON.stringify(temporalData, null, 2))\n }\n\n // Generate structural module docs (skip existing)\n await generateStructuralModuleDocs(root, {\n graph,\n symbols: allSymbols,\n temporal: temporalData,\n })\n\n // Update manifest\n await updateManifest(root, {\n totalFiles: project.files.length,\n totalSymbols: allSymbols.length,\n totalModules: project.modules.length,\n languages: project.languages,\n })\n\n // Regenerate constitution\n await generateConstitution(root, {\n modules: moduleNodes,\n entryPoints: project.entryPoints,\n externalDeps,\n temporal: temporalData,\n })\n\n // Create session log\n const diff = await getUncommittedDiff(root).catch(() => ({ filesChanged: [], summary: 'no changes' }))\n const previousSession = await getLatestSession(root)\n const affectedModules = [...mapFilesToModules(diff.filesChanged).keys()]\n const session = createSession({\n filesChanged: diff.filesChanged,\n modulesAffected: affectedModules,\n summary: `Updated knowledge. ${allSymbols.length} symbols, ${project.modules.length} modules.`,\n previousSession: previousSession || undefined,\n })\n await writeSession(root, session)\n\n console.log('')\n console.log('─'.repeat(50))\n console.log('Update complete!')\n console.log(` Symbols: ${allSymbols.length}`)\n console.log(` Modules: ${project.modules.length}`)\n if (temporalData) {\n console.log(` Commits: ${temporalData.totalCommits}`)\n }\n console.log(` Session: ${session.id}`)\n}\n","import simpleGit from 'simple-git'\n\nexport interface DiffResult {\n filesChanged: string[]\n insertions: number\n deletions: number\n summary: string\n}\n\nexport async function getUncommittedDiff(root: string): Promise<DiffResult> {\n const git = simpleGit(root)\n const diff = await git.diffSummary()\n\n return {\n filesChanged: diff.files.map(f => f.file),\n insertions: diff.insertions,\n deletions: diff.deletions,\n summary: `${diff.files.length} files changed, +${diff.insertions} -${diff.deletions}`,\n }\n}\n\nexport async function getDiffSinceCommit(root: string, commitHash: string): Promise<DiffResult> {\n const git = simpleGit(root)\n const diff = await git.diffSummary([commitHash, 'HEAD'])\n\n return {\n filesChanged: diff.files.map(f => f.file),\n insertions: diff.insertions,\n deletions: diff.deletions,\n summary: `${diff.files.length} files changed since ${commitHash.slice(0, 7)}, +${diff.insertions} -${diff.deletions}`,\n }\n}\n\nexport async function getChangedFilesSinceDate(root: string, sinceDate: string): Promise<string[]> {\n const git = simpleGit(root)\n const log = await git.log({ '--since': sinceDate, '--name-only': null })\n\n const files = new Set<string>()\n for (const commit of log.all) {\n const diff = commit.diff\n if (diff) {\n for (const file of diff.files) {\n files.add(file.file)\n }\n }\n }\n\n return [...files]\n}\n\nexport function mapFilesToModules(files: string[]): Map<string, string[]> {\n const moduleMap = new Map<string, string[]>()\n\n for (const file of files) {\n const parts = file.split('/')\n let module = 'root'\n\n if (parts[0] === 'src' && parts.length >= 3 && parts[1]) {\n module = parts[1]\n } else if (parts[0] === 'lib' && parts.length >= 3 && parts[1]) {\n module = parts[1]\n }\n\n const existing = moduleMap.get(module) || []\n existing.push(file)\n moduleMap.set(module, existing)\n }\n\n return moduleMap\n}\n","import { resolve } from 'node:path'\nimport { existsSync } from 'node:fs'\nimport { cortexPath, readFile } from '../../utils/files.js'\nimport { readManifest } from '../../core/manifest.js'\nimport { listModuleDocs } from '../../core/modules.js'\nimport { listDecisions } from '../../core/decisions.js'\nimport { listSessions, getLatestSession } from '../../core/sessions.js'\nimport type { SymbolIndex, TemporalData } from '../../types/index.js'\n\nexport async function statusCommand(opts: { root: string }): Promise<void> {\n const root = resolve(opts.root)\n\n if (!existsSync(cortexPath(root, 'cortex.yaml'))) {\n console.log('No CodeCortex knowledge found.')\n console.log(`Run 'codecortex init' to analyze this codebase.`)\n return\n }\n\n const manifest = await readManifest(root)\n if (!manifest) {\n console.log('Error reading cortex.yaml')\n return\n }\n\n console.log(`CodeCortex Status — ${manifest.project}`)\n console.log('─'.repeat(50))\n console.log('')\n\n // Core stats\n console.log('Knowledge Store:')\n console.log(` Version: ${manifest.version}`)\n console.log(` Languages: ${manifest.languages.join(', ')}`)\n console.log(` Files: ${manifest.totalFiles}`)\n console.log(` Symbols: ${manifest.totalSymbols}`)\n console.log(` Modules: ${manifest.totalModules}`)\n console.log(` Generated: ${manifest.generated}`)\n console.log(` Last updated: ${manifest.lastUpdated}`)\n console.log('')\n\n // Freshness\n const lastUpdated = new Date(manifest.lastUpdated)\n const ageHours = Math.floor((Date.now() - lastUpdated.getTime()) / (1000 * 60 * 60))\n const ageLabel = ageHours < 1 ? 'just now' :\n ageHours < 24 ? `${ageHours} hours ago` :\n `${Math.floor(ageHours / 24)} days ago`\n console.log(`Freshness: ${ageLabel}`)\n if (ageHours > 24) {\n console.log(' Consider running `codecortex update` to refresh.')\n }\n console.log('')\n\n // Knowledge breakdown\n const modules = await listModuleDocs(root)\n const decisions = await listDecisions(root)\n const sessions = await listSessions(root)\n\n console.log('Knowledge Breakdown:')\n console.log(` Module docs: ${modules.length}${modules.length > 0 ? ` (${modules.join(', ')})` : ''}`)\n console.log(` Decision records: ${decisions.length}`)\n console.log(` Session logs: ${sessions.length}`)\n\n // Check for patterns\n const patterns = await readFile(cortexPath(root, 'patterns.md'))\n const patternCount = patterns ? (patterns.match(/^### /gm) || []).length : 0\n console.log(` Coding patterns: ${patternCount}`)\n console.log('')\n\n // Symbol breakdown\n const symbolContent = await readFile(cortexPath(root, 'symbols.json'))\n if (symbolContent) {\n const index: SymbolIndex = JSON.parse(symbolContent)\n const byKind = new Map<string, number>()\n for (const s of index.symbols) {\n byKind.set(s.kind, (byKind.get(s.kind) || 0) + 1)\n }\n console.log('Symbol Index:')\n for (const [kind, count] of [...byKind.entries()].sort((a, b) => b[1] - a[1])) {\n console.log(` ${kind}: ${count}`)\n }\n const exported = index.symbols.filter(s => s.exported).length\n console.log(` Total exported: ${exported}/${index.total}`)\n console.log('')\n }\n\n // Temporal summary\n const temporalContent = await readFile(cortexPath(root, 'temporal.json'))\n if (temporalContent) {\n const temporal: TemporalData = JSON.parse(temporalContent)\n console.log('Temporal Analysis:')\n console.log(` Period: ${temporal.periodDays} days, ${temporal.totalCommits} commits`)\n console.log(` Hotspots: ${temporal.hotspots.filter(h => h.stability === 'volatile').length} volatile, ${temporal.hotspots.filter(h => h.stability === 'stabilizing').length} stabilizing`)\n console.log(` Couplings: ${temporal.coupling.length} pairs (${temporal.coupling.filter(c => !c.hasImport).length} hidden)`)\n console.log(` Bug records: ${temporal.bugHistory.length} files with fix history`)\n\n // Top 3 hotspots\n const top = temporal.hotspots.slice(0, 3)\n if (top.length > 0) {\n console.log(` Top hotspots:`)\n for (const h of top) {\n console.log(` ${h.file} — ${h.changes} changes (${h.stability})`)\n }\n }\n }\n\n // Feedback\n const feedbackContent = await readFile(cortexPath(root, 'feedback', 'log.json'))\n if (feedbackContent) {\n const feedback = JSON.parse(feedbackContent)\n if (feedback.length > 0) {\n console.log('')\n console.log(`Pending feedback: ${feedback.length} reports (will be addressed on next update)`)\n }\n }\n\n // Latest session\n const latestSession = await getLatestSession(root)\n if (latestSession) {\n console.log('')\n console.log(`Latest session: ${latestSession}`)\n }\n}\n","import { resolve } from 'node:path'\nimport { existsSync } from 'node:fs'\nimport { cortexPath, readFile } from '../../utils/files.js'\nimport type { SymbolIndex } from '../../types/index.js'\n\nexport async function symbolsCommand(\n query: string | undefined,\n opts: { root: string; kind?: string; file?: string; exported?: boolean; limit?: string },\n): Promise<void> {\n const root = resolve(opts.root)\n\n if (!existsSync(cortexPath(root, 'cortex.yaml'))) {\n console.log('No CodeCortex knowledge found.')\n console.log(`Run 'codecortex init' to analyze this codebase.`)\n return\n }\n\n const content = await readFile(cortexPath(root, 'symbols.json'))\n if (!content) {\n console.log('No symbol index found. Run `codecortex init` first.')\n return\n }\n\n const index: SymbolIndex = JSON.parse(content)\n\n if (!query && !opts.kind && !opts.file && !opts.exported) {\n // Summary mode\n printSummary(index)\n return\n }\n\n // Query/filter mode\n let matches = index.symbols\n\n if (query) {\n const q = query.toLowerCase()\n matches = matches.filter(s => s.name.toLowerCase().includes(q))\n }\n if (opts.kind) {\n matches = matches.filter(s => s.kind === opts.kind)\n }\n if (opts.file) {\n matches = matches.filter(s => s.file.includes(opts.file!))\n }\n if (opts.exported) {\n matches = matches.filter(s => s.exported)\n }\n\n const limit = parseInt(opts.limit ?? '30', 10)\n const display = matches.slice(0, limit)\n\n if (display.length === 0) {\n console.log(`No symbols found${query ? ` matching \"${query}\"` : ''}.`)\n return\n }\n\n // Print results\n console.log('')\n for (const s of display) {\n const lines = s.endLine > s.startLine ? `${s.startLine}-${s.endLine}` : `${s.startLine}`\n const exp = s.exported ? 'exported' : 'local'\n console.log(` ${pad(s.kind, 12)} ${pad(s.name, 30)} ${pad(s.file, 40)} ${pad(lines, 10)} ${exp}`)\n if (s.signature) {\n console.log(`${' '.repeat(14)}${s.signature}`)\n }\n }\n\n console.log('')\n if (matches.length > limit) {\n console.log(`Showing ${limit} of ${matches.length} matches. Use -l to show more.`)\n } else {\n console.log(`${matches.length} symbol${matches.length === 1 ? '' : 's'} found.`)\n }\n}\n\nfunction printSummary(index: SymbolIndex): void {\n console.log('')\n console.log(`Symbol Index: ${index.total} symbols`)\n console.log('─'.repeat(50))\n\n // Count by kind\n const byKind = new Map<string, number>()\n for (const s of index.symbols) {\n byKind.set(s.kind, (byKind.get(s.kind) ?? 0) + 1)\n }\n console.log('')\n console.log('By Kind:')\n for (const [kind, count] of [...byKind.entries()].sort((a, b) => b[1] - a[1])) {\n console.log(` ${pad(kind, 14)} ${count}`)\n }\n\n // Count by file (top 10)\n const byFile = new Map<string, number>()\n for (const s of index.symbols) {\n byFile.set(s.file, (byFile.get(s.file) ?? 0) + 1)\n }\n console.log('')\n console.log('Top Files:')\n for (const [file, count] of [...byFile.entries()].sort((a, b) => b[1] - a[1]).slice(0, 10)) {\n console.log(` ${pad(file, 45)} ${count} symbols`)\n }\n\n const exported = index.symbols.filter(s => s.exported).length\n console.log('')\n console.log(`Exported: ${exported}/${index.total}`)\n console.log('')\n console.log('Run `codecortex symbols <query>` to search.')\n}\n\nfunction pad(str: string, len: number): string {\n return str.length >= len ? str : str + ' '.repeat(len - str.length)\n}\n","import { resolve } from 'node:path'\nimport { existsSync } from 'node:fs'\nimport { cortexPath } from '../../utils/files.js'\nimport { searchKnowledge } from '../../core/search.js'\n\nexport async function searchCommand(\n query: string,\n opts: { root: string; limit?: string },\n): Promise<void> {\n const root = resolve(opts.root)\n\n if (!existsSync(cortexPath(root, 'cortex.yaml'))) {\n console.log('No CodeCortex knowledge found.')\n console.log(`Run 'codecortex init' to analyze this codebase.`)\n return\n }\n\n const results = await searchKnowledge(root, query)\n const limit = parseInt(opts.limit ?? '20', 10)\n const display = results.slice(0, limit)\n\n if (display.length === 0) {\n console.log(`No results for \"${query}\".`)\n return\n }\n\n console.log('')\n console.log(`Search: \"${query}\"`)\n console.log('─'.repeat(50))\n\n for (let i = 0; i < display.length; i++) {\n const r = display[i]!\n console.log('')\n console.log(` [${i + 1}] ${r.file}:${r.line}`)\n\n // Print context lines, highlight the match\n const ctxLines = r.context.split('\\n')\n for (const line of ctxLines) {\n const trimmed = line.trim()\n if (!trimmed) continue\n if (trimmed.toLowerCase().includes(query.toLowerCase())) {\n console.log(` > ${trimmed}`)\n } else {\n console.log(` ${trimmed}`)\n }\n }\n }\n\n console.log('')\n if (results.length > limit) {\n console.log(`Showing ${limit} of ${results.length} results. Use -l to show more.`)\n } else {\n console.log(`${results.length} result${results.length === 1 ? '' : 's'} found.`)\n }\n}\n","import { resolve } from 'node:path'\nimport { existsSync } from 'node:fs'\nimport { cortexPath } from '../../utils/files.js'\nimport { readGraph, getModuleDependencies } from '../../core/graph.js'\nimport { readModuleDoc, listModuleDocs } from '../../core/modules.js'\n\nexport async function modulesCommand(\n name: string | undefined,\n opts: { root: string },\n): Promise<void> {\n const root = resolve(opts.root)\n\n if (!existsSync(cortexPath(root, 'cortex.yaml'))) {\n console.log('No CodeCortex knowledge found.')\n console.log(`Run 'codecortex init' to analyze this codebase.`)\n return\n }\n\n const graph = await readGraph(root)\n if (!graph) {\n console.log('No dependency graph found. Run `codecortex init` first.')\n return\n }\n\n if (!name) {\n await printModuleList(root, graph)\n return\n }\n\n await printModuleDetail(root, name, graph)\n}\n\nasync function printModuleList(\n root: string,\n graph: import('../../types/index.js').DependencyGraph,\n): Promise<void> {\n const docsAvailable = new Set(await listModuleDocs(root))\n\n console.log('')\n console.log(`Modules: ${graph.modules.length}`)\n console.log('─'.repeat(70))\n console.log('')\n console.log(` ${pad('MODULE', 18)} ${pad('FILES', 6)} ${pad('LINES', 7)} ${pad('SYMBOLS', 8)} ${pad('LANG', 14)} DOC`)\n\n for (const mod of [...graph.modules].sort((a, b) => a.name.localeCompare(b.name))) {\n const hasDoc = docsAvailable.has(mod.name) ? 'yes' : '--'\n console.log(` ${pad(mod.name, 18)} ${pad(String(mod.files.length), 6)} ${pad(String(mod.lines), 7)} ${pad(String(mod.symbols), 8)} ${pad(mod.language, 14)} ${hasDoc}`)\n }\n\n const withDocs = graph.modules.filter(m => docsAvailable.has(m.name)).length\n console.log('')\n console.log(`${graph.modules.length} modules, ${withDocs} with docs.`)\n console.log('')\n console.log('Run `codecortex modules <name>` to deep-dive into a module.')\n}\n\nasync function printModuleDetail(\n root: string,\n name: string,\n graph: import('../../types/index.js').DependencyGraph,\n): Promise<void> {\n const mod = graph.modules.find(m => m.name === name)\n if (!mod) {\n const available = graph.modules.map(m => m.name).join(', ')\n console.log(`Module \"${name}\" not found. Available: ${available}`)\n return\n }\n\n console.log('')\n console.log(`Module: ${name}`)\n console.log('═'.repeat(50))\n\n // Module doc\n const doc = await readModuleDoc(root, name)\n if (doc) {\n console.log('')\n console.log(doc)\n } else {\n console.log('')\n console.log(`No module doc for \"${name}\".`)\n console.log(`Run \\`codecortex init\\` to generate structural docs.`)\n }\n\n // Dependencies\n const deps = getModuleDependencies(graph, name)\n\n if (deps.imports.length > 0) {\n console.log('')\n console.log('Imports:')\n const seen = new Set<string>()\n for (const edge of deps.imports) {\n const key = `${edge.source} -> ${edge.target}`\n if (seen.has(key)) continue\n seen.add(key)\n const specifiers = edge.specifiers.length > 0 ? ` [${edge.specifiers.join(', ')}]` : ''\n console.log(` ${edge.source} -> ${edge.target}${specifiers}`)\n }\n }\n\n if (deps.importedBy.length > 0) {\n console.log('')\n console.log('Imported By:')\n const seen = new Set<string>()\n for (const edge of deps.importedBy) {\n const key = `${edge.source} -> ${edge.target}`\n if (seen.has(key)) continue\n seen.add(key)\n const specifiers = edge.specifiers.length > 0 ? ` [${edge.specifiers.join(', ')}]` : ''\n console.log(` ${edge.source} -> ${edge.target}${specifiers}`)\n }\n }\n\n console.log('')\n console.log(`Stats: ${mod.files.length} files, ${mod.lines} lines, ${mod.symbols} symbols (${mod.language})`)\n}\n\nfunction pad(str: string, len: number): string {\n return str.length >= len ? str : str + ' '.repeat(len - str.length)\n}\n","import { resolve } from 'node:path'\nimport { existsSync } from 'node:fs'\nimport { cortexPath, readFile } from '../../utils/files.js'\nimport type { TemporalData } from '../../types/index.js'\n\nexport async function hotspotsCommand(\n opts: { root: string; limit?: string },\n): Promise<void> {\n const root = resolve(opts.root)\n\n if (!existsSync(cortexPath(root, 'cortex.yaml'))) {\n console.log('No CodeCortex knowledge found.')\n console.log(`Run 'codecortex init' to analyze this codebase.`)\n return\n }\n\n const content = await readFile(cortexPath(root, 'temporal.json'))\n if (!content) {\n console.log('No temporal data found. Run `codecortex init` in a git repository.')\n return\n }\n\n const temporal: TemporalData = JSON.parse(content)\n const limit = parseInt(opts.limit ?? '15', 10)\n\n // Same risk formula as MCP get_hotspots (read.ts:260-285)\n const riskMap = new Map<string, { churn: number; couplings: number; bugs: number; risk: number }>()\n\n for (const h of temporal.hotspots) {\n riskMap.set(h.file, { churn: h.changes, couplings: 0, bugs: 0, risk: h.changes })\n }\n\n for (const c of temporal.coupling) {\n for (const f of [c.fileA, c.fileB]) {\n const entry = riskMap.get(f) ?? { churn: 0, couplings: 0, bugs: 0, risk: 0 }\n entry.couplings++\n entry.risk += c.strength * 2\n riskMap.set(f, entry)\n }\n }\n\n for (const b of temporal.bugHistory) {\n const entry = riskMap.get(b.file) ?? { churn: 0, couplings: 0, bugs: 0, risk: 0 }\n entry.bugs = b.fixCommits\n entry.risk += b.fixCommits * 3\n riskMap.set(b.file, entry)\n }\n\n const ranked = [...riskMap.entries()]\n .sort((a, b) => b[1].risk - a[1].risk)\n .slice(0, limit)\n .map(([file, data]) => ({ file, ...data, risk: Math.round(data.risk * 100) / 100 }))\n\n console.log('')\n console.log(`Hotspots — ${temporal.periodDays} days, ${temporal.totalCommits} commits`)\n console.log('─'.repeat(70))\n console.log('')\n console.log(` ${pad('#', 4)} ${pad('FILE', 42)} ${pad('CHURN', 6)} ${pad('CPLS', 5)} ${pad('BUGS', 5)} RISK`)\n\n for (let i = 0; i < ranked.length; i++) {\n const r = ranked[i]!\n console.log(` ${pad(String(i + 1), 4)} ${pad(r.file, 42)} ${pad(String(r.churn), 6)} ${pad(String(r.couplings), 5)} ${pad(String(r.bugs), 5)} ${r.risk.toFixed(2)}`)\n }\n\n // Hidden dependencies\n const hidden = temporal.coupling.filter(c => !c.hasImport && c.strength >= 0.3)\n if (hidden.length > 0) {\n console.log('')\n console.log('Hidden Dependencies (co-change but no import):')\n for (const h of hidden.slice(0, 10)) {\n console.log(` ${h.fileA} <-> ${h.fileB} (${h.cochanges} co-changes, ${Math.round(h.strength * 100)}%)`)\n }\n if (hidden.length > 10) {\n console.log(` ... and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AO,aAAa;AAEvB,QACG,QAAQ,iBAAiB,EACzB,YAAY,oCAAoC,EAChD,OAAO,qBAAqB,0BAA0B,QAAQ,IAAI,CAAC,EACnE,OAAO,qBAAqB,2FAA2F,EACvH,OAAO,qBAAqB,qCAAqC,EACjE,OAAO,kBAAkB,4BAA4B,EACrD,OAAO,wBAAwB,eAAe,IAAI,EAClD,OAAO,CAAC,OAAO,SAAS,eAAe,OAAO,IAAI,CAAC;AAEtD,QACG,QAAQ,gBAAgB,EACxB,YAAY,8CAA8C,EAC1D,OAAO,qBAAqB,0BAA0B,QAAQ,IAAI,CAAC,EACnE,OAAO,wBAAwB,eAAe,IAAI,EAClD,OAAO,CAAC,OAAO,SAAS,cAAc,OAAO,IAAI,CAAC;AAErD,QACG,QAAQ,gBAAgB,EACxB,YAAY,kDAAkD,EAC9D,OAAO,qBAAqB,0BAA0B,QAAQ,IAAI,CAAC,EACnE,OAAO,CAAC,MAAM,SAAS,eAAe,MAAM,IAAI,CAAC;AAEpD,QACG,QAAQ,UAAU,EAClB,YAAY,2DAA2D,EACvE,OAAO,qBAAqB,0BAA0B,QAAQ,IAAI,CAAC,EACnE,OAAO,wBAAwB,2BAA2B,IAAI,EAC9D,OAAO,eAAe;AAEzB,QAAQ,MAAM;","names":["createRequire","fsRead","require","fsRead","basename","name","dirname","join","existsSync","readFile","existsSync","existsSync","readFile","topDir","resolve","existsSync","resolve","existsSync","resolve","existsSync","simpleGit","fsRead","resolve","existsSync","fsRead","topDir","resolve","existsSync","resolve","existsSync","resolve","existsSync","resolve","existsSync","resolve","existsSync","resolve","existsSync","resolve","existsSync","resolve","existsSync","pad","resolve","existsSync","resolve","existsSync","pad","require","createRequire"]}
1
+ {"version":3,"sources":["../../src/cli/index.ts","../../src/cli/commands/init.ts","../../src/core/discovery.ts","../../src/extraction/parser.ts","../../src/core/constitution.ts","../../src/git/history.ts","../../src/git/temporal.ts","../../src/extraction/symbols.ts","../../src/extraction/imports.ts","../../src/extraction/calls.ts","../../src/core/module-gen.ts","../../src/cli/commands/serve.ts","../../src/cli/commands/update.ts","../../src/git/diff.ts","../../src/cli/commands/status.ts","../../src/cli/commands/symbols.ts","../../src/cli/commands/search.ts","../../src/cli/commands/modules.ts","../../src/cli/commands/hotspots.ts","../../src/cli/commands/hook.ts","../../src/cli/commands/upgrade.ts","../../src/cli/utils/version-check.ts","../../src/cli/grouped-help.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { createRequire } from 'node:module'\nimport { Command } from 'commander'\nimport { initCommand } from './commands/init.js'\nimport { serveCommand } from './commands/serve.js'\nimport { updateCommand } from './commands/update.js'\nimport { statusCommand } from './commands/status.js'\nimport { symbolsCommand } from './commands/symbols.js'\nimport { searchCommand } from './commands/search.js'\nimport { modulesCommand } from './commands/modules.js'\nimport { hotspotsCommand } from './commands/hotspots.js'\nimport { hookInstallCommand, hookUninstallCommand, hookStatusCommand } from './commands/hook.js'\nimport { upgradeCommand } from './commands/upgrade.js'\nimport { checkForUpdate, shouldNotify, renderUpdateNotification } from './utils/version-check.js'\nimport { formatHelp } from './grouped-help.js'\n\nconst require = createRequire(import.meta.url)\nconst { version } = require('../../package.json') as { version: string }\n\n// Fire update check early (non-blocking) — result used at process exit\nconst updateCheckPromise = shouldNotify()\n ? checkForUpdate(version).catch(() => null)\n : Promise.resolve(null)\n\nconst program = new Command()\n\nprogram\n .name('codecortex')\n .description('Permanent codebase memory for AI agents — extracts symbols, deps, and patterns, serves via MCP')\n .version(version)\n .configureHelp({ formatHelp })\n\nprogram\n .command('init')\n .description('Initialize knowledge: discover files, extract symbols, analyze git')\n .option('-r, --root <path>', 'Project root directory', process.cwd())\n .option('-d, --days <number>', 'Days of git history to analyze', '90')\n .action(initCommand)\n\nprogram\n .command('serve')\n .description('Start MCP server for AI agent access')\n .option('-r, --root <path>', 'Project root directory', process.cwd())\n .action(serveCommand)\n\nprogram\n .command('update')\n .description('Update knowledge for changed files')\n .option('-r, --root <path>', 'Project root directory', process.cwd())\n .option('-d, --days <number>', 'Days of git history to re-analyze', '90')\n .action(updateCommand)\n\nprogram\n .command('status')\n .description('Show knowledge freshness and symbol counts')\n .option('-r, --root <path>', 'Project root directory', process.cwd())\n .action(statusCommand)\n\nprogram\n .command('symbols [query]')\n .description('Browse and filter the symbol index')\n .option('-r, --root <path>', 'Project root directory', process.cwd())\n .option('-k, --kind <kind>', 'Filter by kind: function, class, interface, type, const, enum, method, property, variable')\n .option('-f, --file <path>', 'Filter by file path (partial match)')\n .option('-e, --exported', 'Show only exported symbols')\n .option('-l, --limit <number>', 'Max results', '30')\n .action((query, opts) => symbolsCommand(query, opts))\n\nprogram\n .command('search <query>')\n .description('Search across all knowledge files')\n .option('-r, --root <path>', 'Project root directory', process.cwd())\n .option('-l, --limit <number>', 'Max results', '20')\n .action((query, opts) => searchCommand(query, opts))\n\nprogram\n .command('modules [name]')\n .description('List modules or deep-dive into one')\n .option('-r, --root <path>', 'Project root directory', process.cwd())\n .action((name, opts) => modulesCommand(name, opts))\n\nprogram\n .command('hotspots')\n .description('Files ranked by risk: churn + coupling + bugs')\n .option('-r, --root <path>', 'Project root directory', process.cwd())\n .option('-l, --limit <number>', 'Number of files to show', '15')\n .action(hotspotsCommand)\n\nconst hook = program.command('hook').description('Manage git hooks for auto-updating knowledge')\nhook.command('install')\n .description('Install post-commit and post-merge hooks')\n .option('-r, --root <path>', 'Project root directory', process.cwd())\n .action(hookInstallCommand)\nhook.command('uninstall')\n .description('Remove CodeCortex hooks (preserves other hooks)')\n .option('-r, --root <path>', 'Project root directory', process.cwd())\n .action(hookUninstallCommand)\nhook.command('status')\n .description('Show hook installation state and knowledge freshness')\n .option('-r, --root <path>', 'Project root directory', process.cwd())\n .action(hookStatusCommand)\n\nprogram\n .command('upgrade')\n .description('Check for and install the latest version')\n .action(() => upgradeCommand(version))\n\n// Wrap parse so we can show update notification after the command completes\nasync function main(): Promise<void> {\n await program.parseAsync()\n\n // Show update notification after command output (skip for serve and upgrade)\n const commandName = program.args[0]\n if (commandName !== 'serve' && commandName !== 'upgrade') {\n const result = await updateCheckPromise\n if (result?.isOutdated) {\n renderUpdateNotification(result.current, result.latest)\n }\n }\n}\n\nmain().catch(() => {})\n","import { resolve } from 'node:path'\nimport { discoverProject } from '../../core/discovery.js'\nimport { createManifest, writeManifest } from '../../core/manifest.js'\nimport { buildGraph, writeGraph } from '../../core/graph.js'\nimport { generateConstitution } from '../../core/constitution.js'\nimport { analyzeTemporalData } from '../../git/temporal.js'\nimport { isGitRepo, getHeadCommit } from '../../git/history.js'\nimport { enrichCouplingWithImports } from '../../core/graph.js'\nimport { initParser, parseFile, languageFromPath } from '../../extraction/parser.js'\nimport { extractSymbols } from '../../extraction/symbols.js'\nimport { extractImports } from '../../extraction/imports.js'\nimport { extractCalls } from '../../extraction/calls.js'\nimport { writeFile, writeJsonStream, ensureDir, cortexPath } from '../../utils/files.js'\nimport { readFile } from 'node:fs/promises'\nimport { generateStructuralModuleDocs } from '../../core/module-gen.js'\nimport type { SymbolRecord, ImportEdge, CallEdge, ModuleNode, SymbolIndex, ProjectInfo } from '../../types/index.js'\n\nexport async function initCommand(opts: { root: string; days: string }): Promise<void> {\n const root = resolve(opts.root)\n const days = parseInt(opts.days, 10)\n\n console.log(`CodeCortex init — analyzing ${root}`)\n console.log('')\n\n // Step 1: Discover project\n console.log('Step 1/6: Discovering project structure...')\n const project = await discoverProject(root)\n console.log(` Found ${project.files.length} files in ${project.modules.length} modules`)\n console.log(` Languages: ${project.languages.join(', ')}`)\n console.log(` Type: ${project.type}`)\n console.log('')\n\n // Step 2: Initialize tree-sitter and extract symbols\n console.log('Step 2/6: Extracting symbols with tree-sitter...')\n await initParser()\n\n const allSymbols: SymbolRecord[] = []\n const allImports: ImportEdge[] = []\n const allCalls: CallEdge[] = []\n let extractionErrors = 0\n\n let parsed = 0\n const parseable = project.files.filter(f => languageFromPath(f.path)).length\n const showProgress = parseable > 500\n\n for (const file of project.files) {\n const lang = languageFromPath(file.path)\n if (!lang) continue\n\n try {\n const tree = await parseFile(file.absolutePath, lang)\n const source = await readFile(file.absolutePath, 'utf-8')\n\n const symbols = extractSymbols(tree, file.path, lang, source)\n const imports = extractImports(tree, file.path, lang)\n const calls = extractCalls(tree, file.path, lang)\n\n allSymbols.push(...symbols)\n allImports.push(...imports)\n allCalls.push(...calls)\n } catch {\n extractionErrors++\n }\n parsed++\n if (showProgress && parsed % 5000 === 0) {\n process.stdout.write(`\\r Progress: ${parsed}/${parseable} files (${allSymbols.length} symbols)`)\n }\n }\n if (showProgress) process.stdout.write('\\r' + ' '.repeat(70) + '\\r')\n\n console.log(` Extracted ${allSymbols.length} symbols, ${allImports.length} imports, ${allCalls.length} call edges`)\n if (extractionErrors > 0) {\n console.log(` (${extractionErrors} files skipped due to parse errors)`)\n }\n console.log('')\n\n // Step 3: Build dependency graph\n console.log('Step 3/6: Building dependency graph...')\n const MODULE_ROOTS = new Set(['src', 'lib', 'pkg', 'packages', 'apps', 'extensions', 'crates', 'internal', 'cmd', 'scripts', 'tools', 'rust'])\n const moduleNodes: ModuleNode[] = project.modules.map(modName => {\n const modFiles = project.files.filter(f => {\n const parts = f.path.split('/')\n const topDir = parts[0] ?? ''\n return (MODULE_ROOTS.has(topDir) && parts[1] === modName) ||\n (parts[0] === modName)\n })\n const topDir = modFiles[0]?.path.split('/')[0] ?? 'src'\n return {\n path: `${topDir}/${modName}`,\n name: modName,\n files: modFiles.map(f => f.path),\n language: modFiles[0]?.language || 'unknown',\n lines: modFiles.reduce((sum, f) => sum + f.lines, 0),\n symbols: allSymbols.filter(s => modFiles.some(f => f.path === s.file)).length,\n }\n })\n\n // Detect external dependencies\n const externalDeps: Record<string, string[]> = {}\n for (const file of project.files) {\n try {\n const content = await readFile(file.absolutePath, 'utf-8')\n const importMatches = content.matchAll(/from\\s+['\"]([^.\\/][^'\"]*)['\"]/g)\n for (const match of importMatches) {\n const raw = match[1]\n if (!raw) continue\n const pkg = raw.startsWith('@') ? raw.split('/').slice(0, 2).join('/') : raw.split('/')[0] ?? raw\n if (!externalDeps[pkg]) externalDeps[pkg] = []\n externalDeps[pkg]!.push(file.path)\n }\n } catch { /* skip */ }\n }\n\n const graph = buildGraph({\n modules: moduleNodes,\n imports: allImports,\n calls: allCalls,\n entryPoints: project.entryPoints,\n externalDeps,\n })\n\n console.log(` ${moduleNodes.length} modules, ${Object.keys(externalDeps).length} external deps`)\n console.log('')\n\n // Step 4: Temporal analysis (git history)\n console.log('Step 4/6: Analyzing git history...')\n let temporalData = null\n const hasGit = await isGitRepo(root)\n if (hasGit) {\n temporalData = await analyzeTemporalData(root, days)\n // Enrich coupling with import graph\n enrichCouplingWithImports(graph, temporalData.coupling)\n console.log(` ${temporalData.totalCommits} commits analyzed over ${days} days`)\n console.log(` ${temporalData.hotspots.length} hotspots, ${temporalData.coupling.length} coupling pairs, ${temporalData.bugHistory.length} bug records`)\n } else {\n console.log(' No git repository found, skipping temporal analysis')\n }\n console.log('')\n\n // Step 5: Write knowledge files\n console.log('Step 5/6: Writing knowledge files...')\n await ensureDir(cortexPath(root))\n await ensureDir(cortexPath(root, 'modules'))\n await ensureDir(cortexPath(root, 'decisions'))\n await ensureDir(cortexPath(root, 'sessions'))\n\n // Write symbols.json\n const symbolIndex: SymbolIndex = {\n generated: new Date().toISOString(),\n total: allSymbols.length,\n symbols: allSymbols,\n }\n await writeJsonStream(cortexPath(root, 'symbols.json'), symbolIndex, 'symbols')\n\n // Write graph.json\n await writeGraph(root, graph)\n\n // Write temporal.json\n if (temporalData) {\n await writeFile(cortexPath(root, 'temporal.json'), JSON.stringify(temporalData, null, 2))\n }\n\n // Write overview.md\n const overview = generateOverview(project)\n await writeFile(cortexPath(root, 'overview.md'), overview)\n\n // Write manifest\n const manifest = createManifest({\n project: project.name,\n root,\n languages: project.languages,\n totalFiles: project.files.length,\n totalSymbols: allSymbols.length,\n totalModules: project.modules.length,\n })\n await writeManifest(root, manifest)\n\n // Write patterns.md (empty template)\n await writeFile(cortexPath(root, 'patterns.md'), '# Coding Patterns\\n\\nNo patterns recorded yet. Use `update_patterns` to add patterns.\\n')\n\n // Generate structural module docs\n const moduleDocsGenerated = await generateStructuralModuleDocs(root, {\n graph,\n symbols: allSymbols,\n temporal: temporalData,\n })\n\n console.log(` Written: cortex.yaml, symbols.json, graph.json, temporal.json, overview.md, patterns.md, ${moduleDocsGenerated} module docs`)\n console.log('')\n\n // Step 6: Generate constitution\n console.log('Step 6/6: Generating constitution...')\n await generateConstitution(root, {\n modules: moduleNodes,\n entryPoints: project.entryPoints,\n externalDeps,\n temporal: temporalData,\n })\n console.log(' Written: constitution.md')\n console.log('')\n\n // Summary\n const head = await getHeadCommit(root)\n console.log('─'.repeat(50))\n console.log('CodeCortex initialized successfully!')\n console.log('')\n console.log(` Project: ${project.name}`)\n console.log(` Files: ${project.files.length}`)\n console.log(` Symbols: ${allSymbols.length}`)\n console.log(` Modules: ${project.modules.length}`)\n if (temporalData) {\n console.log(` Commits: ${temporalData.totalCommits} (last ${days} days)`)\n const hidden = temporalData.coupling.filter(c => !c.hasImport && c.strength >= 0.5)\n if (hidden.length > 0) {\n console.log(` Hidden deps: ${hidden.length} (files that co-change but don't import each other)`)\n }\n }\n if (head) {\n console.log(` Git HEAD: ${head.slice(0, 7)}`)\n }\n console.log('')\n console.log(`Knowledge stored in: ${cortexPath(root)}`)\n console.log('Run `codecortex serve` to start the MCP server.')\n}\n\nfunction generateOverview(project: ProjectInfo): string {\n const lines = [\n `# ${project.name} — Overview`,\n '',\n `**Type:** ${project.type}`,\n `**Languages:** ${project.languages.join(', ')}`,\n `**Files:** ${project.files.length}`,\n '',\n `## Entry Points`,\n ...project.entryPoints.map(e => `- \\`${e}\\``),\n '',\n `## Modules`,\n ...project.modules.map(m => `- **${m}**`),\n '',\n `## File Map`,\n ]\n\n // Group files by directory\n const dirs = new Map<string, string[]>()\n for (const file of project.files) {\n const parts = file.path.split('/')\n const dir = parts.length > 1 ? parts.slice(0, -1).join('/') : '.'\n const existing = dirs.get(dir) || []\n const fileName = parts[parts.length - 1]\n if (fileName) existing.push(fileName)\n dirs.set(dir, existing)\n }\n\n for (const [dir, files] of [...dirs.entries()].sort()) {\n lines.push(`\\n### ${dir}/`)\n for (const file of files.sort()) {\n lines.push(`- ${file}`)\n }\n }\n\n return lines.join('\\n') + '\\n'\n}\n","import { execSync } from 'node:child_process'\nimport { readFile as fsRead, stat } from 'node:fs/promises'\nimport { join, relative, dirname, basename, extname } from 'node:path'\nimport { existsSync } from 'node:fs'\nimport type { DiscoveredFile, ProjectInfo } from '../types/index.js'\nimport { EXTENSION_MAP } from '../extraction/parser.js'\n\nconst IGNORED_DIRS = new Set([\n 'node_modules', '.git', 'dist', 'build', 'out', '.next', '.nuxt',\n '.output', 'coverage', '__pycache__', '.mypy_cache', '.pytest_cache',\n 'vendor', 'target', '.codecortex',\n])\n\nconst IGNORED_FILES = new Set([\n 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml',\n '.DS_Store', 'Thumbs.db',\n])\n\nexport async function discoverProject(root: string): Promise<ProjectInfo> {\n const name = detectProjectName(root)\n const type = detectProjectType(root)\n const files = await discoverFiles(root)\n const modules = detectModules(root, files)\n const entryPoints = detectEntryPoints(root, files, type)\n const languages = [...new Set(files.map(f => f.language).filter(Boolean))]\n\n return { name, root, type, files, modules, entryPoints, languages }\n}\n\nfunction detectProjectName(root: string): string {\n // Try package.json\n const pkgPath = join(root, 'package.json')\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(execSync(`cat \"${pkgPath}\"`, { encoding: 'utf-8' }))\n if (pkg.name) return pkg.name\n } catch { /* ignore */ }\n }\n\n // Try Cargo.toml\n const cargoPath = join(root, 'Cargo.toml')\n if (existsSync(cargoPath)) {\n try {\n const cargo = execSync(`cat \"${cargoPath}\"`, { encoding: 'utf-8' })\n const match = cargo.match(/name\\s*=\\s*\"(.+?)\"/)\n if (match?.[1]) return match[1]\n } catch { /* ignore */ }\n }\n\n // Fallback to directory name\n return basename(root)\n}\n\nfunction detectProjectType(root: string): ProjectInfo['type'] {\n if (existsSync(join(root, 'package.json'))) return 'node'\n if (existsSync(join(root, 'pyproject.toml')) || existsSync(join(root, 'setup.py')) || existsSync(join(root, 'requirements.txt'))) return 'python'\n if (existsSync(join(root, 'go.mod'))) return 'go'\n if (existsSync(join(root, 'Cargo.toml'))) return 'rust'\n return 'unknown'\n}\n\nasync function discoverFiles(root: string): Promise<DiscoveredFile[]> {\n const files: DiscoveredFile[] = []\n\n // Use git ls-files if in a git repo (respects .gitignore)\n let filePaths: string[]\n try {\n const output = execSync('git ls-files --cached --others --exclude-standard', {\n cwd: root,\n encoding: 'utf-8',\n maxBuffer: 10 * 1024 * 1024,\n })\n filePaths = output.trim().split('\\n').filter(Boolean)\n } catch {\n // Fallback: walk manually\n filePaths = await walkDirectory(root, root)\n }\n\n for (const relPath of filePaths) {\n const ext = extname(relPath)\n const language = EXTENSION_MAP[ext]\n if (!language) continue\n\n // Skip ignored dirs and files\n const parts = relPath.split('/')\n if (parts.some(p => IGNORED_DIRS.has(p))) continue\n if (IGNORED_FILES.has(basename(relPath))) continue\n\n const absPath = join(root, relPath)\n try {\n const s = await stat(absPath)\n const content = await fsRead(absPath, 'utf-8')\n const lines = content.split('\\n').length\n\n files.push({\n path: relPath,\n absolutePath: absPath,\n language,\n lines,\n bytes: s.size,\n })\n } catch {\n // Skip files that can't be read\n }\n }\n\n return files\n}\n\nasync function walkDirectory(root: string, baseRoot: string): Promise<string[]> {\n const { readdir } = await import('node:fs/promises')\n const paths: string[] = []\n\n const entries = await readdir(root, { withFileTypes: true })\n for (const entry of entries) {\n if (IGNORED_DIRS.has(entry.name)) continue\n if (IGNORED_FILES.has(entry.name)) continue\n\n const fullPath = join(root, entry.name)\n if (entry.isDirectory()) {\n const sub = await walkDirectory(fullPath, baseRoot)\n paths.push(...sub)\n } else if (entry.isFile()) {\n paths.push(relative(baseRoot, fullPath))\n }\n }\n\n return paths\n}\n\nfunction detectModules(root: string, files: DiscoveredFile[]): string[] {\n // Detect top-level directories under src/ (or equivalent)\n const MODULE_ROOTS = new Set(['src', 'lib', 'pkg', 'packages', 'apps', 'extensions', 'crates', 'internal', 'cmd', 'scripts', 'tools', 'rust'])\n const srcDirs = new Set<string>()\n\n for (const file of files) {\n const parts = file.path.split('/')\n if (parts.length >= 3) {\n const topDir = parts[0]\n const dir = parts[1]\n if (!topDir || !dir) continue\n\n if (MODULE_ROOTS.has(topDir)) {\n srcDirs.add(dir)\n }\n }\n }\n\n return [...srcDirs].sort()\n}\n\nfunction detectEntryPoints(root: string, files: DiscoveredFile[], type: ProjectInfo['type']): string[] {\n const entryPoints: string[] = []\n\n // Check package.json for main/bin entries\n if (type === 'node') {\n const pkgPath = join(root, 'package.json')\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(execSync(`cat \"${pkgPath}\"`, { encoding: 'utf-8' }))\n if (pkg.main) entryPoints.push(pkg.main)\n if (pkg.bin) {\n const bins = typeof pkg.bin === 'string' ? [pkg.bin] : Object.values(pkg.bin)\n entryPoints.push(...(bins as string[]))\n }\n } catch { /* ignore */ }\n }\n }\n\n // Common entry point file names\n const commonEntries = ['src/index.ts', 'src/main.ts', 'src/app.ts', 'index.ts', 'main.ts', 'main.go', 'src/main.rs', 'src/lib.rs']\n for (const entry of commonEntries) {\n if (files.some(f => f.path === entry)) {\n if (!entryPoints.includes(entry)) entryPoints.push(entry)\n }\n }\n\n return entryPoints\n}\n","import { createRequire } from 'node:module'\nimport { readFile as fsRead } from 'node:fs/promises'\n\nconst require = createRequire(import.meta.url)\nconst Parser = require('tree-sitter') as typeof import('tree-sitter')\n\n// Re-export types for consumers\nexport type Tree = import('tree-sitter').Tree\nexport type SyntaxNode = import('tree-sitter').SyntaxNode\n\nconst parser = new Parser()\n\n// Lazy grammar loaders — each grammar is require()'d on first use\ntype LanguageLoader = () => unknown\n\nconst LANGUAGE_LOADERS: Record<string, LanguageLoader> = {\n // TypeScript / JavaScript\n typescript: () => require('tree-sitter-typescript').typescript,\n tsx: () => require('tree-sitter-typescript').tsx,\n javascript: () => require('tree-sitter-javascript'),\n // Python\n python: () => require('tree-sitter-python'),\n // Go\n go: () => require('tree-sitter-go'),\n // Rust\n rust: () => require('tree-sitter-rust'),\n // Systems\n c: () => require('tree-sitter-c'),\n cpp: () => require('tree-sitter-cpp'),\n objc: () => require('tree-sitter-objc'),\n zig: () => require('tree-sitter-zig'),\n // JVM\n java: () => require('tree-sitter-java'),\n kotlin: () => require('tree-sitter-kotlin'),\n scala: () => require('tree-sitter-scala'),\n // .NET\n c_sharp: () => require('tree-sitter-c-sharp'),\n // Mobile\n swift: () => require('tree-sitter-swift'),\n dart: () => require('tree-sitter-dart'),\n // Scripting\n ruby: () => require('tree-sitter-ruby'),\n php: () => require('tree-sitter-php').php,\n lua: () => require('tree-sitter-lua'),\n bash: () => require('tree-sitter-bash'),\n elixir: () => require('tree-sitter-elixir'),\n // Functional\n ocaml: () => require('tree-sitter-ocaml').ocaml,\n elm: () => require('tree-sitter-elm'),\n elisp: () => require('tree-sitter-elisp'),\n // Web / Templating\n vue: () => require('tree-sitter-vue'),\n liquid: () => require('tree-sitter-liquid'),\n // Web3 / Other\n solidity: () => require('tree-sitter-solidity'),\n ql: () => require('tree-sitter-ql'),\n}\n\nexport const EXTENSION_MAP: Record<string, string> = {\n // TypeScript / JavaScript\n '.ts': 'typescript',\n '.tsx': 'tsx',\n '.js': 'javascript',\n '.jsx': 'javascript',\n '.mjs': 'javascript',\n '.cjs': 'javascript',\n // Python\n '.py': 'python',\n '.pyw': 'python',\n '.pyi': 'python',\n // Go\n '.go': 'go',\n // Rust\n '.rs': 'rust',\n // C / C++\n '.c': 'c',\n '.h': 'c',\n '.cpp': 'cpp',\n '.cc': 'cpp',\n '.cxx': 'cpp',\n '.hpp': 'cpp',\n '.hxx': 'cpp',\n '.hh': 'cpp',\n // Objective-C\n '.m': 'objc',\n '.mm': 'objc',\n // Zig\n '.zig': 'zig',\n // Java\n '.java': 'java',\n // Kotlin\n '.kt': 'kotlin',\n '.kts': 'kotlin',\n // Scala\n '.scala': 'scala',\n '.sc': 'scala',\n // C#\n '.cs': 'c_sharp',\n // Swift\n '.swift': 'swift',\n // Dart\n '.dart': 'dart',\n // Ruby\n '.rb': 'ruby',\n '.rake': 'ruby',\n // PHP\n '.php': 'php',\n // Lua\n '.lua': 'lua',\n // Bash / Shell\n '.sh': 'bash',\n '.bash': 'bash',\n // Elixir\n '.ex': 'elixir',\n '.exs': 'elixir',\n // OCaml\n '.ml': 'ocaml',\n '.mli': 'ocaml',\n // Elm\n '.elm': 'elm',\n // Emacs Lisp\n '.el': 'elisp',\n // Solidity\n '.sol': 'solidity',\n // Vue\n '.vue': 'vue',\n // Liquid\n '.liquid': 'liquid',\n // CodeQL\n '.ql': 'ql',\n}\n\nconst languageCache = new Map<string, unknown>()\n\nfunction loadLanguage(lang: string): unknown {\n const cached = languageCache.get(lang)\n if (cached) return cached\n\n const loader = LANGUAGE_LOADERS[lang]\n if (!loader) throw new Error(`Unsupported language: ${lang}`)\n\n const language = loader()\n languageCache.set(lang, language)\n return language\n}\n\n/** No-op — kept for backward compatibility with call sites. Native bindings need no async init. */\nexport async function initParser(): Promise<void> {}\n\nexport async function parseFile(filePath: string, language: string): Promise<Tree> {\n const lang = loadLanguage(language)\n parser.setLanguage(lang as Parameters<typeof parser.setLanguage>[0])\n const source = await fsRead(filePath, 'utf-8')\n return parser.parse(source)\n}\n\nexport function parseSource(source: string, language: string): Tree {\n const lang = loadLanguage(language)\n parser.setLanguage(lang as Parameters<typeof parser.setLanguage>[0])\n return parser.parse(source)\n}\n\nexport function languageFromPath(filePath: string): string | null {\n const ext = filePath.substring(filePath.lastIndexOf('.'))\n return EXTENSION_MAP[ext] || null\n}\n\nexport function supportedLanguages(): string[] {\n return Object.keys(LANGUAGE_LOADERS)\n}\n","import type { CortexManifest, TemporalData, ModuleNode } from '../types/index.js'\nimport { readFile, writeFile, cortexPath } from '../utils/files.js'\nimport { readManifest } from './manifest.js'\nimport { listModuleDocs } from './modules.js'\nimport { listDecisions } from './decisions.js'\n\nexport interface ConstitutionData {\n modules?: ModuleNode[]\n entryPoints?: string[]\n externalDeps?: Record<string, string[]>\n temporal?: TemporalData | null\n}\n\nexport async function generateConstitution(projectRoot: string, data?: ConstitutionData): Promise<string> {\n const manifest = await readManifest(projectRoot)\n const modules = await listModuleDocs(projectRoot)\n const decisions = await listDecisions(projectRoot)\n\n // Use passed-in data or read from disk (for small repos / standalone calls)\n let graphModules = data?.modules\n let entryPoints = data?.entryPoints\n let externalDeps = data?.externalDeps\n let temporal = data?.temporal ?? null\n\n if (!graphModules) {\n const graphContent = await readFile(cortexPath(projectRoot, 'graph.json'))\n if (graphContent) {\n try {\n const graph = JSON.parse(graphContent)\n graphModules = graph.modules\n entryPoints = graph.entryPoints\n externalDeps = graph.externalDeps\n } catch { /* graph too large to parse, skip */ }\n }\n }\n\n if (temporal === null && !data) {\n const temporalContent = await readFile(cortexPath(projectRoot, 'temporal.json'))\n if (temporalContent) {\n try { temporal = JSON.parse(temporalContent) as TemporalData } catch { /* skip */ }\n }\n }\n\n const lines: string[] = [\n `# ${manifest?.project || 'Project'} — Constitution`,\n '',\n `> Auto-generated by CodeCortex. This is the AI's starting knowledge for this codebase.`,\n '',\n ]\n\n // Project overview\n if (manifest) {\n lines.push(\n `## Project`,\n `- **Name:** ${manifest.project}`,\n `- **Languages:** ${manifest.languages.join(', ')}`,\n `- **Files:** ${manifest.totalFiles}`,\n `- **Symbols:** ${manifest.totalSymbols}`,\n `- **Modules:** ${manifest.totalModules}`,\n `- **Last updated:** ${manifest.lastUpdated}`,\n '',\n )\n }\n\n // Architecture\n if (graphModules) {\n lines.push(`## Architecture`, '')\n\n if (entryPoints && entryPoints.length > 0) {\n lines.push(`**Entry points:** ${entryPoints.map(e => `\\`${e}\\``).join(', ')}`, '')\n }\n\n lines.push(`**Modules:**`)\n for (const mod of graphModules) {\n lines.push(`- **${mod.name}** (${mod.files.length} files, ${mod.lines} lines) — ${mod.language}`)\n }\n lines.push('')\n\n // Key dependencies\n if (externalDeps) {\n const extDeps = Object.keys(externalDeps)\n if (extDeps.length > 0) {\n lines.push(`**External dependencies:** ${extDeps.map(d => `\\`${d}\\``).join(', ')}`, '')\n }\n }\n }\n\n // Temporal signals\n if (temporal) {\n lines.push(`## Risk Map`, '')\n\n // Top hotspots\n const topHotspots = temporal.hotspots.slice(0, 5)\n if (topHotspots.length > 0) {\n lines.push(`**Hottest files (most changes):**`)\n for (const h of topHotspots) {\n lines.push(`- \\`${h.file}\\` — ${h.changes} changes, ${h.stability.toUpperCase()}`)\n }\n lines.push('')\n }\n\n // Hidden couplings\n const hiddenCouplings = temporal.coupling.filter(c => !c.hasImport && c.strength >= 0.5)\n if (hiddenCouplings.length > 0) {\n lines.push(`**Hidden dependencies (co-change but no import):**`)\n for (const c of hiddenCouplings.slice(0, 5)) {\n lines.push(`- \\`${c.fileA}\\` ↔ \\`${c.fileB}\\` — ${c.cochanges} co-changes (${Math.round(c.strength * 100)}%)`)\n }\n lines.push('')\n }\n\n // Bug-prone files\n const buggy = temporal.bugHistory.filter(b => b.fixCommits >= 2)\n if (buggy.length > 0) {\n lines.push(`**Bug-prone files:**`)\n for (const b of buggy.slice(0, 5)) {\n lines.push(`- \\`${b.file}\\` — ${b.fixCommits} fix commits`)\n for (const lesson of b.lessons.slice(0, 3)) {\n lines.push(` - ${lesson}`)\n }\n }\n lines.push('')\n }\n }\n\n // Knowledge available\n lines.push(`## Available Knowledge`, '')\n if (modules.length > 0) {\n lines.push(`**Module docs:** ${modules.map(m => `\\`${m}\\``).join(', ')}`)\n }\n if (decisions.length > 0) {\n lines.push(`**Decision records:** ${decisions.length}`)\n }\n lines.push(\n ``,\n `Use \\`get_module_context\\` to deep-dive into any module.`,\n `Use \\`get_change_coupling\\` before editing a file to check what else must change.`,\n `Use \\`lookup_symbol\\` to find any function, type, or class.`,\n )\n\n const content = lines.join('\\n') + '\\n'\n await writeFile(cortexPath(projectRoot, 'constitution.md'), content)\n return content\n}\n","import simpleGit from 'simple-git'\n\nexport interface CommitInfo {\n hash: string\n date: string\n message: string\n author: string\n filesChanged: string[]\n}\n\nexport async function getCommitHistory(root: string, days: number = 90): Promise<CommitInfo[]> {\n const git = simpleGit(root)\n const since = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString().split('T')[0]\n\n const log = await git.log({\n '--since': since,\n '--stat': null,\n maxCount: 500,\n })\n\n return log.all.map(commit => ({\n hash: commit.hash,\n date: commit.date,\n message: commit.message,\n author: commit.author_name,\n filesChanged: parseStatFiles(commit.diff),\n }))\n}\n\nfunction parseStatFiles(diff: { files?: { file: string }[] } | null | undefined): string[] {\n if (!diff || !diff.files) return []\n return diff.files.map((f) => f.file)\n}\n\nexport async function getLastCommitDate(root: string, file: string): Promise<string | null> {\n const git = simpleGit(root)\n try {\n const log = await git.log({ file, maxCount: 1 })\n return log.latest?.date || null\n } catch {\n return null\n }\n}\n\nexport async function isGitRepo(root: string): Promise<boolean> {\n const git = simpleGit(root)\n try {\n await git.status()\n return true\n } catch {\n return false\n }\n}\n\nexport async function getHeadCommit(root: string): Promise<string | null> {\n const git = simpleGit(root)\n try {\n const log = await git.log({ maxCount: 1 })\n return log.latest?.hash || null\n } catch {\n return null\n }\n}\n","import type { ChangeCoupling, Hotspot, BugRecord, TemporalData } from '../types/index.js'\nimport type { CommitInfo } from './history.js'\nimport { getCommitHistory } from './history.js'\n\n// Files that pollute temporal metrics (changed every release, not real code risk)\nconst TEMPORAL_NOISE_FILES = new Set([\n 'CHANGELOG.md', 'CHANGES.md', 'HISTORY.md', 'NEWS.md',\n 'package.json', 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml',\n 'Cargo.lock', 'go.sum', 'poetry.lock', 'Pipfile.lock',\n])\n\nfunction isTemporalNoise(file: string): boolean {\n const basename = file.split('/').pop() ?? ''\n return TEMPORAL_NOISE_FILES.has(basename)\n}\n\nexport async function analyzeTemporalData(root: string, days: number = 90): Promise<TemporalData> {\n const commits = await getCommitHistory(root, days)\n\n const hotspots = getHotspots(commits, days)\n const coupling = getChangeCoupling(commits)\n const bugHistory = getBugArchaeology(commits)\n\n return {\n generated: new Date().toISOString(),\n periodDays: days,\n totalCommits: commits.length,\n hotspots,\n coupling,\n bugHistory,\n }\n}\n\nexport function getHotspots(commits: CommitInfo[], days: number): Hotspot[] {\n const fileChanges = new Map<string, { count: number; lastDate: string }>()\n\n for (const commit of commits) {\n for (const file of commit.filesChanged) {\n if (isTemporalNoise(file)) continue\n const existing = fileChanges.get(file) || { count: 0, lastDate: '' }\n existing.count++\n if (commit.date > existing.lastDate) {\n existing.lastDate = commit.date\n }\n fileChanges.set(file, existing)\n }\n }\n\n const now = new Date()\n const results: Hotspot[] = []\n\n for (const [file, data] of fileChanges) {\n const lastChanged = new Date(data.lastDate)\n const daysSinceChange = Math.floor((now.getTime() - lastChanged.getTime()) / (1000 * 60 * 60 * 24))\n\n let stability: Hotspot['stability']\n if (data.count >= 8 && daysSinceChange < 7) stability = 'volatile'\n else if (data.count >= 5 && daysSinceChange < 14) stability = 'stabilizing'\n else if (data.count >= 3) stability = 'moderate'\n else if (daysSinceChange > 30) stability = 'very_stable'\n else stability = 'stable'\n\n results.push({\n file,\n changes: data.count,\n stability,\n lastChanged: data.lastDate,\n daysSinceChange,\n })\n }\n\n // Sort by change frequency (descending)\n return results.sort((a, b) => b.changes - a.changes)\n}\n\nexport function getChangeCoupling(commits: CommitInfo[]): ChangeCoupling[] {\n const pairCounts = new Map<string, number>()\n const fileCounts = new Map<string, number>()\n\n for (const commit of commits) {\n const files = commit.filesChanged.filter(f =>\n !f.endsWith('.md') && !f.endsWith('.json') && !f.endsWith('.lock') && !f.endsWith('.yaml') && !f.endsWith('.yml')\n )\n\n // Count individual file changes\n for (const file of files) {\n fileCounts.set(file, (fileCounts.get(file) || 0) + 1)\n }\n\n // Skip mega-commits for pairing (refactors/renames create noise, not real coupling)\n if (files.length > 50) continue\n\n // Count pair co-changes\n for (let i = 0; i < files.length; i++) {\n for (let j = i + 1; j < files.length; j++) {\n const key = [files[i], files[j]].sort().join('|')\n pairCounts.set(key, (pairCounts.get(key) || 0) + 1)\n }\n }\n }\n\n const results: ChangeCoupling[] = []\n\n for (const [key, cochanges] of pairCounts) {\n if (cochanges < 3) continue // Filter noise\n\n const parts = key.split('|')\n const fileA = parts[0] ?? ''\n const fileB = parts[1] ?? ''\n const maxChanges = Math.max(fileCounts.get(fileA) || 0, fileCounts.get(fileB) || 0)\n const strength = maxChanges > 0 ? cochanges / maxChanges : 0\n\n const coupling: ChangeCoupling = {\n fileA,\n fileB,\n cochanges,\n strength: Math.round(strength * 100) / 100,\n hasImport: false, // Will be enriched by graph analysis\n }\n\n if (strength >= 0.7 && !coupling.hasImport) {\n coupling.warning = `HIDDEN DEPENDENCY — ${Math.round(strength * 100)}% co-change rate`\n }\n\n results.push(coupling)\n }\n\n // Sort by co-change frequency (descending)\n return results.sort((a, b) => b.cochanges - a.cochanges)\n}\n\nexport function getBugArchaeology(commits: CommitInfo[]): BugRecord[] {\n const bugPatterns = /^(fix|bug|hotfix|patch)[\\s:(]/i\n const fileRecords = new Map<string, { fixCommits: number; lessons: Set<string> }>()\n\n for (const commit of commits) {\n if (!bugPatterns.test(commit.message)) continue\n\n // Extract lesson from commit message\n const lesson = commit.message\n .replace(/^(fix|bug|hotfix|patch)[\\s:(]+/i, '')\n .replace(/\\s*\\(#\\d+\\)$/, '') // Remove PR number\n .trim()\n\n for (const file of commit.filesChanged) {\n if (isTemporalNoise(file)) continue\n const existing = fileRecords.get(file) || { fixCommits: 0, lessons: new Set<string>() }\n existing.fixCommits++\n if (lesson) existing.lessons.add(lesson)\n fileRecords.set(file, existing)\n }\n }\n\n const results: BugRecord[] = []\n for (const [file, data] of fileRecords) {\n results.push({\n file,\n fixCommits: data.fixCommits,\n lessons: [...data.lessons],\n })\n }\n\n return results.sort((a, b) => b.fixCommits - a.fixCommits)\n}\n\nexport function getStabilitySignals(commits: CommitInfo[]): Map<string, { daysSinceChange: number; velocity: number }> {\n const now = new Date()\n const fileData = new Map<string, { lastDate: string; changes: number; firstDate: string }>()\n\n for (const commit of commits) {\n for (const file of commit.filesChanged) {\n const existing = fileData.get(file) || { lastDate: '', changes: 0, firstDate: commit.date }\n existing.changes++\n if (commit.date > existing.lastDate) existing.lastDate = commit.date\n if (commit.date < existing.firstDate) existing.firstDate = commit.date\n fileData.set(file, existing)\n }\n }\n\n const signals = new Map<string, { daysSinceChange: number; velocity: number }>()\n\n for (const [file, data] of fileData) {\n const last = new Date(data.lastDate)\n const first = new Date(data.firstDate)\n const daysSinceChange = Math.floor((now.getTime() - last.getTime()) / (1000 * 60 * 60 * 24))\n const spanDays = Math.max(1, Math.floor((last.getTime() - first.getTime()) / (1000 * 60 * 60 * 24)))\n const velocity = data.changes / spanDays * 30 // changes per 30 days\n\n signals.set(file, { daysSinceChange, velocity: Math.round(velocity * 100) / 100 })\n }\n\n return signals\n}\n\nexport function getEvolutionEvents(commits: CommitInfo[]): { date: string; type: string; description: string; filesAffected: number }[] {\n const events: { date: string; type: string; description: string; filesAffected: number }[] = []\n\n const featPattern = /^feat[\\s:(]/i\n const refactorPattern = /^refactor[\\s:(]/i\n\n for (const commit of commits) {\n const fileCount = commit.filesChanged.length\n\n if (refactorPattern.test(commit.message) && fileCount >= 3) {\n events.push({\n date: commit.date,\n type: 'refactor',\n description: commit.message,\n filesAffected: fileCount,\n })\n } else if (featPattern.test(commit.message) && fileCount >= 5) {\n events.push({\n date: commit.date,\n type: 'feature',\n description: commit.message,\n filesAffected: fileCount,\n })\n } else if (fileCount >= 10) {\n events.push({\n date: commit.date,\n type: 'major_change',\n description: commit.message,\n filesAffected: fileCount,\n })\n }\n }\n\n return events\n}\n","import type Parser from 'tree-sitter'\ntype TSNode = Parser.SyntaxNode\ntype Tree = Parser.Tree\nimport type { SymbolRecord } from '../types/index.js'\n\ninterface SymbolQuery {\n nodeTypes: Set<string>\n getKind: (type: string) => SymbolRecord['kind']\n getName: (node: TSNode) => string | null\n getSignature: (node: TSNode, source: string) => string | undefined\n isExported: (node: TSNode) => boolean\n}\n\nconst TS_JS_QUERY: SymbolQuery = {\n nodeTypes: new Set([\n 'function_declaration',\n 'class_declaration',\n 'interface_declaration',\n 'type_alias_declaration',\n 'enum_declaration',\n 'lexical_declaration',\n 'variable_declaration',\n 'method_definition',\n 'public_field_definition',\n 'export_statement',\n ]),\n getKind(type) {\n const map: Record<string, SymbolRecord['kind']> = {\n function_declaration: 'function',\n class_declaration: 'class',\n interface_declaration: 'interface',\n type_alias_declaration: 'type',\n enum_declaration: 'enum',\n lexical_declaration: 'const',\n variable_declaration: 'variable',\n method_definition: 'method',\n public_field_definition: 'property',\n }\n return map[type] || 'variable'\n },\n getName(node: TSNode) {\n const nameNode = node.childForFieldName('name')\n if (nameNode) return nameNode.text\n\n // For lexical_declaration, dig into declarators\n if (node.type === 'lexical_declaration' || node.type === 'variable_declaration') {\n const declarator = (node.namedChildren as TSNode[]).find((c: TSNode) =>\n c.type === 'variable_declarator'\n )\n if (declarator) {\n const name = declarator.childForFieldName('name')\n return name?.text || null\n }\n }\n return null\n },\n getSignature(node: TSNode, source: string) {\n const startLine = node.startPosition.row\n const lines = source.split('\\n')\n const line = lines[startLine]\n if (!line) return undefined\n const sig = line.trim()\n return sig.length > 200 ? sig.slice(0, 200) + '...' : sig\n },\n isExported(node: TSNode) {\n const parent = node.parent\n if (!parent) return false\n if (parent.type === 'export_statement') return true\n if (node.type === 'lexical_declaration') {\n return parent.type === 'export_statement'\n }\n return false\n },\n}\n\nconst PYTHON_QUERY: SymbolQuery = {\n nodeTypes: new Set([\n 'function_definition',\n 'class_definition',\n 'assignment',\n ]),\n getKind(type) {\n const map: Record<string, SymbolRecord['kind']> = {\n function_definition: 'function',\n class_definition: 'class',\n assignment: 'variable',\n }\n return map[type] || 'variable'\n },\n getName(node: TSNode) {\n const nameNode = node.childForFieldName('name')\n if (nameNode) return nameNode.text\n if (node.type === 'assignment') {\n const left = node.childForFieldName('left')\n return left?.text || null\n }\n return null\n },\n getSignature(node: TSNode, source: string) {\n const startLine = node.startPosition.row\n const lines = source.split('\\n')\n return lines[startLine]?.trim()\n },\n isExported(node: TSNode) {\n const name = PYTHON_QUERY.getName(node)\n return name ? !name.startsWith('_') : false\n },\n}\n\nconst GO_QUERY: SymbolQuery = {\n nodeTypes: new Set([\n 'function_declaration',\n 'method_declaration',\n 'type_declaration',\n 'const_declaration',\n 'var_declaration',\n ]),\n getKind(type) {\n const map: Record<string, SymbolRecord['kind']> = {\n function_declaration: 'function',\n method_declaration: 'method',\n type_declaration: 'type',\n const_declaration: 'const',\n var_declaration: 'variable',\n }\n return map[type] || 'variable'\n },\n getName(node: TSNode) {\n const nameNode = node.childForFieldName('name')\n if (nameNode) return nameNode.text\n\n // Go wraps declarations: type_declaration→type_spec, const_declaration→const_spec, var_declaration→var_spec\n // The name field is on the _spec child, not the _declaration itself\n if (node.type === 'type_declaration' || node.type === 'const_declaration' || node.type === 'var_declaration') {\n for (const child of node.namedChildren as TSNode[]) {\n if (child.type === 'type_spec' || child.type === 'const_spec' || child.type === 'var_spec') {\n const specName = child.childForFieldName('name')\n if (specName) return specName.text\n }\n }\n }\n\n return null\n },\n getSignature(node: TSNode, source: string) {\n const startLine = node.startPosition.row\n const lines = source.split('\\n')\n return lines[startLine]?.trim()\n },\n isExported(node: TSNode) {\n const name = GO_QUERY.getName(node)\n return name ? /^[A-Z]/.test(name) : false\n },\n}\n\nconst RUST_QUERY: SymbolQuery = {\n nodeTypes: new Set([\n 'function_item',\n 'struct_item',\n 'enum_item',\n 'impl_item',\n 'trait_item',\n 'type_item',\n 'const_item',\n 'static_item',\n ]),\n getKind(type) {\n const map: Record<string, SymbolRecord['kind']> = {\n function_item: 'function',\n struct_item: 'class',\n enum_item: 'enum',\n impl_item: 'class',\n trait_item: 'interface',\n type_item: 'type',\n const_item: 'const',\n static_item: 'variable',\n }\n return map[type] || 'variable'\n },\n getName(node: TSNode) {\n const nameNode = node.childForFieldName('name')\n return nameNode?.text || null\n },\n getSignature(node: TSNode, source: string) {\n const startLine = node.startPosition.row\n const lines = source.split('\\n')\n return lines[startLine]?.trim()\n },\n isExported(node: TSNode) {\n const text = node.text\n return text.startsWith('pub ')\n },\n}\n\nconst C_CPP_QUERY: SymbolQuery = {\n nodeTypes: new Set([\n 'function_definition',\n 'declaration',\n 'struct_specifier',\n 'enum_specifier',\n 'union_specifier',\n 'type_definition',\n 'preproc_function_def',\n // C++ additions\n 'class_specifier',\n 'namespace_definition',\n ]),\n getKind(type) {\n const map: Record<string, SymbolRecord['kind']> = {\n function_definition: 'function',\n declaration: 'variable',\n struct_specifier: 'class',\n enum_specifier: 'enum',\n union_specifier: 'class',\n type_definition: 'type',\n preproc_function_def: 'function',\n class_specifier: 'class',\n namespace_definition: 'class',\n }\n return map[type] || 'variable'\n },\n getName(node: TSNode) {\n // Try 'name' field (struct, enum, class, namespace, macro)\n const nameNode = node.childForFieldName('name')\n if (nameNode) return nameNode.text\n\n // For function_definition and declaration: dig through declarator chain\n let declarator = node.childForFieldName('declarator')\n while (declarator) {\n if (declarator.type === 'identifier' || declarator.type === 'type_identifier' || declarator.type === 'field_identifier') {\n return declarator.text\n }\n const inner = declarator.childForFieldName('declarator')\n if (inner) {\n declarator = inner\n continue\n }\n const declName = declarator.childForFieldName('name')\n if (declName) return declName.text\n break\n }\n\n return null\n },\n getSignature(node: TSNode, source: string) {\n const startLine = node.startPosition.row\n const lines = source.split('\\n')\n const line = lines[startLine]\n if (!line) return undefined\n const sig = line.trim()\n return sig.length > 200 ? sig.slice(0, 200) + '...' : sig\n },\n isExported(node: TSNode) {\n // C: static means file-private, everything else at top level is exported\n if (node.text.startsWith('static ')) return false\n if (node.text.startsWith('public ')) return true\n return node.parent?.type === 'translation_unit' || false\n },\n}\n\nconst JAVA_QUERY: SymbolQuery = {\n nodeTypes: new Set([\n 'class_declaration',\n 'interface_declaration',\n 'enum_declaration',\n 'method_declaration',\n 'constructor_declaration',\n 'field_declaration',\n 'annotation_type_declaration',\n // Kotlin\n 'function_declaration',\n 'object_declaration',\n ]),\n getKind(type) {\n const map: Record<string, SymbolRecord['kind']> = {\n class_declaration: 'class',\n interface_declaration: 'interface',\n enum_declaration: 'enum',\n method_declaration: 'method',\n constructor_declaration: 'method',\n field_declaration: 'property',\n annotation_type_declaration: 'interface',\n function_declaration: 'function',\n object_declaration: 'class',\n }\n return map[type] || 'variable'\n },\n getName(node: TSNode) {\n const nameNode = node.childForFieldName('name')\n if (nameNode) return nameNode.text\n // For field_declaration: dig into declarators\n for (const child of node.namedChildren as TSNode[]) {\n if (child.type === 'variable_declarator') {\n const name = child.childForFieldName('name')\n if (name) return name.text\n }\n }\n return null\n },\n getSignature(node: TSNode, source: string) {\n const startLine = node.startPosition.row\n const lines = source.split('\\n')\n const line = lines[startLine]\n if (!line) return undefined\n const sig = line.trim()\n return sig.length > 200 ? sig.slice(0, 200) + '...' : sig\n },\n isExported(node: TSNode) {\n return node.text.startsWith('public ') || node.text.startsWith('protected ')\n },\n}\n\nconst GENERIC_QUERY: SymbolQuery = {\n nodeTypes: new Set([\n // Functions\n 'function_declaration', 'function_definition', 'function_item',\n 'method_declaration', 'method_definition', 'method',\n // Classes / structs\n 'class_declaration', 'class_definition', 'class_specifier',\n 'struct_specifier', 'struct_item', 'struct_declaration',\n 'module_definition', 'module',\n // Interfaces / traits / protocols\n 'interface_declaration', 'trait_item', 'protocol_declaration',\n // Enums\n 'enum_declaration', 'enum_item', 'enum_specifier', 'enum_definition',\n // Types\n 'type_declaration', 'type_alias_declaration', 'type_item', 'type_definition',\n // Constants\n 'const_declaration', 'const_item',\n ]),\n getKind(type) {\n if (type.includes('function') || type.includes('method')) return 'function'\n if (type.includes('class') || type.includes('struct') || type.includes('module')) return 'class'\n if (type.includes('interface') || type.includes('trait') || type.includes('protocol')) return 'interface'\n if (type.includes('enum')) return 'enum'\n if (type.includes('type')) return 'type'\n if (type.includes('const')) return 'const'\n return 'variable'\n },\n getName(node: TSNode) {\n // Try standard 'name' field (most languages)\n const nameNode = node.childForFieldName('name')\n if (nameNode) return nameNode.text\n\n // Try 'declarator' chain (C-family)\n let declarator = node.childForFieldName('declarator')\n while (declarator) {\n if (declarator.type === 'identifier' || declarator.type === 'type_identifier') return declarator.text\n const inner = declarator.childForFieldName('declarator') || declarator.childForFieldName('name')\n if (inner) {\n if (inner.type === 'identifier' || inner.type === 'type_identifier') return inner.text\n declarator = inner\n continue\n }\n break\n }\n\n // Last resort: first identifier child\n for (const child of node.namedChildren as TSNode[]) {\n if (child.type === 'identifier' || child.type === 'type_identifier') return child.text\n }\n\n return null\n },\n getSignature(node: TSNode, source: string) {\n const startLine = node.startPosition.row\n const lines = source.split('\\n')\n const line = lines[startLine]\n if (!line) return undefined\n const sig = line.trim()\n return sig.length > 200 ? sig.slice(0, 200) + '...' : sig\n },\n isExported(node: TSNode) {\n const text = node.text\n if (text.startsWith('pub ') || text.startsWith('public ') || text.startsWith('export ')) return true\n const parent = node.parent\n if (parent?.type === 'export_statement') return true\n return false\n },\n}\n\nfunction getQuery(language: string): SymbolQuery {\n switch (language) {\n case 'typescript':\n case 'tsx':\n case 'javascript':\n return TS_JS_QUERY\n case 'python':\n return PYTHON_QUERY\n case 'go':\n return GO_QUERY\n case 'rust':\n return RUST_QUERY\n case 'c':\n case 'cpp':\n case 'objc':\n return C_CPP_QUERY\n case 'java':\n case 'kotlin':\n case 'c_sharp':\n case 'scala':\n case 'dart':\n return JAVA_QUERY\n default:\n return GENERIC_QUERY\n }\n}\n\nexport function extractSymbols(tree: Tree, file: string, language: string, source: string): SymbolRecord[] {\n const query = getQuery(language)\n const symbols: SymbolRecord[] = []\n\n function walk(node: TSNode, parentName?: string) {\n if (query.nodeTypes.has(node.type)) {\n if (node.type === 'export_statement') {\n const declaration = (node.namedChildren as TSNode[]).find((c: TSNode) => query.nodeTypes.has(c.type))\n if (declaration) {\n const name = query.getName(declaration)\n if (name) {\n symbols.push({\n name,\n kind: query.getKind(declaration.type),\n file,\n startLine: declaration.startPosition.row + 1,\n endLine: declaration.endPosition.row + 1,\n signature: query.getSignature(declaration, source),\n exported: true,\n parentName,\n })\n }\n for (const child of declaration.namedChildren as TSNode[]) {\n walk(child, name || parentName)\n }\n return\n }\n return\n }\n\n const name = query.getName(node)\n if (name) {\n symbols.push({\n name,\n kind: query.getKind(node.type),\n file,\n startLine: node.startPosition.row + 1,\n endLine: node.endPosition.row + 1,\n signature: query.getSignature(node, source),\n exported: query.isExported(node),\n parentName,\n })\n }\n\n for (const child of node.namedChildren as TSNode[]) {\n walk(child, name || parentName)\n }\n return\n }\n\n for (const child of node.namedChildren as TSNode[]) {\n walk(child, parentName)\n }\n }\n\n walk(tree.rootNode)\n return symbols\n}\n","import type Parser from 'tree-sitter'\ntype TSNode = Parser.SyntaxNode\ntype Tree = Parser.Tree\nimport type { ImportEdge } from '../types/index.js'\nimport { dirname, join } from 'node:path'\nimport { existsSync } from 'node:fs'\n\nexport function extractImports(tree: Tree, file: string, language: string): ImportEdge[] {\n switch (language) {\n case 'typescript':\n case 'tsx':\n case 'javascript':\n return extractTsImports(tree, file)\n case 'python':\n return extractPythonImports(tree, file)\n case 'go':\n return extractGoImports(tree, file)\n case 'rust':\n return extractRustImports(tree, file)\n case 'c':\n case 'cpp':\n case 'objc':\n return extractCIncludes(tree, file)\n case 'java':\n case 'kotlin':\n case 'c_sharp':\n case 'scala':\n case 'dart':\n return extractJavaImports(tree, file)\n default:\n return extractGenericImports(tree, file)\n }\n}\n\nfunction extractTsImports(tree: Tree, file: string): ImportEdge[] {\n const imports: ImportEdge[] = []\n\n function walk(node: TSNode) {\n if (node.type === 'import_statement') {\n const sourceNode = node.childForFieldName('source')\n if (!sourceNode) {\n for (const child of node.namedChildren as TSNode[]) {\n walk(child)\n }\n return\n }\n\n const rawPath = sourceNode.text.replace(/['\"]/g, '')\n\n if (!rawPath.startsWith('.')) {\n return\n }\n\n const resolved = resolveImportPath(file, rawPath)\n const specifiers = extractSpecifiers(node)\n\n imports.push({\n source: file,\n target: resolved,\n specifiers,\n })\n return\n }\n\n for (const child of node.namedChildren as TSNode[]) {\n walk(child)\n }\n }\n\n walk(tree.rootNode)\n return imports\n}\n\nfunction extractSpecifiers(importNode: TSNode): string[] {\n const specifiers: string[] = []\n\n function walk(node: TSNode) {\n if (node.type === 'import_specifier') {\n const name = node.childForFieldName('name')\n if (name) specifiers.push(name.text)\n } else if (node.type === 'namespace_import') {\n specifiers.push('*')\n } else if (node.type === 'identifier' && node.parent?.type === 'import_clause') {\n specifiers.push(node.text)\n }\n\n for (const child of node.namedChildren as TSNode[]) {\n walk(child)\n }\n }\n\n walk(importNode)\n return specifiers\n}\n\nfunction resolveImportPath(fromFile: string, importPath: string): string {\n const dir = dirname(fromFile)\n let resolved = join(dir, importPath)\n\n resolved = resolved.replace(/\\.(js|ts|tsx|jsx|mjs)$/, '')\n\n const extensions = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '/index.ts', '/index.js']\n for (const ext of extensions) {\n if (existsSync(resolved + ext)) {\n return resolved + ext\n }\n }\n\n return resolved + '.ts'\n}\n\nfunction extractPythonImports(tree: Tree, file: string): ImportEdge[] {\n const imports: ImportEdge[] = []\n\n function walk(node: TSNode) {\n if (node.type === 'import_from_statement') {\n const moduleNode = node.childForFieldName('module_name')\n if (moduleNode) {\n const modulePath = moduleNode.text\n if (modulePath.startsWith('.')) {\n const specifiers: string[] = []\n for (const child of node.namedChildren as TSNode[]) {\n if (child.type === 'dotted_name' && child !== moduleNode) {\n specifiers.push(child.text)\n }\n }\n imports.push({\n source: file,\n target: resolvePythonImport(file, modulePath),\n specifiers,\n })\n }\n }\n }\n\n for (const child of node.namedChildren as TSNode[]) {\n walk(child)\n }\n }\n\n walk(tree.rootNode)\n return imports\n}\n\nfunction resolvePythonImport(fromFile: string, importPath: string): string {\n const dir = dirname(fromFile)\n const parts = importPath.replace(/^\\.+/, '')\n const dots = importPath.match(/^\\.+/)?.[0].length || 1\n let base = dir\n for (let i = 1; i < dots; i++) base = dirname(base)\n return join(base, parts.replace(/\\./g, '/') + '.py')\n}\n\nfunction extractGoImports(tree: Tree, file: string): ImportEdge[] {\n const imports: ImportEdge[] = []\n\n function walk(node: TSNode) {\n if (node.type === 'import_spec') {\n const pathNode = node.childForFieldName('path')\n if (pathNode) {\n imports.push({\n source: file,\n target: pathNode.text.replace(/\"/g, ''),\n specifiers: ['*'],\n })\n }\n }\n\n for (const child of node.namedChildren as TSNode[]) {\n walk(child)\n }\n }\n\n walk(tree.rootNode)\n return imports\n}\n\nfunction extractRustImports(tree: Tree, file: string): ImportEdge[] {\n const imports: ImportEdge[] = []\n\n function walk(node: TSNode) {\n if (node.type === 'use_declaration') {\n const path = (node.namedChildren as TSNode[]).find((c: TSNode) => c.type === 'scoped_identifier' || c.type === 'use_wildcard' || c.type === 'use_list')\n if (path) {\n imports.push({\n source: file,\n target: path.text,\n specifiers: ['*'],\n })\n }\n }\n\n for (const child of node.namedChildren as TSNode[]) {\n walk(child)\n }\n }\n\n walk(tree.rootNode)\n return imports\n}\n\nfunction extractCIncludes(tree: Tree, file: string): ImportEdge[] {\n const imports: ImportEdge[] = []\n\n function walk(node: TSNode) {\n if (node.type === 'preproc_include') {\n const pathNode = node.childForFieldName('path')\n if (pathNode) {\n const raw = pathNode.text.replace(/['\"<>]/g, '')\n imports.push({ source: file, target: raw, specifiers: ['*'] })\n }\n }\n for (const child of node.namedChildren as TSNode[]) walk(child)\n }\n\n walk(tree.rootNode)\n return imports\n}\n\nfunction extractJavaImports(tree: Tree, file: string): ImportEdge[] {\n const imports: ImportEdge[] = []\n\n function walk(node: TSNode) {\n if (node.type === 'import_declaration') {\n // Java imports are like: import java.util.List;\n // The child is a scoped_identifier chain\n for (const child of node.namedChildren as TSNode[]) {\n if (child.type === 'scoped_identifier' || child.type === 'identifier') {\n imports.push({ source: file, target: child.text, specifiers: ['*'] })\n break\n }\n }\n }\n for (const child of node.namedChildren as TSNode[]) walk(child)\n }\n\n walk(tree.rootNode)\n return imports\n}\n\nfunction extractGenericImports(tree: Tree, file: string): ImportEdge[] {\n const imports: ImportEdge[] = []\n const importNodeTypes = new Set([\n 'preproc_include', 'import_declaration', 'import_statement',\n 'import_from_statement', 'use_declaration', 'namespace_use_declaration',\n ])\n\n function walk(node: TSNode) {\n if (importNodeTypes.has(node.type)) {\n const pathNode = node.childForFieldName('path') ||\n node.childForFieldName('source') ||\n node.childForFieldName('module_name')\n\n if (pathNode) {\n const raw = pathNode.text.replace(/['\"<>]/g, '')\n imports.push({ source: file, target: raw, specifiers: ['*'] })\n } else {\n // Fallback: first named child that looks like a path\n for (const child of node.namedChildren as TSNode[]) {\n if (child.type === 'scoped_identifier' || child.type === 'dotted_name' ||\n child.type === 'string_literal' || child.type === 'string') {\n imports.push({ source: file, target: child.text.replace(/['\"]/g, ''), specifiers: ['*'] })\n break\n }\n }\n }\n return\n }\n for (const child of node.namedChildren as TSNode[]) walk(child)\n }\n\n walk(tree.rootNode)\n return imports\n}\n","import type Parser from 'tree-sitter'\ntype TSNode = Parser.SyntaxNode\ntype Tree = Parser.Tree\nimport type { CallEdge } from '../types/index.js'\n\nexport function extractCalls(tree: Tree, file: string, language: string): CallEdge[] {\n switch (language) {\n case 'typescript':\n case 'tsx':\n case 'javascript':\n return extractTsCalls(tree, file)\n case 'python':\n return extractPythonCalls(tree, file)\n case 'go':\n return extractGoCalls(tree, file)\n case 'rust':\n return extractRustCalls(tree, file)\n default:\n return extractGenericCalls(tree, file)\n }\n}\n\nfunction extractTsCalls(tree: Tree, file: string): CallEdge[] {\n const calls: CallEdge[] = []\n const seen = new Set<string>()\n\n function findEnclosingFunction(node: TSNode): string {\n let current = node.parent\n while (current) {\n if (\n current.type === 'function_declaration' ||\n current.type === 'method_definition' ||\n current.type === 'arrow_function'\n ) {\n const name = current.childForFieldName('name')\n if (name) return name.text\n if (current.parent?.type === 'variable_declarator') {\n const varName = current.parent.childForFieldName('name')\n if (varName) return varName.text\n }\n return '<anonymous>'\n }\n current = current.parent\n }\n return '<module>'\n }\n\n function walk(node: TSNode) {\n if (node.type === 'call_expression') {\n const funcNode = node.childForFieldName('function')\n if (funcNode) {\n let callee: string\n if (funcNode.type === 'member_expression') {\n const prop = funcNode.childForFieldName('property')\n callee = prop?.text || funcNode.text\n } else {\n callee = funcNode.text\n }\n\n const caller = findEnclosingFunction(node)\n const key = `${caller}:${callee}:${node.startPosition.row}`\n if (!seen.has(key)) {\n seen.add(key)\n calls.push({\n caller: `${file}:${caller}`,\n callee,\n file,\n line: node.startPosition.row + 1,\n })\n }\n }\n }\n\n for (const child of node.namedChildren as TSNode[]) {\n walk(child)\n }\n }\n\n walk(tree.rootNode)\n return calls\n}\n\nfunction extractPythonCalls(tree: Tree, file: string): CallEdge[] {\n const calls: CallEdge[] = []\n const seen = new Set<string>()\n\n function findEnclosing(node: TSNode): string {\n let current = node.parent\n while (current) {\n if (current.type === 'function_definition') {\n const name = current.childForFieldName('name')\n if (name) return name.text\n }\n current = current.parent\n }\n return '<module>'\n }\n\n function walk(node: TSNode) {\n if (node.type === 'call') {\n const funcNode = node.childForFieldName('function')\n if (funcNode) {\n const callee = funcNode.type === 'attribute'\n ? funcNode.childForFieldName('attribute')?.text || funcNode.text\n : funcNode.text\n const caller = findEnclosing(node)\n const key = `${caller}:${callee}:${node.startPosition.row}`\n if (!seen.has(key)) {\n seen.add(key)\n calls.push({ caller: `${file}:${caller}`, callee, file, line: node.startPosition.row + 1 })\n }\n }\n }\n for (const child of node.namedChildren as TSNode[]) walk(child)\n }\n\n walk(tree.rootNode)\n return calls\n}\n\nfunction extractGoCalls(tree: Tree, file: string): CallEdge[] {\n const calls: CallEdge[] = []\n const seen = new Set<string>()\n\n function findEnclosing(node: TSNode): string {\n let current = node.parent\n while (current) {\n if (current.type === 'function_declaration' || current.type === 'method_declaration') {\n const name = current.childForFieldName('name')\n if (name) return name.text\n }\n current = current.parent\n }\n return '<module>'\n }\n\n function walk(node: TSNode) {\n if (node.type === 'call_expression') {\n const funcNode = node.childForFieldName('function')\n if (funcNode) {\n const callee = funcNode.type === 'selector_expression'\n ? funcNode.childForFieldName('field')?.text || funcNode.text\n : funcNode.text\n const caller = findEnclosing(node)\n const key = `${caller}:${callee}:${node.startPosition.row}`\n if (!seen.has(key)) {\n seen.add(key)\n calls.push({ caller: `${file}:${caller}`, callee, file, line: node.startPosition.row + 1 })\n }\n }\n }\n for (const child of node.namedChildren as TSNode[]) walk(child)\n }\n\n walk(tree.rootNode)\n return calls\n}\n\nfunction extractRustCalls(tree: Tree, file: string): CallEdge[] {\n const calls: CallEdge[] = []\n const seen = new Set<string>()\n\n function findEnclosing(node: TSNode): string {\n let current = node.parent\n while (current) {\n if (current.type === 'function_item') {\n const name = current.childForFieldName('name')\n if (name) return name.text\n }\n current = current.parent\n }\n return '<module>'\n }\n\n function walk(node: TSNode) {\n if (node.type === 'call_expression') {\n const funcNode = node.childForFieldName('function')\n if (funcNode) {\n const callee = funcNode.text.split('::').pop() || funcNode.text\n const caller = findEnclosing(node)\n const key = `${caller}:${callee}:${node.startPosition.row}`\n if (!seen.has(key)) {\n seen.add(key)\n calls.push({ caller: `${file}:${caller}`, callee, file, line: node.startPosition.row + 1 })\n }\n }\n }\n for (const child of node.namedChildren as TSNode[]) walk(child)\n }\n\n walk(tree.rootNode)\n return calls\n}\n\nfunction extractGenericCalls(tree: Tree, file: string): CallEdge[] {\n const calls: CallEdge[] = []\n const seen = new Set<string>()\n\n function findEnclosing(node: TSNode): string {\n let current = node.parent\n while (current) {\n if (current.type.includes('function') || current.type.includes('method')) {\n const name = current.childForFieldName('name')\n if (name) return name.text\n }\n current = current.parent\n }\n return '<module>'\n }\n\n function walk(node: TSNode) {\n if (node.type === 'call_expression' || node.type === 'call') {\n const funcNode = node.childForFieldName('function') || node.childForFieldName('method')\n if (funcNode) {\n let callee: string\n if (funcNode.type.includes('member') || funcNode.type.includes('selector') || funcNode.type === 'attribute') {\n const prop = funcNode.childForFieldName('property') ||\n funcNode.childForFieldName('field') ||\n funcNode.childForFieldName('attribute')\n callee = prop?.text || funcNode.text\n } else {\n callee = funcNode.text\n }\n\n const caller = findEnclosing(node)\n const key = `${caller}:${callee}:${node.startPosition.row}`\n if (!seen.has(key)) {\n seen.add(key)\n calls.push({ caller: `${file}:${caller}`, callee, file, line: node.startPosition.row + 1 })\n }\n }\n }\n for (const child of node.namedChildren as TSNode[]) walk(child)\n }\n\n walk(tree.rootNode)\n return calls\n}\n","import { existsSync } from 'node:fs'\nimport { cortexPath } from '../utils/files.js'\nimport { writeModuleDoc } from './modules.js'\nimport { getModuleDependencies } from './graph.js'\nimport type { DependencyGraph, SymbolRecord, TemporalData, ModuleAnalysis } from '../types/index.js'\n\nexport interface StructuralModuleData {\n graph: DependencyGraph\n symbols: SymbolRecord[]\n temporal: TemporalData | null\n}\n\nexport async function generateStructuralModuleDocs(\n projectRoot: string,\n data: StructuralModuleData,\n): Promise<number> {\n let generated = 0\n\n for (const mod of data.graph.modules) {\n // Never overwrite existing (possibly LLM-generated) docs\n const docPath = cortexPath(projectRoot, 'modules', `${mod.name}.md`)\n if (existsSync(docPath)) continue\n\n // Exported symbols in this module\n const moduleFiles = new Set(mod.files)\n const exported = data.symbols\n .filter(s => moduleFiles.has(s.file) && s.exported)\n .map(s => {\n const loc = s.endLine > s.startLine\n ? `${s.file}:${s.startLine}-${s.endLine}`\n : `${s.file}:${s.startLine}`\n return `${s.name} (${s.kind}, ${loc})`\n })\n\n // Dependencies\n const deps = getModuleDependencies(data.graph, mod.name)\n const importsFromModules = new Set<string>()\n const importedByModules = new Set<string>()\n\n for (const edge of deps.imports) {\n for (const other of data.graph.modules) {\n if (other.name !== mod.name && other.files.includes(edge.target)) {\n importsFromModules.add(other.name)\n }\n }\n }\n for (const edge of deps.importedBy) {\n for (const other of data.graph.modules) {\n if (other.name !== mod.name && other.files.includes(edge.source)) {\n importedByModules.add(other.name)\n }\n }\n }\n\n const depLines: string[] = []\n if (importsFromModules.size > 0) depLines.push(`Imports from: ${[...importsFromModules].join(', ')}`)\n if (importedByModules.size > 0) depLines.push(`Imported by: ${[...importedByModules].join(', ')}`)\n\n // Temporal signals\n let temporalSignals: ModuleAnalysis['temporalSignals']\n if (data.temporal) {\n const hotspots = data.temporal.hotspots.filter(h => moduleFiles.has(h.file))\n const topHotspot = hotspots[0]\n\n const couplings = data.temporal.coupling.filter(c =>\n moduleFiles.has(c.fileA) || moduleFiles.has(c.fileB)\n )\n const coupledWith = couplings.map(c => {\n const other = moduleFiles.has(c.fileA) ? c.fileB : c.fileA\n return `${other} (${c.cochanges} co-changes, ${Math.round(c.strength * 100)}%)`\n })\n\n const bugs = data.temporal.bugHistory.filter(b => moduleFiles.has(b.file))\n\n temporalSignals = {\n churn: topHotspot ? `${topHotspot.changes} changes (${topHotspot.stability})` : 'no hotspot data',\n coupledWith,\n stability: topHotspot?.stability ?? 'unknown',\n bugHistory: bugs.flatMap(b => b.lessons),\n lastChanged: topHotspot?.lastChanged ?? 'unknown',\n }\n }\n\n const analysis: ModuleAnalysis = {\n name: mod.name,\n purpose: `${mod.files.length} files, ${mod.lines} lines (${mod.language}). Auto-generated from code structure — use \\`analyze_module\\` MCP tool for semantic analysis.`,\n dataFlow: `Files: ${mod.files.join(', ')}`,\n publicApi: exported,\n gotchas: [],\n dependencies: depLines,\n temporalSignals,\n }\n\n await writeModuleDoc(projectRoot, analysis)\n generated++\n }\n\n return generated\n}\n","import { resolve } from 'node:path'\nimport { existsSync } from 'node:fs'\nimport { cortexPath } from '../../utils/files.js'\nimport { startServer } from '../../mcp/server.js'\n\nexport async function serveCommand(opts: { root: string }): Promise<void> {\n const root = resolve(opts.root)\n\n // Check if .codecortex/ exists\n if (!existsSync(cortexPath(root, 'cortex.yaml'))) {\n console.error('Error: No CodeCortex knowledge found.')\n console.error(`Run 'codecortex init' first to analyze the codebase.`)\n console.error(`Expected: ${cortexPath(root, 'cortex.yaml')}`)\n process.exit(1)\n }\n\n await startServer(root)\n}\n","import { resolve } from 'node:path'\nimport { existsSync } from 'node:fs'\nimport { cortexPath, readFile, writeFile, writeJsonStream } from '../../utils/files.js'\nimport { readManifest, updateManifest } from '../../core/manifest.js'\nimport { discoverProject } from '../../core/discovery.js'\nimport { analyzeTemporalData } from '../../git/temporal.js'\nimport { isGitRepo } from '../../git/history.js'\nimport { getUncommittedDiff } from '../../git/diff.js'\nimport { mapFilesToModules } from '../../git/diff.js'\nimport { initParser, parseFile, languageFromPath } from '../../extraction/parser.js'\nimport { extractSymbols } from '../../extraction/symbols.js'\nimport { extractImports } from '../../extraction/imports.js'\nimport { extractCalls } from '../../extraction/calls.js'\nimport { buildGraph, writeGraph, enrichCouplingWithImports } from '../../core/graph.js'\nimport { generateConstitution } from '../../core/constitution.js'\nimport { createSession, writeSession, getLatestSession } from '../../core/sessions.js'\nimport { readFile as fsRead } from 'node:fs/promises'\nimport { generateStructuralModuleDocs } from '../../core/module-gen.js'\nimport type { SymbolRecord, ImportEdge, CallEdge, SymbolIndex } from '../../types/index.js'\n\nexport async function updateCommand(opts: { root: string; days: string }): Promise<void> {\n const root = resolve(opts.root)\n const days = parseInt(opts.days, 10)\n\n if (!existsSync(cortexPath(root, 'cortex.yaml'))) {\n console.error('Error: No CodeCortex knowledge found. Run `codecortex init` first.')\n process.exit(1)\n }\n\n console.log('CodeCortex update — refreshing knowledge...')\n console.log('')\n\n // Discover current state\n console.log('Discovering changes...')\n const project = await discoverProject(root)\n\n // Re-extract all symbols (full refresh for now, incremental in v2)\n console.log('Re-extracting symbols...')\n await initParser()\n\n const allSymbols: SymbolRecord[] = []\n const allImports: ImportEdge[] = []\n const allCalls: CallEdge[] = []\n\n for (const file of project.files) {\n const lang = languageFromPath(file.path)\n if (!lang) continue\n try {\n const tree = await parseFile(file.absolutePath, lang)\n const source = await fsRead(file.absolutePath, 'utf-8')\n allSymbols.push(...extractSymbols(tree, file.path, lang, source))\n allImports.push(...extractImports(tree, file.path, lang))\n allCalls.push(...extractCalls(tree, file.path, lang))\n } catch { /* skip */ }\n }\n\n // Rebuild graph\n console.log('Rebuilding dependency graph...')\n const MODULE_ROOTS = new Set(['src', 'lib', 'pkg', 'packages', 'apps', 'extensions', 'crates', 'internal', 'cmd', 'scripts', 'tools', 'rust'])\n const moduleNodes = project.modules.map(modName => {\n const modFiles = project.files.filter(f => {\n const parts = f.path.split('/')\n const topDir = parts[0] ?? ''\n return (MODULE_ROOTS.has(topDir) && parts[1] === modName) ||\n (parts[0] === modName)\n })\n const topDir = modFiles[0]?.path.split('/')[0] ?? 'src'\n return {\n path: `${topDir}/${modName}`,\n name: modName,\n files: modFiles.map(f => f.path),\n language: modFiles[0]?.language || 'unknown',\n lines: modFiles.reduce((sum, f) => sum + f.lines, 0),\n symbols: allSymbols.filter(s => modFiles.some(f => f.path === s.file)).length,\n }\n })\n\n const externalDeps: Record<string, string[]> = {}\n for (const file of project.files) {\n try {\n const content = await fsRead(file.absolutePath, 'utf-8')\n const importMatches = content.matchAll(/from\\s+['\"]([^.\\/][^'\"]*)['\"]/g)\n for (const match of importMatches) {\n const raw = match[1]\n if (!raw) continue\n const pkg = raw.startsWith('@') ? raw.split('/').slice(0, 2).join('/') : raw.split('/')[0] ?? raw\n if (!externalDeps[pkg]) externalDeps[pkg] = []\n externalDeps[pkg]!.push(file.path)\n }\n } catch { /* skip */ }\n }\n\n const graph = buildGraph({\n modules: moduleNodes,\n imports: allImports,\n calls: allCalls,\n entryPoints: project.entryPoints,\n externalDeps,\n })\n\n // Re-analyze temporal data\n console.log('Re-analyzing git history...')\n let temporalData = null\n if (await isGitRepo(root)) {\n temporalData = await analyzeTemporalData(root, days)\n enrichCouplingWithImports(graph, temporalData.coupling)\n }\n\n // Write updated files\n console.log('Writing updated knowledge...')\n const symbolIndex: SymbolIndex = {\n generated: new Date().toISOString(),\n total: allSymbols.length,\n symbols: allSymbols,\n }\n await writeJsonStream(cortexPath(root, 'symbols.json'), symbolIndex, 'symbols')\n await writeGraph(root, graph)\n if (temporalData) {\n await writeFile(cortexPath(root, 'temporal.json'), JSON.stringify(temporalData, null, 2))\n }\n\n // Generate structural module docs (skip existing)\n await generateStructuralModuleDocs(root, {\n graph,\n symbols: allSymbols,\n temporal: temporalData,\n })\n\n // Update manifest\n await updateManifest(root, {\n totalFiles: project.files.length,\n totalSymbols: allSymbols.length,\n totalModules: project.modules.length,\n languages: project.languages,\n })\n\n // Regenerate constitution\n await generateConstitution(root, {\n modules: moduleNodes,\n entryPoints: project.entryPoints,\n externalDeps,\n temporal: temporalData,\n })\n\n // Create session log\n const diff = await getUncommittedDiff(root).catch(() => ({ filesChanged: [], summary: 'no changes' }))\n const previousSession = await getLatestSession(root)\n const affectedModules = [...mapFilesToModules(diff.filesChanged).keys()]\n const session = createSession({\n filesChanged: diff.filesChanged,\n modulesAffected: affectedModules,\n summary: `Updated knowledge. ${allSymbols.length} symbols, ${project.modules.length} modules.`,\n previousSession: previousSession || undefined,\n })\n await writeSession(root, session)\n\n console.log('')\n console.log('─'.repeat(50))\n console.log('Update complete!')\n console.log(` Symbols: ${allSymbols.length}`)\n console.log(` Modules: ${project.modules.length}`)\n if (temporalData) {\n console.log(` Commits: ${temporalData.totalCommits}`)\n }\n console.log(` Session: ${session.id}`)\n}\n","import simpleGit from 'simple-git'\n\nexport interface DiffResult {\n filesChanged: string[]\n insertions: number\n deletions: number\n summary: string\n}\n\nexport async function getUncommittedDiff(root: string): Promise<DiffResult> {\n const git = simpleGit(root)\n const diff = await git.diffSummary()\n\n return {\n filesChanged: diff.files.map(f => f.file),\n insertions: diff.insertions,\n deletions: diff.deletions,\n summary: `${diff.files.length} files changed, +${diff.insertions} -${diff.deletions}`,\n }\n}\n\nexport async function getDiffSinceCommit(root: string, commitHash: string): Promise<DiffResult> {\n const git = simpleGit(root)\n const diff = await git.diffSummary([commitHash, 'HEAD'])\n\n return {\n filesChanged: diff.files.map(f => f.file),\n insertions: diff.insertions,\n deletions: diff.deletions,\n summary: `${diff.files.length} files changed since ${commitHash.slice(0, 7)}, +${diff.insertions} -${diff.deletions}`,\n }\n}\n\nexport async function getChangedFilesSinceDate(root: string, sinceDate: string): Promise<string[]> {\n const git = simpleGit(root)\n const log = await git.log({ '--since': sinceDate, '--name-only': null })\n\n const files = new Set<string>()\n for (const commit of log.all) {\n const diff = commit.diff\n if (diff) {\n for (const file of diff.files) {\n files.add(file.file)\n }\n }\n }\n\n return [...files]\n}\n\nexport function mapFilesToModules(files: string[]): Map<string, string[]> {\n const moduleMap = new Map<string, string[]>()\n\n for (const file of files) {\n const parts = file.split('/')\n let module = 'root'\n\n if (parts[0] === 'src' && parts.length >= 3 && parts[1]) {\n module = parts[1]\n } else if (parts[0] === 'lib' && parts.length >= 3 && parts[1]) {\n module = parts[1]\n }\n\n const existing = moduleMap.get(module) || []\n existing.push(file)\n moduleMap.set(module, existing)\n }\n\n return moduleMap\n}\n","import { resolve } from 'node:path'\nimport { existsSync } from 'node:fs'\nimport { cortexPath, readFile } from '../../utils/files.js'\nimport { readManifest } from '../../core/manifest.js'\nimport { listModuleDocs } from '../../core/modules.js'\nimport { listDecisions } from '../../core/decisions.js'\nimport { listSessions, getLatestSession } from '../../core/sessions.js'\nimport type { SymbolIndex, TemporalData } from '../../types/index.js'\n\nexport async function statusCommand(opts: { root: string }): Promise<void> {\n const root = resolve(opts.root)\n\n if (!existsSync(cortexPath(root, 'cortex.yaml'))) {\n console.log('No CodeCortex knowledge found.')\n console.log(`Run 'codecortex init' to analyze this codebase.`)\n return\n }\n\n const manifest = await readManifest(root)\n if (!manifest) {\n console.log('Error reading cortex.yaml')\n return\n }\n\n console.log(`CodeCortex Status — ${manifest.project}`)\n console.log('─'.repeat(50))\n console.log('')\n\n // Core stats\n console.log('Knowledge Store:')\n console.log(` Version: ${manifest.version}`)\n console.log(` Languages: ${manifest.languages.join(', ')}`)\n console.log(` Files: ${manifest.totalFiles}`)\n console.log(` Symbols: ${manifest.totalSymbols}`)\n console.log(` Modules: ${manifest.totalModules}`)\n console.log(` Generated: ${manifest.generated}`)\n console.log(` Last updated: ${manifest.lastUpdated}`)\n console.log('')\n\n // Freshness\n const lastUpdated = new Date(manifest.lastUpdated)\n const ageHours = Math.floor((Date.now() - lastUpdated.getTime()) / (1000 * 60 * 60))\n const ageLabel = ageHours < 1 ? 'just now' :\n ageHours < 24 ? `${ageHours} hours ago` :\n `${Math.floor(ageHours / 24)} days ago`\n console.log(`Freshness: ${ageLabel}`)\n if (ageHours > 24) {\n console.log(' Consider running `codecortex update` to refresh.')\n }\n console.log('')\n\n // Knowledge breakdown\n const modules = await listModuleDocs(root)\n const decisions = await listDecisions(root)\n const sessions = await listSessions(root)\n\n console.log('Knowledge Breakdown:')\n console.log(` Module docs: ${modules.length}${modules.length > 0 ? ` (${modules.join(', ')})` : ''}`)\n console.log(` Decision records: ${decisions.length}`)\n console.log(` Session logs: ${sessions.length}`)\n\n // Check for patterns\n const patterns = await readFile(cortexPath(root, 'patterns.md'))\n const patternCount = patterns ? (patterns.match(/^### /gm) || []).length : 0\n console.log(` Coding patterns: ${patternCount}`)\n console.log('')\n\n // Symbol breakdown\n const symbolContent = await readFile(cortexPath(root, 'symbols.json'))\n if (symbolContent) {\n const index: SymbolIndex = JSON.parse(symbolContent)\n const byKind = new Map<string, number>()\n for (const s of index.symbols) {\n byKind.set(s.kind, (byKind.get(s.kind) || 0) + 1)\n }\n console.log('Symbol Index:')\n for (const [kind, count] of [...byKind.entries()].sort((a, b) => b[1] - a[1])) {\n console.log(` ${kind}: ${count}`)\n }\n const exported = index.symbols.filter(s => s.exported).length\n console.log(` Total exported: ${exported}/${index.total}`)\n console.log('')\n }\n\n // Temporal summary\n const temporalContent = await readFile(cortexPath(root, 'temporal.json'))\n if (temporalContent) {\n const temporal: TemporalData = JSON.parse(temporalContent)\n console.log('Temporal Analysis:')\n console.log(` Period: ${temporal.periodDays} days, ${temporal.totalCommits} commits`)\n console.log(` Hotspots: ${temporal.hotspots.filter(h => h.stability === 'volatile').length} volatile, ${temporal.hotspots.filter(h => h.stability === 'stabilizing').length} stabilizing`)\n console.log(` Couplings: ${temporal.coupling.length} pairs (${temporal.coupling.filter(c => !c.hasImport).length} hidden)`)\n console.log(` Bug records: ${temporal.bugHistory.length} files with fix history`)\n\n // Top 3 hotspots\n const top = temporal.hotspots.slice(0, 3)\n if (top.length > 0) {\n console.log(` Top hotspots:`)\n for (const h of top) {\n console.log(` ${h.file} — ${h.changes} changes (${h.stability})`)\n }\n }\n }\n\n // Feedback\n const feedbackContent = await readFile(cortexPath(root, 'feedback', 'log.json'))\n if (feedbackContent) {\n const feedback = JSON.parse(feedbackContent)\n if (feedback.length > 0) {\n console.log('')\n console.log(`Pending feedback: ${feedback.length} reports (will be addressed on next update)`)\n }\n }\n\n // Latest session\n const latestSession = await getLatestSession(root)\n if (latestSession) {\n console.log('')\n console.log(`Latest session: ${latestSession}`)\n }\n}\n","import { resolve } from 'node:path'\nimport { existsSync } from 'node:fs'\nimport { cortexPath, readFile } from '../../utils/files.js'\nimport type { SymbolIndex } from '../../types/index.js'\n\nexport async function symbolsCommand(\n query: string | undefined,\n opts: { root: string; kind?: string; file?: string; exported?: boolean; limit?: string },\n): Promise<void> {\n const root = resolve(opts.root)\n\n if (!existsSync(cortexPath(root, 'cortex.yaml'))) {\n console.log('No CodeCortex knowledge found.')\n console.log(`Run 'codecortex init' to analyze this codebase.`)\n return\n }\n\n const content = await readFile(cortexPath(root, 'symbols.json'))\n if (!content) {\n console.log('No symbol index found. Run `codecortex init` first.')\n return\n }\n\n const index: SymbolIndex = JSON.parse(content)\n\n if (!query && !opts.kind && !opts.file && !opts.exported) {\n // Summary mode\n printSummary(index)\n return\n }\n\n // Query/filter mode\n let matches = index.symbols\n\n if (query) {\n const q = query.toLowerCase()\n matches = matches.filter(s => s.name.toLowerCase().includes(q))\n }\n if (opts.kind) {\n matches = matches.filter(s => s.kind === opts.kind)\n }\n if (opts.file) {\n matches = matches.filter(s => s.file.includes(opts.file!))\n }\n if (opts.exported) {\n matches = matches.filter(s => s.exported)\n }\n\n const limit = parseInt(opts.limit ?? '30', 10)\n const display = matches.slice(0, limit)\n\n if (display.length === 0) {\n console.log(`No symbols found${query ? ` matching \"${query}\"` : ''}.`)\n return\n }\n\n // Print results\n console.log('')\n for (const s of display) {\n const lines = s.endLine > s.startLine ? `${s.startLine}-${s.endLine}` : `${s.startLine}`\n const exp = s.exported ? 'exported' : 'local'\n console.log(` ${pad(s.kind, 12)} ${pad(s.name, 30)} ${pad(s.file, 40)} ${pad(lines, 10)} ${exp}`)\n if (s.signature) {\n console.log(`${' '.repeat(14)}${s.signature}`)\n }\n }\n\n console.log('')\n if (matches.length > limit) {\n console.log(`Showing ${limit} of ${matches.length} matches. Use -l to show more.`)\n } else {\n console.log(`${matches.length} symbol${matches.length === 1 ? '' : 's'} found.`)\n }\n}\n\nfunction printSummary(index: SymbolIndex): void {\n console.log('')\n console.log(`Symbol Index: ${index.total} symbols`)\n console.log('─'.repeat(50))\n\n // Count by kind\n const byKind = new Map<string, number>()\n for (const s of index.symbols) {\n byKind.set(s.kind, (byKind.get(s.kind) ?? 0) + 1)\n }\n console.log('')\n console.log('By Kind:')\n for (const [kind, count] of [...byKind.entries()].sort((a, b) => b[1] - a[1])) {\n console.log(` ${pad(kind, 14)} ${count}`)\n }\n\n // Count by file (top 10)\n const byFile = new Map<string, number>()\n for (const s of index.symbols) {\n byFile.set(s.file, (byFile.get(s.file) ?? 0) + 1)\n }\n console.log('')\n console.log('Top Files:')\n for (const [file, count] of [...byFile.entries()].sort((a, b) => b[1] - a[1]).slice(0, 10)) {\n console.log(` ${pad(file, 45)} ${count} symbols`)\n }\n\n const exported = index.symbols.filter(s => s.exported).length\n console.log('')\n console.log(`Exported: ${exported}/${index.total}`)\n console.log('')\n console.log('Run `codecortex symbols <query>` to search.')\n}\n\nfunction pad(str: string, len: number): string {\n return str.length >= len ? str : str + ' '.repeat(len - str.length)\n}\n","import { resolve } from 'node:path'\nimport { existsSync } from 'node:fs'\nimport { cortexPath } from '../../utils/files.js'\nimport { searchKnowledge } from '../../core/search.js'\n\nexport async function searchCommand(\n query: string,\n opts: { root: string; limit?: string },\n): Promise<void> {\n const root = resolve(opts.root)\n\n if (!existsSync(cortexPath(root, 'cortex.yaml'))) {\n console.log('No CodeCortex knowledge found.')\n console.log(`Run 'codecortex init' to analyze this codebase.`)\n return\n }\n\n const results = await searchKnowledge(root, query)\n const limit = parseInt(opts.limit ?? '20', 10)\n const display = results.slice(0, limit)\n\n if (display.length === 0) {\n console.log(`No results for \"${query}\".`)\n return\n }\n\n console.log('')\n console.log(`Search: \"${query}\"`)\n console.log('─'.repeat(50))\n\n for (let i = 0; i < display.length; i++) {\n const r = display[i]!\n console.log('')\n console.log(` [${i + 1}] ${r.file}:${r.line}`)\n\n // Print context lines, highlight the match\n const ctxLines = r.context.split('\\n')\n for (const line of ctxLines) {\n const trimmed = line.trim()\n if (!trimmed) continue\n if (trimmed.toLowerCase().includes(query.toLowerCase())) {\n console.log(` > ${trimmed}`)\n } else {\n console.log(` ${trimmed}`)\n }\n }\n }\n\n console.log('')\n if (results.length > limit) {\n console.log(`Showing ${limit} of ${results.length} results. Use -l to show more.`)\n } else {\n console.log(`${results.length} result${results.length === 1 ? '' : 's'} found.`)\n }\n}\n","import { resolve } from 'node:path'\nimport { existsSync } from 'node:fs'\nimport { cortexPath } from '../../utils/files.js'\nimport { readGraph, getModuleDependencies } from '../../core/graph.js'\nimport { readModuleDoc, listModuleDocs } from '../../core/modules.js'\n\nexport async function modulesCommand(\n name: string | undefined,\n opts: { root: string },\n): Promise<void> {\n const root = resolve(opts.root)\n\n if (!existsSync(cortexPath(root, 'cortex.yaml'))) {\n console.log('No CodeCortex knowledge found.')\n console.log(`Run 'codecortex init' to analyze this codebase.`)\n return\n }\n\n const graph = await readGraph(root)\n if (!graph) {\n console.log('No dependency graph found. Run `codecortex init` first.')\n return\n }\n\n if (!name) {\n await printModuleList(root, graph)\n return\n }\n\n await printModuleDetail(root, name, graph)\n}\n\nasync function printModuleList(\n root: string,\n graph: import('../../types/index.js').DependencyGraph,\n): Promise<void> {\n const docsAvailable = new Set(await listModuleDocs(root))\n\n console.log('')\n console.log(`Modules: ${graph.modules.length}`)\n console.log('─'.repeat(70))\n console.log('')\n console.log(` ${pad('MODULE', 18)} ${pad('FILES', 6)} ${pad('LINES', 7)} ${pad('SYMBOLS', 8)} ${pad('LANG', 14)} DOC`)\n\n for (const mod of [...graph.modules].sort((a, b) => a.name.localeCompare(b.name))) {\n const hasDoc = docsAvailable.has(mod.name) ? 'yes' : '--'\n console.log(` ${pad(mod.name, 18)} ${pad(String(mod.files.length), 6)} ${pad(String(mod.lines), 7)} ${pad(String(mod.symbols), 8)} ${pad(mod.language, 14)} ${hasDoc}`)\n }\n\n const withDocs = graph.modules.filter(m => docsAvailable.has(m.name)).length\n console.log('')\n console.log(`${graph.modules.length} modules, ${withDocs} with docs.`)\n console.log('')\n console.log('Run `codecortex modules <name>` to deep-dive into a module.')\n}\n\nasync function printModuleDetail(\n root: string,\n name: string,\n graph: import('../../types/index.js').DependencyGraph,\n): Promise<void> {\n const mod = graph.modules.find(m => m.name === name)\n if (!mod) {\n const available = graph.modules.map(m => m.name).join(', ')\n console.log(`Module \"${name}\" not found. Available: ${available}`)\n return\n }\n\n console.log('')\n console.log(`Module: ${name}`)\n console.log('═'.repeat(50))\n\n // Module doc\n const doc = await readModuleDoc(root, name)\n if (doc) {\n console.log('')\n console.log(doc)\n } else {\n console.log('')\n console.log(`No module doc for \"${name}\".`)\n console.log(`Run \\`codecortex init\\` to generate structural docs.`)\n }\n\n // Dependencies\n const deps = getModuleDependencies(graph, name)\n\n if (deps.imports.length > 0) {\n console.log('')\n console.log('Imports:')\n const seen = new Set<string>()\n for (const edge of deps.imports) {\n const key = `${edge.source} -> ${edge.target}`\n if (seen.has(key)) continue\n seen.add(key)\n const specifiers = edge.specifiers.length > 0 ? ` [${edge.specifiers.join(', ')}]` : ''\n console.log(` ${edge.source} -> ${edge.target}${specifiers}`)\n }\n }\n\n if (deps.importedBy.length > 0) {\n console.log('')\n console.log('Imported By:')\n const seen = new Set<string>()\n for (const edge of deps.importedBy) {\n const key = `${edge.source} -> ${edge.target}`\n if (seen.has(key)) continue\n seen.add(key)\n const specifiers = edge.specifiers.length > 0 ? ` [${edge.specifiers.join(', ')}]` : ''\n console.log(` ${edge.source} -> ${edge.target}${specifiers}`)\n }\n }\n\n console.log('')\n console.log(`Stats: ${mod.files.length} files, ${mod.lines} lines, ${mod.symbols} symbols (${mod.language})`)\n}\n\nfunction pad(str: string, len: number): string {\n return str.length >= len ? str : str + ' '.repeat(len - str.length)\n}\n","import { resolve } from 'node:path'\nimport { existsSync } from 'node:fs'\nimport { cortexPath, readFile } from '../../utils/files.js'\nimport type { TemporalData } from '../../types/index.js'\n\nexport async function hotspotsCommand(\n opts: { root: string; limit?: string },\n): Promise<void> {\n const root = resolve(opts.root)\n\n if (!existsSync(cortexPath(root, 'cortex.yaml'))) {\n console.log('No CodeCortex knowledge found.')\n console.log(`Run 'codecortex init' to analyze this codebase.`)\n return\n }\n\n const content = await readFile(cortexPath(root, 'temporal.json'))\n if (!content) {\n console.log('No temporal data found. Run `codecortex init` in a git repository.')\n return\n }\n\n const temporal: TemporalData = JSON.parse(content)\n const limit = parseInt(opts.limit ?? '15', 10)\n\n // Same risk formula as MCP get_hotspots (read.ts:260-285)\n const riskMap = new Map<string, { churn: number; couplings: number; bugs: number; risk: number }>()\n\n for (const h of temporal.hotspots) {\n riskMap.set(h.file, { churn: h.changes, couplings: 0, bugs: 0, risk: h.changes })\n }\n\n for (const c of temporal.coupling) {\n for (const f of [c.fileA, c.fileB]) {\n const entry = riskMap.get(f) ?? { churn: 0, couplings: 0, bugs: 0, risk: 0 }\n entry.couplings++\n entry.risk += c.strength * 2\n riskMap.set(f, entry)\n }\n }\n\n for (const b of temporal.bugHistory) {\n const entry = riskMap.get(b.file) ?? { churn: 0, couplings: 0, bugs: 0, risk: 0 }\n entry.bugs = b.fixCommits\n entry.risk += b.fixCommits * 3\n riskMap.set(b.file, entry)\n }\n\n const ranked = [...riskMap.entries()]\n .sort((a, b) => b[1].risk - a[1].risk)\n .slice(0, limit)\n .map(([file, data]) => ({ file, ...data, risk: Math.round(data.risk * 100) / 100 }))\n\n console.log('')\n console.log(`Hotspots — ${temporal.periodDays} days, ${temporal.totalCommits} commits`)\n console.log('─'.repeat(70))\n console.log('')\n console.log(` ${pad('#', 4)} ${pad('FILE', 42)} ${pad('CHURN', 6)} ${pad('CPLS', 5)} ${pad('BUGS', 5)} RISK`)\n\n for (let i = 0; i < ranked.length; i++) {\n const r = ranked[i]!\n console.log(` ${pad(String(i + 1), 4)} ${pad(r.file, 42)} ${pad(String(r.churn), 6)} ${pad(String(r.couplings), 5)} ${pad(String(r.bugs), 5)} ${r.risk.toFixed(2)}`)\n }\n\n // Hidden dependencies\n const hidden = temporal.coupling.filter(c => !c.hasImport && c.strength >= 0.3)\n if (hidden.length > 0) {\n console.log('')\n console.log('Hidden Dependencies (co-change but no import):')\n for (const h of hidden.slice(0, 10)) {\n console.log(` ${h.fileA} <-> ${h.fileB} (${h.cochanges} co-changes, ${Math.round(h.strength * 100)}%)`)\n }\n if (hidden.length > 10) {\n console.log(` ... and ${hidden.length - 10} more`)\n }\n }\n\n console.log('')\n}\n\nfunction pad(str: string, len: number): string {\n return str.length >= len ? str : str + ' '.repeat(len - str.length)\n}\n","import { resolve, join } from 'node:path'\nimport { existsSync } from 'node:fs'\nimport { readFile, writeFile, stat, chmod, unlink } from 'node:fs/promises'\nimport simpleGit from 'simple-git'\nimport { isGitRepo } from '../../git/history.js'\nimport { readManifest } from '../../core/manifest.js'\n\nconst HOOK_START = '# --- codecortex-hook-start ---'\nconst HOOK_END = '# --- codecortex-hook-end ---'\nconst HOOK_TYPES = ['post-commit', 'post-merge'] as const\n\nconst HOOK_SCRIPT = `\n${HOOK_START}\n# Auto-update CodeCortex knowledge after git operations\n# Installed by: codecortex hook install\n(\n if command -v codecortex >/dev/null 2>&1; then\n codecortex update >/dev/null 2>&1\n elif command -v npx >/dev/null 2>&1; then\n npx codecortex-ai update >/dev/null 2>&1\n fi\n) &\n${HOOK_END}\n`.trimStart()\n\n// --- Pure helpers ---\n\nexport function hasCodeCortexHook(content: string): boolean {\n return content.includes(HOOK_START)\n}\n\nexport function removeCodeCortexHook(content: string): string {\n const startIdx = content.indexOf(HOOK_START)\n if (startIdx === -1) return content\n const endIdx = content.indexOf(HOOK_END)\n if (endIdx === -1) return content\n\n const before = content.slice(0, startIdx)\n const after = content.slice(endIdx + HOOK_END.length)\n\n // Remove trailing newline left by the section\n return before + after.replace(/^\\n/, '')\n}\n\nexport function isEmptyHook(content: string): boolean {\n const stripped = content\n .split('\\n')\n .filter(line => {\n const trimmed = line.trim()\n return trimmed !== '' && !trimmed.startsWith('#!') && !trimmed.startsWith('#')\n })\n .join('')\n return stripped.length === 0\n}\n\n// --- Git hooks dir resolution ---\n\nasync function getGitHooksDir(root: string): Promise<string> {\n const git = simpleGit(root)\n const gitDir = (await git.revparse(['--git-dir'])).trim()\n const resolved = resolve(root, gitDir)\n return join(resolved, 'hooks')\n}\n\n// --- .gitignore check ---\n\nasync function isCodeCortexIgnored(root: string): Promise<boolean> {\n const gitignorePath = join(root, '.gitignore')\n if (!existsSync(gitignorePath)) return false\n try {\n const content = await readFile(gitignorePath, 'utf-8')\n return content.split('\\n').some(line => {\n const trimmed = line.trim()\n return trimmed === '.codecortex' || trimmed === '.codecortex/' || trimmed === '.codecortex/**'\n })\n } catch {\n return false\n }\n}\n\n// --- Commands ---\n\nexport async function hookInstallCommand(opts: { root: string }): Promise<void> {\n const root = resolve(opts.root)\n\n if (!(await isGitRepo(root))) {\n console.error('Error: not a git repository.')\n process.exitCode = 1\n return\n }\n\n if (process.platform === 'win32') {\n console.warn('Warning: shell-based git hooks may not work natively on Windows.')\n console.warn('Consider using WSL or Git Bash.')\n }\n\n const hooksDir = await getGitHooksDir(root)\n\n // Warn if .codecortex is gitignored\n if (await isCodeCortexIgnored(root)) {\n console.warn(\"Warning: .codecortex is in .gitignore — knowledge won't be shared.\")\n console.warn('Remove .codecortex from .gitignore to commit it alongside code.')\n console.log('')\n }\n\n for (const hookType of HOOK_TYPES) {\n const hookPath = join(hooksDir, hookType)\n let status: string\n\n if (existsSync(hookPath)) {\n const content = await readFile(hookPath, 'utf-8')\n if (hasCodeCortexHook(content)) {\n status = 'already installed'\n } else {\n // Append to existing hook\n const newContent = content.trimEnd() + '\\n\\n' + HOOK_SCRIPT\n await writeFile(hookPath, newContent, 'utf-8')\n await chmod(hookPath, 0o755)\n status = 'installed'\n }\n } else {\n // Create new hook file\n const content = '#!/bin/sh\\n\\n' + HOOK_SCRIPT\n await writeFile(hookPath, content, 'utf-8')\n await chmod(hookPath, 0o755)\n status = 'installed'\n }\n\n console.log(` ${hookType}: ${status}`)\n }\n\n const allNew = true // If we got here, hooks are installed\n console.log('')\n console.log('Knowledge will auto-update after every commit and merge.')\n}\n\nexport async function hookUninstallCommand(opts: { root: string }): Promise<void> {\n const root = resolve(opts.root)\n\n if (!(await isGitRepo(root))) {\n console.error('Error: not a git repository.')\n process.exitCode = 1\n return\n }\n\n const hooksDir = await getGitHooksDir(root)\n\n for (const hookType of HOOK_TYPES) {\n const hookPath = join(hooksDir, hookType)\n let status: string\n\n if (!existsSync(hookPath)) {\n status = 'not installed'\n } else {\n const content = await readFile(hookPath, 'utf-8')\n if (!hasCodeCortexHook(content)) {\n status = 'not installed'\n } else {\n const cleaned = removeCodeCortexHook(content)\n if (isEmptyHook(cleaned)) {\n await unlink(hookPath)\n } else {\n await writeFile(hookPath, cleaned, 'utf-8')\n }\n status = 'removed'\n }\n }\n\n console.log(` ${hookType}: ${status}`)\n }\n}\n\nexport async function hookStatusCommand(opts: { root: string }): Promise<void> {\n const root = resolve(opts.root)\n\n if (!(await isGitRepo(root))) {\n console.error('Error: not a git repository.')\n process.exitCode = 1\n return\n }\n\n const hooksDir = await getGitHooksDir(root)\n\n for (const hookType of HOOK_TYPES) {\n const hookPath = join(hooksDir, hookType)\n let installed = false\n\n if (existsSync(hookPath)) {\n const content = await readFile(hookPath, 'utf-8')\n installed = hasCodeCortexHook(content)\n }\n\n console.log(` ${hookType}: ${installed ? 'installed' : 'not installed'}`)\n }\n\n // Knowledge freshness\n const manifest = await readManifest(root)\n if (manifest) {\n const lastUpdated = new Date(manifest.lastUpdated)\n const ageHours = Math.floor((Date.now() - lastUpdated.getTime()) / (1000 * 60 * 60))\n const ageLabel = ageHours < 1 ? 'just now' :\n ageHours < 24 ? `${ageHours} hour${ageHours === 1 ? '' : 's'} ago` :\n `${Math.floor(ageHours / 24)} day${Math.floor(ageHours / 24) === 1 ? '' : 's'} ago`\n console.log(` Knowledge: last updated ${ageLabel}`)\n } else {\n console.log(' Knowledge: not initialized (run codecortex init)')\n }\n}\n","import { execSync } from 'node:child_process'\nimport { checkForUpdate, getUpgradeCommand } from '../utils/version-check.js'\n\nexport async function upgradeCommand(currentVersion: string): Promise<void> {\n console.log('Checking for updates...')\n console.log('')\n\n const result = await checkForUpdate(currentVersion)\n\n if (!result) {\n console.log('Could not reach the npm registry. Check your internet connection.')\n return\n }\n\n if (!result.isOutdated) {\n console.log(`Already on the latest version (${result.current}).`)\n return\n }\n\n const cmd = getUpgradeCommand()\n console.log(`Update available: ${result.current} → ${result.latest}`)\n console.log('')\n console.log(`Running: ${cmd}`)\n console.log('')\n\n try {\n execSync(cmd, { stdio: 'inherit' })\n console.log('')\n console.log(`Successfully upgraded to ${result.latest}!`)\n } catch {\n console.error('')\n console.error('Upgrade failed. Try running manually:')\n console.error(` ${cmd}`)\n console.error('')\n console.error('If you get a permission error, try:')\n console.error(` sudo ${cmd}`)\n }\n}\n","import { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport { readFileSync, writeFileSync } from 'node:fs'\n\nconst CACHE_FILE = join(tmpdir(), 'codecortex-update-check.json')\nconst CACHE_TTL = 24 * 60 * 60 * 1000 // 24 hours\nconst REGISTRY_URL = 'https://registry.npmjs.org/codecortex-ai/latest'\nconst FETCH_TIMEOUT = 3000\n\ninterface CachedCheck {\n latest: string\n lastCheck: number\n}\n\ninterface VersionCheckResult {\n current: string\n latest: string\n isOutdated: boolean\n}\n\nfunction readCache(): CachedCheck | null {\n try {\n const raw = readFileSync(CACHE_FILE, 'utf-8')\n const data: unknown = JSON.parse(raw)\n if (\n typeof data === 'object' && data !== null &&\n 'latest' in data && typeof data.latest === 'string' &&\n 'lastCheck' in data && typeof data.lastCheck === 'number'\n ) {\n return data as CachedCheck\n }\n return null\n } catch {\n return null\n }\n}\n\nfunction writeCache(latest: string): void {\n try {\n writeFileSync(CACHE_FILE, JSON.stringify({ latest, lastCheck: Date.now() }))\n } catch {\n // silent — cache is best-effort\n }\n}\n\nfunction compareVersions(current: string, latest: string): boolean {\n const parse = (v: string) => v.replace(/^v/, '').split('.').map(Number)\n const c = parse(current)\n const l = parse(latest)\n const cMaj = c[0] ?? 0, cMin = c[1] ?? 0, cPatch = c[2] ?? 0\n const lMaj = l[0] ?? 0, lMin = l[1] ?? 0, lPatch = l[2] ?? 0\n if (lMaj !== cMaj) return lMaj > cMaj\n if (lMin !== cMin) return lMin > cMin\n return lPatch > cPatch\n}\n\nasync function fetchLatestVersion(): Promise<string | null> {\n try {\n const res = await fetch(REGISTRY_URL, { signal: AbortSignal.timeout(FETCH_TIMEOUT) })\n if (!res.ok) return null\n const data = await res.json() as { version?: string }\n return data.version ?? null\n } catch {\n return null\n }\n}\n\n/**\n * Check if a newer version is available on npm.\n * Returns immediately from cache if fresh, otherwise fires a background fetch.\n * Designed to never block or throw.\n */\nexport async function checkForUpdate(currentVersion: string): Promise<VersionCheckResult | null> {\n const cached = readCache()\n\n // Cache is fresh — return cached result without hitting network\n if (cached && Date.now() - cached.lastCheck < CACHE_TTL) {\n return {\n current: currentVersion,\n latest: cached.latest,\n isOutdated: compareVersions(currentVersion, cached.latest),\n }\n }\n\n // Cache is stale or missing — fetch from registry\n const latest = await fetchLatestVersion()\n if (!latest) return null\n\n writeCache(latest)\n\n return {\n current: currentVersion,\n latest,\n isOutdated: compareVersions(currentVersion, latest),\n }\n}\n\n/** Detect which package manager invoked this process */\nexport function detectPackageManager(): 'npm' | 'yarn' | 'pnpm' | 'bun' {\n const ua = process.env.npm_config_user_agent ?? ''\n if (ua.startsWith('yarn')) return 'yarn'\n if (ua.startsWith('pnpm')) return 'pnpm'\n if (ua.startsWith('bun')) return 'bun'\n\n // Fallback: inspect argv path\n const bin = process.argv[1] ?? ''\n if (bin.includes('yarn')) return 'yarn'\n if (bin.includes('pnpm')) return 'pnpm'\n if (bin.includes('bun')) return 'bun'\n\n return 'npm'\n}\n\n/** Get the correct upgrade command for the user's package manager */\nexport function getUpgradeCommand(): string {\n const pm = detectPackageManager()\n switch (pm) {\n case 'yarn': return 'yarn global add codecortex-ai@latest'\n case 'pnpm': return 'pnpm add -g codecortex-ai@latest'\n case 'bun': return 'bun add -g codecortex-ai@latest'\n default: return 'npm install -g codecortex-ai@latest'\n }\n}\n\n/** Should we show update notifications? */\nexport function shouldNotify(): boolean {\n if (process.env.CI || process.env.BUILD_NUMBER || process.env.RUN_ID) return false\n if (process.env.NO_UPDATE_NOTIFIER) return false\n if (process.env.NODE_ENV === 'test') return false\n if (!process.stderr.isTTY) return false\n return true\n}\n\n/** Render the update notification to stderr */\nexport function renderUpdateNotification(current: string, latest: string): void {\n const cmd = getUpgradeCommand()\n const yellow = '\\x1b[33m'\n const cyan = '\\x1b[36m'\n const dim = '\\x1b[2m'\n const reset = '\\x1b[0m'\n const bold = '\\x1b[1m'\n\n // Dynamic width based on content (visible chars only)\n const line1Text = `Update available: ${current} → ${latest}`\n const line2Text = `Run ${cmd}`\n const contentWidth = Math.max(line1Text.length, line2Text.length)\n const innerWidth = contentWidth + 6 // 3 padding each side\n const rpad = (text: string) => ' '.repeat(Math.max(0, contentWidth - text.length + 3))\n\n const msg = [\n '',\n `${dim}╭${'─'.repeat(innerWidth)}╮${reset}`,\n `${dim}│${reset}${' '.repeat(innerWidth)}${dim}│${reset}`,\n `${dim}│${reset} ${yellow}Update available:${reset} ${dim}${current}${reset} → ${cyan}${bold}${latest}${reset}${rpad(line1Text)}${dim}│${reset}`,\n `${dim}│${reset} Run ${cyan}${cmd}${reset}${rpad(line2Text)}${dim}│${reset}`,\n `${dim}│${reset}${' '.repeat(innerWidth)}${dim}│${reset}`,\n `${dim}╰${'─'.repeat(innerWidth)}╯${reset}`,\n '',\n ].join('\\n')\n\n process.stderr.write(msg)\n}\n","import type { Command, Help } from 'commander'\n\nconst COMMAND_GROUPS: Array<{ title: string; commands: string[] }> = [\n { title: 'Core', commands: ['init', 'serve', 'update', 'status'] },\n { title: 'Query', commands: ['symbols', 'search', 'modules', 'hotspots'] },\n { title: 'Utility', commands: ['hook', 'upgrade'] },\n]\n\nexport function formatHelp(cmd: Command, helper: Help): string {\n // Only apply grouping to the root program — subcommands use default format\n if (cmd.parent) {\n return defaultFormatHelp(cmd, helper)\n }\n\n const termWidth = helper.padWidth(cmd, helper)\n const helpWidth = helper.helpWidth ?? 80\n\n const item = (term: string, desc: string) =>\n helper.formatItem(term, termWidth, desc, helper)\n\n const output: string[] = [\n `${helper.styleTitle('Usage:')} ${helper.styleUsage(helper.commandUsage(cmd))}`,\n '',\n ]\n\n // Description\n const desc = helper.commandDescription(cmd)\n if (desc) {\n output.push(helper.boxWrap(helper.styleCommandDescription(desc), helpWidth), '')\n }\n\n // Options\n const opts = helper.visibleOptions(cmd)\n if (opts.length) {\n output.push(helper.styleTitle('Options:'))\n for (const opt of opts) {\n output.push(item(\n helper.styleOptionTerm(helper.optionTerm(opt)),\n helper.styleOptionDescription(helper.optionDescription(opt)),\n ))\n }\n output.push('')\n }\n\n // Grouped commands\n const allCmds = helper.visibleCommands(cmd)\n const cmdByName = new Map(allCmds.map(c => [c.name(), c]))\n\n for (const group of COMMAND_GROUPS) {\n const groupCmds = group.commands\n .map(name => cmdByName.get(name))\n .filter((c): c is Command => c !== undefined)\n if (!groupCmds.length) continue\n\n output.push(helper.styleTitle(`${group.title}:`))\n for (const c of groupCmds) {\n output.push(item(\n helper.styleSubcommandTerm(helper.subcommandTerm(c)),\n helper.styleSubcommandDescription(helper.subcommandDescription(c)),\n ))\n }\n output.push('')\n for (const c of groupCmds) cmdByName.delete(c.name())\n }\n\n // Remaining (built-in help command)\n if (cmdByName.size) {\n for (const c of cmdByName.values()) {\n output.push(item(\n helper.styleSubcommandTerm(helper.subcommandTerm(c)),\n helper.styleSubcommandDescription(helper.subcommandDescription(c)),\n ))\n }\n output.push('')\n }\n\n return output.join('\\n')\n}\n\n/** Default Commander formatHelp — used for subcommands */\nfunction defaultFormatHelp(cmd: Command, helper: Help): string {\n const termWidth = helper.padWidth(cmd, helper)\n const helpWidth = helper.helpWidth ?? 80\n\n const item = (term: string, desc: string) =>\n helper.formatItem(term, termWidth, desc, helper)\n\n const output: string[] = [\n `${helper.styleTitle('Usage:')} ${helper.styleUsage(helper.commandUsage(cmd))}`,\n '',\n ]\n\n const desc = helper.commandDescription(cmd)\n if (desc) {\n output.push(helper.boxWrap(helper.styleCommandDescription(desc), helpWidth), '')\n }\n\n const opts = helper.visibleOptions(cmd)\n if (opts.length) {\n output.push(helper.styleTitle('Options:'))\n for (const opt of opts) {\n output.push(item(\n helper.styleOptionTerm(helper.optionTerm(opt)),\n helper.styleOptionDescription(helper.optionDescription(opt)),\n ))\n }\n output.push('')\n }\n\n const cmds = helper.visibleCommands(cmd)\n if (cmds.length) {\n output.push(helper.styleTitle('Commands:'))\n for (const c of cmds) {\n output.push(item(\n helper.styleSubcommandTerm(helper.subcommandTerm(c)),\n helper.styleSubcommandDescription(helper.subcommandDescription(c)),\n ))\n }\n output.push('')\n }\n\n return output.join('\\n')\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,SAAS,iBAAAA,sBAAqB;AAC9B,SAAS,eAAe;;;ACHxB,SAAS,eAAe;;;ACAxB,SAAS,gBAAgB;AACzB,SAAS,YAAYC,SAAQ,YAAY;AACzC,SAAS,MAAM,UAAmB,UAAU,eAAe;AAC3D,SAAS,kBAAkB;;;ACH3B,SAAS,qBAAqB;AAC9B,SAAS,YAAY,cAAc;AAEnC,IAAMC,WAAU,cAAc,YAAY,GAAG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,IAAI,CAAC;AAEpD,QACG,QAAQ,UAAU,EAClB,YAAY,+CAA+C,EAC3D,OAAO,qBAAqB,0BAA0B,QAAQ,IAAI,CAAC,EACnE,OAAO,wBAAwB,2BAA2B,IAAI,EAC9D,OAAO,eAAe;AAEzB,IAAM,OAAO,QAAQ,QAAQ,MAAM,EAAE,YAAY,8CAA8C;AAC/F,KAAK,QAAQ,SAAS,EACnB,YAAY,0CAA0C,EACtD,OAAO,qBAAqB,0BAA0B,QAAQ,IAAI,CAAC,EACnE,OAAO,kBAAkB;AAC5B,KAAK,QAAQ,WAAW,EACrB,YAAY,iDAAiD,EAC7D,OAAO,qBAAqB,0BAA0B,QAAQ,IAAI,CAAC,EACnE,OAAO,oBAAoB;AAC9B,KAAK,QAAQ,QAAQ,EAClB,YAAY,sDAAsD,EAClE,OAAO,qBAAqB,0BAA0B,QAAQ,IAAI,CAAC,EACnE,OAAO,iBAAiB;AAE3B,QACG,QAAQ,SAAS,EACjB,YAAY,0CAA0C,EACtD,OAAO,MAAM,eAAe,OAAO,CAAC;AAGvC,eAAe,OAAsB;AACnC,QAAM,QAAQ,WAAW;AAGzB,QAAM,cAAc,QAAQ,KAAK,CAAC;AAClC,MAAI,gBAAgB,WAAW,gBAAgB,WAAW;AACxD,UAAM,SAAS,MAAM;AACrB,QAAI,QAAQ,YAAY;AACtB,+BAAyB,OAAO,SAAS,OAAO,MAAM;AAAA,IACxD;AAAA,EACF;AACF;AAEA,KAAK,EAAE,MAAM,MAAM;AAAC,CAAC;","names":["createRequire","fsRead","require","fsRead","basename","name","dirname","join","existsSync","readFile","existsSync","existsSync","readFile","topDir","resolve","existsSync","resolve","existsSync","resolve","existsSync","simpleGit","fsRead","resolve","existsSync","fsRead","topDir","resolve","existsSync","resolve","existsSync","resolve","existsSync","resolve","existsSync","resolve","existsSync","resolve","existsSync","resolve","existsSync","resolve","existsSync","pad","resolve","existsSync","resolve","existsSync","pad","resolve","join","existsSync","readFile","writeFile","simpleGit","simpleGit","resolve","join","existsSync","readFile","writeFile","execSync","join","execSync","desc","require","createRequire"]}