ctxo-mcp 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -41,13 +41,16 @@ Ctxo is an **MCP server** that **enhances** your existing AI tools with dependen
41
41
 
42
42
  ## Quick Start
43
43
 
44
- One command sets up everything — index directory, AI tool rules, and git hooks:
44
+ One command sets up everything — index directory, MCP server registration, AI tool rules, and git hooks:
45
45
 
46
46
  ```Shell
47
47
  npx ctxo-mcp init
48
48
  ```
49
49
 
50
- Then add ctxo to your IDE's MCP config:
50
+ That's it. The interactive wizard detects your AI tools, registers the ctxo MCP server in the correct config file (`.mcp.json`, `.vscode/mcp.json`, etc.), and generates usage rules so your assistant knows when to call each tool.
51
+
52
+ <details>
53
+ <summary>Manual MCP config (if not using <code>ctxo init</code>)</summary>
51
54
 
52
55
  **Claude Code / Cursor / Windsurf / Cline** — `.mcp.json`:
53
56
 
@@ -67,6 +70,8 @@ Then add ctxo to your IDE's MCP config:
67
70
  { "context_servers": { "ctxo": { "command": { "path": "npx", "args": ["-y", "ctxo-mcp"] } } } }
68
71
  ```
69
72
 
73
+ </details>
74
+
70
75
  ## 14 Tools
71
76
 
72
77
  | Tool | What it does |
@@ -1720,6 +1720,55 @@ function ensureConfig(projectRoot) {
1720
1720
  writeFileSync4(filePath, DEFAULT_CONFIG, "utf-8");
1721
1721
  return { file: ".ctxo/config.yaml", action: "created" };
1722
1722
  }
1723
+ var CTXO_MCP_ENTRY = { command: "npx", args: ["-y", "ctxo-mcp"] };
1724
+ function getMcpConfigTargets(selectedPlatformIds) {
1725
+ const targets = /* @__PURE__ */ new Map();
1726
+ for (const id of selectedPlatformIds) {
1727
+ switch (id) {
1728
+ case "claude-code":
1729
+ case "cursor":
1730
+ case "windsurf":
1731
+ case "augment":
1732
+ case "antigravity":
1733
+ targets.set(".mcp.json", { file: ".mcp.json", serverKey: "mcpServers" });
1734
+ break;
1735
+ case "github-copilot":
1736
+ targets.set(".vscode/mcp.json", { file: ".vscode/mcp.json", serverKey: "servers", extraFields: { type: "stdio" } });
1737
+ break;
1738
+ case "amazonq":
1739
+ targets.set(".amazonq/mcp.json", { file: ".amazonq/mcp.json", serverKey: "mcpServers" });
1740
+ break;
1741
+ }
1742
+ }
1743
+ return [...targets.values()];
1744
+ }
1745
+ function ensureMcpConfig(projectRoot, target) {
1746
+ const filePath = join8(projectRoot, target.file);
1747
+ const dir = dirname4(filePath);
1748
+ if (!existsSync5(dir)) mkdirSync3(dir, { recursive: true });
1749
+ const entry = target.extraFields ? { ...target.extraFields, ...CTXO_MCP_ENTRY } : { ...CTXO_MCP_ENTRY };
1750
+ if (!existsSync5(filePath)) {
1751
+ const config = { [target.serverKey]: { ctxo: entry } };
1752
+ writeFileSync4(filePath, JSON.stringify(config, null, 2) + "\n", "utf-8");
1753
+ return { file: target.file, action: "created" };
1754
+ }
1755
+ let existing;
1756
+ try {
1757
+ existing = JSON.parse(readFileSync3(filePath, "utf-8"));
1758
+ } catch {
1759
+ const config = { [target.serverKey]: { ctxo: entry } };
1760
+ writeFileSync4(filePath, JSON.stringify(config, null, 2) + "\n", "utf-8");
1761
+ return { file: target.file, action: "updated" };
1762
+ }
1763
+ const servers = existing[target.serverKey] ?? {};
1764
+ if (servers["ctxo"]) {
1765
+ return { file: target.file, action: "skipped" };
1766
+ }
1767
+ servers["ctxo"] = entry;
1768
+ existing[target.serverKey] = servers;
1769
+ writeFileSync4(filePath, JSON.stringify(existing, null, 2) + "\n", "utf-8");
1770
+ return { file: target.file, action: "updated" };
1771
+ }
1723
1772
 
1724
1773
  // src/cli/init-command.ts
1725
1774
  var CTXO_START = "# ctxo-start";
@@ -1908,6 +1957,13 @@ var InitCommand = class {
1908
1957
  const result = installRules(this.projectRoot, toolId);
1909
1958
  results.push(`${pc.green("\u2713")} ${pc.bold(result.file)} ${pc.dim(result.action)}`);
1910
1959
  }
1960
+ const mcpTargets = getMcpConfigTargets(selectedTools);
1961
+ for (const target of mcpTargets) {
1962
+ const result = ensureMcpConfig(this.projectRoot, target);
1963
+ if (result.action !== "skipped") {
1964
+ results.push(`${pc.green("\u2713")} ${pc.bold(result.file)} ${pc.dim(result.action + " \u2014 MCP server registered")}`);
1965
+ }
1966
+ }
1911
1967
  if (installGitHooks) {
1912
1968
  this.installHooks();
1913
1969
  results.push(`${pc.green("\u2713")} ${pc.bold("post-commit, post-merge")} ${pc.dim("hooks installed")}`);
@@ -1958,6 +2014,13 @@ var InitCommand = class {
1958
2014
  const result = installRules(this.projectRoot, toolId);
1959
2015
  console.error(`[ctxo] \u2713 ${result.file} \u2014 ${result.action}`);
1960
2016
  }
2017
+ const mcpTargets = getMcpConfigTargets(toolIds);
2018
+ for (const target of mcpTargets) {
2019
+ const result = ensureMcpConfig(this.projectRoot, target);
2020
+ if (result.action !== "skipped") {
2021
+ console.error(`[ctxo] \u2713 ${result.file} \u2014 ${result.action} (MCP server registered)`);
2022
+ }
2023
+ }
1961
2024
  if (!options.rulesOnly) {
1962
2025
  this.installHooks();
1963
2026
  console.error("[ctxo] \u2713 Git hooks installed");
@@ -2882,4 +2945,4 @@ Usage:
2882
2945
  export {
2883
2946
  CliRouter
2884
2947
  };
2885
- //# sourceMappingURL=cli-router-L64DKAXT.js.map
2948
+ //# sourceMappingURL=cli-router-VZGJSSE5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/adapters/language/tree-sitter-adapter.ts","../src/adapters/language/go-adapter.ts","../src/adapters/language/csharp-adapter.ts","../src/cli/index-command.ts","../src/core/staleness/content-hasher.ts","../src/adapters/language/ts-morph-adapter.ts","../src/adapters/language/language-adapter-registry.ts","../src/adapters/storage/json-index-writer.ts","../src/adapters/storage/schema-manager.ts","../src/cli/sync-command.ts","../src/cli/status-command.ts","../src/cli/verify-command.ts","../src/cli/init-command.ts","../src/cli/ai-rules.ts","../src/cli/watch-command.ts","../src/adapters/watcher/chokidar-watcher-adapter.ts","../src/cli/stats-command.ts","../src/cli/doctor-command.ts","../src/adapters/diagnostics/health-checker.ts","../src/adapters/diagnostics/doctor-reporter.ts","../src/adapters/diagnostics/checks/runtime-check.ts","../src/adapters/diagnostics/checks/git-check.ts","../src/adapters/diagnostics/checks/index-check.ts","../src/adapters/diagnostics/checks/storage-check.ts","../src/adapters/diagnostics/checks/config-check.ts","../src/adapters/diagnostics/checks/disk-check.ts","../src/cli/cli-router.ts"],"sourcesContent":["import Parser from 'tree-sitter';\nimport type { Tree, SyntaxNode } from 'tree-sitter';\ntype Language = Parameters<InstanceType<typeof Parser>['setLanguage']>[0];\nimport { extname } from 'node:path';\nimport type { SymbolNode, GraphEdge, ComplexityMetrics, SymbolKind } from '../../core/types.js';\nimport type { ILanguageAdapter } from '../../ports/i-language-adapter.js';\n\nexport abstract class TreeSitterAdapter implements ILanguageAdapter {\n abstract readonly extensions: readonly string[];\n readonly tier = 'syntax' as const;\n\n protected parser: Parser;\n protected symbolRegistry = new Map<string, SymbolKind>();\n\n constructor(language: Language) {\n this.parser = new Parser();\n this.parser.setLanguage(language);\n }\n\n isSupported(filePath: string): boolean {\n const ext = extname(filePath).toLowerCase();\n return (this.extensions as readonly string[]).includes(ext);\n }\n\n setSymbolRegistry(registry: Map<string, SymbolKind>): void {\n this.symbolRegistry = registry;\n }\n\n protected parse(source: string): Tree {\n return this.parser.parse(source);\n }\n\n protected buildSymbolId(filePath: string, name: string, kind: SymbolKind): string {\n return `${filePath}::${name}::${kind}`;\n }\n\n protected nodeToLineRange(node: SyntaxNode): {\n startLine: number;\n endLine: number;\n startOffset: number;\n endOffset: number;\n } {\n return {\n startLine: node.startPosition.row,\n endLine: node.endPosition.row,\n startOffset: node.startIndex,\n endOffset: node.endIndex,\n };\n }\n\n protected countCyclomaticComplexity(node: SyntaxNode, branchTypes: string[]): number {\n let complexity = 1;\n const visit = (n: SyntaxNode) => {\n if (branchTypes.includes(n.type)) {\n complexity++;\n }\n for (let i = 0; i < n.childCount; i++) {\n visit(n.child(i)!);\n }\n };\n visit(node);\n return complexity;\n }\n\n abstract extractSymbols(filePath: string, source: string): SymbolNode[];\n abstract extractEdges(filePath: string, source: string): GraphEdge[];\n abstract extractComplexity(filePath: string, source: string): ComplexityMetrics[];\n}\n","import GoLanguage from 'tree-sitter-go';\nimport type { SyntaxNode } from 'tree-sitter';\nimport { TreeSitterAdapter } from './tree-sitter-adapter.js';\nimport type { SymbolNode, GraphEdge, ComplexityMetrics } from '../../core/types.js';\n\nconst GO_BRANCH_TYPES = [\n 'if_statement', 'for_statement',\n 'expression_switch_statement', 'type_switch_statement',\n 'expression_case', 'type_case',\n 'select_statement', 'communication_case',\n];\n\nexport class GoAdapter extends TreeSitterAdapter {\n readonly extensions = ['.go'] as const;\n\n constructor() {\n super(GoLanguage);\n }\n\n extractSymbols(filePath: string, source: string): SymbolNode[] {\n try {\n const tree = this.parse(source);\n const symbols: SymbolNode[] = [];\n\n for (let i = 0; i < tree.rootNode.childCount; i++) {\n const node = tree.rootNode.child(i)!;\n\n if (node.type === 'function_declaration') {\n const name = node.childForFieldName('name')?.text;\n if (!name || !this.isExported(name)) continue;\n const range = this.nodeToLineRange(node);\n symbols.push({\n symbolId: this.buildSymbolId(filePath, name, 'function'),\n name,\n kind: 'function',\n ...range,\n });\n }\n\n if (node.type === 'method_declaration') {\n const methodName = node.childForFieldName('name')?.text;\n if (!methodName || !this.isExported(methodName)) continue;\n const receiverType = this.extractReceiverType(node);\n const qualifiedName = receiverType ? `${receiverType}.${methodName}` : methodName;\n const range = this.nodeToLineRange(node);\n symbols.push({\n symbolId: this.buildSymbolId(filePath, qualifiedName, 'method'),\n name: qualifiedName,\n kind: 'method',\n ...range,\n });\n }\n\n if (node.type === 'type_declaration') {\n this.extractTypeSymbols(node, filePath, symbols);\n }\n }\n\n return symbols;\n } catch (err) {\n console.error(`[ctxo:go] Symbol extraction failed for ${filePath}: ${(err as Error).message}`);\n return [];\n }\n }\n\n extractEdges(filePath: string, source: string): GraphEdge[] {\n try {\n const tree = this.parse(source);\n const edges: GraphEdge[] = [];\n const firstExportedSymbol = this.findFirstExportedSymbolId(tree.rootNode, filePath);\n if (!firstExportedSymbol) return edges;\n\n for (let i = 0; i < tree.rootNode.childCount; i++) {\n const node = tree.rootNode.child(i)!;\n\n if (node.type === 'import_declaration') {\n this.extractImportEdges(node, filePath, firstExportedSymbol, edges);\n }\n }\n\n return edges;\n } catch (err) {\n console.error(`[ctxo:go] Edge extraction failed for ${filePath}: ${(err as Error).message}`);\n return [];\n }\n }\n\n extractComplexity(filePath: string, source: string): ComplexityMetrics[] {\n try {\n const tree = this.parse(source);\n const metrics: ComplexityMetrics[] = [];\n\n for (let i = 0; i < tree.rootNode.childCount; i++) {\n const node = tree.rootNode.child(i)!;\n\n if (node.type === 'function_declaration') {\n const name = node.childForFieldName('name')?.text;\n if (!name || !this.isExported(name)) continue;\n metrics.push({\n symbolId: this.buildSymbolId(filePath, name, 'function'),\n cyclomatic: this.countCyclomaticComplexity(node, GO_BRANCH_TYPES),\n });\n }\n\n if (node.type === 'method_declaration') {\n const methodName = node.childForFieldName('name')?.text;\n if (!methodName || !this.isExported(methodName)) continue;\n const receiverType = this.extractReceiverType(node);\n const qualifiedName = receiverType ? `${receiverType}.${methodName}` : methodName;\n metrics.push({\n symbolId: this.buildSymbolId(filePath, qualifiedName, 'method'),\n cyclomatic: this.countCyclomaticComplexity(node, GO_BRANCH_TYPES),\n });\n }\n }\n\n return metrics;\n } catch (err) {\n console.error(`[ctxo:go] Complexity extraction failed for ${filePath}: ${(err as Error).message}`);\n return [];\n }\n }\n\n // ── Private helpers ─────────────────────────────────────────\n\n private isExported(name: string): boolean {\n return name.length > 0 && name[0]! === name[0]!.toUpperCase() && name[0]! !== name[0]!.toLowerCase();\n }\n\n private extractReceiverType(methodNode: SyntaxNode): string | undefined {\n // method_declaration has parameter_list as first child (receiver)\n const params = methodNode.child(1);\n if (params?.type !== 'parameter_list') return undefined;\n\n for (let i = 0; i < params.childCount; i++) {\n const param = params.child(i)!;\n if (param.type === 'parameter_declaration') {\n // Find type identifier — may be pointer (*Type) or plain (Type)\n const typeNode = param.childForFieldName('type');\n if (typeNode) {\n const text = typeNode.text;\n return text.replace(/^\\*/, '');\n }\n }\n }\n return undefined;\n }\n\n private extractTypeSymbols(typeDecl: SyntaxNode, filePath: string, symbols: SymbolNode[]): void {\n for (let i = 0; i < typeDecl.childCount; i++) {\n const spec = typeDecl.child(i)!;\n if (spec.type !== 'type_spec') continue;\n\n const name = spec.childForFieldName('name')?.text;\n if (!name || !this.isExported(name)) continue;\n\n // Determine kind from the type body\n const typeBody = spec.childForFieldName('type');\n let kind: 'class' | 'interface' | 'type' = 'type';\n if (typeBody?.type === 'struct_type') kind = 'class';\n else if (typeBody?.type === 'interface_type') kind = 'interface';\n\n const range = this.nodeToLineRange(spec);\n symbols.push({\n symbolId: this.buildSymbolId(filePath, name, kind),\n name,\n kind,\n ...range,\n });\n }\n }\n\n private extractImportEdges(\n importDecl: SyntaxNode,\n _filePath: string,\n fromSymbol: string,\n edges: GraphEdge[],\n ): void {\n const visit = (node: SyntaxNode) => {\n if (node.type === 'import_spec') {\n const pathNode = node.childForFieldName('path') ?? node.child(0);\n if (pathNode) {\n const importPath = pathNode.text.replace(/\"/g, '');\n edges.push({\n from: fromSymbol,\n to: `${importPath}::${importPath.split('/').pop()}::variable`,\n kind: 'imports',\n });\n }\n }\n for (let i = 0; i < node.childCount; i++) {\n visit(node.child(i)!);\n }\n };\n visit(importDecl);\n }\n\n private findFirstExportedSymbolId(rootNode: SyntaxNode, filePath: string): string | undefined {\n for (let i = 0; i < rootNode.childCount; i++) {\n const node = rootNode.child(i)!;\n\n if (node.type === 'function_declaration') {\n const name = node.childForFieldName('name')?.text;\n if (name && this.isExported(name)) return this.buildSymbolId(filePath, name, 'function');\n }\n if (node.type === 'type_declaration') {\n for (let j = 0; j < node.childCount; j++) {\n const spec = node.child(j)!;\n if (spec.type === 'type_spec') {\n const name = spec.childForFieldName('name')?.text;\n if (name && this.isExported(name)) {\n const typeBody = spec.childForFieldName('type');\n const kind = typeBody?.type === 'struct_type' ? 'class' : typeBody?.type === 'interface_type' ? 'interface' : 'type';\n return this.buildSymbolId(filePath, name, kind);\n }\n }\n }\n }\n }\n return undefined;\n }\n}\n","import CSharpLanguage from 'tree-sitter-c-sharp';\nimport type { SyntaxNode } from 'tree-sitter';\nimport { TreeSitterAdapter } from './tree-sitter-adapter.js';\nimport type { SymbolNode, GraphEdge, ComplexityMetrics, SymbolKind } from '../../core/types.js';\n\nconst CSHARP_BRANCH_TYPES = [\n 'if_statement', 'for_statement', 'foreach_statement',\n 'while_statement', 'do_statement', 'switch_section',\n 'catch_clause', 'conditional_expression',\n];\n\nexport class CSharpAdapter extends TreeSitterAdapter {\n readonly extensions = ['.cs'] as const;\n\n constructor() {\n super(CSharpLanguage);\n }\n\n extractSymbols(filePath: string, source: string): SymbolNode[] {\n try {\n const tree = this.parse(source);\n const symbols: SymbolNode[] = [];\n this.visitSymbols(tree.rootNode, filePath, '', symbols);\n return symbols;\n } catch (err) {\n console.error(`[ctxo:csharp] Symbol extraction failed for ${filePath}: ${(err as Error).message}`);\n return [];\n }\n }\n\n extractEdges(filePath: string, source: string): GraphEdge[] {\n try {\n const tree = this.parse(source);\n const edges: GraphEdge[] = [];\n const symbols = this.extractSymbols(filePath, source);\n const firstSymbol = symbols.length > 0 ? symbols[0]!.symbolId : undefined;\n if (!firstSymbol) return edges;\n\n this.visitEdges(tree.rootNode, filePath, firstSymbol, '', edges);\n return edges;\n } catch (err) {\n console.error(`[ctxo:csharp] Edge extraction failed for ${filePath}: ${(err as Error).message}`);\n return [];\n }\n }\n\n extractComplexity(filePath: string, source: string): ComplexityMetrics[] {\n try {\n const tree = this.parse(source);\n const metrics: ComplexityMetrics[] = [];\n this.visitComplexity(tree.rootNode, filePath, '', metrics);\n return metrics;\n } catch (err) {\n console.error(`[ctxo:csharp] Complexity extraction failed for ${filePath}: ${(err as Error).message}`);\n return [];\n }\n }\n\n // ── Symbol visitor ──────────────────────────────────────────\n\n private visitSymbols(\n node: SyntaxNode,\n filePath: string,\n namespace: string,\n symbols: SymbolNode[],\n ): void {\n if (node.type === 'namespace_declaration') {\n const name = node.childForFieldName('name')?.text ?? '';\n const ns = namespace ? `${namespace}.${name}` : name;\n for (let i = 0; i < node.childCount; i++) {\n this.visitSymbols(node.child(i)!, filePath, ns, symbols);\n }\n return;\n }\n\n if (node.type === 'declaration_list') {\n for (let i = 0; i < node.childCount; i++) {\n this.visitSymbols(node.child(i)!, filePath, namespace, symbols);\n }\n return;\n }\n\n const typeMapping: Record<string, SymbolKind> = {\n class_declaration: 'class',\n struct_declaration: 'class',\n record_declaration: 'class',\n interface_declaration: 'interface',\n enum_declaration: 'type',\n };\n\n const kind = typeMapping[node.type];\n if (kind) {\n if (!this.isPublic(node)) return;\n const name = node.childForFieldName('name')?.text;\n if (!name) return;\n\n const qualifiedName = namespace ? `${namespace}.${name}` : name;\n const range = this.nodeToLineRange(node);\n symbols.push({\n symbolId: this.buildSymbolId(filePath, qualifiedName, kind),\n name: qualifiedName,\n kind,\n ...range,\n });\n\n // Extract methods inside the class/struct/record\n if (kind === 'class') {\n this.extractMethodSymbols(node, filePath, qualifiedName, symbols);\n }\n return;\n }\n\n // Recurse into compilation_unit and other containers\n for (let i = 0; i < node.childCount; i++) {\n this.visitSymbols(node.child(i)!, filePath, namespace, symbols);\n }\n }\n\n private extractMethodSymbols(\n classNode: SyntaxNode,\n filePath: string,\n className: string,\n symbols: SymbolNode[],\n ): void {\n const declList = classNode.children.find(c => c.type === 'declaration_list');\n if (!declList) return;\n\n for (let i = 0; i < declList.childCount; i++) {\n const child = declList.child(i)!;\n if (child.type !== 'method_declaration' && child.type !== 'constructor_declaration') continue;\n if (!this.isPublic(child)) continue;\n\n const name = child.childForFieldName('name')?.text;\n if (!name) continue;\n\n const paramCount = this.countParameters(child);\n const qualifiedName = `${className}.${name}(${paramCount})`;\n const range = this.nodeToLineRange(child);\n symbols.push({\n symbolId: this.buildSymbolId(filePath, qualifiedName, 'method'),\n name: qualifiedName,\n kind: 'method',\n ...range,\n });\n }\n }\n\n // ── Edge visitor ────────────────────────────────────────────\n\n private visitEdges(\n node: SyntaxNode,\n filePath: string,\n fromSymbol: string,\n namespace: string,\n edges: GraphEdge[],\n ): void {\n if (node.type === 'using_directive') {\n const nameNode = node.children.find(c => c.type === 'identifier' || c.type === 'qualified_name');\n if (nameNode) {\n edges.push({\n from: fromSymbol,\n to: `${nameNode.text}::${nameNode.text.split('.').pop()}::variable`,\n kind: 'imports',\n });\n }\n return;\n }\n\n if (node.type === 'namespace_declaration') {\n const name = node.childForFieldName('name')?.text ?? '';\n const ns = namespace ? `${namespace}.${name}` : name;\n for (let i = 0; i < node.childCount; i++) {\n this.visitEdges(node.child(i)!, filePath, fromSymbol, ns, edges);\n }\n return;\n }\n\n if (node.type === 'class_declaration' || node.type === 'struct_declaration') {\n if (!this.isPublic(node)) return;\n const name = node.childForFieldName('name')?.text;\n if (!name) return;\n\n const qualifiedName = namespace ? `${namespace}.${name}` : name;\n const classSymbolId = this.buildSymbolId(filePath, qualifiedName, 'class');\n\n // Check base_list for extends/implements\n const baseList = node.children.find(c => c.type === 'base_list');\n if (baseList) {\n for (let i = 0; i < baseList.childCount; i++) {\n const child = baseList.child(i)!;\n if (child.type === 'identifier' || child.type === 'qualified_name') {\n const baseName = child.text;\n // Heuristic: I-prefix = interface → implements, otherwise extends\n const edgeKind = baseName.match(/^I[A-Z]/) ? 'implements' : 'extends';\n const targetKind = edgeKind === 'implements' ? 'interface' : 'class';\n edges.push({\n from: classSymbolId,\n to: this.resolveBaseType(baseName, namespace, targetKind),\n kind: edgeKind,\n });\n }\n }\n }\n }\n\n for (let i = 0; i < node.childCount; i++) {\n this.visitEdges(node.child(i)!, filePath, fromSymbol, namespace, edges);\n }\n }\n\n // ── Complexity visitor ──────────────────────────────────────\n\n private visitComplexity(\n node: SyntaxNode,\n filePath: string,\n namespace: string,\n metrics: ComplexityMetrics[],\n ): void {\n if (node.type === 'namespace_declaration') {\n const name = node.childForFieldName('name')?.text ?? '';\n const ns = namespace ? `${namespace}.${name}` : name;\n for (let i = 0; i < node.childCount; i++) {\n this.visitComplexity(node.child(i)!, filePath, ns, metrics);\n }\n return;\n }\n\n const typeMapping: Record<string, true> = {\n class_declaration: true,\n struct_declaration: true,\n record_declaration: true,\n };\n\n if (typeMapping[node.type]) {\n if (!this.isPublic(node)) return;\n const className = node.childForFieldName('name')?.text;\n if (!className) return;\n\n const qualifiedClass = namespace ? `${namespace}.${className}` : className;\n const declList = node.children.find(c => c.type === 'declaration_list');\n if (!declList) return;\n\n for (let i = 0; i < declList.childCount; i++) {\n const child = declList.child(i)!;\n if (child.type !== 'method_declaration') continue;\n if (!this.isPublic(child)) continue;\n\n const methodName = child.childForFieldName('name')?.text;\n if (!methodName) continue;\n\n const paramCount = this.countParameters(child);\n metrics.push({\n symbolId: this.buildSymbolId(filePath, `${qualifiedClass}.${methodName}(${paramCount})`, 'method'),\n cyclomatic: this.countCyclomaticComplexity(child, CSHARP_BRANCH_TYPES),\n });\n }\n return;\n }\n\n for (let i = 0; i < node.childCount; i++) {\n this.visitComplexity(node.child(i)!, filePath, namespace, metrics);\n }\n }\n\n // ── Helpers ─────────────────────────────────────────────────\n\n private countParameters(methodNode: SyntaxNode): number {\n const paramList = methodNode.childForFieldName('parameters');\n if (!paramList) return 0;\n let count = 0;\n for (let i = 0; i < paramList.childCount; i++) {\n if (paramList.child(i)!.type === 'parameter') count++;\n }\n return count;\n }\n\n private isPublic(node: SyntaxNode): boolean {\n for (let i = 0; i < node.childCount; i++) {\n const child = node.child(i)!;\n if (child.type === 'modifier' && child.text === 'public') return true;\n }\n return false;\n }\n\n private resolveBaseType(baseName: string, namespace: string, defaultKind: SymbolKind): string {\n // Check symbol registry first\n const prefix = namespace ? `${namespace}.${baseName}` : baseName;\n for (const [id] of this.symbolRegistry) {\n if (id.includes(`::${prefix}::`)) return id;\n if (id.includes(`::${baseName}::`)) return id;\n }\n // Fallback: assume same namespace\n const qualifiedName = namespace ? `${namespace}.${baseName}` : baseName;\n return `${qualifiedName}::${baseName}::${defaultKind}`;\n }\n}\n","import { execFileSync } from 'node:child_process';\nimport { readFileSync, writeFileSync, existsSync, statSync, readdirSync } from 'node:fs';\nimport { join, relative, extname } from 'node:path';\nimport { ContentHasher } from '../core/staleness/content-hasher.js';\nimport { TsMorphAdapter } from '../adapters/language/ts-morph-adapter.js';\nimport { LanguageAdapterRegistry } from '../adapters/language/language-adapter-registry.js';\nimport { JsonIndexWriter } from '../adapters/storage/json-index-writer.js';\nimport { SqliteStorageAdapter } from '../adapters/storage/sqlite-storage-adapter.js';\nimport { SchemaManager } from '../adapters/storage/schema-manager.js';\nimport { SimpleGitAdapter } from '../adapters/git/simple-git-adapter.js';\nimport { RevertDetector } from '../core/why-context/revert-detector.js';\nimport { aggregateCoChanges } from '../core/co-change/co-change-analyzer.js';\nimport type { FileIndex, SymbolKind } from '../core/types.js';\n\nexport class IndexCommand {\n private readonly projectRoot: string;\n ctxoRoot: string;\n private supportedExtensions: Set<string>;\n\n constructor(projectRoot: string, ctxoRoot?: string) {\n this.projectRoot = projectRoot;\n this.ctxoRoot = ctxoRoot ?? join(projectRoot, '.ctxo');\n this.supportedExtensions = new Set(['.ts', '.tsx', '.js', '.jsx', '.go', '.cs']);\n }\n\n async run(options: { file?: string; check?: boolean; skipSideEffects?: boolean; skipHistory?: boolean; maxHistory?: number } = {}): Promise<void> {\n if (options.check) {\n // Delegate to verify logic: hash-based freshness check\n return this.runCheck();\n }\n\n // Set up adapters\n const registry = new LanguageAdapterRegistry();\n const tsMorphAdapter = new TsMorphAdapter();\n registry.register(tsMorphAdapter);\n this.registerTreeSitterAdapters(registry);\n this.supportedExtensions = registry.getSupportedExtensions();\n\n const writer = new JsonIndexWriter(this.ctxoRoot);\n const schemaManager = new SchemaManager(this.ctxoRoot);\n const hasher = new ContentHasher();\n const gitAdapter = new SimpleGitAdapter(this.projectRoot);\n const revertDetector = new RevertDetector();\n\n // Discover files (single file, monorepo workspaces, or full project)\n let files: string[];\n if (options.file) {\n const fullPath = join(this.projectRoot, options.file);\n files = [fullPath];\n console.error(`[ctxo] Incremental re-index: ${options.file}`);\n } else {\n // Check for monorepo workspaces — discover files across all roots\n const workspaces = this.discoverWorkspaces();\n files = [];\n for (const ws of workspaces) {\n const wsFiles = this.discoverFilesIn(ws);\n files.push(...wsFiles);\n }\n console.error(`[ctxo] Building codebase index... Found ${files.length} source files`);\n }\n\n // Phase 1a: Extract symbols (CPU-bound, builds symbol registry for edge resolution)\n const symbolRegistry = new Map<string, SymbolKind>();\n const pendingIndices: Array<{\n relativePath: string;\n source: string;\n fileIndex: FileIndex;\n }> = [];\n let processed = 0;\n\n for (const filePath of files) {\n const adapter = registry.getAdapter(filePath);\n if (!adapter) continue;\n\n const relativePath = relative(this.projectRoot, filePath).replace(/\\\\/g, '/');\n\n try {\n const source = readFileSync(filePath, 'utf-8');\n const lastModified = Math.floor(Date.now() / 1000);\n\n const symbols = adapter.extractSymbols(relativePath, source);\n const complexity = adapter.extractComplexity(relativePath, source);\n\n // Build symbol registry for accurate edge resolution\n for (const sym of symbols) {\n symbolRegistry.set(sym.symbolId, sym.kind);\n }\n\n pendingIndices.push({\n relativePath,\n source,\n fileIndex: {\n file: relativePath,\n lastModified,\n contentHash: hasher.hash(source),\n symbols,\n edges: [],\n complexity,\n intent: [],\n antiPatterns: [],\n },\n });\n\n processed++;\n if (processed % 50 === 0) {\n console.error(`[ctxo] Processed ${processed}/${files.length} files (symbols)`);\n }\n } catch (err) {\n console.error(`[ctxo] Skipped ${relativePath}: ${(err as Error).message}`);\n }\n }\n\n // Pre-load all sources into ts-morph for cross-file resolution\n const allSources = new Map<string, string>();\n for (const entry of pendingIndices) {\n allSources.set(entry.relativePath, entry.source);\n }\n tsMorphAdapter.loadProjectSources(allSources);\n\n // Phase 1b: Extract edges (uses symbol registry for correct kind resolution)\n for (const entry of pendingIndices) {\n const adapter = registry.getAdapter(entry.relativePath);\n if (!adapter) continue;\n\n try {\n adapter.setSymbolRegistry?.(symbolRegistry);\n entry.fileIndex.edges = adapter.extractEdges(entry.relativePath, entry.source);\n } catch (err) {\n console.error(`[ctxo] Edge extraction failed for ${entry.relativePath}: ${(err as Error).message}`);\n }\n }\n\n // Clean up pre-loaded sources\n tsMorphAdapter.clearProjectSources();\n\n // Phase 2: Batch git history (single git call for all files)\n if (!options.skipHistory && pendingIndices.length > 0) {\n const maxHistory = options.maxHistory ?? 20;\n const batchHistory = await gitAdapter.getBatchHistory?.(maxHistory) ?? new Map<string, import('../core/types.js').CommitRecord[]>();\n\n for (const { relativePath, fileIndex } of pendingIndices) {\n const commits = batchHistory.get(relativePath) ?? [];\n fileIndex.intent = commits.map((c) => ({\n hash: c.hash,\n message: c.message,\n date: c.date,\n kind: 'commit' as const,\n }));\n fileIndex.antiPatterns = revertDetector.detect(commits);\n }\n }\n\n // Phase 2b: Aggregate co-change data from git history\n if (!options.skipHistory && pendingIndices.length > 0) {\n const fileIndices = pendingIndices.map(e => e.fileIndex);\n const coChangeMatrix = aggregateCoChanges(fileIndices);\n writer.writeCoChanges(coChangeMatrix);\n console.error(`[ctxo] Co-change analysis: ${coChangeMatrix.entries.length} file pairs detected`);\n }\n\n // Phase 3: Write all indices\n const indices: FileIndex[] = [];\n for (const { fileIndex } of pendingIndices) {\n writer.write(fileIndex);\n indices.push(fileIndex);\n }\n\n // Write schema version\n schemaManager.writeVersion();\n\n // Populate SQLite cache (skip rebuildFromJson since we just wrote the JSON)\n const storage = new SqliteStorageAdapter(this.ctxoRoot);\n try {\n await storage.initEmpty();\n storage.bulkWrite(indices);\n } finally {\n storage.close();\n }\n\n // Ensure .ctxo/.cache/ is in .gitignore (skip during verify runs)\n if (!options.skipSideEffects) {\n this.ensureGitignore();\n }\n\n console.error(`[ctxo] Index complete: ${processed} files indexed`);\n }\n\n private registerTreeSitterAdapters(registry: LanguageAdapterRegistry): void {\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { GoAdapter } = require('../adapters/language/go-adapter.js');\n registry.register(new GoAdapter());\n } catch {\n console.error('[ctxo] Go adapter unavailable (tree-sitter-go not installed)');\n }\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { CSharpAdapter } = require('../adapters/language/csharp-adapter.js');\n registry.register(new CSharpAdapter());\n } catch {\n console.error('[ctxo] C# adapter unavailable (tree-sitter-c-sharp not installed)');\n }\n }\n\n private discoverFilesIn(root: string): string[] {\n try {\n const output = execFileSync('git', ['ls-files', '--cached', '--others', '--exclude-standard'], {\n cwd: root,\n encoding: 'utf-8',\n maxBuffer: 10 * 1024 * 1024,\n });\n\n return output\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .filter((line) => this.isSupportedExtension(line))\n .map((line) => join(root, line));\n } catch {\n console.error(`[ctxo] git ls-files failed for ${root}`);\n return [];\n }\n }\n\n private discoverWorkspaces(): string[] {\n const pkgPath = join(this.projectRoot, 'package.json');\n if (!existsSync(pkgPath)) return [this.projectRoot];\n\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));\n const workspaces: string[] | undefined = Array.isArray(pkg.workspaces)\n ? pkg.workspaces\n : pkg.workspaces?.packages;\n\n if (!workspaces || workspaces.length === 0) return [this.projectRoot];\n\n // Resolve workspace patterns (supports simple globs like packages/*)\n const resolved: string[] = [];\n for (const ws of workspaces) {\n if (ws.endsWith('/*') || ws.endsWith('\\\\*')) {\n // Glob: packages/* → list subdirectories of packages/\n const parentDir = join(this.projectRoot, ws.slice(0, -2));\n if (existsSync(parentDir)) {\n for (const entry of readdirSync(parentDir, { withFileTypes: true })) {\n if (entry.isDirectory()) {\n resolved.push(join(parentDir, entry.name));\n }\n }\n }\n } else {\n // Literal path\n const wsPath = join(this.projectRoot, ws);\n if (existsSync(wsPath)) {\n resolved.push(wsPath);\n }\n }\n }\n\n if (resolved.length === 0) return [this.projectRoot];\n\n console.error(`[ctxo] Monorepo detected: ${resolved.length} workspace(s)`);\n return resolved;\n } catch {\n return [this.projectRoot];\n }\n }\n\n private isSupportedExtension(filePath: string): boolean {\n const ext = extname(filePath).toLowerCase();\n return this.supportedExtensions.has(ext);\n }\n\n private async runCheck(): Promise<void> {\n console.error('[ctxo] Checking index freshness...');\n\n // Register adapters so supportedExtensions includes .go/.cs\n const registry = new LanguageAdapterRegistry();\n registry.register(new TsMorphAdapter());\n this.registerTreeSitterAdapters(registry);\n this.supportedExtensions = registry.getSupportedExtensions();\n\n const hasher = new ContentHasher();\n const files = this.discoverFilesIn(this.projectRoot);\n const reader = new (await import('../adapters/storage/json-index-reader.js')).JsonIndexReader(this.ctxoRoot);\n const indices = reader.readAll();\n const indexedMap = new Map(indices.map((i) => [i.file, i]));\n\n let staleCount = 0;\n\n for (const filePath of files) {\n if (!this.isSupportedExtension(filePath)) continue;\n\n const relativePath = relative(this.projectRoot, filePath).replace(/\\\\/g, '/');\n const indexed = indexedMap.get(relativePath);\n\n if (!indexed) {\n console.error(`[ctxo] NOT INDEXED: ${relativePath}`);\n staleCount++;\n continue;\n }\n\n // Guard: file may be deleted from disk but still tracked by git\n if (!existsSync(filePath)) {\n console.error(`[ctxo] DELETED: ${relativePath}`);\n staleCount++;\n continue;\n }\n\n // Fast path: mtime check (skip hash if mtime hasn't changed)\n const mtime = Math.floor(statSync(filePath).mtimeMs / 1000);\n if (mtime <= indexed.lastModified) continue;\n\n // Slow path: hash-based verification (handles git checkout, cp -p, CI)\n if (indexed.contentHash) {\n const source = readFileSync(filePath, 'utf-8');\n const currentHash = hasher.hash(source);\n if (currentHash === indexed.contentHash) continue;\n }\n\n console.error(`[ctxo] STALE: ${relativePath}`);\n staleCount++;\n }\n\n if (staleCount > 0) {\n console.error(`[ctxo] ${staleCount} file(s) need re-indexing. Run \"ctxo index\"`);\n process.exit(1);\n }\n\n console.error('[ctxo] Index is up to date');\n }\n\n private ensureGitignore(): void {\n const gitignorePath = join(this.projectRoot, '.gitignore');\n const cachePattern = '.ctxo/.cache/';\n const suffix = `\\n# Ctxo local cache (never committed)\\n${cachePattern}\\n`;\n\n // Read-modify-write atomically to avoid TOCTOU race\n const existing = existsSync(gitignorePath) ? readFileSync(gitignorePath, 'utf-8') : '';\n if (existing.includes(cachePattern)) return;\n\n writeFileSync(gitignorePath, existing + suffix, 'utf-8');\n console.error('[ctxo] Added .ctxo/.cache/ to .gitignore');\n }\n}\n","import { createHash } from 'node:crypto';\n\nexport class ContentHasher {\n hash(content: string): string {\n return createHash('sha256').update(content, 'utf-8').digest('hex');\n }\n}\n","import {\n Project,\n SyntaxKind,\n Node,\n type SourceFile,\n type FunctionDeclaration,\n type MethodDeclaration,\n ScriptTarget,\n} from 'ts-morph';\nimport { extname, dirname, join, normalize } from 'node:path';\nimport { type SymbolNode, type GraphEdge, type ComplexityMetrics, type SymbolKind, SYMBOL_KINDS } from '../../core/types.js';\nimport type { ILanguageAdapter } from '../../ports/i-language-adapter.js';\n\nconst SUPPORTED_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx'] as const;\n\nexport class TsMorphAdapter implements ILanguageAdapter {\n readonly extensions = SUPPORTED_EXTENSIONS;\n readonly tier = 'full' as const;\n\n private readonly project: Project;\n private symbolRegistry = new Map<string, SymbolKind>();\n private projectPreloaded = false;\n\n constructor() {\n this.project = new Project({\n compilerOptions: {\n target: ScriptTarget.ES2022,\n allowJs: true,\n jsx: 2, // React\n skipLibCheck: true,\n },\n useInMemoryFileSystem: true,\n });\n }\n\n isSupported(filePath: string): boolean {\n const ext = extname(filePath).toLowerCase();\n return (SUPPORTED_EXTENSIONS as readonly string[]).includes(ext);\n }\n\n setSymbolRegistry(registry: Map<string, SymbolKind>): void {\n this.symbolRegistry = registry;\n }\n\n loadProjectSources(files: Map<string, string>): void {\n for (const [filePath, source] of files) {\n try {\n const existing = this.project.getSourceFile(filePath);\n if (existing) this.project.removeSourceFile(existing);\n this.project.createSourceFile(filePath, source, { overwrite: true });\n } catch (err) {\n console.error(`[ctxo:ts-morph] Failed to preload ${filePath}: ${(err as Error).message}`);\n }\n }\n this.projectPreloaded = true;\n }\n\n clearProjectSources(): void {\n for (const sf of this.project.getSourceFiles()) {\n this.project.removeSourceFile(sf);\n }\n this.projectPreloaded = false;\n }\n\n extractSymbols(filePath: string, source: string): SymbolNode[] {\n const sourceFile = this.parseSource(filePath, source);\n if (!sourceFile) return [];\n\n try {\n const symbols: SymbolNode[] = [];\n\n this.extractFunctions(sourceFile, filePath, symbols);\n this.extractClasses(sourceFile, filePath, symbols);\n this.extractInterfaces(sourceFile, filePath, symbols);\n this.extractTypeAliases(sourceFile, filePath, symbols);\n this.extractVariables(sourceFile, filePath, symbols);\n\n return symbols;\n } catch (err) {\n console.error(`[ctxo:ts-morph] Symbol extraction failed for ${filePath}: ${(err as Error).message}`);\n return [];\n } finally {\n this.cleanupSourceFile(filePath);\n }\n }\n\n extractEdges(filePath: string, source: string): GraphEdge[] {\n const sourceFile = this.parseSource(filePath, source);\n if (!sourceFile) return [];\n\n try {\n const edges: GraphEdge[] = [];\n\n this.extractImportEdges(sourceFile, filePath, edges);\n this.extractInheritanceEdges(sourceFile, filePath, edges);\n this.extractCallEdges(sourceFile, filePath, edges);\n this.extractReferenceEdges(sourceFile, filePath, edges);\n\n return edges;\n } catch (err) {\n console.error(`[ctxo:ts-morph] Edge extraction failed for ${filePath}: ${(err as Error).message}`);\n return [];\n } finally {\n if (!this.projectPreloaded) {\n this.cleanupSourceFile(filePath);\n }\n }\n }\n\n extractComplexity(filePath: string, source: string): ComplexityMetrics[] {\n const sourceFile = this.parseSource(filePath, source);\n if (!sourceFile) return [];\n\n try {\n const metrics: ComplexityMetrics[] = [];\n\n for (const fn of sourceFile.getFunctions()) {\n if (!this.isExported(fn)) continue;\n const name = fn.getName();\n if (!name) continue;\n const symbolId = this.buildSymbolId(filePath, name, 'function');\n metrics.push({ symbolId, cyclomatic: this.countCyclomaticComplexity(fn) });\n }\n\n for (const cls of sourceFile.getClasses()) {\n const className = cls.getName();\n if (!className || !this.isExported(cls)) continue;\n\n for (const method of cls.getMethods()) {\n const methodName = method.getName();\n const symbolId = this.buildSymbolId(filePath, `${className}.${methodName}`, 'method');\n metrics.push({ symbolId, cyclomatic: this.countCyclomaticComplexity(method) });\n }\n }\n\n return metrics;\n } catch (err) {\n console.error(`[ctxo:ts-morph] Complexity extraction failed for ${filePath}: ${(err as Error).message}`);\n return [];\n } finally {\n this.cleanupSourceFile(filePath);\n }\n }\n\n // ── Symbol Extraction ───────────────────────────────────────\n\n private extractFunctions(\n sourceFile: SourceFile,\n filePath: string,\n symbols: SymbolNode[],\n ): void {\n for (const fn of sourceFile.getFunctions()) {\n if (!this.isExported(fn)) continue;\n const name = fn.getName();\n if (!name) continue;\n\n symbols.push({\n symbolId: this.buildSymbolId(filePath, name, 'function'),\n name,\n kind: 'function',\n startLine: fn.getStartLineNumber() - 1,\n endLine: fn.getEndLineNumber() - 1,\n startOffset: fn.getStart(),\n endOffset: fn.getEnd(),\n });\n }\n }\n\n private extractClasses(\n sourceFile: SourceFile,\n filePath: string,\n symbols: SymbolNode[],\n ): void {\n for (const cls of sourceFile.getClasses()) {\n const name = cls.getName();\n if (!name || !this.isExported(cls)) continue;\n\n symbols.push({\n symbolId: this.buildSymbolId(filePath, name, 'class'),\n name,\n kind: 'class',\n startLine: cls.getStartLineNumber() - 1,\n endLine: cls.getEndLineNumber() - 1,\n startOffset: cls.getStart(),\n endOffset: cls.getEnd(),\n });\n\n // Extract methods\n for (const method of cls.getMethods()) {\n const methodName = method.getName();\n symbols.push({\n symbolId: this.buildSymbolId(filePath, `${name}.${methodName}`, 'method'),\n name: `${name}.${methodName}`,\n kind: 'method',\n startLine: method.getStartLineNumber() - 1,\n endLine: method.getEndLineNumber() - 1,\n startOffset: method.getStart(),\n endOffset: method.getEnd(),\n });\n }\n }\n }\n\n private extractInterfaces(\n sourceFile: SourceFile,\n filePath: string,\n symbols: SymbolNode[],\n ): void {\n for (const iface of sourceFile.getInterfaces()) {\n if (!this.isExported(iface)) continue;\n const name = iface.getName();\n\n symbols.push({\n symbolId: this.buildSymbolId(filePath, name, 'interface'),\n name,\n kind: 'interface',\n startLine: iface.getStartLineNumber() - 1,\n endLine: iface.getEndLineNumber() - 1,\n startOffset: iface.getStart(),\n endOffset: iface.getEnd(),\n });\n }\n }\n\n private extractTypeAliases(\n sourceFile: SourceFile,\n filePath: string,\n symbols: SymbolNode[],\n ): void {\n for (const typeAlias of sourceFile.getTypeAliases()) {\n if (!this.isExported(typeAlias)) continue;\n const name = typeAlias.getName();\n\n symbols.push({\n symbolId: this.buildSymbolId(filePath, name, 'type'),\n name,\n kind: 'type',\n startLine: typeAlias.getStartLineNumber() - 1,\n endLine: typeAlias.getEndLineNumber() - 1,\n startOffset: typeAlias.getStart(),\n endOffset: typeAlias.getEnd(),\n });\n }\n }\n\n private extractVariables(\n sourceFile: SourceFile,\n filePath: string,\n symbols: SymbolNode[],\n ): void {\n for (const stmt of sourceFile.getVariableStatements()) {\n if (!this.isExported(stmt)) continue;\n\n for (const decl of stmt.getDeclarations()) {\n const name = decl.getName();\n\n symbols.push({\n symbolId: this.buildSymbolId(filePath, name, 'variable'),\n name,\n kind: 'variable',\n startLine: stmt.getStartLineNumber() - 1,\n endLine: stmt.getEndLineNumber() - 1,\n startOffset: decl.getStart(),\n endOffset: decl.getEnd(),\n });\n }\n }\n }\n\n // ── Edge Extraction ─────────────────────────────────────────\n\n private extractImportEdges(\n sourceFile: SourceFile,\n filePath: string,\n edges: GraphEdge[],\n ): void {\n // BUG-1 FIX: use sourceFile directly instead of project lookup (file may be cleaned up)\n const fileSymbolId = this.buildSymbolId(filePath, sourceFile.getBaseName().replace(/\\.[^.]+$/, ''), 'variable');\n const fromSymbols = this.getExportedSymbolIds(sourceFile, filePath);\n const fromSymbol = fromSymbols.length > 0 ? fromSymbols[0]! : fileSymbolId;\n\n for (const imp of sourceFile.getImportDeclarations()) {\n const moduleSpecifier = imp.getModuleSpecifierValue();\n\n // Only track local imports (relative paths)\n if (!moduleSpecifier.startsWith('.') && !moduleSpecifier.startsWith('/')) {\n continue;\n }\n\n // Resolve relative import to project-relative path\n const normalizedTarget = this.resolveRelativeImport(filePath, moduleSpecifier);\n\n // SCHEMA-40 FIX: detect type-only imports\n const isTypeOnly = imp.isTypeOnly();\n\n for (const named of imp.getNamedImports()) {\n const importedName = named.getName();\n const edge: GraphEdge = {\n from: fromSymbol,\n to: this.resolveImportTarget(normalizedTarget, importedName),\n kind: 'imports',\n };\n if (isTypeOnly || named.isTypeOnly()) edge.typeOnly = true;\n edges.push(edge);\n }\n\n const defaultImport = imp.getDefaultImport();\n if (defaultImport) {\n const edge: GraphEdge = {\n from: fromSymbol,\n to: this.resolveImportTarget(normalizedTarget, defaultImport.getText()),\n kind: 'imports',\n };\n if (isTypeOnly) edge.typeOnly = true;\n edges.push(edge);\n }\n\n // GAP-3 FIX: namespace imports (import * as X from './mod')\n const nsImport = imp.getNamespaceImport();\n if (nsImport) {\n const edge: GraphEdge = {\n from: fromSymbol,\n to: this.buildSymbolId(normalizedTarget, nsImport.getText(), 'variable'),\n kind: 'imports',\n };\n if (isTypeOnly) edge.typeOnly = true;\n edges.push(edge);\n }\n }\n }\n\n private extractInheritanceEdges(\n sourceFile: SourceFile,\n filePath: string,\n edges: GraphEdge[],\n ): void {\n for (const cls of sourceFile.getClasses()) {\n const className = cls.getName();\n if (!className || !this.isExported(cls)) continue;\n\n const classSymbolId = this.buildSymbolId(filePath, className, 'class');\n\n // extends\n const baseClass = cls.getExtends();\n if (baseClass) {\n // BUG-17 FIX: strip generic type arguments (Base<string> → Base)\n const baseName = baseClass.getExpression().getText().replace(/<.*>$/, '');\n edges.push({\n from: classSymbolId,\n to: this.resolveSymbolReference(sourceFile, baseName, 'class'),\n kind: 'extends',\n });\n }\n\n // implements\n for (const impl of cls.getImplements()) {\n // BUG-18 FIX: strip generic type arguments (IRepo<User> → IRepo)\n const ifaceName = impl.getExpression().getText().replace(/<.*>$/, '');\n edges.push({\n from: classSymbolId,\n to: this.resolveSymbolReference(sourceFile, ifaceName, 'interface'),\n kind: 'implements',\n });\n }\n }\n }\n\n private extractCallEdges(\n sourceFile: SourceFile,\n filePath: string,\n edges: GraphEdge[],\n ): void {\n // Extract function call edges from exported functions and methods\n for (const fn of sourceFile.getFunctions()) {\n if (!this.isExported(fn)) continue;\n const fnName = fn.getName();\n if (!fnName) continue;\n\n const fnSymbolId = this.buildSymbolId(filePath, fnName, 'function');\n\n for (const call of fn.getDescendantsOfKind(SyntaxKind.CallExpression)) {\n const calledName = call.getExpression().getText().split('.').pop();\n if (!calledName || calledName === fnName) continue;\n\n const resolved = this.resolveLocalCallTarget(sourceFile, filePath, calledName);\n if (resolved) {\n edges.push({ from: fnSymbolId, to: resolved, kind: 'calls' });\n }\n }\n\n // GAP-11 FIX: constructor calls (new Foo())\n for (const newExpr of fn.getDescendantsOfKind(SyntaxKind.NewExpression)) {\n const calledName = newExpr.getExpression().getText().split('.').pop();\n if (!calledName) continue;\n\n const resolved = this.resolveLocalCallTarget(sourceFile, filePath, calledName);\n if (resolved) {\n edges.push({ from: fnSymbolId, to: resolved, kind: 'calls' });\n }\n }\n }\n\n // Extract calls from class methods\n for (const cls of sourceFile.getClasses()) {\n const className = cls.getName();\n if (!className || !this.isExported(cls)) continue;\n\n for (const method of cls.getMethods()) {\n const methodName = method.getName();\n const methodSymbolId = this.buildSymbolId(filePath, `${className}.${methodName}`, 'method');\n\n for (const call of method.getDescendantsOfKind(SyntaxKind.CallExpression)) {\n const calledText = call.getExpression().getText();\n const calledName = calledText.split('.').pop();\n if (!calledName || calledName === methodName) continue;\n\n let resolved: string | undefined;\n if (calledText.startsWith('this.')) {\n resolved = this.resolveThisMethodCall(sourceFile, filePath, className, calledName);\n } else {\n resolved = this.resolveLocalCallTarget(sourceFile, filePath, calledName);\n }\n if (resolved) {\n edges.push({ from: methodSymbolId, to: resolved, kind: 'calls' });\n }\n }\n\n // GAP-11 FIX: constructor calls from methods (new Foo())\n for (const newExpr of method.getDescendantsOfKind(SyntaxKind.NewExpression)) {\n const calledText = newExpr.getExpression().getText();\n const calledName = calledText.split('.').pop();\n if (!calledName) continue;\n\n let resolved: string | undefined;\n if (calledText.startsWith('this.')) {\n resolved = this.resolveThisMethodCall(sourceFile, filePath, className, calledName);\n } else {\n resolved = this.resolveLocalCallTarget(sourceFile, filePath, calledName);\n }\n if (resolved) {\n edges.push({ from: methodSymbolId, to: resolved, kind: 'calls' });\n }\n }\n }\n }\n }\n\n private extractReferenceEdges(\n sourceFile: SourceFile,\n filePath: string,\n edges: GraphEdge[],\n ): void {\n // Build map of all named imports from local modules: importedName → resolved symbolId\n const importMap = new Map<string, string>();\n for (const imp of sourceFile.getImportDeclarations()) {\n const mod = imp.getModuleSpecifierValue();\n if (!mod.startsWith('.') && !mod.startsWith('/')) continue;\n const targetFile = this.resolveRelativeImport(filePath, mod);\n for (const named of imp.getNamedImports()) {\n importMap.set(named.getName(), this.resolveImportTarget(targetFile, named.getName()));\n }\n const defaultImport = imp.getDefaultImport();\n if (defaultImport) {\n importMap.set(defaultImport.getText(), this.resolveImportTarget(targetFile, defaultImport.getText()));\n }\n }\n if (importMap.size === 0) return;\n\n // Scan each exported symbol's body for identifier references to imports\n for (const fn of sourceFile.getFunctions()) {\n if (!this.isExported(fn)) continue;\n const fnName = fn.getName();\n if (!fnName) continue;\n const fromId = this.buildSymbolId(filePath, fnName, 'function');\n this.emitUsesEdges(fn, fromId, importMap, edges);\n }\n\n for (const cls of sourceFile.getClasses()) {\n if (!this.isExported(cls)) continue;\n const className = cls.getName();\n if (!className) continue;\n\n // Class-level references (property types, constructor params)\n const classId = this.buildSymbolId(filePath, className, 'class');\n this.emitUsesEdges(cls, classId, importMap, edges);\n }\n }\n\n private emitUsesEdges(\n node: Node,\n fromId: string,\n importMap: Map<string, string>,\n edges: GraphEdge[],\n ): void {\n const seen = new Set<string>();\n for (const id of node.getDescendantsOfKind(SyntaxKind.Identifier)) {\n const name = id.getText();\n if (seen.has(name)) continue;\n const target = importMap.get(name);\n if (target) {\n seen.add(name);\n edges.push({ from: fromId, to: target, kind: 'uses' });\n }\n }\n }\n\n private resolveLocalCallTarget(\n sourceFile: SourceFile,\n filePath: string,\n calledName: string,\n ): string | undefined {\n // Check if the called name is imported from a local module\n for (const imp of sourceFile.getImportDeclarations()) {\n const moduleSpecifier = imp.getModuleSpecifierValue();\n if (!moduleSpecifier.startsWith('.') && !moduleSpecifier.startsWith('/')) continue;\n\n for (const named of imp.getNamedImports()) {\n if (named.getName() === calledName) {\n const targetFile = this.resolveRelativeImport(filePath, moduleSpecifier);\n return this.resolveImportTarget(targetFile, calledName);\n }\n }\n }\n\n // Check if it's a locally defined function in the same file\n for (const fn of sourceFile.getFunctions()) {\n if (fn.getName() === calledName) {\n return this.buildSymbolId(filePath, calledName, 'function');\n }\n }\n\n return undefined;\n }\n\n private resolveThisMethodCall(\n sourceFile: SourceFile,\n filePath: string,\n className: string,\n calledName: string,\n ): string | undefined {\n for (const cls of sourceFile.getClasses()) {\n if (cls.getName() !== className) continue;\n for (const method of cls.getMethods()) {\n if (method.getName() === calledName) {\n return this.buildSymbolId(filePath, `${className}.${calledName}`, 'method');\n }\n }\n }\n return undefined;\n }\n\n // ── Helpers ─────────────────────────────────────────────────\n\n private parseSource(filePath: string, source: string): SourceFile | undefined {\n try {\n const existing = this.project.getSourceFile(filePath);\n if (existing && this.projectPreloaded) {\n return existing;\n }\n if (existing) {\n this.project.removeSourceFile(existing);\n }\n return this.project.createSourceFile(filePath, source, { overwrite: true });\n } catch (err) {\n console.error(`[ctxo:ts-morph] Parse failed for ${filePath}: ${(err as Error).message}`);\n return undefined;\n }\n }\n\n private cleanupSourceFile(filePath: string): void {\n const existing = this.project.getSourceFile(filePath);\n if (existing) {\n this.project.removeSourceFile(existing);\n }\n }\n\n private buildSymbolId(filePath: string, name: string, kind: SymbolKind): string {\n return `${filePath}::${name}::${kind}`;\n }\n\n private resolveRelativeImport(fromFile: string, moduleSpecifier: string): string {\n // Convert relative import like '../types.js' to project-relative 'src/core/types.ts'\n const fromDir = dirname(fromFile);\n let resolved = normalize(join(fromDir, moduleSpecifier)).replace(/\\\\/g, '/');\n\n // Strip .js extension (TypeScript imports use .js but source files are .ts)\n if (resolved.endsWith('.js')) {\n resolved = resolved.slice(0, -3) + '.ts';\n } else if (resolved.endsWith('.jsx')) {\n resolved = resolved.slice(0, -4) + '.tsx';\n } else if (!extname(resolved)) {\n resolved += '.ts';\n }\n\n return resolved;\n }\n\n private resolveImportTarget(targetFile: string, name: string): string {\n // BUG-8/9 FIX: check symbol registry first (populated from Phase 1 of indexing)\n const prefix = `${targetFile}::${name}::`;\n for (const kind of SYMBOL_KINDS) {\n if (this.symbolRegistry.has(`${prefix}${kind}`)) {\n return `${prefix}${kind}`;\n }\n }\n\n // Try to find the symbol in the already-parsed project to get the correct kind\n const targetSourceFile = this.project.getSourceFile(targetFile);\n if (targetSourceFile) {\n for (const fn of targetSourceFile.getFunctions()) {\n if (fn.getName() === name && this.isExported(fn)) {\n return this.buildSymbolId(targetFile, name, 'function');\n }\n }\n for (const cls of targetSourceFile.getClasses()) {\n if (cls.getName() === name && this.isExported(cls)) {\n return this.buildSymbolId(targetFile, name, 'class');\n }\n }\n for (const iface of targetSourceFile.getInterfaces()) {\n if (iface.getName() === name && this.isExported(iface)) {\n return this.buildSymbolId(targetFile, name, 'interface');\n }\n }\n for (const t of targetSourceFile.getTypeAliases()) {\n if (t.getName() === name && this.isExported(t)) {\n return this.buildSymbolId(targetFile, name, 'type');\n }\n }\n }\n // Fallback: infer kind from naming conventions\n const kind = this.inferSymbolKind(name);\n return `${targetFile}::${name}::${kind}`;\n }\n\n private resolveSymbolReference(\n sourceFile: SourceFile,\n name: string,\n defaultKind: SymbolKind,\n ): string {\n // Check if the name is imported\n for (const imp of sourceFile.getImportDeclarations()) {\n const moduleSpecifier = imp.getModuleSpecifierValue();\n if (!moduleSpecifier.startsWith('.') && !moduleSpecifier.startsWith('/')) continue;\n\n for (const named of imp.getNamedImports()) {\n if (named.getName() === name) {\n const resolved = imp.getModuleSpecifierSourceFile()?.getFilePath();\n if (resolved) {\n return `${this.normalizeFilePath(resolved)}::${name}::${defaultKind}`;\n }\n // Fallback: resolve relative module specifier manually\n const sourceDir = dirname(this.normalizeFilePath(sourceFile.getFilePath()));\n const resolvedPath = normalize(join(sourceDir, moduleSpecifier))\n .replace(/\\\\/g, '/')\n .replace(/\\.jsx$/, '.tsx')\n .replace(/\\.js$/, '.ts');\n return `${resolvedPath}::${name}::${defaultKind}`;\n }\n }\n }\n\n // Assume it's in the same file\n return `${sourceFile.getFilePath()}::${name}::${defaultKind}`;\n }\n\n private inferSymbolKind(name: string): SymbolKind {\n // Interface: starts with I followed by uppercase (IStoragePort, IGitPort)\n if (/^I[A-Z]/.test(name) && name.length > 2) return 'interface';\n // All caps with underscores: variable/constant (MAX_AMOUNT, EDGE_KINDS)\n if (/^[A-Z][A-Z_0-9]+$/.test(name)) return 'variable';\n // PascalCase: could be class, interface, or type — default to class\n if (/^[A-Z]/.test(name)) return 'class';\n // camelCase: function\n return 'function';\n }\n\n private normalizeFilePath(filePath: string): string {\n // Remove leading / from in-memory file system paths\n return filePath.replace(/^\\//, '');\n }\n\n private getExportedSymbolIds(sourceFile: SourceFile, filePath: string): string[] {\n const ids: string[] = [];\n for (const fn of sourceFile.getFunctions()) {\n if (!this.isExported(fn)) continue;\n const name = fn.getName();\n if (name) ids.push(this.buildSymbolId(filePath, name, 'function'));\n }\n for (const cls of sourceFile.getClasses()) {\n if (!this.isExported(cls)) continue;\n const name = cls.getName();\n if (name) ids.push(this.buildSymbolId(filePath, name, 'class'));\n }\n for (const iface of sourceFile.getInterfaces()) {\n if (!this.isExported(iface)) continue;\n ids.push(this.buildSymbolId(filePath, iface.getName(), 'interface'));\n }\n for (const t of sourceFile.getTypeAliases()) {\n if (!this.isExported(t)) continue;\n ids.push(this.buildSymbolId(filePath, t.getName(), 'type'));\n }\n for (const stmt of sourceFile.getVariableStatements()) {\n if (!this.isExported(stmt)) continue;\n for (const decl of stmt.getDeclarations()) {\n ids.push(this.buildSymbolId(filePath, decl.getName(), 'variable'));\n }\n }\n return ids;\n }\n\n private isExported(node: Node): boolean {\n if (Node.isExportable(node)) {\n return node.isExported();\n }\n return false;\n }\n\n private countCyclomaticComplexity(node: FunctionDeclaration | MethodDeclaration): number {\n let complexity = 1;\n\n node.forEachDescendant((child) => {\n switch (child.getKind()) {\n case SyntaxKind.IfStatement:\n case SyntaxKind.ConditionalExpression:\n case SyntaxKind.ForStatement:\n case SyntaxKind.ForInStatement:\n case SyntaxKind.ForOfStatement:\n case SyntaxKind.WhileStatement:\n case SyntaxKind.DoStatement:\n case SyntaxKind.CaseClause:\n case SyntaxKind.CatchClause:\n case SyntaxKind.BinaryExpression: {\n const text = child.getText();\n if (child.getKind() === SyntaxKind.BinaryExpression) {\n if (text.includes('&&') || text.includes('||') || text.includes('??')) {\n complexity++;\n }\n } else {\n complexity++;\n }\n break;\n }\n }\n });\n\n return complexity;\n }\n}\n","import { extname } from 'node:path';\nimport type { ILanguageAdapter } from '../../ports/i-language-adapter.js';\n\nexport class LanguageAdapterRegistry {\n private readonly adaptersByExtension = new Map<string, ILanguageAdapter>();\n\n register(adapter: ILanguageAdapter): void {\n for (const ext of adapter.extensions) {\n this.adaptersByExtension.set(ext.toLowerCase(), adapter);\n }\n }\n\n getSupportedExtensions(): Set<string> {\n return new Set(this.adaptersByExtension.keys());\n }\n\n getAdapter(filePath: string): ILanguageAdapter | undefined {\n if (!filePath) return undefined;\n\n const ext = extname(filePath).toLowerCase();\n if (!ext) return undefined;\n\n return this.adaptersByExtension.get(ext);\n }\n}\n","import { writeFileSync, renameSync, mkdirSync, unlinkSync, existsSync } from 'node:fs';\nimport { dirname, join, resolve, sep } from 'node:path';\nimport type { FileIndex, CoChangeMatrix } from '../../core/types.js';\n\nexport class JsonIndexWriter {\n private readonly indexDir: string;\n\n constructor(ctxoRoot: string) {\n this.indexDir = join(ctxoRoot, 'index');\n }\n\n write(fileIndex: FileIndex): void {\n if (!fileIndex.file) {\n throw new Error('FileIndex.file must not be empty');\n }\n\n const targetPath = this.resolveIndexPath(fileIndex.file);\n mkdirSync(dirname(targetPath), { recursive: true });\n\n const sorted = this.sortKeys(fileIndex);\n const json = JSON.stringify(sorted, null, 2);\n this.atomicWrite(targetPath, json);\n }\n\n writeCoChanges(matrix: CoChangeMatrix): void {\n mkdirSync(this.indexDir, { recursive: true });\n const targetPath = join(this.indexDir, 'co-changes.json');\n this.atomicWrite(targetPath, JSON.stringify(matrix, null, 2));\n }\n\n private atomicWrite(targetPath: string, content: string): void {\n const tmpPath = `${targetPath}.${process.pid}.tmp`;\n writeFileSync(tmpPath, content, 'utf-8');\n renameSync(tmpPath, targetPath);\n }\n\n delete(relativePath: string): void {\n const targetPath = this.resolveIndexPath(relativePath);\n if (existsSync(targetPath)) {\n unlinkSync(targetPath);\n }\n }\n\n private resolveIndexPath(relativePath: string): string {\n const resolved = resolve(this.indexDir, `${relativePath}.json`);\n const normalizedDir = resolve(this.indexDir) + sep;\n if (!resolved.startsWith(normalizedDir)) {\n throw new Error(`Path traversal detected: ${relativePath}`);\n }\n return resolved;\n }\n\n private sortKeys(obj: unknown): unknown {\n if (Array.isArray(obj)) {\n return obj.map((item) => this.sortKeys(item));\n }\n if (obj !== null && typeof obj === 'object') {\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(obj).sort()) {\n sorted[key] = this.sortKeys((obj as Record<string, unknown>)[key]);\n }\n return sorted;\n }\n return obj;\n }\n}\n","import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';\nimport { join, dirname } from 'node:path';\n\nconst CURRENT_SCHEMA_VERSION = '1.0.0';\n\nexport class SchemaManager {\n private readonly versionFilePath: string;\n\n constructor(ctxoRoot: string) {\n this.versionFilePath = join(ctxoRoot, 'index', 'schema-version');\n }\n\n currentVersion(): string {\n return CURRENT_SCHEMA_VERSION;\n }\n\n readStoredVersion(): string | undefined {\n if (!existsSync(this.versionFilePath)) {\n return undefined;\n }\n return readFileSync(this.versionFilePath, 'utf-8').trim();\n }\n\n writeVersion(): void {\n mkdirSync(dirname(this.versionFilePath), { recursive: true });\n writeFileSync(this.versionFilePath, CURRENT_SCHEMA_VERSION, 'utf-8');\n }\n\n isCompatible(): boolean {\n const stored = this.readStoredVersion();\n if (!stored) return false;\n return stored === CURRENT_SCHEMA_VERSION;\n }\n}\n","import { join } from 'node:path';\nimport { SqliteStorageAdapter } from '../adapters/storage/sqlite-storage-adapter.js';\n\nexport class SyncCommand {\n private readonly ctxoRoot: string;\n\n constructor(projectRoot: string) {\n this.ctxoRoot = join(projectRoot, '.ctxo');\n }\n\n async run(): Promise<void> {\n console.error('[ctxo] Rebuilding SQLite cache from committed JSON index...');\n\n const storage = new SqliteStorageAdapter(this.ctxoRoot);\n try {\n await storage.init();\n } finally {\n storage.close();\n }\n\n console.error('[ctxo] Sync complete');\n }\n}\n","import { join } from 'node:path';\nimport { existsSync } from 'node:fs';\nimport { execFileSync } from 'node:child_process';\nimport { JsonIndexReader } from '../adapters/storage/json-index-reader.js';\nimport { SchemaManager } from '../adapters/storage/schema-manager.js';\n\nexport class StatusCommand {\n private readonly projectRoot: string;\n private readonly ctxoRoot: string;\n\n constructor(projectRoot: string) {\n this.projectRoot = projectRoot;\n this.ctxoRoot = join(projectRoot, '.ctxo');\n }\n\n run(): void {\n const indexDir = join(this.ctxoRoot, 'index');\n\n if (!existsSync(indexDir)) {\n console.error('[ctxo] No index found. Run \"ctxo index\" first.');\n return;\n }\n\n const schemaManager = new SchemaManager(this.ctxoRoot);\n const version = schemaManager.readStoredVersion() ?? 'unknown';\n\n const reader = new JsonIndexReader(this.ctxoRoot);\n const indices = reader.readAll();\n\n const totalSymbols = indices.reduce((sum, idx) => sum + idx.symbols.length, 0);\n const totalEdges = indices.reduce((sum, idx) => sum + idx.edges.length, 0);\n\n console.error(`[ctxo] Index Status`);\n console.error(` Schema version: ${version}`);\n console.error(` Indexed files: ${indices.length}`);\n console.error(` Total symbols: ${totalSymbols}`);\n console.error(` Total edges: ${totalEdges}`);\n\n const cacheExists = existsSync(join(this.ctxoRoot, '.cache', 'symbols.db'));\n console.error(` SQLite cache: ${cacheExists ? 'present' : 'missing (run ctxo sync)'}`);\n\n // Per-file listing with timestamps\n if (indices.length > 0) {\n console.error('');\n console.error(' Files:');\n\n // Get source files to detect orphans\n const sourceFiles = this.getSourceFiles();\n\n for (const idx of indices.sort((a, b) => a.file.localeCompare(b.file))) {\n const ts = new Date(idx.lastModified * 1000).toISOString();\n const isOrphaned = sourceFiles.size > 0 && !sourceFiles.has(idx.file);\n const badge = isOrphaned ? ' [orphaned]' : '';\n console.error(` ${idx.file} ${ts} (${idx.symbols.length} symbols, ${idx.edges.length} edges)${badge}`);\n }\n }\n }\n\n private getSourceFiles(): Set<string> {\n try {\n const output = execFileSync('git', ['ls-files', '--cached', '--others', '--exclude-standard'], {\n cwd: this.projectRoot,\n encoding: 'utf-8',\n });\n return new Set(output.split('\\n').map((l) => l.trim()).filter((l) => l.length > 0));\n } catch {\n return new Set();\n }\n }\n}\n","import { mkdtempSync, rmSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { tmpdir } from 'node:os';\nimport { IndexCommand } from './index-command.js';\nimport { JsonIndexReader } from '../adapters/storage/json-index-reader.js';\n\nexport class VerifyCommand {\n private readonly projectRoot: string;\n\n constructor(projectRoot: string) {\n this.projectRoot = projectRoot;\n }\n\n async run(): Promise<void> {\n console.error('[ctxo] Verifying index freshness...');\n\n // Build index into a temp directory to avoid overwriting committed index\n const tempDir = mkdtempSync(join(tmpdir(), 'ctxo-verify-'));\n\n try {\n const tempCtxo = join(tempDir, '.ctxo');\n\n // Run index into temp .ctxo (does not touch committed index)\n const indexCmd = new IndexCommand(this.projectRoot, tempCtxo);\n await indexCmd.run({ skipSideEffects: true });\n\n // Compare temp index with committed index\n const committedReader = new JsonIndexReader(join(this.projectRoot, '.ctxo'));\n const freshReader = new JsonIndexReader(tempCtxo);\n\n const committedIndices = committedReader.readAll();\n const freshIndices = freshReader.readAll();\n\n // Compare full index: symbols + edges + intent + antiPatterns\n const serialize = (i: { symbols: unknown; edges: unknown; intent: unknown; antiPatterns: unknown }) =>\n JSON.stringify({ symbols: i.symbols, edges: i.edges, intent: i.intent, antiPatterns: i.antiPatterns });\n\n const committedMap = new Map(committedIndices.map((i) => [i.file, serialize(i)]));\n const freshMap = new Map(freshIndices.map((i) => [i.file, serialize(i)]));\n\n let stale = false;\n\n // Check for files that changed or were added\n for (const [file, freshData] of freshMap) {\n const committed = committedMap.get(file);\n if (committed !== freshData) {\n console.error(`[ctxo] STALE: ${file}`);\n stale = true;\n }\n }\n\n // Check for files that were removed\n for (const file of committedMap.keys()) {\n if (!freshMap.has(file)) {\n console.error(`[ctxo] REMOVED: ${file}`);\n stale = true;\n }\n }\n\n if (stale) {\n console.error('[ctxo] Index is STALE — run \"ctxo index\" and commit .ctxo/index/');\n process.exit(1);\n }\n\n console.error('[ctxo] Index is up to date');\n } finally {\n rmSync(tempDir, { recursive: true, force: true });\n }\n }\n}\n","import { join } from 'node:path';\nimport { existsSync, readFileSync, writeFileSync, mkdirSync, chmodSync } from 'node:fs';\nimport { PLATFORMS, detectPlatforms, installRules, ensureGitignore, ensureConfig, getMcpConfigTargets, ensureMcpConfig } from './ai-rules.js';\n\n/* ------------------------------------------------------------------ */\n/* Git hook content */\n/* ------------------------------------------------------------------ */\n\nconst CTXO_START = '# ctxo-start';\nconst CTXO_END = '# ctxo-end';\n\nconst POST_COMMIT_CONTENT = `\n${CTXO_START}\n# Incremental re-index on commit (only changed files)\nif command -v ctxo >/dev/null 2>&1; then\n for file in $(git diff --name-only HEAD~1 HEAD 2>/dev/null); do\n ctxo index --file \"$file\" 2>/dev/null || true\n done\nfi\n${CTXO_END}\n`.trim();\n\nconst POST_MERGE_CONTENT = `\n${CTXO_START}\n# Rebuild SQLite cache after merge (index updated via git pull)\nif command -v ctxo >/dev/null 2>&1; then\n ctxo sync 2>/dev/null || true\nfi\n${CTXO_END}\n`.trim();\n\n/* ------------------------------------------------------------------ */\n/* Options */\n/* ------------------------------------------------------------------ */\n\nexport interface InitOptions {\n tools?: string[];\n yes?: boolean;\n rulesOnly?: boolean;\n dryRun?: boolean;\n}\n\n/* ------------------------------------------------------------------ */\n/* Terminal UI helpers (zero dependency — picocolors only) */\n/* ------------------------------------------------------------------ */\n\nimport type picocolorsType from 'picocolors';\ntype PC = typeof picocolorsType;\n\nconst STRIP_ANSI = /\\u001b\\[[0-9;]*m/g;\nconst strip = (s: string) => s.replace(STRIP_ANSI, '');\n\nfunction box(lines: string[], opts: { title?: string; border?: (s: string) => string; width?: number }, pc: PC): string {\n const border = opts.border ?? pc.dim;\n const w = opts.width ?? Math.max(...lines.map(l => strip(l).length), strip(opts.title ?? '').length + 4, 48);\n const pad = (s: string) => s + ' '.repeat(Math.max(0, w - strip(s).length));\n\n const hr = '\\u2500'.repeat(w + 2);\n let top: string;\n if (opts.title) {\n const tLen = strip(opts.title).length;\n top = border('\\u256d\\u2500 ') + opts.title + border(` ${ '\\u2500'.repeat(Math.max(0, w - tLen - 2))}\\u256e`);\n } else {\n top = border(`\\u256d${hr}\\u256e`);\n }\n const bot = border(`\\u2570${hr}\\u256f`);\n const body = lines.map(l => `${border('\\u2502')} ${pad(l)} ${border('\\u2502')}`).join('\\n');\n return `${top}\\n${body}\\n${bot}`;\n}\n\nfunction stepHeader(step: number, total: number, title: string, desc: string, pc: PC): string {\n const stepLabel = pc.bold(pc.cyan(`${step}/${total}`));\n const titleStr = pc.bold(title);\n return box(\n [`${pc.dim(desc)}`],\n { title: `${stepLabel} ${titleStr}`, border: pc.cyan },\n pc,\n );\n}\n\n/* ------------------------------------------------------------------ */\n/* ASCII banner with faux gradient */\n/* ------------------------------------------------------------------ */\n\nfunction renderBanner(_version: string | undefined, pc: PC): string {\n const art = [\n ' \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2557\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2557\\u2588\\u2588\\u2557 \\u2588\\u2588\\u2557 \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2557 ',\n ' \\u2588\\u2588\\u2554\\u2550\\u2550\\u2550\\u255d\\u255a\\u2550\\u2550\\u2588\\u2588\\u2554\\u2550\\u2550\\u255d\\u255a\\u2588\\u2588\\u2557\\u2588\\u2588\\u2554\\u255d\\u2588\\u2588\\u2554\\u2550\\u2550\\u2550\\u2588\\u2588\\u2557',\n ' \\u2588\\u2588\\u2551 \\u2588\\u2588\\u2551 \\u255a\\u2588\\u2588\\u2588\\u2554\\u255d \\u2588\\u2588\\u2551 \\u2588\\u2588\\u2551',\n ' \\u2588\\u2588\\u2551 \\u2588\\u2588\\u2551 \\u2588\\u2588\\u2554\\u2588\\u2588\\u2557 \\u2588\\u2588\\u2551 \\u2588\\u2588\\u2551',\n ' \\u255a\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2557 \\u2588\\u2588\\u2551 \\u2588\\u2588\\u2554\\u255d\\u255a\\u2588\\u2588\\u2557\\u255a\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2554\\u255d',\n ' \\u255a\\u2550\\u2550\\u2550\\u2550\\u2550\\u255d \\u255a\\u2550\\u255d \\u255a\\u2550\\u255d \\u255a\\u2550\\u255d \\u255a\\u2550\\u2550\\u2550\\u2550\\u2550\\u255d ',\n ];\n\n // Faux vertical gradient: cyan → blueBright → magentaBright\n const colors = [pc.cyan, pc.cyan, pc.blueBright, pc.blueBright, pc.magentaBright, pc.magentaBright] as const;\n const coloredArt = art.map((line, i) => colors[i]!(line));\n\n const tagline1 = pc.bold(pc.white(' Code intelligence for AI agents.'));\n const tagline2 = pc.dim(' One call instead of hundreds.');\n\n const inner = [\n '',\n ...coloredArt,\n '',\n tagline1,\n tagline2,\n '',\n ];\n\n return box(inner, { border: pc.dim }, pc);\n}\n\n/* ------------------------------------------------------------------ */\n/* InitCommand */\n/* ------------------------------------------------------------------ */\n\nexport class InitCommand {\n private readonly projectRoot: string;\n\n constructor(projectRoot: string) {\n this.projectRoot = projectRoot;\n }\n\n installHooks(): void {\n const hooksDir = join(this.projectRoot, '.git', 'hooks');\n mkdirSync(hooksDir, { recursive: true });\n this.installHook(hooksDir, 'post-commit', POST_COMMIT_CONTENT);\n this.installHook(hooksDir, 'post-merge', POST_MERGE_CONTENT);\n }\n\n async run(options: InitOptions = {}): Promise<void> {\n if (!existsSync(join(this.projectRoot, '.git'))) {\n console.error('[ctxo] Not a git repository. Run \"git init\" first.');\n process.exit(1);\n }\n\n if (options.dryRun) return this.dryRun(options);\n if (options.yes || options.tools) return this.runNonInteractive(options);\n return this.runInteractive(options);\n }\n\n /* ---------------------------------------------------------------- */\n /* Interactive flow */\n /* ---------------------------------------------------------------- */\n\n private async runInteractive(options: InitOptions): Promise<void> {\n const clack = await import('@clack/prompts');\n const pc = (await import('picocolors')).default;\n\n const version = await this.getVersion();\n const totalSteps = options.rulesOnly ? 1 : 3;\n\n // ── Banner ──\n console.error('');\n console.error(renderBanner(version, pc));\n console.error('');\n\n // ── Step 1: Index directory ──\n let stepNum = 0;\n if (!options.rulesOnly) {\n stepNum++;\n console.error(stepHeader(stepNum, totalSteps, 'Index Directory', 'Where ctxo stores the symbol graph and metadata.', pc));\n console.error('');\n\n const indexDir = await clack.text({\n message: pc.cyan('Directory path'),\n placeholder: '.ctxo/index',\n initialValue: '.ctxo/index',\n validate: (val) => {\n if (!val?.trim()) return 'Directory path is required';\n return undefined;\n },\n });\n\n if (clack.isCancel(indexDir)) { clack.cancel('Setup cancelled.'); process.exit(0); }\n\n const fullPath = join(this.projectRoot, indexDir as string);\n if (!existsSync(fullPath)) mkdirSync(fullPath, { recursive: true });\n console.error('');\n }\n\n // ── Step 2: AI tool selection ──\n stepNum++;\n const detected = detectPlatforms(this.projectRoot);\n const detectedCount = detected.size;\n const detectedHint = detectedCount > 0 ? pc.green(` ${detectedCount} detected`) : '';\n\n console.error(stepHeader(stepNum, totalSteps, `AI Tools${detectedHint}`, 'Select your tools. Generates MCP usage rules for each.', pc));\n console.error('');\n\n const toolChoices = PLATFORMS.map(p => {\n const isDetected = detected.has(p.id);\n const star = p.starred ? pc.yellow(' \\u2605') : '';\n const detect = isDetected ? pc.green(' (detected)') : '';\n return {\n value: p.id,\n label: `${p.name}${star}${detect}`,\n hint: isDetected ? undefined : pc.dim(p.file),\n };\n });\n\n const selectedTools = await clack.multiselect({\n message: pc.cyan('Select tools'),\n options: toolChoices,\n initialValues: [...detected],\n required: false,\n });\n\n if (clack.isCancel(selectedTools)) { clack.cancel('Setup cancelled.'); process.exit(0); }\n console.error('');\n\n // ── Step 3: Git hooks ──\n let installGitHooks = false;\n if (!options.rulesOnly) {\n stepNum++;\n console.error(stepHeader(stepNum, totalSteps, `Git Hooks ${pc.yellow('recommended')}`, 'Auto-updates index on every commit and pull.', pc));\n console.error('');\n\n const hooks = await clack.confirm({\n message: pc.cyan('Install hooks?'),\n initialValue: true,\n });\n\n if (clack.isCancel(hooks)) { clack.cancel('Setup cancelled.'); process.exit(0); }\n installGitHooks = hooks as boolean;\n console.error('');\n }\n\n // ── Execute with spinner ──\n const s = clack.spinner();\n s.start(pc.dim('Configuring...'));\n\n const results: string[] = [];\n\n // Automatic scaffolding (always runs, no prompt needed)\n const gitignoreResult = ensureGitignore(this.projectRoot);\n const configResult = ensureConfig(this.projectRoot);\n\n if (!options.rulesOnly) {\n results.push(`${pc.green('\\u2713')} ${pc.bold('.ctxo/index/')} ${pc.dim('index directory')}`);\n }\n\n if (configResult.action !== 'skipped') {\n results.push(`${pc.green('\\u2713')} ${pc.bold(configResult.file)} ${pc.dim(configResult.action)}`);\n }\n\n if (gitignoreResult.action !== 'skipped') {\n results.push(`${pc.green('\\u2713')} ${pc.bold(gitignoreResult.file)} ${pc.dim(gitignoreResult.action)}`);\n }\n\n for (const toolId of (selectedTools as string[])) {\n const result = installRules(this.projectRoot, toolId);\n results.push(`${pc.green('\\u2713')} ${pc.bold(result.file)} ${pc.dim(result.action)}`);\n }\n\n // MCP server registration (automatic based on selected tools)\n const mcpTargets = getMcpConfigTargets(selectedTools as string[]);\n for (const target of mcpTargets) {\n const result = ensureMcpConfig(this.projectRoot, target);\n if (result.action !== 'skipped') {\n results.push(`${pc.green('\\u2713')} ${pc.bold(result.file)} ${pc.dim(result.action + ' \\u2014 MCP server registered')}`);\n }\n }\n\n if (installGitHooks) {\n this.installHooks();\n results.push(`${pc.green('\\u2713')} ${pc.bold('post-commit, post-merge')} ${pc.dim('hooks installed')}`);\n }\n\n s.stop(pc.green('Done!'));\n\n // ── Summary box ──\n if (results.length > 0) {\n console.error('');\n console.error(box(results, { title: pc.green('\\u2713 Created'), border: pc.green }, pc));\n }\n\n // ── Next steps box ──\n const hasWork = (selectedTools as string[]).length > 0 || installGitHooks;\n if (hasWork) {\n const steps = [\n `${pc.cyan('\\u25b6')} npx ctxo index ${pc.dim('\\u2500 build codebase index')}`,\n `${pc.cyan('\\u25b6')} npx ctxo doctor ${pc.dim('\\u2500 verify everything works')}`,\n ];\n console.error('');\n console.error(box(steps, { title: pc.cyan('\\u2192 Next steps'), border: pc.cyan }, pc));\n }\n\n console.error('');\n console.error(` ${pc.dim('Happy coding!')} ${pc.magentaBright('\\u2764')}`);\n console.error('');\n }\n\n /* ---------------------------------------------------------------- */\n /* Non-interactive flow */\n /* ---------------------------------------------------------------- */\n\n private runNonInteractive(options: InitOptions): void {\n const toolIds = options.tools ?? [];\n\n for (const id of toolIds) {\n if (!PLATFORMS.find(p => p.id === id)) {\n console.error(`[ctxo] Unknown tool: \"${id}\". Valid: ${PLATFORMS.map(p => p.id).join(', ')}`);\n process.exit(1);\n }\n }\n\n // Automatic scaffolding\n const gitignoreResult = ensureGitignore(this.projectRoot);\n const configResult = ensureConfig(this.projectRoot);\n\n if (!options.rulesOnly) {\n const indexDir = join(this.projectRoot, '.ctxo', 'index');\n if (!existsSync(indexDir)) mkdirSync(indexDir, { recursive: true });\n console.error('[ctxo] \\u2713 .ctxo/index/ ready');\n }\n\n if (configResult.action !== 'skipped') {\n console.error(`[ctxo] \\u2713 ${configResult.file} \\u2014 ${configResult.action}`);\n }\n if (gitignoreResult.action !== 'skipped') {\n console.error(`[ctxo] \\u2713 ${gitignoreResult.file} \\u2014 ${gitignoreResult.action}`);\n }\n\n for (const toolId of toolIds) {\n const result = installRules(this.projectRoot, toolId);\n console.error(`[ctxo] \\u2713 ${result.file} \\u2014 ${result.action}`);\n }\n\n // MCP server registration\n const mcpTargets = getMcpConfigTargets(toolIds);\n for (const target of mcpTargets) {\n const result = ensureMcpConfig(this.projectRoot, target);\n if (result.action !== 'skipped') {\n console.error(`[ctxo] \\u2713 ${result.file} \\u2014 ${result.action} (MCP server registered)`);\n }\n }\n\n if (!options.rulesOnly) {\n this.installHooks();\n console.error('[ctxo] \\u2713 Git hooks installed');\n }\n }\n\n /* ---------------------------------------------------------------- */\n /* Dry run */\n /* ---------------------------------------------------------------- */\n\n private dryRun(options: InitOptions): void {\n const toolIds = options.tools ?? PLATFORMS.map(p => p.id);\n\n console.error('[ctxo] Dry run \\u2014 the following files would be created/updated:\\n');\n\n if (!options.rulesOnly) {\n console.error(' .ctxo/index/ (index directory)');\n }\n\n for (const id of toolIds) {\n const platform = PLATFORMS.find(p => p.id === id);\n if (platform) {\n const exists = existsSync(join(this.projectRoot, platform.file));\n const action = platform.mode === 'append' && exists ? 'append section' : 'create';\n console.error(` ${platform.file.padEnd(42)} (${action})`);\n }\n }\n\n if (!options.rulesOnly) {\n console.error(' .git/hooks/post-commit (git hook)');\n console.error(' .git/hooks/post-merge (git hook)');\n }\n }\n\n /* ---------------------------------------------------------------- */\n /* Helpers */\n /* ---------------------------------------------------------------- */\n\n private async getVersion(): Promise<string | undefined> {\n try {\n const pkgPath = join(this.projectRoot, 'node_modules', 'ctxo-mcp', 'package.json');\n if (existsSync(pkgPath)) {\n return JSON.parse(readFileSync(pkgPath, 'utf-8')).version;\n }\n const { createRequire } = await import('node:module');\n const require = createRequire(import.meta.url);\n return require('../../package.json').version;\n } catch {\n return undefined;\n }\n }\n\n private installHook(hooksDir: string, hookName: string, hookContent: string): void {\n const hookPath = join(hooksDir, hookName);\n\n let existing = '';\n if (existsSync(hookPath)) {\n existing = readFileSync(hookPath, 'utf-8');\n if (existing.includes(CTXO_START)) return;\n } else {\n existing = '#!/bin/sh\\n';\n }\n\n const updated = existing.endsWith('\\n')\n ? existing + '\\n' + hookContent + '\\n'\n : existing + '\\n\\n' + hookContent + '\\n';\n\n writeFileSync(hookPath, updated, 'utf-8');\n chmodSync(hookPath, 0o755);\n }\n}\n","/**\n * Platform configurations and MCP tool usage rule generator.\n *\n * Each platform entry defines where the AI coding assistant reads its\n * project-level instructions and how ctxo should write them.\n */\n\nimport { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';\nimport { join, dirname } from 'node:path';\n\nexport interface Platform {\n id: string;\n name: string;\n file: string;\n /** 'append' inserts a marked section into an existing file; 'create' writes from scratch */\n mode: 'append' | 'create';\n /** Paths to check for auto-detection (relative to project root) */\n detectPaths: string[];\n /** Show a star next to this platform name */\n starred: boolean;\n}\n\nexport const PLATFORMS: Platform[] = [\n { id: 'claude-code', name: 'Claude Code', file: 'CLAUDE.md', mode: 'append', detectPaths: ['CLAUDE.md', '.claude'], starred: true },\n { id: 'cursor', name: 'Cursor', file: '.cursor/rules/ctxo-mcp.mdc', mode: 'create', detectPaths: ['.cursor', '.cursorrules'], starred: false },\n { id: 'github-copilot', name: 'GitHub Copilot', file: '.github/copilot-instructions.md', mode: 'create', detectPaths: ['.github', '.vscode'], starred: false },\n { id: 'windsurf', name: 'Windsurf', file: '.windsurfrules', mode: 'create', detectPaths: ['.windsurfrules', '.windsurf'], starred: false },\n { id: 'antigravity', name: 'Google Antigravity', file: 'AGENTS.md', mode: 'create', detectPaths: ['AGENTS.md', 'GEMINI.md', '.gemini'], starred: false },\n { id: 'augment', name: 'Augment Code', file: 'augment-guidelines.md', mode: 'create', detectPaths: ['augment-guidelines.md', '.augment'], starred: false },\n { id: 'amazonq', name: 'Amazon Q', file: '.amazonq/rules/ctxo-mcp.md', mode: 'create', detectPaths: ['.amazonq'], starred: false },\n];\n\nexport function detectPlatforms(projectRoot: string): Set<string> {\n const detected = new Set<string>();\n for (const p of PLATFORMS) {\n if (p.detectPaths.some(d => existsSync(join(projectRoot, d)))) {\n detected.add(p.id);\n }\n }\n return detected;\n}\n\nconst SECTION_START = '<!-- ctxo-rules-start -->';\nconst SECTION_END = '<!-- ctxo-rules-end -->';\n\n/* ------------------------------------------------------------------ */\n/* Rule content */\n/* ------------------------------------------------------------------ */\n\nfunction ruleBody(): string {\n return `## ctxo MCP Tool Usage (MANDATORY)\n\n**ALWAYS use ctxo MCP tools before reading source files or making code changes.** The ctxo index contains dependency graphs, git intent, anti-patterns, and change health that cannot be derived from reading files alone. Skipping these tools leads to blind edits and broken dependencies.\n\n### Before ANY Code Modification\n1. Call \\`get_blast_radius\\` for the symbol you are about to change — understand what breaks\n2. Call \\`get_why_context\\` for the same symbol — check for revert history or anti-patterns\n3. Only then read and edit source files\n\n### Before Starting a Task\n| Task Type | REQUIRED First Call |\n|---|---|\n| Fixing a bug | \\`get_context_for_task(taskType: \"fix\")\\` |\n| Adding/extending a feature | \\`get_context_for_task(taskType: \"extend\")\\` |\n| Refactoring | \\`get_context_for_task(taskType: \"refactor\")\\` |\n| Understanding code | \\`get_context_for_task(taskType: \"understand\")\\` |\n\n### Before Reviewing a PR or Diff\n- Call \\`get_pr_impact\\` — single call gives full risk assessment with co-change analysis\n\n### When Exploring or Searching Code\n- Use \\`search_symbols\\` for name/regex lookup — DO NOT grep source files for symbol discovery\n- Use \\`get_ranked_context\\` for natural language queries — DO NOT manually browse directories\n\n### Orientation in Unfamiliar Areas\n- Call \\`get_architectural_overlay\\` to understand layer boundaries\n- Call \\`get_symbol_importance\\` to identify critical symbols\n\n### NEVER Do These\n- NEVER edit a function without first calling \\`get_blast_radius\\` on it\n- NEVER skip \\`get_why_context\\` — reverted code and anti-patterns are invisible without it\n- NEVER grep source files to find symbols when \\`search_symbols\\` exists\n- NEVER manually trace imports when \\`find_importers\\` gives the full reverse dependency graph`;\n}\n\n/* ------------------------------------------------------------------ */\n/* Per-platform rendering */\n/* ------------------------------------------------------------------ */\n\nfunction cursorFrontmatter(): string {\n return `---\ndescription: ctxo MCP tool usage rules — always applied\nglobs:\nalwaysApply: true\n---\n\n`;\n}\n\nexport function generateRules(platformId: string): string {\n const body = ruleBody();\n\n if (platformId === 'cursor') {\n return cursorFrontmatter() + body + '\\n';\n }\n\n return body + '\\n';\n}\n\n/* ------------------------------------------------------------------ */\n/* File operations */\n/* ------------------------------------------------------------------ */\n\nexport interface InstallResult {\n file: string;\n action: 'created' | 'updated' | 'skipped';\n}\n\nexport function installRules(projectRoot: string, platformId: string): InstallResult {\n const platform = PLATFORMS.find(p => p.id === platformId);\n if (!platform) throw new Error(`Unknown platform: ${platformId}`);\n\n const filePath = join(projectRoot, platform.file);\n const content = generateRules(platformId);\n\n // Ensure parent directory exists\n const dir = dirname(filePath);\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true });\n\n if (platform.mode === 'create') {\n // For 'create' mode: write or replace entire file\n writeFileSync(filePath, content, 'utf-8');\n return { file: platform.file, action: existsSync(filePath) ? 'updated' : 'created' };\n }\n\n // 'append' mode: insert marked section into existing file\n if (!existsSync(filePath)) {\n writeFileSync(filePath, content, 'utf-8');\n return { file: platform.file, action: 'created' };\n }\n\n const existing = readFileSync(filePath, 'utf-8');\n\n // Already has ctxo rules section — replace it\n if (existing.includes(SECTION_START)) {\n const re = new RegExp(`${escapeRegExp(SECTION_START)}[\\\\s\\\\S]*?${escapeRegExp(SECTION_END)}`, 'm');\n const updated = existing.replace(re, `${SECTION_START}\\n${content}${SECTION_END}`);\n writeFileSync(filePath, updated, 'utf-8');\n return { file: platform.file, action: 'updated' };\n }\n\n // Append new section\n const separator = existing.endsWith('\\n') ? '\\n' : '\\n\\n';\n const updated = existing + separator + `${SECTION_START}\\n${content}${SECTION_END}\\n`;\n writeFileSync(filePath, updated, 'utf-8');\n return { file: platform.file, action: 'updated' };\n}\n\nfunction escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/* ------------------------------------------------------------------ */\n/* Project scaffolding (automatic, not prompted) */\n/* ------------------------------------------------------------------ */\n\nconst GITIGNORE_ENTRY = '.ctxo/.cache/';\n\nexport function ensureGitignore(projectRoot: string): InstallResult {\n const filePath = join(projectRoot, '.gitignore');\n\n if (!existsSync(filePath)) {\n writeFileSync(filePath, `# Ctxo local cache (auto-rebuilt, never committed)\\n${GITIGNORE_ENTRY}\\n`, 'utf-8');\n return { file: '.gitignore', action: 'created' };\n }\n\n const existing = readFileSync(filePath, 'utf-8');\n if (existing.includes(GITIGNORE_ENTRY)) {\n return { file: '.gitignore', action: 'skipped' };\n }\n\n const separator = existing.endsWith('\\n') ? '\\n' : '\\n\\n';\n const updated = existing + `${separator}# Ctxo local cache (auto-rebuilt, never committed)\\n${GITIGNORE_ENTRY}\\n`;\n writeFileSync(filePath, updated, 'utf-8');\n return { file: '.gitignore', action: 'updated' };\n}\n\nconst DEFAULT_CONFIG = `# ctxo project configuration\n# Docs: https://github.com/alperhankendi/Ctxo\nversion: \"1.0\"\n`;\n\nexport function ensureConfig(projectRoot: string): InstallResult {\n const filePath = join(projectRoot, '.ctxo', 'config.yaml');\n const dir = dirname(filePath);\n\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true });\n\n if (existsSync(filePath)) {\n return { file: '.ctxo/config.yaml', action: 'skipped' };\n }\n\n writeFileSync(filePath, DEFAULT_CONFIG, 'utf-8');\n return { file: '.ctxo/config.yaml', action: 'created' };\n}\n\n/* ------------------------------------------------------------------ */\n/* MCP server registration */\n/* ------------------------------------------------------------------ */\n\nconst CTXO_MCP_ENTRY = { command: 'npx', args: ['-y', 'ctxo-mcp'] };\n\ninterface McpConfigTarget {\n file: string;\n /** JSON key that holds server map */\n serverKey: 'mcpServers' | 'servers';\n /** Extra fields per server entry */\n extraFields?: Record<string, string>;\n}\n\n/**\n * Returns which MCP config files to create/update based on selected platforms.\n * Multiple platforms may map to the same config file (deduplicated).\n */\nexport function getMcpConfigTargets(selectedPlatformIds: string[]): McpConfigTarget[] {\n const targets = new Map<string, McpConfigTarget>();\n\n for (const id of selectedPlatformIds) {\n switch (id) {\n case 'claude-code':\n case 'cursor':\n case 'windsurf':\n case 'augment':\n case 'antigravity':\n // .mcp.json is the universal project-level MCP config\n targets.set('.mcp.json', { file: '.mcp.json', serverKey: 'mcpServers' });\n break;\n case 'github-copilot':\n targets.set('.vscode/mcp.json', { file: '.vscode/mcp.json', serverKey: 'servers', extraFields: { type: 'stdio' } });\n break;\n case 'amazonq':\n targets.set('.amazonq/mcp.json', { file: '.amazonq/mcp.json', serverKey: 'mcpServers' });\n break;\n }\n }\n\n return [...targets.values()];\n}\n\nexport function ensureMcpConfig(projectRoot: string, target: McpConfigTarget): InstallResult {\n const filePath = join(projectRoot, target.file);\n const dir = dirname(filePath);\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true });\n\n const entry = target.extraFields\n ? { ...target.extraFields, ...CTXO_MCP_ENTRY }\n : { ...CTXO_MCP_ENTRY };\n\n if (!existsSync(filePath)) {\n const config = { [target.serverKey]: { ctxo: entry } };\n writeFileSync(filePath, JSON.stringify(config, null, 2) + '\\n', 'utf-8');\n return { file: target.file, action: 'created' };\n }\n\n // Merge into existing config\n let existing: Record<string, unknown>;\n try {\n existing = JSON.parse(readFileSync(filePath, 'utf-8'));\n } catch {\n // Corrupt JSON — overwrite\n const config = { [target.serverKey]: { ctxo: entry } };\n writeFileSync(filePath, JSON.stringify(config, null, 2) + '\\n', 'utf-8');\n return { file: target.file, action: 'updated' };\n }\n\n const servers = (existing[target.serverKey] ?? {}) as Record<string, unknown>;\n if (servers['ctxo']) {\n return { file: target.file, action: 'skipped' };\n }\n\n servers['ctxo'] = entry;\n existing[target.serverKey] = servers;\n writeFileSync(filePath, JSON.stringify(existing, null, 2) + '\\n', 'utf-8');\n return { file: target.file, action: 'updated' };\n}\n","import { join, extname, relative } from 'node:path';\nimport { readFileSync } from 'node:fs';\nimport { TsMorphAdapter } from '../adapters/language/ts-morph-adapter.js';\nimport { LanguageAdapterRegistry } from '../adapters/language/language-adapter-registry.js';\nimport { JsonIndexWriter } from '../adapters/storage/json-index-writer.js';\nimport { SqliteStorageAdapter } from '../adapters/storage/sqlite-storage-adapter.js';\nimport { ChokidarWatcherAdapter } from '../adapters/watcher/chokidar-watcher-adapter.js';\nimport { ContentHasher } from '../core/staleness/content-hasher.js';\nimport { SimpleGitAdapter } from '../adapters/git/simple-git-adapter.js';\nimport { RevertDetector } from '../core/why-context/revert-detector.js';\nimport type { FileIndex, CommitIntent, AntiPattern } from '../core/types.js';\n\nconst DEBOUNCE_MS = 300;\n\nexport class WatchCommand {\n private readonly projectRoot: string;\n private readonly ctxoRoot: string;\n\n constructor(projectRoot: string) {\n this.projectRoot = projectRoot;\n this.ctxoRoot = join(projectRoot, '.ctxo');\n }\n\n async run(): Promise<void> {\n console.error('[ctxo] Starting file watcher...');\n\n const registry = new LanguageAdapterRegistry();\n registry.register(new TsMorphAdapter());\n this.registerTreeSitterAdapters(registry);\n const supportedExtensions = registry.getSupportedExtensions();\n\n const writer = new JsonIndexWriter(this.ctxoRoot);\n const storage = new SqliteStorageAdapter(this.ctxoRoot);\n await storage.init();\n const hasher = new ContentHasher();\n\n const gitAdapter = new SimpleGitAdapter(this.projectRoot);\n const revertDetector = new RevertDetector();\n const watcher = new ChokidarWatcherAdapter(this.projectRoot);\n const pendingFiles = new Map<string, NodeJS.Timeout>();\n\n const reindexFile = async (filePath: string) => {\n const adapter = registry.getAdapter(filePath);\n if (!adapter) return;\n\n const relativePath = relative(this.projectRoot, filePath).replace(/\\\\/g, '/');\n\n try {\n const source = readFileSync(filePath, 'utf-8');\n const lastModified = Math.floor(Date.now() / 1000);\n\n const symbols = adapter.extractSymbols(relativePath, source);\n const edges = adapter.extractEdges(relativePath, source);\n const complexity = adapter.extractComplexity(relativePath, source);\n\n // Git history and anti-patterns\n const commits = await gitAdapter.getCommitHistory(relativePath);\n const intent: CommitIntent[] = commits.map((c) => ({\n hash: c.hash, message: c.message, date: c.date, kind: 'commit' as const,\n }));\n const antiPatterns: AntiPattern[] = revertDetector.detect(commits);\n\n const fileIndex: FileIndex = {\n file: relativePath,\n lastModified,\n contentHash: hasher.hash(source),\n symbols,\n edges,\n complexity,\n intent,\n antiPatterns,\n };\n\n writer.write(fileIndex);\n storage.writeSymbolFile(fileIndex);\n console.error(`[ctxo] Re-indexed: ${relativePath}`);\n } catch (err) {\n console.error(`[ctxo] Failed to re-index ${relativePath}: ${(err as Error).message}`);\n }\n };\n\n const debouncedReindex = (filePath: string) => {\n const existing = pendingFiles.get(filePath);\n if (existing) clearTimeout(existing);\n\n pendingFiles.set(\n filePath,\n setTimeout(() => {\n pendingFiles.delete(filePath);\n reindexFile(filePath);\n }, DEBOUNCE_MS),\n );\n };\n\n watcher.start((event, filePath) => {\n if (event === 'unlink') {\n const ext = extname(filePath).toLowerCase();\n if (!supportedExtensions.has(ext)) return;\n\n const relativePath = relative(this.projectRoot, filePath).replace(/\\\\/g, '/');\n writer.delete(relativePath);\n storage.deleteSymbolFile(relativePath);\n console.error(`[ctxo] Removed from index: ${relativePath}`);\n } else {\n debouncedReindex(filePath);\n }\n });\n\n console.error('[ctxo] Watching for file changes... (Ctrl+C to stop)');\n\n const cleanup = () => {\n console.error('\\n[ctxo] Stopping watcher...');\n for (const timeout of pendingFiles.values()) {\n clearTimeout(timeout);\n }\n watcher.stop().then(() => {\n storage.close();\n console.error('[ctxo] Watcher stopped');\n process.exit(0);\n });\n };\n\n process.on('SIGINT', cleanup);\n process.on('SIGTERM', cleanup);\n }\n\n private registerTreeSitterAdapters(registry: LanguageAdapterRegistry): void {\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { GoAdapter } = require('../adapters/language/go-adapter.js');\n registry.register(new GoAdapter());\n } catch {\n console.error('[ctxo] Go adapter unavailable (tree-sitter-go not installed)');\n }\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { CSharpAdapter } = require('../adapters/language/csharp-adapter.js');\n registry.register(new CSharpAdapter());\n } catch {\n console.error('[ctxo] C# adapter unavailable (tree-sitter-c-sharp not installed)');\n }\n }\n}\n","import { watch, type FSWatcher } from 'chokidar';\nimport type { IWatcherPort, FileChangeHandler } from '../../ports/i-watcher-port.js';\n\nconst DEFAULT_IGNORED = [\n '**/node_modules/**',\n '**/.git/**',\n '**/.ctxo/**',\n '**/dist/**',\n '**/coverage/**',\n];\n\nexport class ChokidarWatcherAdapter implements IWatcherPort {\n private readonly projectRoot: string;\n private readonly ignored: string[];\n private watcher: FSWatcher | undefined;\n\n constructor(projectRoot: string, ignored?: string[]) {\n this.projectRoot = projectRoot;\n this.ignored = ignored ?? DEFAULT_IGNORED;\n }\n\n start(handler: FileChangeHandler): void {\n if (this.watcher) {\n throw new Error('Watcher already started. Call stop() before starting again.');\n }\n\n this.watcher = watch(this.projectRoot, {\n ignored: this.ignored,\n persistent: true,\n ignoreInitial: true,\n });\n\n this.watcher.on('add', (path) => handler('add', path));\n this.watcher.on('change', (path) => handler('change', path));\n this.watcher.on('unlink', (path) => handler('unlink', path));\n }\n\n async stop(): Promise<void> {\n if (this.watcher) {\n await this.watcher.close();\n this.watcher = undefined;\n }\n }\n}\n","import { join } from 'node:path';\nimport { existsSync, readFileSync } from 'node:fs';\nimport initSqlJs from 'sql.js';\nimport { SessionRecorderAdapter } from '../adapters/stats/session-recorder-adapter.js';\nimport type { AggregatedStats } from '../ports/i-session-recorder-port.js';\nimport type { StatsReport } from '../core/stats/stats-types.js';\n\nexport class StatsCommand {\n private readonly ctxoRoot: string;\n\n constructor(projectRoot: string) {\n this.ctxoRoot = join(projectRoot, '.ctxo');\n }\n\n async run(options: { days?: number; json?: boolean; clear?: boolean }): Promise<void> {\n // Check if stats are enabled\n if (!this.isStatsEnabled()) {\n console.error('[ctxo] Stats collection is disabled in .ctxo/config.yaml');\n return;\n }\n\n const dbPath = join(this.ctxoRoot, '.cache', 'symbols.db');\n if (!existsSync(dbPath)) {\n if (options.json) {\n process.stdout.write(JSON.stringify(this.emptyReport(options.days)) + '\\n');\n } else {\n console.error('[ctxo] No usage data yet. Start using Ctxo MCP tools to collect stats.');\n }\n return;\n }\n\n // Open DB\n const SQL = await initSqlJs();\n const buffer = readFileSync(dbPath);\n const db = new SQL.Database(buffer);\n const recorder = new SessionRecorderAdapter(db);\n\n try {\n if (options.clear) {\n recorder.clear();\n // Persist cleared DB\n const data = db.export();\n const { writeFileSync } = await import('node:fs');\n writeFileSync(dbPath, Buffer.from(data));\n console.error('[ctxo] Session data cleared.');\n return;\n }\n\n // Validate --days\n if (options.days != null) {\n if (!Number.isInteger(options.days) || options.days <= 0) {\n console.error('[ctxo] --days must be a positive integer');\n process.exit(1);\n return;\n }\n }\n\n const stats = recorder.queryStats(options.days);\n\n if (stats.totalCalls === 0) {\n if (options.json) {\n process.stdout.write(JSON.stringify(this.emptyReport(options.days)) + '\\n');\n } else {\n console.error('[ctxo] No usage data yet. Start using Ctxo MCP tools to collect stats.');\n }\n return;\n }\n\n if (options.json) {\n process.stdout.write(JSON.stringify(this.buildReport(stats, options.days), null, 2) + '\\n');\n } else {\n this.printHumanReadable(stats, options.days);\n }\n } finally {\n db.close();\n }\n }\n\n private isStatsEnabled(): boolean {\n const configPath = join(this.ctxoRoot, 'config.yaml');\n if (!existsSync(configPath)) return true;\n\n try {\n const raw = readFileSync(configPath, 'utf-8');\n const match = raw.match(/stats:\\s*\\n\\s*enabled:\\s*(true|false)/);\n if (match) return match[1] !== 'false';\n return true;\n } catch {\n return true;\n }\n }\n\n private buildReport(stats: AggregatedStats, days?: number): StatsReport {\n const now = new Date().toISOString();\n const from = days != null\n ? new Date(Date.now() - days * 86400000).toISOString()\n : null;\n\n return {\n timeRange: { from, to: now, daysFilter: days ?? null },\n summary: {\n totalCalls: stats.totalCalls,\n totalTokensServed: stats.totalTokensServed,\n },\n topTools: stats.topTools,\n topSymbols: stats.topSymbols,\n detailLevelDistribution: stats.detailLevelDistribution.map((d) => ({\n level: d.level,\n count: d.count,\n percentage: d.percentage,\n })),\n };\n }\n\n private emptyReport(days?: number): StatsReport {\n return this.buildReport({\n totalCalls: 0,\n totalTokensServed: 0,\n topTools: [],\n topSymbols: [],\n detailLevelDistribution: [],\n }, days);\n }\n\n private printHumanReadable(stats: AggregatedStats, days?: number): void {\n const header = days != null ? `last ${days} days` : 'all time';\n\n console.error('');\n console.error(` Usage Summary (${header})`);\n console.error(' ────────────────────────────────────────');\n console.error(` Total tool calls: ${this.formatNumber(stats.totalCalls)}`);\n console.error(` Total tokens served: ${this.formatTokens(stats.totalTokensServed)}`);\n\n if (stats.topTools.length > 0) {\n console.error('');\n console.error(' Top Tools');\n console.error(' ────────────────────────────────────────');\n for (const t of stats.topTools) {\n const name = t.tool.padEnd(24);\n const calls = `${this.formatNumber(t.calls)} calls`.padEnd(14);\n console.error(` ${name}${calls}avg ${this.formatNumber(t.avgTokens)} tokens`);\n }\n }\n\n if (stats.topSymbols.length > 0) {\n console.error('');\n console.error(' Top Queried Symbols');\n console.error(' ────────────────────────────────────────');\n for (const s of stats.topSymbols) {\n const name = s.name.padEnd(32);\n console.error(` ${name}${this.formatNumber(s.queries)} queries`);\n }\n }\n\n if (stats.detailLevelDistribution.length > 0) {\n console.error('');\n console.error(' Detail Level Distribution');\n console.error(' ────────────────────────────────────────');\n for (const d of stats.detailLevelDistribution) {\n const bar = this.renderBar(d.percentage);\n const pct = `${d.percentage}%`.padStart(4);\n console.error(` ${d.level}: ${bar} ${pct}`);\n }\n }\n\n console.error('');\n }\n\n private renderBar(percentage: number): string {\n const filled = Math.round(percentage / 10);\n const empty = 10 - filled;\n return '█'.repeat(filled) + '░'.repeat(empty);\n }\n\n private formatNumber(n: number): string {\n return n.toLocaleString('en-US');\n }\n\n private formatTokens(n: number): string {\n if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;\n if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`;\n return String(n);\n }\n}\n","import { join } from 'node:path';\nimport { existsSync } from 'node:fs';\nimport type { IHealthCheck } from '../core/diagnostics/types.js';\nimport { JsonIndexReader } from '../adapters/storage/json-index-reader.js';\nimport { HealthChecker } from '../adapters/diagnostics/health-checker.js';\nimport { DoctorReporter } from '../adapters/diagnostics/doctor-reporter.js';\nimport { NodeVersionCheck, TsMorphCheck, TreeSitterCheck } from '../adapters/diagnostics/checks/runtime-check.js';\nimport { GitBinaryCheck, GitRepoCheck } from '../adapters/diagnostics/checks/git-check.js';\nimport {\n IndexDirectoryCheck,\n IndexFreshnessCheck,\n SymbolCountCheck,\n EdgeCountCheck,\n OrphanedFilesCheck,\n CoChangesCacheCheck,\n SchemaVersionCheck,\n} from '../adapters/diagnostics/checks/index-check.js';\nimport { SqliteCacheCheck } from '../adapters/diagnostics/checks/storage-check.js';\nimport { ConfigFileCheck } from '../adapters/diagnostics/checks/config-check.js';\nimport { DiskUsageCheck } from '../adapters/diagnostics/checks/disk-check.js';\n\nexport interface DoctorOptions {\n json?: boolean;\n quiet?: boolean;\n}\n\nexport class DoctorCommand {\n private readonly projectRoot: string;\n private readonly ctxoRoot: string;\n\n constructor(projectRoot: string) {\n this.projectRoot = projectRoot;\n this.ctxoRoot = join(projectRoot, '.ctxo');\n }\n\n async run(options: DoctorOptions = {}): Promise<void> {\n const checks: IHealthCheck[] = [\n new NodeVersionCheck(),\n new GitBinaryCheck(),\n new GitRepoCheck(),\n new IndexDirectoryCheck(),\n new IndexFreshnessCheck(),\n new SqliteCacheCheck(),\n new ConfigFileCheck(),\n new TsMorphCheck(),\n new TreeSitterCheck(),\n new DiskUsageCheck(),\n new SymbolCountCheck(),\n new EdgeCountCheck(),\n new OrphanedFilesCheck(),\n new CoChangesCacheCheck(),\n new SchemaVersionCheck(),\n ];\n\n // Pre-load index once — shared by all index-related checks (avoids 5x redundant readAll)\n const indexDir = join(this.ctxoRoot, 'index');\n const indices = existsSync(indexDir)\n ? new JsonIndexReader(this.ctxoRoot).readAll()\n : [];\n\n const checker = new HealthChecker(checks);\n const report = await checker.runAll({\n projectRoot: this.projectRoot,\n ctxoRoot: this.ctxoRoot,\n indices,\n });\n\n const reporter = new DoctorReporter();\n let output: string;\n\n if (options.json) {\n output = reporter.formatJson(report);\n process.stdout.write(output + '\\n');\n } else if (options.quiet) {\n output = reporter.formatQuiet(report);\n console.error(output);\n } else {\n output = reporter.formatHuman(report);\n console.error(output);\n }\n\n if (report.exitCode !== 0) {\n process.exitCode = 1;\n }\n }\n}\n","import { createLogger } from '../../core/logger.js';\nimport type { IHealthCheck, CheckContext, CheckResult, DoctorReport } from '../../core/diagnostics/types.js';\n\nconst log = createLogger('ctxo:doctor');\n\nexport class HealthChecker {\n private readonly checks: IHealthCheck[];\n\n constructor(checks: IHealthCheck[]) {\n this.checks = checks;\n }\n\n async runAll(ctx: CheckContext): Promise<DoctorReport> {\n const settled = await Promise.allSettled(\n this.checks.map(check => check.run(ctx)),\n );\n\n const results: CheckResult[] = settled.map((outcome, i) => {\n const check = this.checks[i]!;\n if (outcome.status === 'fulfilled') {\n const r = outcome.value;\n log.info(`${r.id}: ${r.status.toUpperCase()} (${r.message})`);\n return r;\n }\n const message = (outcome.reason as Error)?.message ?? 'Unknown error';\n log.error(`${check.id}: FAIL (${message})`);\n return {\n id: check.id,\n title: check.title,\n status: 'fail' as const,\n message: `Check crashed: ${message}`,\n };\n });\n\n const summary = {\n pass: results.filter(r => r.status === 'pass').length,\n warn: results.filter(r => r.status === 'warn').length,\n fail: results.filter(r => r.status === 'fail').length,\n };\n\n const exitCode = summary.fail > 0 ? 1 as const : 0 as const;\n\n return { checks: results, summary, exitCode };\n }\n}\n","import type { DoctorReport, CheckResult } from '../../core/diagnostics/types.js';\n\nconst ICONS: Record<string, string> = {\n pass: '✓',\n warn: '⚠',\n fail: '✗',\n};\n\nexport class DoctorReporter {\n formatHuman(report: DoctorReport): string {\n const lines: string[] = ['ctxo doctor — Health Check', ''];\n\n for (const check of report.checks) {\n lines.push(this.formatCheckLine(check));\n }\n\n lines.push('');\n lines.push(` Summary: ${report.summary.pass} passed, ${report.summary.warn} warnings, ${report.summary.fail} failures`);\n\n return lines.join('\\n');\n }\n\n formatQuiet(report: DoctorReport): string {\n const lines: string[] = [];\n\n for (const check of report.checks) {\n if (check.status === 'warn' || check.status === 'fail') {\n lines.push(this.formatCheckLine(check));\n }\n }\n\n if (lines.length > 0) lines.push('');\n lines.push(` Summary: ${report.summary.pass} passed, ${report.summary.warn} warnings, ${report.summary.fail} failures`);\n\n return lines.join('\\n');\n }\n\n formatJson(report: DoctorReport): string {\n return JSON.stringify({\n checks: report.checks.map(c => ({\n name: c.id,\n status: c.status,\n value: c.value ?? null,\n message: c.message,\n ...(c.fix ? { fix: c.fix } : {}),\n })),\n summary: report.summary,\n exitCode: report.exitCode,\n }, null, 2);\n }\n\n private formatCheckLine(check: CheckResult): string {\n const icon = ICONS[check.status] ?? '?';\n const title = check.title.padEnd(24);\n const suffix = check.fix ? ` (${check.fix})` : '';\n return ` ${icon} ${title} ${check.message}${suffix}`;\n }\n}\n","import { createRequire } from 'node:module';\nimport type { IHealthCheck, CheckResult, CheckContext } from '../../../core/diagnostics/types.js';\n\nconst require = createRequire(import.meta.url);\n\nfunction pass(id: string, title: string, message: string): CheckResult {\n return { id, title, status: 'pass', message };\n}\nfunction warn(id: string, title: string, message: string, fix: string): CheckResult {\n return { id, title, status: 'warn', message, fix };\n}\nfunction fail(id: string, title: string, message: string, fix: string): CheckResult {\n return { id, title, status: 'fail', message, fix };\n}\n\nexport function checkNodeVersion(version: string): CheckResult {\n const id = 'node_version';\n const title = 'Node.js version';\n const major = parseInt(version.slice(1).split('.')[0] ?? '0', 10);\n if (major >= 20) return { id, title, status: 'pass', message: `Node.js ${version} (required: ≥20)`, value: version };\n if (major >= 18) return { id, title, status: 'warn', message: `Node.js ${version} — v20+ recommended`, fix: 'Upgrade to Node.js 20 or later', value: version };\n return { id, title, status: 'fail', message: `Node.js ${version} — v20+ required`, fix: 'Upgrade to Node.js 20 or later', value: version };\n}\n\nexport class NodeVersionCheck implements IHealthCheck {\n readonly id = 'node_version';\n readonly title = 'Node.js version';\n\n async run(_ctx: CheckContext): Promise<CheckResult> {\n return checkNodeVersion(process.version);\n }\n}\n\nexport class TsMorphCheck implements IHealthCheck {\n readonly id = 'ts_morph';\n readonly title = 'ts-morph';\n\n async run(_ctx: CheckContext): Promise<CheckResult> {\n try {\n require.resolve('ts-morph');\n return pass(this.id, this.title, 'available');\n } catch {\n return fail(this.id, this.title, 'ts-morph not installed', 'Run \"npm install\"');\n }\n }\n}\n\nexport class TreeSitterCheck implements IHealthCheck {\n readonly id = 'tree_sitter';\n readonly title = 'tree-sitter';\n\n async run(_ctx: CheckContext): Promise<CheckResult> {\n try {\n require.resolve('tree-sitter');\n require.resolve('tree-sitter-language-pack');\n return pass(this.id, this.title, 'available');\n } catch {\n return warn(this.id, this.title, 'tree-sitter not found — Go/C# indexing disabled', 'Run \"npm install tree-sitter tree-sitter-language-pack\"');\n }\n }\n}\n","import { execFileSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { IHealthCheck, CheckResult, CheckContext } from '../../../core/diagnostics/types.js';\n\nexport class GitBinaryCheck implements IHealthCheck {\n readonly id = 'git_binary';\n readonly title = 'Git available';\n\n async run(_ctx: CheckContext): Promise<CheckResult> {\n try {\n const version = execFileSync('git', ['--version'], { encoding: 'utf-8' }).trim();\n return { id: this.id, title: this.title, status: 'pass', message: version, value: version };\n } catch {\n return { id: this.id, title: this.title, status: 'fail', message: 'git not found in PATH', fix: 'Install git and ensure it is in your PATH' };\n }\n }\n}\n\nexport class GitRepoCheck implements IHealthCheck {\n readonly id = 'git_repo';\n readonly title = 'Git repository';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n if (existsSync(join(ctx.projectRoot, '.git'))) {\n return { id: this.id, title: this.title, status: 'pass', message: ctx.projectRoot, value: ctx.projectRoot };\n }\n return { id: this.id, title: this.title, status: 'fail', message: 'Not a git repository', fix: 'Run \"git init\" or clone a repository' };\n }\n}\n","import { existsSync } from 'node:fs';\nimport { execFileSync } from 'node:child_process';\nimport { join } from 'node:path';\nimport type { IHealthCheck, CheckResult, CheckContext } from '../../../core/diagnostics/types.js';\nimport type { FileIndex } from '../../../core/types.js';\nimport { JsonIndexReader } from '../../storage/json-index-reader.js';\nimport { StalenessDetector } from '../../../core/staleness/staleness-detector.js';\nimport { SchemaManager } from '../../storage/schema-manager.js';\n\nfunction pass(id: string, title: string, message: string, value?: string): CheckResult {\n return { id, title, status: 'pass', message, value };\n}\nfunction warn(id: string, title: string, message: string, fix?: string, value?: string): CheckResult {\n return { id, title, status: 'warn', message, fix, value };\n}\nfunction fail(id: string, title: string, message: string, fix?: string, value?: string): CheckResult {\n return { id, title, status: 'fail', message, fix, value };\n}\n\n/** Use pre-loaded indices from context, or fall back to reading from disk */\nfunction getIndices(ctx: CheckContext): readonly FileIndex[] {\n return ctx.indices ?? new JsonIndexReader(ctx.ctxoRoot).readAll();\n}\n\nexport class IndexDirectoryCheck implements IHealthCheck {\n readonly id = 'index_directory';\n readonly title = 'Index directory';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n const indexDir = join(ctx.ctxoRoot, 'index');\n if (!existsSync(indexDir)) {\n return fail(this.id, this.title, 'No index directory', 'Run \"ctxo index\"');\n }\n const indices = getIndices(ctx);\n if (indices.length === 0) {\n return fail(this.id, this.title, 'Index directory empty', 'Run \"ctxo index\"');\n }\n return pass(this.id, this.title, `${indices.length} files indexed`, String(indices.length));\n }\n}\n\nexport class IndexFreshnessCheck implements IHealthCheck {\n readonly id = 'index_freshness';\n readonly title = 'Index freshness';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n const indices = getIndices(ctx);\n if (indices.length === 0) {\n return fail(this.id, this.title, 'No indexed files to check', 'Run \"ctxo index\"');\n }\n\n const indexedFiles = indices.map(idx => idx.file);\n const staleness = new StalenessDetector(ctx.projectRoot, ctx.ctxoRoot);\n const warning = staleness.check(indexedFiles);\n\n if (!warning) {\n return pass(this.id, this.title, `All ${indices.length} files fresh`, `0/${indices.length} stale`);\n }\n\n const staleCount = warning.staleFiles.length;\n const pct = staleCount / indices.length;\n const value = `${staleCount}/${indices.length} stale`;\n\n if (pct <= 0.1) {\n return warn(this.id, this.title, `${staleCount} of ${indices.length} files stale`, 'Run \"ctxo index\"', value);\n }\n return fail(this.id, this.title, `${staleCount} of ${indices.length} files stale (${Math.round(pct * 100)}%)`, 'Run \"ctxo index\"', value);\n }\n}\n\nexport class SymbolCountCheck implements IHealthCheck {\n readonly id = 'symbol_count';\n readonly title = 'Symbol count';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n const indices = getIndices(ctx);\n const total = indices.reduce((sum, idx) => sum + idx.symbols.length, 0);\n if (total > 0) {\n return pass(this.id, this.title, `${total.toLocaleString()} symbols`, String(total));\n }\n return fail(this.id, this.title, '0 symbols (index empty)', 'Run \"ctxo index\"', '0');\n }\n}\n\nexport class EdgeCountCheck implements IHealthCheck {\n readonly id = 'edge_count';\n readonly title = 'Edge count';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n const indices = getIndices(ctx);\n const total = indices.reduce((sum, idx) => sum + idx.edges.length, 0);\n if (total > 0) {\n return pass(this.id, this.title, `${total.toLocaleString()} edges`, String(total));\n }\n return warn(this.id, this.title, '0 edges (possible isolated files)', undefined, '0');\n }\n}\n\nexport class OrphanedFilesCheck implements IHealthCheck {\n readonly id = 'orphaned_files';\n readonly title = 'Orphaned index files';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n const indices = getIndices(ctx);\n if (indices.length === 0) {\n return pass(this.id, this.title, 'no index files to check');\n }\n\n const sourceFiles = this.getSourceFiles(ctx.projectRoot);\n if (sourceFiles.size === 0) {\n return pass(this.id, this.title, 'none (git ls-files unavailable)');\n }\n\n const orphaned = indices.filter(idx => !sourceFiles.has(idx.file));\n if (orphaned.length === 0) {\n return pass(this.id, this.title, 'none', '0');\n }\n if (orphaned.length <= 5) {\n return warn(this.id, this.title, `${orphaned.length} orphaned index files`, 'Delete orphaned files from .ctxo/index/', String(orphaned.length));\n }\n return fail(this.id, this.title, `${orphaned.length} orphaned index files`, 'Delete orphaned files from .ctxo/index/', String(orphaned.length));\n }\n\n private getSourceFiles(projectRoot: string): Set<string> {\n try {\n const output = execFileSync('git', ['ls-files', '--cached', '--others', '--exclude-standard'], {\n cwd: projectRoot,\n encoding: 'utf-8',\n });\n return new Set(output.split('\\n').map(l => l.trim()).filter(l => l.length > 0));\n } catch {\n return new Set();\n }\n }\n}\n\nexport class CoChangesCacheCheck implements IHealthCheck {\n readonly id = 'co_changes_cache';\n readonly title = 'Co-changes cache';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n const coChangesPath = join(ctx.ctxoRoot, 'index', 'co-changes.json');\n if (existsSync(coChangesPath)) {\n return pass(this.id, this.title, 'present');\n }\n return warn(this.id, this.title, 'missing (co-change analysis disabled)', 'Run \"ctxo index\" with git history');\n }\n}\n\nexport class SchemaVersionCheck implements IHealthCheck {\n readonly id = 'schema_version';\n readonly title = 'Schema version';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n const manager = new SchemaManager(ctx.ctxoRoot);\n const stored = manager.readStoredVersion();\n const current = manager.currentVersion();\n\n if (!stored) {\n return fail(this.id, this.title, 'No schema version found', 'Run \"ctxo index\"');\n }\n if (manager.isCompatible()) {\n return pass(this.id, this.title, `${stored} (current)`, stored);\n }\n return fail(this.id, this.title, `${stored} (expected ${current})`, 'Run \"ctxo index\" to re-index with current schema', stored);\n }\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { IHealthCheck, CheckResult, CheckContext } from '../../../core/diagnostics/types.js';\n\nexport class SqliteCacheCheck implements IHealthCheck {\n readonly id = 'sqlite_cache';\n readonly title = 'SQLite cache';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n const dbPath = join(ctx.ctxoRoot, '.cache', 'symbols.db');\n if (!existsSync(dbPath)) {\n return { id: this.id, title: this.title, status: 'warn', message: 'SQLite cache missing', fix: 'Run \"ctxo sync\" to rebuild' };\n }\n\n try {\n const { default: initSqlJs } = await import('sql.js');\n const SQL = await initSqlJs();\n const buffer = readFileSync(dbPath);\n const db = new SQL.Database(new Uint8Array(buffer));\n const result = db.exec('PRAGMA integrity_check');\n db.close();\n\n const firstRow = result[0]?.values[0];\n if (firstRow && firstRow[0] === 'ok') {\n return { id: this.id, title: this.title, status: 'pass', message: 'integrity_check passed' };\n }\n return { id: this.id, title: this.title, status: 'fail', message: `SQLite corrupt: ${String(firstRow?.[0])}`, fix: 'Run \"ctxo sync\" to rebuild' };\n } catch (err) {\n return { id: this.id, title: this.title, status: 'fail', message: `SQLite unreadable: ${(err as Error).message}`, fix: 'Run \"ctxo sync\" to rebuild' };\n }\n }\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { IHealthCheck, CheckResult, CheckContext } from '../../../core/diagnostics/types.js';\n\nexport class ConfigFileCheck implements IHealthCheck {\n readonly id = 'config_file';\n readonly title = 'Config file';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n const configPath = join(ctx.ctxoRoot, 'config.yaml');\n if (!existsSync(configPath)) {\n return { id: this.id, title: this.title, status: 'warn', message: 'No config.yaml (using defaults)' };\n }\n\n try {\n const content = readFileSync(configPath, 'utf-8');\n if (content.trim().length === 0) {\n return { id: this.id, title: this.title, status: 'warn', message: 'config.yaml is empty (using defaults)' };\n }\n // Basic YAML structure check — tabs are invalid in YAML\n if (content.includes('\\t')) {\n return { id: this.id, title: this.title, status: 'fail', message: 'Invalid config.yaml: tabs are not allowed in YAML', fix: 'Replace tabs with spaces in .ctxo/config.yaml' };\n }\n return { id: this.id, title: this.title, status: 'pass', message: '.ctxo/config.yaml valid' };\n } catch (err) {\n return { id: this.id, title: this.title, status: 'fail', message: `Cannot read config.yaml: ${(err as Error).message}`, fix: 'Check file permissions for .ctxo/config.yaml' };\n }\n }\n}\n","import { existsSync, readdirSync, statSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { IHealthCheck, CheckResult, CheckContext } from '../../../core/diagnostics/types.js';\n\nexport interface DiskThresholds {\n readonly warnMb: number;\n readonly failMb: number;\n}\n\nconst DEFAULT_THRESHOLDS: DiskThresholds = { warnMb: 100, failMb: 500 };\n\nexport class DiskUsageCheck implements IHealthCheck {\n readonly id = 'disk_usage';\n readonly title = 'Disk usage';\n private readonly thresholds: DiskThresholds;\n\n constructor(thresholds: DiskThresholds = DEFAULT_THRESHOLDS) {\n this.thresholds = thresholds;\n }\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n if (!existsSync(ctx.ctxoRoot)) {\n return { id: this.id, title: this.title, status: 'pass', message: 'no .ctxo/ directory', value: '0' };\n }\n\n const bytes = this.getDirSize(ctx.ctxoRoot);\n const mb = bytes / (1024 * 1024);\n const formatted = mb < 1 ? `${Math.round(bytes / 1024)} KB` : `${mb.toFixed(1)} MB`;\n\n if (mb < this.thresholds.warnMb) {\n return { id: this.id, title: this.title, status: 'pass', message: formatted, value: formatted };\n }\n if (mb < this.thresholds.failMb) {\n return { id: this.id, title: this.title, status: 'warn', message: `${formatted} — consider pruning orphaned index files`, value: formatted };\n }\n return { id: this.id, title: this.title, status: 'fail', message: `${formatted} — unusually large`, fix: 'Check for stale data in .ctxo/', value: formatted };\n }\n\n private getDirSize(dirPath: string): number {\n let total = 0;\n try {\n const entries = readdirSync(dirPath, { withFileTypes: true, recursive: true });\n for (const entry of entries) {\n if (entry.isFile()) {\n try {\n // parentPath available in Node 20.12+, path in earlier Node 20.x\n const parent = (entry as unknown as { parentPath?: string; path?: string }).parentPath\n ?? (entry as unknown as { path?: string }).path\n ?? dirPath;\n total += statSync(join(parent, entry.name)).size;\n } catch {\n // skip unreadable files\n }\n }\n }\n } catch {\n // skip unreadable directories\n }\n return total;\n }\n}\n","import { IndexCommand } from './index-command.js';\nimport { SyncCommand } from './sync-command.js';\nimport { StatusCommand } from './status-command.js';\nimport { VerifyCommand } from './verify-command.js';\nimport { InitCommand } from './init-command.js';\nimport { WatchCommand } from './watch-command.js';\nimport { StatsCommand } from './stats-command.js';\nimport { DoctorCommand } from './doctor-command.js';\n\nexport class CliRouter {\n private readonly projectRoot: string;\n\n constructor(projectRoot: string) {\n this.projectRoot = projectRoot;\n }\n\n async route(args: string[]): Promise<void> {\n const command = args[0];\n\n if (!command || command === '--help' || command === '-h') {\n this.printHelp();\n return;\n }\n\n switch (command) {\n case 'index': {\n const fileIdx = args.indexOf('--file');\n const fileArg = fileIdx !== -1 ? args[fileIdx + 1] : undefined;\n if (fileIdx !== -1 && (!fileArg || fileArg.startsWith('--'))) {\n console.error('[ctxo] --file requires a path argument');\n process.exit(1);\n return;\n }\n const checkArg = args.includes('--check');\n const skipHistory = args.includes('--skip-history');\n const maxHistoryIdx = args.indexOf('--max-history');\n const maxHistoryArg = maxHistoryIdx !== -1 ? Number(args[maxHistoryIdx + 1]) : undefined;\n if (maxHistoryIdx !== -1 && (!maxHistoryArg || isNaN(maxHistoryArg) || maxHistoryArg < 1)) {\n console.error('[ctxo] --max-history requires a positive integer');\n process.exit(1);\n return;\n }\n await new IndexCommand(this.projectRoot).run({ file: fileArg, check: checkArg, skipHistory, maxHistory: maxHistoryArg });\n break;\n }\n\n case 'sync':\n await new SyncCommand(this.projectRoot).run();\n break;\n\n case 'watch':\n await new WatchCommand(this.projectRoot).run();\n break;\n\n case 'verify-index':\n await new VerifyCommand(this.projectRoot).run();\n break;\n\n case 'status':\n new StatusCommand(this.projectRoot).run();\n break;\n\n case 'init': {\n const toolsIdx = args.indexOf('--tools');\n const toolsArg = toolsIdx !== -1 ? args[toolsIdx + 1] : undefined;\n const yesArg = args.includes('--yes') || args.includes('-y');\n const rulesOnly = args.includes('--rules');\n const dryRun = args.includes('--dry-run');\n const tools = toolsArg ? toolsArg.split(',').map(t => t.trim()) : undefined;\n await new InitCommand(this.projectRoot).run({ tools, yes: yesArg, rulesOnly, dryRun });\n break;\n }\n\n case 'stats': {\n const daysIdx = args.indexOf('--days');\n const daysArg = daysIdx !== -1 ? Number(args[daysIdx + 1]) : undefined;\n const jsonArg = args.includes('--json');\n const clearArg = args.includes('--clear');\n await new StatsCommand(this.projectRoot).run({ days: daysArg, json: jsonArg, clear: clearArg });\n break;\n }\n\n case 'doctor': {\n const jsonArg = args.includes('--json');\n const quietArg = args.includes('--quiet');\n await new DoctorCommand(this.projectRoot).run({ json: jsonArg, quiet: quietArg });\n break;\n }\n\n default:\n console.error(`[ctxo] Unknown command: \"${command}\". Run \"ctxo --help\" for usage.`);\n process.exit(1);\n return;\n }\n }\n\n private printHelp(): void {\n console.error(`\nctxo — MCP server for dependency-aware codebase context\n\nUsage:\n ctxo Start MCP server (stdio transport)\n ctxo index Build full codebase index (--max-history N, default 20)\n ctxo sync Rebuild SQLite cache from committed JSON index\n ctxo watch Start file watcher for incremental re-indexing\n ctxo verify-index CI gate: fail if index is stale\n ctxo status Show index manifest\n ctxo init Interactive setup (tools, rules, hooks)\n ctxo init --rules Regenerate AI tool rules only\n ctxo init --tools a,b -y Non-interactive (claude-code,cursor,...)\n ctxo init --dry-run Preview what would be created\n ctxo stats Show usage statistics (--json, --days N, --clear)\n ctxo doctor Health check all subsystems (--json, --quiet)\n ctxo --help Show this help message\n`.trim());\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,YAAY;AAGnB,SAAS,WAAAA,gBAAe;AAHxB,IAOsB;AAPtB;AAAA;AAAA;AAOO,IAAe,oBAAf,MAA6D;AAAA,MAEzD,OAAO;AAAA,MAEN;AAAA,MACA,iBAAiB,oBAAI,IAAwB;AAAA,MAEvD,YAAY,UAAoB;AAC9B,aAAK,SAAS,IAAI,OAAO;AACzB,aAAK,OAAO,YAAY,QAAQ;AAAA,MAClC;AAAA,MAEA,YAAY,UAA2B;AACrC,cAAM,MAAMA,SAAQ,QAAQ,EAAE,YAAY;AAC1C,eAAQ,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,SAAS,MAAM,GAAG,EAAE,IAAI,OAAK,EAAE,KAAK,CAAC,IAAI;AAClE,cAAM,IAAI,YAAY,KAAK,WAAW,EAAE,IAAI,EAAE,OAAO,KAAK,QAAQ,WAAW,OAAO,CAAC;AACrF;AAAA,MACF;AAAA,MAEA,KAAK,SAAS;AACZ,cAAM,UAAU,KAAK,QAAQ,QAAQ;AACrC,cAAM,UAAU,YAAY,KAAK,OAAO,KAAK,UAAU,CAAC,CAAC,IAAI;AAC7D,cAAM,UAAU,KAAK,SAAS,QAAQ;AACtC,cAAM,WAAW,KAAK,SAAS,SAAS;AACxC,cAAM,IAAI,aAAa,KAAK,WAAW,EAAE,IAAI,EAAE,MAAM,SAAS,MAAM,SAAS,OAAO,SAAS,CAAC;AAC9F;AAAA,MACF;AAAA,MAEA,KAAK,UAAU;AACb,cAAM,UAAU,KAAK,SAAS,QAAQ;AACtC,cAAM,WAAW,KAAK,SAAS,SAAS;AACxC,cAAM,IAAI,cAAc,KAAK,WAAW,EAAE,IAAI,EAAE,MAAM,SAAS,OAAO,SAAS,CAAC;AAChF;AAAA,MACF;AAAA,MAEA;AACE,gBAAQ,MAAM,4BAA4B,OAAO,iCAAiC;AAClF,gBAAQ,KAAK,CAAC;AACd;AAAA,IACJ;AAAA,EACF;AAAA,EAEQ,YAAkB;AACxB,YAAQ,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiBhB,KAAK,CAAC;AAAA,EACN;AACF;","names":["extname","readFileSync","writeFileSync","existsSync","join","extname","kind","extname","dirname","join","writeFileSync","existsSync","mkdirSync","join","dirname","join","readFileSync","GoAdapter","CSharpAdapter","existsSync","extname","writeFileSync","join","join","join","existsSync","execFileSync","join","existsSync","execFileSync","join","join","join","existsSync","readFileSync","writeFileSync","mkdirSync","existsSync","readFileSync","writeFileSync","mkdirSync","join","dirname","updated","join","mkdirSync","existsSync","readFileSync","createRequire","require","writeFileSync","join","extname","relative","readFileSync","join","relative","readFileSync","extname","GoAdapter","CSharpAdapter","join","existsSync","readFileSync","join","existsSync","readFileSync","writeFileSync","join","existsSync","require","execFileSync","existsSync","join","existsSync","execFileSync","join","pass","warn","fail","join","existsSync","execFileSync","existsSync","readFileSync","join","initSqlJs","existsSync","readFileSync","join","existsSync","readdirSync","statSync","join","join","existsSync"]}
package/dist/index.js CHANGED
@@ -2928,7 +2928,7 @@ async function main() {
2928
2928
  const args = process.argv.slice(2);
2929
2929
  const httpPortStr = process.env.CTXO_HTTP_PORT || (args.includes("--http") ? args[args.indexOf("--port") + 1] || "3001" : null);
2930
2930
  if (!httpPortStr && args.length > 0) {
2931
- const { CliRouter } = await import("./cli-router-L64DKAXT.js");
2931
+ const { CliRouter } = await import("./cli-router-VZGJSSE5.js");
2932
2932
  const router = new CliRouter(process.cwd());
2933
2933
  await router.route(args);
2934
2934
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ctxo-mcp",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "description": "MCP server delivering dependency-aware, history-enriched context for codebases",
5
5
  "type": "module",
6
6
  "engines": {
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/adapters/language/tree-sitter-adapter.ts","../src/adapters/language/go-adapter.ts","../src/adapters/language/csharp-adapter.ts","../src/cli/index-command.ts","../src/core/staleness/content-hasher.ts","../src/adapters/language/ts-morph-adapter.ts","../src/adapters/language/language-adapter-registry.ts","../src/adapters/storage/json-index-writer.ts","../src/adapters/storage/schema-manager.ts","../src/cli/sync-command.ts","../src/cli/status-command.ts","../src/cli/verify-command.ts","../src/cli/init-command.ts","../src/cli/ai-rules.ts","../src/cli/watch-command.ts","../src/adapters/watcher/chokidar-watcher-adapter.ts","../src/cli/stats-command.ts","../src/cli/doctor-command.ts","../src/adapters/diagnostics/health-checker.ts","../src/adapters/diagnostics/doctor-reporter.ts","../src/adapters/diagnostics/checks/runtime-check.ts","../src/adapters/diagnostics/checks/git-check.ts","../src/adapters/diagnostics/checks/index-check.ts","../src/adapters/diagnostics/checks/storage-check.ts","../src/adapters/diagnostics/checks/config-check.ts","../src/adapters/diagnostics/checks/disk-check.ts","../src/cli/cli-router.ts"],"sourcesContent":["import Parser from 'tree-sitter';\nimport type { Tree, SyntaxNode } from 'tree-sitter';\ntype Language = Parameters<InstanceType<typeof Parser>['setLanguage']>[0];\nimport { extname } from 'node:path';\nimport type { SymbolNode, GraphEdge, ComplexityMetrics, SymbolKind } from '../../core/types.js';\nimport type { ILanguageAdapter } from '../../ports/i-language-adapter.js';\n\nexport abstract class TreeSitterAdapter implements ILanguageAdapter {\n abstract readonly extensions: readonly string[];\n readonly tier = 'syntax' as const;\n\n protected parser: Parser;\n protected symbolRegistry = new Map<string, SymbolKind>();\n\n constructor(language: Language) {\n this.parser = new Parser();\n this.parser.setLanguage(language);\n }\n\n isSupported(filePath: string): boolean {\n const ext = extname(filePath).toLowerCase();\n return (this.extensions as readonly string[]).includes(ext);\n }\n\n setSymbolRegistry(registry: Map<string, SymbolKind>): void {\n this.symbolRegistry = registry;\n }\n\n protected parse(source: string): Tree {\n return this.parser.parse(source);\n }\n\n protected buildSymbolId(filePath: string, name: string, kind: SymbolKind): string {\n return `${filePath}::${name}::${kind}`;\n }\n\n protected nodeToLineRange(node: SyntaxNode): {\n startLine: number;\n endLine: number;\n startOffset: number;\n endOffset: number;\n } {\n return {\n startLine: node.startPosition.row,\n endLine: node.endPosition.row,\n startOffset: node.startIndex,\n endOffset: node.endIndex,\n };\n }\n\n protected countCyclomaticComplexity(node: SyntaxNode, branchTypes: string[]): number {\n let complexity = 1;\n const visit = (n: SyntaxNode) => {\n if (branchTypes.includes(n.type)) {\n complexity++;\n }\n for (let i = 0; i < n.childCount; i++) {\n visit(n.child(i)!);\n }\n };\n visit(node);\n return complexity;\n }\n\n abstract extractSymbols(filePath: string, source: string): SymbolNode[];\n abstract extractEdges(filePath: string, source: string): GraphEdge[];\n abstract extractComplexity(filePath: string, source: string): ComplexityMetrics[];\n}\n","import GoLanguage from 'tree-sitter-go';\nimport type { SyntaxNode } from 'tree-sitter';\nimport { TreeSitterAdapter } from './tree-sitter-adapter.js';\nimport type { SymbolNode, GraphEdge, ComplexityMetrics } from '../../core/types.js';\n\nconst GO_BRANCH_TYPES = [\n 'if_statement', 'for_statement',\n 'expression_switch_statement', 'type_switch_statement',\n 'expression_case', 'type_case',\n 'select_statement', 'communication_case',\n];\n\nexport class GoAdapter extends TreeSitterAdapter {\n readonly extensions = ['.go'] as const;\n\n constructor() {\n super(GoLanguage);\n }\n\n extractSymbols(filePath: string, source: string): SymbolNode[] {\n try {\n const tree = this.parse(source);\n const symbols: SymbolNode[] = [];\n\n for (let i = 0; i < tree.rootNode.childCount; i++) {\n const node = tree.rootNode.child(i)!;\n\n if (node.type === 'function_declaration') {\n const name = node.childForFieldName('name')?.text;\n if (!name || !this.isExported(name)) continue;\n const range = this.nodeToLineRange(node);\n symbols.push({\n symbolId: this.buildSymbolId(filePath, name, 'function'),\n name,\n kind: 'function',\n ...range,\n });\n }\n\n if (node.type === 'method_declaration') {\n const methodName = node.childForFieldName('name')?.text;\n if (!methodName || !this.isExported(methodName)) continue;\n const receiverType = this.extractReceiverType(node);\n const qualifiedName = receiverType ? `${receiverType}.${methodName}` : methodName;\n const range = this.nodeToLineRange(node);\n symbols.push({\n symbolId: this.buildSymbolId(filePath, qualifiedName, 'method'),\n name: qualifiedName,\n kind: 'method',\n ...range,\n });\n }\n\n if (node.type === 'type_declaration') {\n this.extractTypeSymbols(node, filePath, symbols);\n }\n }\n\n return symbols;\n } catch (err) {\n console.error(`[ctxo:go] Symbol extraction failed for ${filePath}: ${(err as Error).message}`);\n return [];\n }\n }\n\n extractEdges(filePath: string, source: string): GraphEdge[] {\n try {\n const tree = this.parse(source);\n const edges: GraphEdge[] = [];\n const firstExportedSymbol = this.findFirstExportedSymbolId(tree.rootNode, filePath);\n if (!firstExportedSymbol) return edges;\n\n for (let i = 0; i < tree.rootNode.childCount; i++) {\n const node = tree.rootNode.child(i)!;\n\n if (node.type === 'import_declaration') {\n this.extractImportEdges(node, filePath, firstExportedSymbol, edges);\n }\n }\n\n return edges;\n } catch (err) {\n console.error(`[ctxo:go] Edge extraction failed for ${filePath}: ${(err as Error).message}`);\n return [];\n }\n }\n\n extractComplexity(filePath: string, source: string): ComplexityMetrics[] {\n try {\n const tree = this.parse(source);\n const metrics: ComplexityMetrics[] = [];\n\n for (let i = 0; i < tree.rootNode.childCount; i++) {\n const node = tree.rootNode.child(i)!;\n\n if (node.type === 'function_declaration') {\n const name = node.childForFieldName('name')?.text;\n if (!name || !this.isExported(name)) continue;\n metrics.push({\n symbolId: this.buildSymbolId(filePath, name, 'function'),\n cyclomatic: this.countCyclomaticComplexity(node, GO_BRANCH_TYPES),\n });\n }\n\n if (node.type === 'method_declaration') {\n const methodName = node.childForFieldName('name')?.text;\n if (!methodName || !this.isExported(methodName)) continue;\n const receiverType = this.extractReceiverType(node);\n const qualifiedName = receiverType ? `${receiverType}.${methodName}` : methodName;\n metrics.push({\n symbolId: this.buildSymbolId(filePath, qualifiedName, 'method'),\n cyclomatic: this.countCyclomaticComplexity(node, GO_BRANCH_TYPES),\n });\n }\n }\n\n return metrics;\n } catch (err) {\n console.error(`[ctxo:go] Complexity extraction failed for ${filePath}: ${(err as Error).message}`);\n return [];\n }\n }\n\n // ── Private helpers ─────────────────────────────────────────\n\n private isExported(name: string): boolean {\n return name.length > 0 && name[0]! === name[0]!.toUpperCase() && name[0]! !== name[0]!.toLowerCase();\n }\n\n private extractReceiverType(methodNode: SyntaxNode): string | undefined {\n // method_declaration has parameter_list as first child (receiver)\n const params = methodNode.child(1);\n if (params?.type !== 'parameter_list') return undefined;\n\n for (let i = 0; i < params.childCount; i++) {\n const param = params.child(i)!;\n if (param.type === 'parameter_declaration') {\n // Find type identifier — may be pointer (*Type) or plain (Type)\n const typeNode = param.childForFieldName('type');\n if (typeNode) {\n const text = typeNode.text;\n return text.replace(/^\\*/, '');\n }\n }\n }\n return undefined;\n }\n\n private extractTypeSymbols(typeDecl: SyntaxNode, filePath: string, symbols: SymbolNode[]): void {\n for (let i = 0; i < typeDecl.childCount; i++) {\n const spec = typeDecl.child(i)!;\n if (spec.type !== 'type_spec') continue;\n\n const name = spec.childForFieldName('name')?.text;\n if (!name || !this.isExported(name)) continue;\n\n // Determine kind from the type body\n const typeBody = spec.childForFieldName('type');\n let kind: 'class' | 'interface' | 'type' = 'type';\n if (typeBody?.type === 'struct_type') kind = 'class';\n else if (typeBody?.type === 'interface_type') kind = 'interface';\n\n const range = this.nodeToLineRange(spec);\n symbols.push({\n symbolId: this.buildSymbolId(filePath, name, kind),\n name,\n kind,\n ...range,\n });\n }\n }\n\n private extractImportEdges(\n importDecl: SyntaxNode,\n _filePath: string,\n fromSymbol: string,\n edges: GraphEdge[],\n ): void {\n const visit = (node: SyntaxNode) => {\n if (node.type === 'import_spec') {\n const pathNode = node.childForFieldName('path') ?? node.child(0);\n if (pathNode) {\n const importPath = pathNode.text.replace(/\"/g, '');\n edges.push({\n from: fromSymbol,\n to: `${importPath}::${importPath.split('/').pop()}::variable`,\n kind: 'imports',\n });\n }\n }\n for (let i = 0; i < node.childCount; i++) {\n visit(node.child(i)!);\n }\n };\n visit(importDecl);\n }\n\n private findFirstExportedSymbolId(rootNode: SyntaxNode, filePath: string): string | undefined {\n for (let i = 0; i < rootNode.childCount; i++) {\n const node = rootNode.child(i)!;\n\n if (node.type === 'function_declaration') {\n const name = node.childForFieldName('name')?.text;\n if (name && this.isExported(name)) return this.buildSymbolId(filePath, name, 'function');\n }\n if (node.type === 'type_declaration') {\n for (let j = 0; j < node.childCount; j++) {\n const spec = node.child(j)!;\n if (spec.type === 'type_spec') {\n const name = spec.childForFieldName('name')?.text;\n if (name && this.isExported(name)) {\n const typeBody = spec.childForFieldName('type');\n const kind = typeBody?.type === 'struct_type' ? 'class' : typeBody?.type === 'interface_type' ? 'interface' : 'type';\n return this.buildSymbolId(filePath, name, kind);\n }\n }\n }\n }\n }\n return undefined;\n }\n}\n","import CSharpLanguage from 'tree-sitter-c-sharp';\nimport type { SyntaxNode } from 'tree-sitter';\nimport { TreeSitterAdapter } from './tree-sitter-adapter.js';\nimport type { SymbolNode, GraphEdge, ComplexityMetrics, SymbolKind } from '../../core/types.js';\n\nconst CSHARP_BRANCH_TYPES = [\n 'if_statement', 'for_statement', 'foreach_statement',\n 'while_statement', 'do_statement', 'switch_section',\n 'catch_clause', 'conditional_expression',\n];\n\nexport class CSharpAdapter extends TreeSitterAdapter {\n readonly extensions = ['.cs'] as const;\n\n constructor() {\n super(CSharpLanguage);\n }\n\n extractSymbols(filePath: string, source: string): SymbolNode[] {\n try {\n const tree = this.parse(source);\n const symbols: SymbolNode[] = [];\n this.visitSymbols(tree.rootNode, filePath, '', symbols);\n return symbols;\n } catch (err) {\n console.error(`[ctxo:csharp] Symbol extraction failed for ${filePath}: ${(err as Error).message}`);\n return [];\n }\n }\n\n extractEdges(filePath: string, source: string): GraphEdge[] {\n try {\n const tree = this.parse(source);\n const edges: GraphEdge[] = [];\n const symbols = this.extractSymbols(filePath, source);\n const firstSymbol = symbols.length > 0 ? symbols[0]!.symbolId : undefined;\n if (!firstSymbol) return edges;\n\n this.visitEdges(tree.rootNode, filePath, firstSymbol, '', edges);\n return edges;\n } catch (err) {\n console.error(`[ctxo:csharp] Edge extraction failed for ${filePath}: ${(err as Error).message}`);\n return [];\n }\n }\n\n extractComplexity(filePath: string, source: string): ComplexityMetrics[] {\n try {\n const tree = this.parse(source);\n const metrics: ComplexityMetrics[] = [];\n this.visitComplexity(tree.rootNode, filePath, '', metrics);\n return metrics;\n } catch (err) {\n console.error(`[ctxo:csharp] Complexity extraction failed for ${filePath}: ${(err as Error).message}`);\n return [];\n }\n }\n\n // ── Symbol visitor ──────────────────────────────────────────\n\n private visitSymbols(\n node: SyntaxNode,\n filePath: string,\n namespace: string,\n symbols: SymbolNode[],\n ): void {\n if (node.type === 'namespace_declaration') {\n const name = node.childForFieldName('name')?.text ?? '';\n const ns = namespace ? `${namespace}.${name}` : name;\n for (let i = 0; i < node.childCount; i++) {\n this.visitSymbols(node.child(i)!, filePath, ns, symbols);\n }\n return;\n }\n\n if (node.type === 'declaration_list') {\n for (let i = 0; i < node.childCount; i++) {\n this.visitSymbols(node.child(i)!, filePath, namespace, symbols);\n }\n return;\n }\n\n const typeMapping: Record<string, SymbolKind> = {\n class_declaration: 'class',\n struct_declaration: 'class',\n record_declaration: 'class',\n interface_declaration: 'interface',\n enum_declaration: 'type',\n };\n\n const kind = typeMapping[node.type];\n if (kind) {\n if (!this.isPublic(node)) return;\n const name = node.childForFieldName('name')?.text;\n if (!name) return;\n\n const qualifiedName = namespace ? `${namespace}.${name}` : name;\n const range = this.nodeToLineRange(node);\n symbols.push({\n symbolId: this.buildSymbolId(filePath, qualifiedName, kind),\n name: qualifiedName,\n kind,\n ...range,\n });\n\n // Extract methods inside the class/struct/record\n if (kind === 'class') {\n this.extractMethodSymbols(node, filePath, qualifiedName, symbols);\n }\n return;\n }\n\n // Recurse into compilation_unit and other containers\n for (let i = 0; i < node.childCount; i++) {\n this.visitSymbols(node.child(i)!, filePath, namespace, symbols);\n }\n }\n\n private extractMethodSymbols(\n classNode: SyntaxNode,\n filePath: string,\n className: string,\n symbols: SymbolNode[],\n ): void {\n const declList = classNode.children.find(c => c.type === 'declaration_list');\n if (!declList) return;\n\n for (let i = 0; i < declList.childCount; i++) {\n const child = declList.child(i)!;\n if (child.type !== 'method_declaration' && child.type !== 'constructor_declaration') continue;\n if (!this.isPublic(child)) continue;\n\n const name = child.childForFieldName('name')?.text;\n if (!name) continue;\n\n const paramCount = this.countParameters(child);\n const qualifiedName = `${className}.${name}(${paramCount})`;\n const range = this.nodeToLineRange(child);\n symbols.push({\n symbolId: this.buildSymbolId(filePath, qualifiedName, 'method'),\n name: qualifiedName,\n kind: 'method',\n ...range,\n });\n }\n }\n\n // ── Edge visitor ────────────────────────────────────────────\n\n private visitEdges(\n node: SyntaxNode,\n filePath: string,\n fromSymbol: string,\n namespace: string,\n edges: GraphEdge[],\n ): void {\n if (node.type === 'using_directive') {\n const nameNode = node.children.find(c => c.type === 'identifier' || c.type === 'qualified_name');\n if (nameNode) {\n edges.push({\n from: fromSymbol,\n to: `${nameNode.text}::${nameNode.text.split('.').pop()}::variable`,\n kind: 'imports',\n });\n }\n return;\n }\n\n if (node.type === 'namespace_declaration') {\n const name = node.childForFieldName('name')?.text ?? '';\n const ns = namespace ? `${namespace}.${name}` : name;\n for (let i = 0; i < node.childCount; i++) {\n this.visitEdges(node.child(i)!, filePath, fromSymbol, ns, edges);\n }\n return;\n }\n\n if (node.type === 'class_declaration' || node.type === 'struct_declaration') {\n if (!this.isPublic(node)) return;\n const name = node.childForFieldName('name')?.text;\n if (!name) return;\n\n const qualifiedName = namespace ? `${namespace}.${name}` : name;\n const classSymbolId = this.buildSymbolId(filePath, qualifiedName, 'class');\n\n // Check base_list for extends/implements\n const baseList = node.children.find(c => c.type === 'base_list');\n if (baseList) {\n for (let i = 0; i < baseList.childCount; i++) {\n const child = baseList.child(i)!;\n if (child.type === 'identifier' || child.type === 'qualified_name') {\n const baseName = child.text;\n // Heuristic: I-prefix = interface → implements, otherwise extends\n const edgeKind = baseName.match(/^I[A-Z]/) ? 'implements' : 'extends';\n const targetKind = edgeKind === 'implements' ? 'interface' : 'class';\n edges.push({\n from: classSymbolId,\n to: this.resolveBaseType(baseName, namespace, targetKind),\n kind: edgeKind,\n });\n }\n }\n }\n }\n\n for (let i = 0; i < node.childCount; i++) {\n this.visitEdges(node.child(i)!, filePath, fromSymbol, namespace, edges);\n }\n }\n\n // ── Complexity visitor ──────────────────────────────────────\n\n private visitComplexity(\n node: SyntaxNode,\n filePath: string,\n namespace: string,\n metrics: ComplexityMetrics[],\n ): void {\n if (node.type === 'namespace_declaration') {\n const name = node.childForFieldName('name')?.text ?? '';\n const ns = namespace ? `${namespace}.${name}` : name;\n for (let i = 0; i < node.childCount; i++) {\n this.visitComplexity(node.child(i)!, filePath, ns, metrics);\n }\n return;\n }\n\n const typeMapping: Record<string, true> = {\n class_declaration: true,\n struct_declaration: true,\n record_declaration: true,\n };\n\n if (typeMapping[node.type]) {\n if (!this.isPublic(node)) return;\n const className = node.childForFieldName('name')?.text;\n if (!className) return;\n\n const qualifiedClass = namespace ? `${namespace}.${className}` : className;\n const declList = node.children.find(c => c.type === 'declaration_list');\n if (!declList) return;\n\n for (let i = 0; i < declList.childCount; i++) {\n const child = declList.child(i)!;\n if (child.type !== 'method_declaration') continue;\n if (!this.isPublic(child)) continue;\n\n const methodName = child.childForFieldName('name')?.text;\n if (!methodName) continue;\n\n const paramCount = this.countParameters(child);\n metrics.push({\n symbolId: this.buildSymbolId(filePath, `${qualifiedClass}.${methodName}(${paramCount})`, 'method'),\n cyclomatic: this.countCyclomaticComplexity(child, CSHARP_BRANCH_TYPES),\n });\n }\n return;\n }\n\n for (let i = 0; i < node.childCount; i++) {\n this.visitComplexity(node.child(i)!, filePath, namespace, metrics);\n }\n }\n\n // ── Helpers ─────────────────────────────────────────────────\n\n private countParameters(methodNode: SyntaxNode): number {\n const paramList = methodNode.childForFieldName('parameters');\n if (!paramList) return 0;\n let count = 0;\n for (let i = 0; i < paramList.childCount; i++) {\n if (paramList.child(i)!.type === 'parameter') count++;\n }\n return count;\n }\n\n private isPublic(node: SyntaxNode): boolean {\n for (let i = 0; i < node.childCount; i++) {\n const child = node.child(i)!;\n if (child.type === 'modifier' && child.text === 'public') return true;\n }\n return false;\n }\n\n private resolveBaseType(baseName: string, namespace: string, defaultKind: SymbolKind): string {\n // Check symbol registry first\n const prefix = namespace ? `${namespace}.${baseName}` : baseName;\n for (const [id] of this.symbolRegistry) {\n if (id.includes(`::${prefix}::`)) return id;\n if (id.includes(`::${baseName}::`)) return id;\n }\n // Fallback: assume same namespace\n const qualifiedName = namespace ? `${namespace}.${baseName}` : baseName;\n return `${qualifiedName}::${baseName}::${defaultKind}`;\n }\n}\n","import { execFileSync } from 'node:child_process';\nimport { readFileSync, writeFileSync, existsSync, statSync, readdirSync } from 'node:fs';\nimport { join, relative, extname } from 'node:path';\nimport { ContentHasher } from '../core/staleness/content-hasher.js';\nimport { TsMorphAdapter } from '../adapters/language/ts-morph-adapter.js';\nimport { LanguageAdapterRegistry } from '../adapters/language/language-adapter-registry.js';\nimport { JsonIndexWriter } from '../adapters/storage/json-index-writer.js';\nimport { SqliteStorageAdapter } from '../adapters/storage/sqlite-storage-adapter.js';\nimport { SchemaManager } from '../adapters/storage/schema-manager.js';\nimport { SimpleGitAdapter } from '../adapters/git/simple-git-adapter.js';\nimport { RevertDetector } from '../core/why-context/revert-detector.js';\nimport { aggregateCoChanges } from '../core/co-change/co-change-analyzer.js';\nimport type { FileIndex, SymbolKind } from '../core/types.js';\n\nexport class IndexCommand {\n private readonly projectRoot: string;\n ctxoRoot: string;\n private supportedExtensions: Set<string>;\n\n constructor(projectRoot: string, ctxoRoot?: string) {\n this.projectRoot = projectRoot;\n this.ctxoRoot = ctxoRoot ?? join(projectRoot, '.ctxo');\n this.supportedExtensions = new Set(['.ts', '.tsx', '.js', '.jsx', '.go', '.cs']);\n }\n\n async run(options: { file?: string; check?: boolean; skipSideEffects?: boolean; skipHistory?: boolean; maxHistory?: number } = {}): Promise<void> {\n if (options.check) {\n // Delegate to verify logic: hash-based freshness check\n return this.runCheck();\n }\n\n // Set up adapters\n const registry = new LanguageAdapterRegistry();\n const tsMorphAdapter = new TsMorphAdapter();\n registry.register(tsMorphAdapter);\n this.registerTreeSitterAdapters(registry);\n this.supportedExtensions = registry.getSupportedExtensions();\n\n const writer = new JsonIndexWriter(this.ctxoRoot);\n const schemaManager = new SchemaManager(this.ctxoRoot);\n const hasher = new ContentHasher();\n const gitAdapter = new SimpleGitAdapter(this.projectRoot);\n const revertDetector = new RevertDetector();\n\n // Discover files (single file, monorepo workspaces, or full project)\n let files: string[];\n if (options.file) {\n const fullPath = join(this.projectRoot, options.file);\n files = [fullPath];\n console.error(`[ctxo] Incremental re-index: ${options.file}`);\n } else {\n // Check for monorepo workspaces — discover files across all roots\n const workspaces = this.discoverWorkspaces();\n files = [];\n for (const ws of workspaces) {\n const wsFiles = this.discoverFilesIn(ws);\n files.push(...wsFiles);\n }\n console.error(`[ctxo] Building codebase index... Found ${files.length} source files`);\n }\n\n // Phase 1a: Extract symbols (CPU-bound, builds symbol registry for edge resolution)\n const symbolRegistry = new Map<string, SymbolKind>();\n const pendingIndices: Array<{\n relativePath: string;\n source: string;\n fileIndex: FileIndex;\n }> = [];\n let processed = 0;\n\n for (const filePath of files) {\n const adapter = registry.getAdapter(filePath);\n if (!adapter) continue;\n\n const relativePath = relative(this.projectRoot, filePath).replace(/\\\\/g, '/');\n\n try {\n const source = readFileSync(filePath, 'utf-8');\n const lastModified = Math.floor(Date.now() / 1000);\n\n const symbols = adapter.extractSymbols(relativePath, source);\n const complexity = adapter.extractComplexity(relativePath, source);\n\n // Build symbol registry for accurate edge resolution\n for (const sym of symbols) {\n symbolRegistry.set(sym.symbolId, sym.kind);\n }\n\n pendingIndices.push({\n relativePath,\n source,\n fileIndex: {\n file: relativePath,\n lastModified,\n contentHash: hasher.hash(source),\n symbols,\n edges: [],\n complexity,\n intent: [],\n antiPatterns: [],\n },\n });\n\n processed++;\n if (processed % 50 === 0) {\n console.error(`[ctxo] Processed ${processed}/${files.length} files (symbols)`);\n }\n } catch (err) {\n console.error(`[ctxo] Skipped ${relativePath}: ${(err as Error).message}`);\n }\n }\n\n // Pre-load all sources into ts-morph for cross-file resolution\n const allSources = new Map<string, string>();\n for (const entry of pendingIndices) {\n allSources.set(entry.relativePath, entry.source);\n }\n tsMorphAdapter.loadProjectSources(allSources);\n\n // Phase 1b: Extract edges (uses symbol registry for correct kind resolution)\n for (const entry of pendingIndices) {\n const adapter = registry.getAdapter(entry.relativePath);\n if (!adapter) continue;\n\n try {\n adapter.setSymbolRegistry?.(symbolRegistry);\n entry.fileIndex.edges = adapter.extractEdges(entry.relativePath, entry.source);\n } catch (err) {\n console.error(`[ctxo] Edge extraction failed for ${entry.relativePath}: ${(err as Error).message}`);\n }\n }\n\n // Clean up pre-loaded sources\n tsMorphAdapter.clearProjectSources();\n\n // Phase 2: Batch git history (single git call for all files)\n if (!options.skipHistory && pendingIndices.length > 0) {\n const maxHistory = options.maxHistory ?? 20;\n const batchHistory = await gitAdapter.getBatchHistory?.(maxHistory) ?? new Map<string, import('../core/types.js').CommitRecord[]>();\n\n for (const { relativePath, fileIndex } of pendingIndices) {\n const commits = batchHistory.get(relativePath) ?? [];\n fileIndex.intent = commits.map((c) => ({\n hash: c.hash,\n message: c.message,\n date: c.date,\n kind: 'commit' as const,\n }));\n fileIndex.antiPatterns = revertDetector.detect(commits);\n }\n }\n\n // Phase 2b: Aggregate co-change data from git history\n if (!options.skipHistory && pendingIndices.length > 0) {\n const fileIndices = pendingIndices.map(e => e.fileIndex);\n const coChangeMatrix = aggregateCoChanges(fileIndices);\n writer.writeCoChanges(coChangeMatrix);\n console.error(`[ctxo] Co-change analysis: ${coChangeMatrix.entries.length} file pairs detected`);\n }\n\n // Phase 3: Write all indices\n const indices: FileIndex[] = [];\n for (const { fileIndex } of pendingIndices) {\n writer.write(fileIndex);\n indices.push(fileIndex);\n }\n\n // Write schema version\n schemaManager.writeVersion();\n\n // Populate SQLite cache (skip rebuildFromJson since we just wrote the JSON)\n const storage = new SqliteStorageAdapter(this.ctxoRoot);\n try {\n await storage.initEmpty();\n storage.bulkWrite(indices);\n } finally {\n storage.close();\n }\n\n // Ensure .ctxo/.cache/ is in .gitignore (skip during verify runs)\n if (!options.skipSideEffects) {\n this.ensureGitignore();\n }\n\n console.error(`[ctxo] Index complete: ${processed} files indexed`);\n }\n\n private registerTreeSitterAdapters(registry: LanguageAdapterRegistry): void {\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { GoAdapter } = require('../adapters/language/go-adapter.js');\n registry.register(new GoAdapter());\n } catch {\n console.error('[ctxo] Go adapter unavailable (tree-sitter-go not installed)');\n }\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { CSharpAdapter } = require('../adapters/language/csharp-adapter.js');\n registry.register(new CSharpAdapter());\n } catch {\n console.error('[ctxo] C# adapter unavailable (tree-sitter-c-sharp not installed)');\n }\n }\n\n private discoverFilesIn(root: string): string[] {\n try {\n const output = execFileSync('git', ['ls-files', '--cached', '--others', '--exclude-standard'], {\n cwd: root,\n encoding: 'utf-8',\n maxBuffer: 10 * 1024 * 1024,\n });\n\n return output\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .filter((line) => this.isSupportedExtension(line))\n .map((line) => join(root, line));\n } catch {\n console.error(`[ctxo] git ls-files failed for ${root}`);\n return [];\n }\n }\n\n private discoverWorkspaces(): string[] {\n const pkgPath = join(this.projectRoot, 'package.json');\n if (!existsSync(pkgPath)) return [this.projectRoot];\n\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));\n const workspaces: string[] | undefined = Array.isArray(pkg.workspaces)\n ? pkg.workspaces\n : pkg.workspaces?.packages;\n\n if (!workspaces || workspaces.length === 0) return [this.projectRoot];\n\n // Resolve workspace patterns (supports simple globs like packages/*)\n const resolved: string[] = [];\n for (const ws of workspaces) {\n if (ws.endsWith('/*') || ws.endsWith('\\\\*')) {\n // Glob: packages/* → list subdirectories of packages/\n const parentDir = join(this.projectRoot, ws.slice(0, -2));\n if (existsSync(parentDir)) {\n for (const entry of readdirSync(parentDir, { withFileTypes: true })) {\n if (entry.isDirectory()) {\n resolved.push(join(parentDir, entry.name));\n }\n }\n }\n } else {\n // Literal path\n const wsPath = join(this.projectRoot, ws);\n if (existsSync(wsPath)) {\n resolved.push(wsPath);\n }\n }\n }\n\n if (resolved.length === 0) return [this.projectRoot];\n\n console.error(`[ctxo] Monorepo detected: ${resolved.length} workspace(s)`);\n return resolved;\n } catch {\n return [this.projectRoot];\n }\n }\n\n private isSupportedExtension(filePath: string): boolean {\n const ext = extname(filePath).toLowerCase();\n return this.supportedExtensions.has(ext);\n }\n\n private async runCheck(): Promise<void> {\n console.error('[ctxo] Checking index freshness...');\n\n // Register adapters so supportedExtensions includes .go/.cs\n const registry = new LanguageAdapterRegistry();\n registry.register(new TsMorphAdapter());\n this.registerTreeSitterAdapters(registry);\n this.supportedExtensions = registry.getSupportedExtensions();\n\n const hasher = new ContentHasher();\n const files = this.discoverFilesIn(this.projectRoot);\n const reader = new (await import('../adapters/storage/json-index-reader.js')).JsonIndexReader(this.ctxoRoot);\n const indices = reader.readAll();\n const indexedMap = new Map(indices.map((i) => [i.file, i]));\n\n let staleCount = 0;\n\n for (const filePath of files) {\n if (!this.isSupportedExtension(filePath)) continue;\n\n const relativePath = relative(this.projectRoot, filePath).replace(/\\\\/g, '/');\n const indexed = indexedMap.get(relativePath);\n\n if (!indexed) {\n console.error(`[ctxo] NOT INDEXED: ${relativePath}`);\n staleCount++;\n continue;\n }\n\n // Guard: file may be deleted from disk but still tracked by git\n if (!existsSync(filePath)) {\n console.error(`[ctxo] DELETED: ${relativePath}`);\n staleCount++;\n continue;\n }\n\n // Fast path: mtime check (skip hash if mtime hasn't changed)\n const mtime = Math.floor(statSync(filePath).mtimeMs / 1000);\n if (mtime <= indexed.lastModified) continue;\n\n // Slow path: hash-based verification (handles git checkout, cp -p, CI)\n if (indexed.contentHash) {\n const source = readFileSync(filePath, 'utf-8');\n const currentHash = hasher.hash(source);\n if (currentHash === indexed.contentHash) continue;\n }\n\n console.error(`[ctxo] STALE: ${relativePath}`);\n staleCount++;\n }\n\n if (staleCount > 0) {\n console.error(`[ctxo] ${staleCount} file(s) need re-indexing. Run \"ctxo index\"`);\n process.exit(1);\n }\n\n console.error('[ctxo] Index is up to date');\n }\n\n private ensureGitignore(): void {\n const gitignorePath = join(this.projectRoot, '.gitignore');\n const cachePattern = '.ctxo/.cache/';\n const suffix = `\\n# Ctxo local cache (never committed)\\n${cachePattern}\\n`;\n\n // Read-modify-write atomically to avoid TOCTOU race\n const existing = existsSync(gitignorePath) ? readFileSync(gitignorePath, 'utf-8') : '';\n if (existing.includes(cachePattern)) return;\n\n writeFileSync(gitignorePath, existing + suffix, 'utf-8');\n console.error('[ctxo] Added .ctxo/.cache/ to .gitignore');\n }\n}\n","import { createHash } from 'node:crypto';\n\nexport class ContentHasher {\n hash(content: string): string {\n return createHash('sha256').update(content, 'utf-8').digest('hex');\n }\n}\n","import {\n Project,\n SyntaxKind,\n Node,\n type SourceFile,\n type FunctionDeclaration,\n type MethodDeclaration,\n ScriptTarget,\n} from 'ts-morph';\nimport { extname, dirname, join, normalize } from 'node:path';\nimport { type SymbolNode, type GraphEdge, type ComplexityMetrics, type SymbolKind, SYMBOL_KINDS } from '../../core/types.js';\nimport type { ILanguageAdapter } from '../../ports/i-language-adapter.js';\n\nconst SUPPORTED_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx'] as const;\n\nexport class TsMorphAdapter implements ILanguageAdapter {\n readonly extensions = SUPPORTED_EXTENSIONS;\n readonly tier = 'full' as const;\n\n private readonly project: Project;\n private symbolRegistry = new Map<string, SymbolKind>();\n private projectPreloaded = false;\n\n constructor() {\n this.project = new Project({\n compilerOptions: {\n target: ScriptTarget.ES2022,\n allowJs: true,\n jsx: 2, // React\n skipLibCheck: true,\n },\n useInMemoryFileSystem: true,\n });\n }\n\n isSupported(filePath: string): boolean {\n const ext = extname(filePath).toLowerCase();\n return (SUPPORTED_EXTENSIONS as readonly string[]).includes(ext);\n }\n\n setSymbolRegistry(registry: Map<string, SymbolKind>): void {\n this.symbolRegistry = registry;\n }\n\n loadProjectSources(files: Map<string, string>): void {\n for (const [filePath, source] of files) {\n try {\n const existing = this.project.getSourceFile(filePath);\n if (existing) this.project.removeSourceFile(existing);\n this.project.createSourceFile(filePath, source, { overwrite: true });\n } catch (err) {\n console.error(`[ctxo:ts-morph] Failed to preload ${filePath}: ${(err as Error).message}`);\n }\n }\n this.projectPreloaded = true;\n }\n\n clearProjectSources(): void {\n for (const sf of this.project.getSourceFiles()) {\n this.project.removeSourceFile(sf);\n }\n this.projectPreloaded = false;\n }\n\n extractSymbols(filePath: string, source: string): SymbolNode[] {\n const sourceFile = this.parseSource(filePath, source);\n if (!sourceFile) return [];\n\n try {\n const symbols: SymbolNode[] = [];\n\n this.extractFunctions(sourceFile, filePath, symbols);\n this.extractClasses(sourceFile, filePath, symbols);\n this.extractInterfaces(sourceFile, filePath, symbols);\n this.extractTypeAliases(sourceFile, filePath, symbols);\n this.extractVariables(sourceFile, filePath, symbols);\n\n return symbols;\n } catch (err) {\n console.error(`[ctxo:ts-morph] Symbol extraction failed for ${filePath}: ${(err as Error).message}`);\n return [];\n } finally {\n this.cleanupSourceFile(filePath);\n }\n }\n\n extractEdges(filePath: string, source: string): GraphEdge[] {\n const sourceFile = this.parseSource(filePath, source);\n if (!sourceFile) return [];\n\n try {\n const edges: GraphEdge[] = [];\n\n this.extractImportEdges(sourceFile, filePath, edges);\n this.extractInheritanceEdges(sourceFile, filePath, edges);\n this.extractCallEdges(sourceFile, filePath, edges);\n this.extractReferenceEdges(sourceFile, filePath, edges);\n\n return edges;\n } catch (err) {\n console.error(`[ctxo:ts-morph] Edge extraction failed for ${filePath}: ${(err as Error).message}`);\n return [];\n } finally {\n if (!this.projectPreloaded) {\n this.cleanupSourceFile(filePath);\n }\n }\n }\n\n extractComplexity(filePath: string, source: string): ComplexityMetrics[] {\n const sourceFile = this.parseSource(filePath, source);\n if (!sourceFile) return [];\n\n try {\n const metrics: ComplexityMetrics[] = [];\n\n for (const fn of sourceFile.getFunctions()) {\n if (!this.isExported(fn)) continue;\n const name = fn.getName();\n if (!name) continue;\n const symbolId = this.buildSymbolId(filePath, name, 'function');\n metrics.push({ symbolId, cyclomatic: this.countCyclomaticComplexity(fn) });\n }\n\n for (const cls of sourceFile.getClasses()) {\n const className = cls.getName();\n if (!className || !this.isExported(cls)) continue;\n\n for (const method of cls.getMethods()) {\n const methodName = method.getName();\n const symbolId = this.buildSymbolId(filePath, `${className}.${methodName}`, 'method');\n metrics.push({ symbolId, cyclomatic: this.countCyclomaticComplexity(method) });\n }\n }\n\n return metrics;\n } catch (err) {\n console.error(`[ctxo:ts-morph] Complexity extraction failed for ${filePath}: ${(err as Error).message}`);\n return [];\n } finally {\n this.cleanupSourceFile(filePath);\n }\n }\n\n // ── Symbol Extraction ───────────────────────────────────────\n\n private extractFunctions(\n sourceFile: SourceFile,\n filePath: string,\n symbols: SymbolNode[],\n ): void {\n for (const fn of sourceFile.getFunctions()) {\n if (!this.isExported(fn)) continue;\n const name = fn.getName();\n if (!name) continue;\n\n symbols.push({\n symbolId: this.buildSymbolId(filePath, name, 'function'),\n name,\n kind: 'function',\n startLine: fn.getStartLineNumber() - 1,\n endLine: fn.getEndLineNumber() - 1,\n startOffset: fn.getStart(),\n endOffset: fn.getEnd(),\n });\n }\n }\n\n private extractClasses(\n sourceFile: SourceFile,\n filePath: string,\n symbols: SymbolNode[],\n ): void {\n for (const cls of sourceFile.getClasses()) {\n const name = cls.getName();\n if (!name || !this.isExported(cls)) continue;\n\n symbols.push({\n symbolId: this.buildSymbolId(filePath, name, 'class'),\n name,\n kind: 'class',\n startLine: cls.getStartLineNumber() - 1,\n endLine: cls.getEndLineNumber() - 1,\n startOffset: cls.getStart(),\n endOffset: cls.getEnd(),\n });\n\n // Extract methods\n for (const method of cls.getMethods()) {\n const methodName = method.getName();\n symbols.push({\n symbolId: this.buildSymbolId(filePath, `${name}.${methodName}`, 'method'),\n name: `${name}.${methodName}`,\n kind: 'method',\n startLine: method.getStartLineNumber() - 1,\n endLine: method.getEndLineNumber() - 1,\n startOffset: method.getStart(),\n endOffset: method.getEnd(),\n });\n }\n }\n }\n\n private extractInterfaces(\n sourceFile: SourceFile,\n filePath: string,\n symbols: SymbolNode[],\n ): void {\n for (const iface of sourceFile.getInterfaces()) {\n if (!this.isExported(iface)) continue;\n const name = iface.getName();\n\n symbols.push({\n symbolId: this.buildSymbolId(filePath, name, 'interface'),\n name,\n kind: 'interface',\n startLine: iface.getStartLineNumber() - 1,\n endLine: iface.getEndLineNumber() - 1,\n startOffset: iface.getStart(),\n endOffset: iface.getEnd(),\n });\n }\n }\n\n private extractTypeAliases(\n sourceFile: SourceFile,\n filePath: string,\n symbols: SymbolNode[],\n ): void {\n for (const typeAlias of sourceFile.getTypeAliases()) {\n if (!this.isExported(typeAlias)) continue;\n const name = typeAlias.getName();\n\n symbols.push({\n symbolId: this.buildSymbolId(filePath, name, 'type'),\n name,\n kind: 'type',\n startLine: typeAlias.getStartLineNumber() - 1,\n endLine: typeAlias.getEndLineNumber() - 1,\n startOffset: typeAlias.getStart(),\n endOffset: typeAlias.getEnd(),\n });\n }\n }\n\n private extractVariables(\n sourceFile: SourceFile,\n filePath: string,\n symbols: SymbolNode[],\n ): void {\n for (const stmt of sourceFile.getVariableStatements()) {\n if (!this.isExported(stmt)) continue;\n\n for (const decl of stmt.getDeclarations()) {\n const name = decl.getName();\n\n symbols.push({\n symbolId: this.buildSymbolId(filePath, name, 'variable'),\n name,\n kind: 'variable',\n startLine: stmt.getStartLineNumber() - 1,\n endLine: stmt.getEndLineNumber() - 1,\n startOffset: decl.getStart(),\n endOffset: decl.getEnd(),\n });\n }\n }\n }\n\n // ── Edge Extraction ─────────────────────────────────────────\n\n private extractImportEdges(\n sourceFile: SourceFile,\n filePath: string,\n edges: GraphEdge[],\n ): void {\n // BUG-1 FIX: use sourceFile directly instead of project lookup (file may be cleaned up)\n const fileSymbolId = this.buildSymbolId(filePath, sourceFile.getBaseName().replace(/\\.[^.]+$/, ''), 'variable');\n const fromSymbols = this.getExportedSymbolIds(sourceFile, filePath);\n const fromSymbol = fromSymbols.length > 0 ? fromSymbols[0]! : fileSymbolId;\n\n for (const imp of sourceFile.getImportDeclarations()) {\n const moduleSpecifier = imp.getModuleSpecifierValue();\n\n // Only track local imports (relative paths)\n if (!moduleSpecifier.startsWith('.') && !moduleSpecifier.startsWith('/')) {\n continue;\n }\n\n // Resolve relative import to project-relative path\n const normalizedTarget = this.resolveRelativeImport(filePath, moduleSpecifier);\n\n // SCHEMA-40 FIX: detect type-only imports\n const isTypeOnly = imp.isTypeOnly();\n\n for (const named of imp.getNamedImports()) {\n const importedName = named.getName();\n const edge: GraphEdge = {\n from: fromSymbol,\n to: this.resolveImportTarget(normalizedTarget, importedName),\n kind: 'imports',\n };\n if (isTypeOnly || named.isTypeOnly()) edge.typeOnly = true;\n edges.push(edge);\n }\n\n const defaultImport = imp.getDefaultImport();\n if (defaultImport) {\n const edge: GraphEdge = {\n from: fromSymbol,\n to: this.resolveImportTarget(normalizedTarget, defaultImport.getText()),\n kind: 'imports',\n };\n if (isTypeOnly) edge.typeOnly = true;\n edges.push(edge);\n }\n\n // GAP-3 FIX: namespace imports (import * as X from './mod')\n const nsImport = imp.getNamespaceImport();\n if (nsImport) {\n const edge: GraphEdge = {\n from: fromSymbol,\n to: this.buildSymbolId(normalizedTarget, nsImport.getText(), 'variable'),\n kind: 'imports',\n };\n if (isTypeOnly) edge.typeOnly = true;\n edges.push(edge);\n }\n }\n }\n\n private extractInheritanceEdges(\n sourceFile: SourceFile,\n filePath: string,\n edges: GraphEdge[],\n ): void {\n for (const cls of sourceFile.getClasses()) {\n const className = cls.getName();\n if (!className || !this.isExported(cls)) continue;\n\n const classSymbolId = this.buildSymbolId(filePath, className, 'class');\n\n // extends\n const baseClass = cls.getExtends();\n if (baseClass) {\n // BUG-17 FIX: strip generic type arguments (Base<string> → Base)\n const baseName = baseClass.getExpression().getText().replace(/<.*>$/, '');\n edges.push({\n from: classSymbolId,\n to: this.resolveSymbolReference(sourceFile, baseName, 'class'),\n kind: 'extends',\n });\n }\n\n // implements\n for (const impl of cls.getImplements()) {\n // BUG-18 FIX: strip generic type arguments (IRepo<User> → IRepo)\n const ifaceName = impl.getExpression().getText().replace(/<.*>$/, '');\n edges.push({\n from: classSymbolId,\n to: this.resolveSymbolReference(sourceFile, ifaceName, 'interface'),\n kind: 'implements',\n });\n }\n }\n }\n\n private extractCallEdges(\n sourceFile: SourceFile,\n filePath: string,\n edges: GraphEdge[],\n ): void {\n // Extract function call edges from exported functions and methods\n for (const fn of sourceFile.getFunctions()) {\n if (!this.isExported(fn)) continue;\n const fnName = fn.getName();\n if (!fnName) continue;\n\n const fnSymbolId = this.buildSymbolId(filePath, fnName, 'function');\n\n for (const call of fn.getDescendantsOfKind(SyntaxKind.CallExpression)) {\n const calledName = call.getExpression().getText().split('.').pop();\n if (!calledName || calledName === fnName) continue;\n\n const resolved = this.resolveLocalCallTarget(sourceFile, filePath, calledName);\n if (resolved) {\n edges.push({ from: fnSymbolId, to: resolved, kind: 'calls' });\n }\n }\n\n // GAP-11 FIX: constructor calls (new Foo())\n for (const newExpr of fn.getDescendantsOfKind(SyntaxKind.NewExpression)) {\n const calledName = newExpr.getExpression().getText().split('.').pop();\n if (!calledName) continue;\n\n const resolved = this.resolveLocalCallTarget(sourceFile, filePath, calledName);\n if (resolved) {\n edges.push({ from: fnSymbolId, to: resolved, kind: 'calls' });\n }\n }\n }\n\n // Extract calls from class methods\n for (const cls of sourceFile.getClasses()) {\n const className = cls.getName();\n if (!className || !this.isExported(cls)) continue;\n\n for (const method of cls.getMethods()) {\n const methodName = method.getName();\n const methodSymbolId = this.buildSymbolId(filePath, `${className}.${methodName}`, 'method');\n\n for (const call of method.getDescendantsOfKind(SyntaxKind.CallExpression)) {\n const calledText = call.getExpression().getText();\n const calledName = calledText.split('.').pop();\n if (!calledName || calledName === methodName) continue;\n\n let resolved: string | undefined;\n if (calledText.startsWith('this.')) {\n resolved = this.resolveThisMethodCall(sourceFile, filePath, className, calledName);\n } else {\n resolved = this.resolveLocalCallTarget(sourceFile, filePath, calledName);\n }\n if (resolved) {\n edges.push({ from: methodSymbolId, to: resolved, kind: 'calls' });\n }\n }\n\n // GAP-11 FIX: constructor calls from methods (new Foo())\n for (const newExpr of method.getDescendantsOfKind(SyntaxKind.NewExpression)) {\n const calledText = newExpr.getExpression().getText();\n const calledName = calledText.split('.').pop();\n if (!calledName) continue;\n\n let resolved: string | undefined;\n if (calledText.startsWith('this.')) {\n resolved = this.resolveThisMethodCall(sourceFile, filePath, className, calledName);\n } else {\n resolved = this.resolveLocalCallTarget(sourceFile, filePath, calledName);\n }\n if (resolved) {\n edges.push({ from: methodSymbolId, to: resolved, kind: 'calls' });\n }\n }\n }\n }\n }\n\n private extractReferenceEdges(\n sourceFile: SourceFile,\n filePath: string,\n edges: GraphEdge[],\n ): void {\n // Build map of all named imports from local modules: importedName → resolved symbolId\n const importMap = new Map<string, string>();\n for (const imp of sourceFile.getImportDeclarations()) {\n const mod = imp.getModuleSpecifierValue();\n if (!mod.startsWith('.') && !mod.startsWith('/')) continue;\n const targetFile = this.resolveRelativeImport(filePath, mod);\n for (const named of imp.getNamedImports()) {\n importMap.set(named.getName(), this.resolveImportTarget(targetFile, named.getName()));\n }\n const defaultImport = imp.getDefaultImport();\n if (defaultImport) {\n importMap.set(defaultImport.getText(), this.resolveImportTarget(targetFile, defaultImport.getText()));\n }\n }\n if (importMap.size === 0) return;\n\n // Scan each exported symbol's body for identifier references to imports\n for (const fn of sourceFile.getFunctions()) {\n if (!this.isExported(fn)) continue;\n const fnName = fn.getName();\n if (!fnName) continue;\n const fromId = this.buildSymbolId(filePath, fnName, 'function');\n this.emitUsesEdges(fn, fromId, importMap, edges);\n }\n\n for (const cls of sourceFile.getClasses()) {\n if (!this.isExported(cls)) continue;\n const className = cls.getName();\n if (!className) continue;\n\n // Class-level references (property types, constructor params)\n const classId = this.buildSymbolId(filePath, className, 'class');\n this.emitUsesEdges(cls, classId, importMap, edges);\n }\n }\n\n private emitUsesEdges(\n node: Node,\n fromId: string,\n importMap: Map<string, string>,\n edges: GraphEdge[],\n ): void {\n const seen = new Set<string>();\n for (const id of node.getDescendantsOfKind(SyntaxKind.Identifier)) {\n const name = id.getText();\n if (seen.has(name)) continue;\n const target = importMap.get(name);\n if (target) {\n seen.add(name);\n edges.push({ from: fromId, to: target, kind: 'uses' });\n }\n }\n }\n\n private resolveLocalCallTarget(\n sourceFile: SourceFile,\n filePath: string,\n calledName: string,\n ): string | undefined {\n // Check if the called name is imported from a local module\n for (const imp of sourceFile.getImportDeclarations()) {\n const moduleSpecifier = imp.getModuleSpecifierValue();\n if (!moduleSpecifier.startsWith('.') && !moduleSpecifier.startsWith('/')) continue;\n\n for (const named of imp.getNamedImports()) {\n if (named.getName() === calledName) {\n const targetFile = this.resolveRelativeImport(filePath, moduleSpecifier);\n return this.resolveImportTarget(targetFile, calledName);\n }\n }\n }\n\n // Check if it's a locally defined function in the same file\n for (const fn of sourceFile.getFunctions()) {\n if (fn.getName() === calledName) {\n return this.buildSymbolId(filePath, calledName, 'function');\n }\n }\n\n return undefined;\n }\n\n private resolveThisMethodCall(\n sourceFile: SourceFile,\n filePath: string,\n className: string,\n calledName: string,\n ): string | undefined {\n for (const cls of sourceFile.getClasses()) {\n if (cls.getName() !== className) continue;\n for (const method of cls.getMethods()) {\n if (method.getName() === calledName) {\n return this.buildSymbolId(filePath, `${className}.${calledName}`, 'method');\n }\n }\n }\n return undefined;\n }\n\n // ── Helpers ─────────────────────────────────────────────────\n\n private parseSource(filePath: string, source: string): SourceFile | undefined {\n try {\n const existing = this.project.getSourceFile(filePath);\n if (existing && this.projectPreloaded) {\n return existing;\n }\n if (existing) {\n this.project.removeSourceFile(existing);\n }\n return this.project.createSourceFile(filePath, source, { overwrite: true });\n } catch (err) {\n console.error(`[ctxo:ts-morph] Parse failed for ${filePath}: ${(err as Error).message}`);\n return undefined;\n }\n }\n\n private cleanupSourceFile(filePath: string): void {\n const existing = this.project.getSourceFile(filePath);\n if (existing) {\n this.project.removeSourceFile(existing);\n }\n }\n\n private buildSymbolId(filePath: string, name: string, kind: SymbolKind): string {\n return `${filePath}::${name}::${kind}`;\n }\n\n private resolveRelativeImport(fromFile: string, moduleSpecifier: string): string {\n // Convert relative import like '../types.js' to project-relative 'src/core/types.ts'\n const fromDir = dirname(fromFile);\n let resolved = normalize(join(fromDir, moduleSpecifier)).replace(/\\\\/g, '/');\n\n // Strip .js extension (TypeScript imports use .js but source files are .ts)\n if (resolved.endsWith('.js')) {\n resolved = resolved.slice(0, -3) + '.ts';\n } else if (resolved.endsWith('.jsx')) {\n resolved = resolved.slice(0, -4) + '.tsx';\n } else if (!extname(resolved)) {\n resolved += '.ts';\n }\n\n return resolved;\n }\n\n private resolveImportTarget(targetFile: string, name: string): string {\n // BUG-8/9 FIX: check symbol registry first (populated from Phase 1 of indexing)\n const prefix = `${targetFile}::${name}::`;\n for (const kind of SYMBOL_KINDS) {\n if (this.symbolRegistry.has(`${prefix}${kind}`)) {\n return `${prefix}${kind}`;\n }\n }\n\n // Try to find the symbol in the already-parsed project to get the correct kind\n const targetSourceFile = this.project.getSourceFile(targetFile);\n if (targetSourceFile) {\n for (const fn of targetSourceFile.getFunctions()) {\n if (fn.getName() === name && this.isExported(fn)) {\n return this.buildSymbolId(targetFile, name, 'function');\n }\n }\n for (const cls of targetSourceFile.getClasses()) {\n if (cls.getName() === name && this.isExported(cls)) {\n return this.buildSymbolId(targetFile, name, 'class');\n }\n }\n for (const iface of targetSourceFile.getInterfaces()) {\n if (iface.getName() === name && this.isExported(iface)) {\n return this.buildSymbolId(targetFile, name, 'interface');\n }\n }\n for (const t of targetSourceFile.getTypeAliases()) {\n if (t.getName() === name && this.isExported(t)) {\n return this.buildSymbolId(targetFile, name, 'type');\n }\n }\n }\n // Fallback: infer kind from naming conventions\n const kind = this.inferSymbolKind(name);\n return `${targetFile}::${name}::${kind}`;\n }\n\n private resolveSymbolReference(\n sourceFile: SourceFile,\n name: string,\n defaultKind: SymbolKind,\n ): string {\n // Check if the name is imported\n for (const imp of sourceFile.getImportDeclarations()) {\n const moduleSpecifier = imp.getModuleSpecifierValue();\n if (!moduleSpecifier.startsWith('.') && !moduleSpecifier.startsWith('/')) continue;\n\n for (const named of imp.getNamedImports()) {\n if (named.getName() === name) {\n const resolved = imp.getModuleSpecifierSourceFile()?.getFilePath();\n if (resolved) {\n return `${this.normalizeFilePath(resolved)}::${name}::${defaultKind}`;\n }\n // Fallback: resolve relative module specifier manually\n const sourceDir = dirname(this.normalizeFilePath(sourceFile.getFilePath()));\n const resolvedPath = normalize(join(sourceDir, moduleSpecifier))\n .replace(/\\\\/g, '/')\n .replace(/\\.jsx$/, '.tsx')\n .replace(/\\.js$/, '.ts');\n return `${resolvedPath}::${name}::${defaultKind}`;\n }\n }\n }\n\n // Assume it's in the same file\n return `${sourceFile.getFilePath()}::${name}::${defaultKind}`;\n }\n\n private inferSymbolKind(name: string): SymbolKind {\n // Interface: starts with I followed by uppercase (IStoragePort, IGitPort)\n if (/^I[A-Z]/.test(name) && name.length > 2) return 'interface';\n // All caps with underscores: variable/constant (MAX_AMOUNT, EDGE_KINDS)\n if (/^[A-Z][A-Z_0-9]+$/.test(name)) return 'variable';\n // PascalCase: could be class, interface, or type — default to class\n if (/^[A-Z]/.test(name)) return 'class';\n // camelCase: function\n return 'function';\n }\n\n private normalizeFilePath(filePath: string): string {\n // Remove leading / from in-memory file system paths\n return filePath.replace(/^\\//, '');\n }\n\n private getExportedSymbolIds(sourceFile: SourceFile, filePath: string): string[] {\n const ids: string[] = [];\n for (const fn of sourceFile.getFunctions()) {\n if (!this.isExported(fn)) continue;\n const name = fn.getName();\n if (name) ids.push(this.buildSymbolId(filePath, name, 'function'));\n }\n for (const cls of sourceFile.getClasses()) {\n if (!this.isExported(cls)) continue;\n const name = cls.getName();\n if (name) ids.push(this.buildSymbolId(filePath, name, 'class'));\n }\n for (const iface of sourceFile.getInterfaces()) {\n if (!this.isExported(iface)) continue;\n ids.push(this.buildSymbolId(filePath, iface.getName(), 'interface'));\n }\n for (const t of sourceFile.getTypeAliases()) {\n if (!this.isExported(t)) continue;\n ids.push(this.buildSymbolId(filePath, t.getName(), 'type'));\n }\n for (const stmt of sourceFile.getVariableStatements()) {\n if (!this.isExported(stmt)) continue;\n for (const decl of stmt.getDeclarations()) {\n ids.push(this.buildSymbolId(filePath, decl.getName(), 'variable'));\n }\n }\n return ids;\n }\n\n private isExported(node: Node): boolean {\n if (Node.isExportable(node)) {\n return node.isExported();\n }\n return false;\n }\n\n private countCyclomaticComplexity(node: FunctionDeclaration | MethodDeclaration): number {\n let complexity = 1;\n\n node.forEachDescendant((child) => {\n switch (child.getKind()) {\n case SyntaxKind.IfStatement:\n case SyntaxKind.ConditionalExpression:\n case SyntaxKind.ForStatement:\n case SyntaxKind.ForInStatement:\n case SyntaxKind.ForOfStatement:\n case SyntaxKind.WhileStatement:\n case SyntaxKind.DoStatement:\n case SyntaxKind.CaseClause:\n case SyntaxKind.CatchClause:\n case SyntaxKind.BinaryExpression: {\n const text = child.getText();\n if (child.getKind() === SyntaxKind.BinaryExpression) {\n if (text.includes('&&') || text.includes('||') || text.includes('??')) {\n complexity++;\n }\n } else {\n complexity++;\n }\n break;\n }\n }\n });\n\n return complexity;\n }\n}\n","import { extname } from 'node:path';\nimport type { ILanguageAdapter } from '../../ports/i-language-adapter.js';\n\nexport class LanguageAdapterRegistry {\n private readonly adaptersByExtension = new Map<string, ILanguageAdapter>();\n\n register(adapter: ILanguageAdapter): void {\n for (const ext of adapter.extensions) {\n this.adaptersByExtension.set(ext.toLowerCase(), adapter);\n }\n }\n\n getSupportedExtensions(): Set<string> {\n return new Set(this.adaptersByExtension.keys());\n }\n\n getAdapter(filePath: string): ILanguageAdapter | undefined {\n if (!filePath) return undefined;\n\n const ext = extname(filePath).toLowerCase();\n if (!ext) return undefined;\n\n return this.adaptersByExtension.get(ext);\n }\n}\n","import { writeFileSync, renameSync, mkdirSync, unlinkSync, existsSync } from 'node:fs';\nimport { dirname, join, resolve, sep } from 'node:path';\nimport type { FileIndex, CoChangeMatrix } from '../../core/types.js';\n\nexport class JsonIndexWriter {\n private readonly indexDir: string;\n\n constructor(ctxoRoot: string) {\n this.indexDir = join(ctxoRoot, 'index');\n }\n\n write(fileIndex: FileIndex): void {\n if (!fileIndex.file) {\n throw new Error('FileIndex.file must not be empty');\n }\n\n const targetPath = this.resolveIndexPath(fileIndex.file);\n mkdirSync(dirname(targetPath), { recursive: true });\n\n const sorted = this.sortKeys(fileIndex);\n const json = JSON.stringify(sorted, null, 2);\n this.atomicWrite(targetPath, json);\n }\n\n writeCoChanges(matrix: CoChangeMatrix): void {\n mkdirSync(this.indexDir, { recursive: true });\n const targetPath = join(this.indexDir, 'co-changes.json');\n this.atomicWrite(targetPath, JSON.stringify(matrix, null, 2));\n }\n\n private atomicWrite(targetPath: string, content: string): void {\n const tmpPath = `${targetPath}.${process.pid}.tmp`;\n writeFileSync(tmpPath, content, 'utf-8');\n renameSync(tmpPath, targetPath);\n }\n\n delete(relativePath: string): void {\n const targetPath = this.resolveIndexPath(relativePath);\n if (existsSync(targetPath)) {\n unlinkSync(targetPath);\n }\n }\n\n private resolveIndexPath(relativePath: string): string {\n const resolved = resolve(this.indexDir, `${relativePath}.json`);\n const normalizedDir = resolve(this.indexDir) + sep;\n if (!resolved.startsWith(normalizedDir)) {\n throw new Error(`Path traversal detected: ${relativePath}`);\n }\n return resolved;\n }\n\n private sortKeys(obj: unknown): unknown {\n if (Array.isArray(obj)) {\n return obj.map((item) => this.sortKeys(item));\n }\n if (obj !== null && typeof obj === 'object') {\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(obj).sort()) {\n sorted[key] = this.sortKeys((obj as Record<string, unknown>)[key]);\n }\n return sorted;\n }\n return obj;\n }\n}\n","import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';\nimport { join, dirname } from 'node:path';\n\nconst CURRENT_SCHEMA_VERSION = '1.0.0';\n\nexport class SchemaManager {\n private readonly versionFilePath: string;\n\n constructor(ctxoRoot: string) {\n this.versionFilePath = join(ctxoRoot, 'index', 'schema-version');\n }\n\n currentVersion(): string {\n return CURRENT_SCHEMA_VERSION;\n }\n\n readStoredVersion(): string | undefined {\n if (!existsSync(this.versionFilePath)) {\n return undefined;\n }\n return readFileSync(this.versionFilePath, 'utf-8').trim();\n }\n\n writeVersion(): void {\n mkdirSync(dirname(this.versionFilePath), { recursive: true });\n writeFileSync(this.versionFilePath, CURRENT_SCHEMA_VERSION, 'utf-8');\n }\n\n isCompatible(): boolean {\n const stored = this.readStoredVersion();\n if (!stored) return false;\n return stored === CURRENT_SCHEMA_VERSION;\n }\n}\n","import { join } from 'node:path';\nimport { SqliteStorageAdapter } from '../adapters/storage/sqlite-storage-adapter.js';\n\nexport class SyncCommand {\n private readonly ctxoRoot: string;\n\n constructor(projectRoot: string) {\n this.ctxoRoot = join(projectRoot, '.ctxo');\n }\n\n async run(): Promise<void> {\n console.error('[ctxo] Rebuilding SQLite cache from committed JSON index...');\n\n const storage = new SqliteStorageAdapter(this.ctxoRoot);\n try {\n await storage.init();\n } finally {\n storage.close();\n }\n\n console.error('[ctxo] Sync complete');\n }\n}\n","import { join } from 'node:path';\nimport { existsSync } from 'node:fs';\nimport { execFileSync } from 'node:child_process';\nimport { JsonIndexReader } from '../adapters/storage/json-index-reader.js';\nimport { SchemaManager } from '../adapters/storage/schema-manager.js';\n\nexport class StatusCommand {\n private readonly projectRoot: string;\n private readonly ctxoRoot: string;\n\n constructor(projectRoot: string) {\n this.projectRoot = projectRoot;\n this.ctxoRoot = join(projectRoot, '.ctxo');\n }\n\n run(): void {\n const indexDir = join(this.ctxoRoot, 'index');\n\n if (!existsSync(indexDir)) {\n console.error('[ctxo] No index found. Run \"ctxo index\" first.');\n return;\n }\n\n const schemaManager = new SchemaManager(this.ctxoRoot);\n const version = schemaManager.readStoredVersion() ?? 'unknown';\n\n const reader = new JsonIndexReader(this.ctxoRoot);\n const indices = reader.readAll();\n\n const totalSymbols = indices.reduce((sum, idx) => sum + idx.symbols.length, 0);\n const totalEdges = indices.reduce((sum, idx) => sum + idx.edges.length, 0);\n\n console.error(`[ctxo] Index Status`);\n console.error(` Schema version: ${version}`);\n console.error(` Indexed files: ${indices.length}`);\n console.error(` Total symbols: ${totalSymbols}`);\n console.error(` Total edges: ${totalEdges}`);\n\n const cacheExists = existsSync(join(this.ctxoRoot, '.cache', 'symbols.db'));\n console.error(` SQLite cache: ${cacheExists ? 'present' : 'missing (run ctxo sync)'}`);\n\n // Per-file listing with timestamps\n if (indices.length > 0) {\n console.error('');\n console.error(' Files:');\n\n // Get source files to detect orphans\n const sourceFiles = this.getSourceFiles();\n\n for (const idx of indices.sort((a, b) => a.file.localeCompare(b.file))) {\n const ts = new Date(idx.lastModified * 1000).toISOString();\n const isOrphaned = sourceFiles.size > 0 && !sourceFiles.has(idx.file);\n const badge = isOrphaned ? ' [orphaned]' : '';\n console.error(` ${idx.file} ${ts} (${idx.symbols.length} symbols, ${idx.edges.length} edges)${badge}`);\n }\n }\n }\n\n private getSourceFiles(): Set<string> {\n try {\n const output = execFileSync('git', ['ls-files', '--cached', '--others', '--exclude-standard'], {\n cwd: this.projectRoot,\n encoding: 'utf-8',\n });\n return new Set(output.split('\\n').map((l) => l.trim()).filter((l) => l.length > 0));\n } catch {\n return new Set();\n }\n }\n}\n","import { mkdtempSync, rmSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { tmpdir } from 'node:os';\nimport { IndexCommand } from './index-command.js';\nimport { JsonIndexReader } from '../adapters/storage/json-index-reader.js';\n\nexport class VerifyCommand {\n private readonly projectRoot: string;\n\n constructor(projectRoot: string) {\n this.projectRoot = projectRoot;\n }\n\n async run(): Promise<void> {\n console.error('[ctxo] Verifying index freshness...');\n\n // Build index into a temp directory to avoid overwriting committed index\n const tempDir = mkdtempSync(join(tmpdir(), 'ctxo-verify-'));\n\n try {\n const tempCtxo = join(tempDir, '.ctxo');\n\n // Run index into temp .ctxo (does not touch committed index)\n const indexCmd = new IndexCommand(this.projectRoot, tempCtxo);\n await indexCmd.run({ skipSideEffects: true });\n\n // Compare temp index with committed index\n const committedReader = new JsonIndexReader(join(this.projectRoot, '.ctxo'));\n const freshReader = new JsonIndexReader(tempCtxo);\n\n const committedIndices = committedReader.readAll();\n const freshIndices = freshReader.readAll();\n\n // Compare full index: symbols + edges + intent + antiPatterns\n const serialize = (i: { symbols: unknown; edges: unknown; intent: unknown; antiPatterns: unknown }) =>\n JSON.stringify({ symbols: i.symbols, edges: i.edges, intent: i.intent, antiPatterns: i.antiPatterns });\n\n const committedMap = new Map(committedIndices.map((i) => [i.file, serialize(i)]));\n const freshMap = new Map(freshIndices.map((i) => [i.file, serialize(i)]));\n\n let stale = false;\n\n // Check for files that changed or were added\n for (const [file, freshData] of freshMap) {\n const committed = committedMap.get(file);\n if (committed !== freshData) {\n console.error(`[ctxo] STALE: ${file}`);\n stale = true;\n }\n }\n\n // Check for files that were removed\n for (const file of committedMap.keys()) {\n if (!freshMap.has(file)) {\n console.error(`[ctxo] REMOVED: ${file}`);\n stale = true;\n }\n }\n\n if (stale) {\n console.error('[ctxo] Index is STALE — run \"ctxo index\" and commit .ctxo/index/');\n process.exit(1);\n }\n\n console.error('[ctxo] Index is up to date');\n } finally {\n rmSync(tempDir, { recursive: true, force: true });\n }\n }\n}\n","import { join } from 'node:path';\nimport { existsSync, readFileSync, writeFileSync, mkdirSync, chmodSync } from 'node:fs';\nimport { PLATFORMS, detectPlatforms, installRules, ensureGitignore, ensureConfig } from './ai-rules.js';\n\n/* ------------------------------------------------------------------ */\n/* Git hook content */\n/* ------------------------------------------------------------------ */\n\nconst CTXO_START = '# ctxo-start';\nconst CTXO_END = '# ctxo-end';\n\nconst POST_COMMIT_CONTENT = `\n${CTXO_START}\n# Incremental re-index on commit (only changed files)\nif command -v ctxo >/dev/null 2>&1; then\n for file in $(git diff --name-only HEAD~1 HEAD 2>/dev/null); do\n ctxo index --file \"$file\" 2>/dev/null || true\n done\nfi\n${CTXO_END}\n`.trim();\n\nconst POST_MERGE_CONTENT = `\n${CTXO_START}\n# Rebuild SQLite cache after merge (index updated via git pull)\nif command -v ctxo >/dev/null 2>&1; then\n ctxo sync 2>/dev/null || true\nfi\n${CTXO_END}\n`.trim();\n\n/* ------------------------------------------------------------------ */\n/* Options */\n/* ------------------------------------------------------------------ */\n\nexport interface InitOptions {\n tools?: string[];\n yes?: boolean;\n rulesOnly?: boolean;\n dryRun?: boolean;\n}\n\n/* ------------------------------------------------------------------ */\n/* Terminal UI helpers (zero dependency — picocolors only) */\n/* ------------------------------------------------------------------ */\n\nimport type picocolorsType from 'picocolors';\ntype PC = typeof picocolorsType;\n\nconst STRIP_ANSI = /\\u001b\\[[0-9;]*m/g;\nconst strip = (s: string) => s.replace(STRIP_ANSI, '');\n\nfunction box(lines: string[], opts: { title?: string; border?: (s: string) => string; width?: number }, pc: PC): string {\n const border = opts.border ?? pc.dim;\n const w = opts.width ?? Math.max(...lines.map(l => strip(l).length), strip(opts.title ?? '').length + 4, 48);\n const pad = (s: string) => s + ' '.repeat(Math.max(0, w - strip(s).length));\n\n const hr = '\\u2500'.repeat(w + 2);\n let top: string;\n if (opts.title) {\n const tLen = strip(opts.title).length;\n top = border('\\u256d\\u2500 ') + opts.title + border(` ${ '\\u2500'.repeat(Math.max(0, w - tLen - 2))}\\u256e`);\n } else {\n top = border(`\\u256d${hr}\\u256e`);\n }\n const bot = border(`\\u2570${hr}\\u256f`);\n const body = lines.map(l => `${border('\\u2502')} ${pad(l)} ${border('\\u2502')}`).join('\\n');\n return `${top}\\n${body}\\n${bot}`;\n}\n\nfunction stepHeader(step: number, total: number, title: string, desc: string, pc: PC): string {\n const stepLabel = pc.bold(pc.cyan(`${step}/${total}`));\n const titleStr = pc.bold(title);\n return box(\n [`${pc.dim(desc)}`],\n { title: `${stepLabel} ${titleStr}`, border: pc.cyan },\n pc,\n );\n}\n\n/* ------------------------------------------------------------------ */\n/* ASCII banner with faux gradient */\n/* ------------------------------------------------------------------ */\n\nfunction renderBanner(_version: string | undefined, pc: PC): string {\n const art = [\n ' \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2557\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2557\\u2588\\u2588\\u2557 \\u2588\\u2588\\u2557 \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2557 ',\n ' \\u2588\\u2588\\u2554\\u2550\\u2550\\u2550\\u255d\\u255a\\u2550\\u2550\\u2588\\u2588\\u2554\\u2550\\u2550\\u255d\\u255a\\u2588\\u2588\\u2557\\u2588\\u2588\\u2554\\u255d\\u2588\\u2588\\u2554\\u2550\\u2550\\u2550\\u2588\\u2588\\u2557',\n ' \\u2588\\u2588\\u2551 \\u2588\\u2588\\u2551 \\u255a\\u2588\\u2588\\u2588\\u2554\\u255d \\u2588\\u2588\\u2551 \\u2588\\u2588\\u2551',\n ' \\u2588\\u2588\\u2551 \\u2588\\u2588\\u2551 \\u2588\\u2588\\u2554\\u2588\\u2588\\u2557 \\u2588\\u2588\\u2551 \\u2588\\u2588\\u2551',\n ' \\u255a\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2557 \\u2588\\u2588\\u2551 \\u2588\\u2588\\u2554\\u255d\\u255a\\u2588\\u2588\\u2557\\u255a\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2554\\u255d',\n ' \\u255a\\u2550\\u2550\\u2550\\u2550\\u2550\\u255d \\u255a\\u2550\\u255d \\u255a\\u2550\\u255d \\u255a\\u2550\\u255d \\u255a\\u2550\\u2550\\u2550\\u2550\\u2550\\u255d ',\n ];\n\n // Faux vertical gradient: cyan → blueBright → magentaBright\n const colors = [pc.cyan, pc.cyan, pc.blueBright, pc.blueBright, pc.magentaBright, pc.magentaBright] as const;\n const coloredArt = art.map((line, i) => colors[i]!(line));\n\n const tagline1 = pc.bold(pc.white(' Code intelligence for AI agents.'));\n const tagline2 = pc.dim(' One call instead of hundreds.');\n\n const inner = [\n '',\n ...coloredArt,\n '',\n tagline1,\n tagline2,\n '',\n ];\n\n return box(inner, { border: pc.dim }, pc);\n}\n\n/* ------------------------------------------------------------------ */\n/* InitCommand */\n/* ------------------------------------------------------------------ */\n\nexport class InitCommand {\n private readonly projectRoot: string;\n\n constructor(projectRoot: string) {\n this.projectRoot = projectRoot;\n }\n\n installHooks(): void {\n const hooksDir = join(this.projectRoot, '.git', 'hooks');\n mkdirSync(hooksDir, { recursive: true });\n this.installHook(hooksDir, 'post-commit', POST_COMMIT_CONTENT);\n this.installHook(hooksDir, 'post-merge', POST_MERGE_CONTENT);\n }\n\n async run(options: InitOptions = {}): Promise<void> {\n if (!existsSync(join(this.projectRoot, '.git'))) {\n console.error('[ctxo] Not a git repository. Run \"git init\" first.');\n process.exit(1);\n }\n\n if (options.dryRun) return this.dryRun(options);\n if (options.yes || options.tools) return this.runNonInteractive(options);\n return this.runInteractive(options);\n }\n\n /* ---------------------------------------------------------------- */\n /* Interactive flow */\n /* ---------------------------------------------------------------- */\n\n private async runInteractive(options: InitOptions): Promise<void> {\n const clack = await import('@clack/prompts');\n const pc = (await import('picocolors')).default;\n\n const version = await this.getVersion();\n const totalSteps = options.rulesOnly ? 1 : 3;\n\n // ── Banner ──\n console.error('');\n console.error(renderBanner(version, pc));\n console.error('');\n\n // ── Step 1: Index directory ──\n let stepNum = 0;\n if (!options.rulesOnly) {\n stepNum++;\n console.error(stepHeader(stepNum, totalSteps, 'Index Directory', 'Where ctxo stores the symbol graph and metadata.', pc));\n console.error('');\n\n const indexDir = await clack.text({\n message: pc.cyan('Directory path'),\n placeholder: '.ctxo/index',\n initialValue: '.ctxo/index',\n validate: (val) => {\n if (!val?.trim()) return 'Directory path is required';\n return undefined;\n },\n });\n\n if (clack.isCancel(indexDir)) { clack.cancel('Setup cancelled.'); process.exit(0); }\n\n const fullPath = join(this.projectRoot, indexDir as string);\n if (!existsSync(fullPath)) mkdirSync(fullPath, { recursive: true });\n console.error('');\n }\n\n // ── Step 2: AI tool selection ──\n stepNum++;\n const detected = detectPlatforms(this.projectRoot);\n const detectedCount = detected.size;\n const detectedHint = detectedCount > 0 ? pc.green(` ${detectedCount} detected`) : '';\n\n console.error(stepHeader(stepNum, totalSteps, `AI Tools${detectedHint}`, 'Select your tools. Generates MCP usage rules for each.', pc));\n console.error('');\n\n const toolChoices = PLATFORMS.map(p => {\n const isDetected = detected.has(p.id);\n const star = p.starred ? pc.yellow(' \\u2605') : '';\n const detect = isDetected ? pc.green(' (detected)') : '';\n return {\n value: p.id,\n label: `${p.name}${star}${detect}`,\n hint: isDetected ? undefined : pc.dim(p.file),\n };\n });\n\n const selectedTools = await clack.multiselect({\n message: pc.cyan('Select tools'),\n options: toolChoices,\n initialValues: [...detected],\n required: false,\n });\n\n if (clack.isCancel(selectedTools)) { clack.cancel('Setup cancelled.'); process.exit(0); }\n console.error('');\n\n // ── Step 3: Git hooks ──\n let installGitHooks = false;\n if (!options.rulesOnly) {\n stepNum++;\n console.error(stepHeader(stepNum, totalSteps, `Git Hooks ${pc.yellow('recommended')}`, 'Auto-updates index on every commit and pull.', pc));\n console.error('');\n\n const hooks = await clack.confirm({\n message: pc.cyan('Install hooks?'),\n initialValue: true,\n });\n\n if (clack.isCancel(hooks)) { clack.cancel('Setup cancelled.'); process.exit(0); }\n installGitHooks = hooks as boolean;\n console.error('');\n }\n\n // ── Execute with spinner ──\n const s = clack.spinner();\n s.start(pc.dim('Configuring...'));\n\n const results: string[] = [];\n\n // Automatic scaffolding (always runs, no prompt needed)\n const gitignoreResult = ensureGitignore(this.projectRoot);\n const configResult = ensureConfig(this.projectRoot);\n\n if (!options.rulesOnly) {\n results.push(`${pc.green('\\u2713')} ${pc.bold('.ctxo/index/')} ${pc.dim('index directory')}`);\n }\n\n if (configResult.action !== 'skipped') {\n results.push(`${pc.green('\\u2713')} ${pc.bold(configResult.file)} ${pc.dim(configResult.action)}`);\n }\n\n if (gitignoreResult.action !== 'skipped') {\n results.push(`${pc.green('\\u2713')} ${pc.bold(gitignoreResult.file)} ${pc.dim(gitignoreResult.action)}`);\n }\n\n for (const toolId of (selectedTools as string[])) {\n const result = installRules(this.projectRoot, toolId);\n results.push(`${pc.green('\\u2713')} ${pc.bold(result.file)} ${pc.dim(result.action)}`);\n }\n\n if (installGitHooks) {\n this.installHooks();\n results.push(`${pc.green('\\u2713')} ${pc.bold('post-commit, post-merge')} ${pc.dim('hooks installed')}`);\n }\n\n s.stop(pc.green('Done!'));\n\n // ── Summary box ──\n if (results.length > 0) {\n console.error('');\n console.error(box(results, { title: pc.green('\\u2713 Created'), border: pc.green }, pc));\n }\n\n // ── Next steps box ──\n const hasWork = (selectedTools as string[]).length > 0 || installGitHooks;\n if (hasWork) {\n const steps = [\n `${pc.cyan('\\u25b6')} npx ctxo index ${pc.dim('\\u2500 build codebase index')}`,\n `${pc.cyan('\\u25b6')} npx ctxo doctor ${pc.dim('\\u2500 verify everything works')}`,\n ];\n console.error('');\n console.error(box(steps, { title: pc.cyan('\\u2192 Next steps'), border: pc.cyan }, pc));\n }\n\n console.error('');\n console.error(` ${pc.dim('Happy coding!')} ${pc.magentaBright('\\u2764')}`);\n console.error('');\n }\n\n /* ---------------------------------------------------------------- */\n /* Non-interactive flow */\n /* ---------------------------------------------------------------- */\n\n private runNonInteractive(options: InitOptions): void {\n const toolIds = options.tools ?? [];\n\n for (const id of toolIds) {\n if (!PLATFORMS.find(p => p.id === id)) {\n console.error(`[ctxo] Unknown tool: \"${id}\". Valid: ${PLATFORMS.map(p => p.id).join(', ')}`);\n process.exit(1);\n }\n }\n\n // Automatic scaffolding\n const gitignoreResult = ensureGitignore(this.projectRoot);\n const configResult = ensureConfig(this.projectRoot);\n\n if (!options.rulesOnly) {\n const indexDir = join(this.projectRoot, '.ctxo', 'index');\n if (!existsSync(indexDir)) mkdirSync(indexDir, { recursive: true });\n console.error('[ctxo] \\u2713 .ctxo/index/ ready');\n }\n\n if (configResult.action !== 'skipped') {\n console.error(`[ctxo] \\u2713 ${configResult.file} \\u2014 ${configResult.action}`);\n }\n if (gitignoreResult.action !== 'skipped') {\n console.error(`[ctxo] \\u2713 ${gitignoreResult.file} \\u2014 ${gitignoreResult.action}`);\n }\n\n for (const toolId of toolIds) {\n const result = installRules(this.projectRoot, toolId);\n console.error(`[ctxo] \\u2713 ${result.file} \\u2014 ${result.action}`);\n }\n\n if (!options.rulesOnly) {\n this.installHooks();\n console.error('[ctxo] \\u2713 Git hooks installed');\n }\n }\n\n /* ---------------------------------------------------------------- */\n /* Dry run */\n /* ---------------------------------------------------------------- */\n\n private dryRun(options: InitOptions): void {\n const toolIds = options.tools ?? PLATFORMS.map(p => p.id);\n\n console.error('[ctxo] Dry run \\u2014 the following files would be created/updated:\\n');\n\n if (!options.rulesOnly) {\n console.error(' .ctxo/index/ (index directory)');\n }\n\n for (const id of toolIds) {\n const platform = PLATFORMS.find(p => p.id === id);\n if (platform) {\n const exists = existsSync(join(this.projectRoot, platform.file));\n const action = platform.mode === 'append' && exists ? 'append section' : 'create';\n console.error(` ${platform.file.padEnd(42)} (${action})`);\n }\n }\n\n if (!options.rulesOnly) {\n console.error(' .git/hooks/post-commit (git hook)');\n console.error(' .git/hooks/post-merge (git hook)');\n }\n }\n\n /* ---------------------------------------------------------------- */\n /* Helpers */\n /* ---------------------------------------------------------------- */\n\n private async getVersion(): Promise<string | undefined> {\n try {\n const pkgPath = join(this.projectRoot, 'node_modules', 'ctxo-mcp', 'package.json');\n if (existsSync(pkgPath)) {\n return JSON.parse(readFileSync(pkgPath, 'utf-8')).version;\n }\n const { createRequire } = await import('node:module');\n const require = createRequire(import.meta.url);\n return require('../../package.json').version;\n } catch {\n return undefined;\n }\n }\n\n private installHook(hooksDir: string, hookName: string, hookContent: string): void {\n const hookPath = join(hooksDir, hookName);\n\n let existing = '';\n if (existsSync(hookPath)) {\n existing = readFileSync(hookPath, 'utf-8');\n if (existing.includes(CTXO_START)) return;\n } else {\n existing = '#!/bin/sh\\n';\n }\n\n const updated = existing.endsWith('\\n')\n ? existing + '\\n' + hookContent + '\\n'\n : existing + '\\n\\n' + hookContent + '\\n';\n\n writeFileSync(hookPath, updated, 'utf-8');\n chmodSync(hookPath, 0o755);\n }\n}\n","/**\n * Platform configurations and MCP tool usage rule generator.\n *\n * Each platform entry defines where the AI coding assistant reads its\n * project-level instructions and how ctxo should write them.\n */\n\nimport { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';\nimport { join, dirname } from 'node:path';\n\nexport interface Platform {\n id: string;\n name: string;\n file: string;\n /** 'append' inserts a marked section into an existing file; 'create' writes from scratch */\n mode: 'append' | 'create';\n /** Paths to check for auto-detection (relative to project root) */\n detectPaths: string[];\n /** Show a star next to this platform name */\n starred: boolean;\n}\n\nexport const PLATFORMS: Platform[] = [\n { id: 'claude-code', name: 'Claude Code', file: 'CLAUDE.md', mode: 'append', detectPaths: ['CLAUDE.md', '.claude'], starred: true },\n { id: 'cursor', name: 'Cursor', file: '.cursor/rules/ctxo-mcp.mdc', mode: 'create', detectPaths: ['.cursor', '.cursorrules'], starred: false },\n { id: 'github-copilot', name: 'GitHub Copilot', file: '.github/copilot-instructions.md', mode: 'create', detectPaths: ['.github', '.vscode'], starred: false },\n { id: 'windsurf', name: 'Windsurf', file: '.windsurfrules', mode: 'create', detectPaths: ['.windsurfrules', '.windsurf'], starred: false },\n { id: 'antigravity', name: 'Google Antigravity', file: 'AGENTS.md', mode: 'create', detectPaths: ['AGENTS.md', 'GEMINI.md', '.gemini'], starred: false },\n { id: 'augment', name: 'Augment Code', file: 'augment-guidelines.md', mode: 'create', detectPaths: ['augment-guidelines.md', '.augment'], starred: false },\n { id: 'amazonq', name: 'Amazon Q', file: '.amazonq/rules/ctxo-mcp.md', mode: 'create', detectPaths: ['.amazonq'], starred: false },\n];\n\nexport function detectPlatforms(projectRoot: string): Set<string> {\n const detected = new Set<string>();\n for (const p of PLATFORMS) {\n if (p.detectPaths.some(d => existsSync(join(projectRoot, d)))) {\n detected.add(p.id);\n }\n }\n return detected;\n}\n\nconst SECTION_START = '<!-- ctxo-rules-start -->';\nconst SECTION_END = '<!-- ctxo-rules-end -->';\n\n/* ------------------------------------------------------------------ */\n/* Rule content */\n/* ------------------------------------------------------------------ */\n\nfunction ruleBody(): string {\n return `## ctxo MCP Tool Usage (MANDATORY)\n\n**ALWAYS use ctxo MCP tools before reading source files or making code changes.** The ctxo index contains dependency graphs, git intent, anti-patterns, and change health that cannot be derived from reading files alone. Skipping these tools leads to blind edits and broken dependencies.\n\n### Before ANY Code Modification\n1. Call \\`get_blast_radius\\` for the symbol you are about to change — understand what breaks\n2. Call \\`get_why_context\\` for the same symbol — check for revert history or anti-patterns\n3. Only then read and edit source files\n\n### Before Starting a Task\n| Task Type | REQUIRED First Call |\n|---|---|\n| Fixing a bug | \\`get_context_for_task(taskType: \"fix\")\\` |\n| Adding/extending a feature | \\`get_context_for_task(taskType: \"extend\")\\` |\n| Refactoring | \\`get_context_for_task(taskType: \"refactor\")\\` |\n| Understanding code | \\`get_context_for_task(taskType: \"understand\")\\` |\n\n### Before Reviewing a PR or Diff\n- Call \\`get_pr_impact\\` — single call gives full risk assessment with co-change analysis\n\n### When Exploring or Searching Code\n- Use \\`search_symbols\\` for name/regex lookup — DO NOT grep source files for symbol discovery\n- Use \\`get_ranked_context\\` for natural language queries — DO NOT manually browse directories\n\n### Orientation in Unfamiliar Areas\n- Call \\`get_architectural_overlay\\` to understand layer boundaries\n- Call \\`get_symbol_importance\\` to identify critical symbols\n\n### NEVER Do These\n- NEVER edit a function without first calling \\`get_blast_radius\\` on it\n- NEVER skip \\`get_why_context\\` — reverted code and anti-patterns are invisible without it\n- NEVER grep source files to find symbols when \\`search_symbols\\` exists\n- NEVER manually trace imports when \\`find_importers\\` gives the full reverse dependency graph`;\n}\n\n/* ------------------------------------------------------------------ */\n/* Per-platform rendering */\n/* ------------------------------------------------------------------ */\n\nfunction cursorFrontmatter(): string {\n return `---\ndescription: ctxo MCP tool usage rules — always applied\nglobs:\nalwaysApply: true\n---\n\n`;\n}\n\nexport function generateRules(platformId: string): string {\n const body = ruleBody();\n\n if (platformId === 'cursor') {\n return cursorFrontmatter() + body + '\\n';\n }\n\n return body + '\\n';\n}\n\n/* ------------------------------------------------------------------ */\n/* File operations */\n/* ------------------------------------------------------------------ */\n\nexport interface InstallResult {\n file: string;\n action: 'created' | 'updated' | 'skipped';\n}\n\nexport function installRules(projectRoot: string, platformId: string): InstallResult {\n const platform = PLATFORMS.find(p => p.id === platformId);\n if (!platform) throw new Error(`Unknown platform: ${platformId}`);\n\n const filePath = join(projectRoot, platform.file);\n const content = generateRules(platformId);\n\n // Ensure parent directory exists\n const dir = dirname(filePath);\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true });\n\n if (platform.mode === 'create') {\n // For 'create' mode: write or replace entire file\n writeFileSync(filePath, content, 'utf-8');\n return { file: platform.file, action: existsSync(filePath) ? 'updated' : 'created' };\n }\n\n // 'append' mode: insert marked section into existing file\n if (!existsSync(filePath)) {\n writeFileSync(filePath, content, 'utf-8');\n return { file: platform.file, action: 'created' };\n }\n\n const existing = readFileSync(filePath, 'utf-8');\n\n // Already has ctxo rules section — replace it\n if (existing.includes(SECTION_START)) {\n const re = new RegExp(`${escapeRegExp(SECTION_START)}[\\\\s\\\\S]*?${escapeRegExp(SECTION_END)}`, 'm');\n const updated = existing.replace(re, `${SECTION_START}\\n${content}${SECTION_END}`);\n writeFileSync(filePath, updated, 'utf-8');\n return { file: platform.file, action: 'updated' };\n }\n\n // Append new section\n const separator = existing.endsWith('\\n') ? '\\n' : '\\n\\n';\n const updated = existing + separator + `${SECTION_START}\\n${content}${SECTION_END}\\n`;\n writeFileSync(filePath, updated, 'utf-8');\n return { file: platform.file, action: 'updated' };\n}\n\nfunction escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/* ------------------------------------------------------------------ */\n/* Project scaffolding (automatic, not prompted) */\n/* ------------------------------------------------------------------ */\n\nconst GITIGNORE_ENTRY = '.ctxo/.cache/';\n\nexport function ensureGitignore(projectRoot: string): InstallResult {\n const filePath = join(projectRoot, '.gitignore');\n\n if (!existsSync(filePath)) {\n writeFileSync(filePath, `# Ctxo local cache (auto-rebuilt, never committed)\\n${GITIGNORE_ENTRY}\\n`, 'utf-8');\n return { file: '.gitignore', action: 'created' };\n }\n\n const existing = readFileSync(filePath, 'utf-8');\n if (existing.includes(GITIGNORE_ENTRY)) {\n return { file: '.gitignore', action: 'skipped' };\n }\n\n const separator = existing.endsWith('\\n') ? '\\n' : '\\n\\n';\n const updated = existing + `${separator}# Ctxo local cache (auto-rebuilt, never committed)\\n${GITIGNORE_ENTRY}\\n`;\n writeFileSync(filePath, updated, 'utf-8');\n return { file: '.gitignore', action: 'updated' };\n}\n\nconst DEFAULT_CONFIG = `# ctxo project configuration\n# Docs: https://github.com/alperhankendi/Ctxo\nversion: \"1.0\"\n`;\n\nexport function ensureConfig(projectRoot: string): InstallResult {\n const filePath = join(projectRoot, '.ctxo', 'config.yaml');\n const dir = dirname(filePath);\n\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true });\n\n if (existsSync(filePath)) {\n return { file: '.ctxo/config.yaml', action: 'skipped' };\n }\n\n writeFileSync(filePath, DEFAULT_CONFIG, 'utf-8');\n return { file: '.ctxo/config.yaml', action: 'created' };\n}\n","import { join, extname, relative } from 'node:path';\nimport { readFileSync } from 'node:fs';\nimport { TsMorphAdapter } from '../adapters/language/ts-morph-adapter.js';\nimport { LanguageAdapterRegistry } from '../adapters/language/language-adapter-registry.js';\nimport { JsonIndexWriter } from '../adapters/storage/json-index-writer.js';\nimport { SqliteStorageAdapter } from '../adapters/storage/sqlite-storage-adapter.js';\nimport { ChokidarWatcherAdapter } from '../adapters/watcher/chokidar-watcher-adapter.js';\nimport { ContentHasher } from '../core/staleness/content-hasher.js';\nimport { SimpleGitAdapter } from '../adapters/git/simple-git-adapter.js';\nimport { RevertDetector } from '../core/why-context/revert-detector.js';\nimport type { FileIndex, CommitIntent, AntiPattern } from '../core/types.js';\n\nconst DEBOUNCE_MS = 300;\n\nexport class WatchCommand {\n private readonly projectRoot: string;\n private readonly ctxoRoot: string;\n\n constructor(projectRoot: string) {\n this.projectRoot = projectRoot;\n this.ctxoRoot = join(projectRoot, '.ctxo');\n }\n\n async run(): Promise<void> {\n console.error('[ctxo] Starting file watcher...');\n\n const registry = new LanguageAdapterRegistry();\n registry.register(new TsMorphAdapter());\n this.registerTreeSitterAdapters(registry);\n const supportedExtensions = registry.getSupportedExtensions();\n\n const writer = new JsonIndexWriter(this.ctxoRoot);\n const storage = new SqliteStorageAdapter(this.ctxoRoot);\n await storage.init();\n const hasher = new ContentHasher();\n\n const gitAdapter = new SimpleGitAdapter(this.projectRoot);\n const revertDetector = new RevertDetector();\n const watcher = new ChokidarWatcherAdapter(this.projectRoot);\n const pendingFiles = new Map<string, NodeJS.Timeout>();\n\n const reindexFile = async (filePath: string) => {\n const adapter = registry.getAdapter(filePath);\n if (!adapter) return;\n\n const relativePath = relative(this.projectRoot, filePath).replace(/\\\\/g, '/');\n\n try {\n const source = readFileSync(filePath, 'utf-8');\n const lastModified = Math.floor(Date.now() / 1000);\n\n const symbols = adapter.extractSymbols(relativePath, source);\n const edges = adapter.extractEdges(relativePath, source);\n const complexity = adapter.extractComplexity(relativePath, source);\n\n // Git history and anti-patterns\n const commits = await gitAdapter.getCommitHistory(relativePath);\n const intent: CommitIntent[] = commits.map((c) => ({\n hash: c.hash, message: c.message, date: c.date, kind: 'commit' as const,\n }));\n const antiPatterns: AntiPattern[] = revertDetector.detect(commits);\n\n const fileIndex: FileIndex = {\n file: relativePath,\n lastModified,\n contentHash: hasher.hash(source),\n symbols,\n edges,\n complexity,\n intent,\n antiPatterns,\n };\n\n writer.write(fileIndex);\n storage.writeSymbolFile(fileIndex);\n console.error(`[ctxo] Re-indexed: ${relativePath}`);\n } catch (err) {\n console.error(`[ctxo] Failed to re-index ${relativePath}: ${(err as Error).message}`);\n }\n };\n\n const debouncedReindex = (filePath: string) => {\n const existing = pendingFiles.get(filePath);\n if (existing) clearTimeout(existing);\n\n pendingFiles.set(\n filePath,\n setTimeout(() => {\n pendingFiles.delete(filePath);\n reindexFile(filePath);\n }, DEBOUNCE_MS),\n );\n };\n\n watcher.start((event, filePath) => {\n if (event === 'unlink') {\n const ext = extname(filePath).toLowerCase();\n if (!supportedExtensions.has(ext)) return;\n\n const relativePath = relative(this.projectRoot, filePath).replace(/\\\\/g, '/');\n writer.delete(relativePath);\n storage.deleteSymbolFile(relativePath);\n console.error(`[ctxo] Removed from index: ${relativePath}`);\n } else {\n debouncedReindex(filePath);\n }\n });\n\n console.error('[ctxo] Watching for file changes... (Ctrl+C to stop)');\n\n const cleanup = () => {\n console.error('\\n[ctxo] Stopping watcher...');\n for (const timeout of pendingFiles.values()) {\n clearTimeout(timeout);\n }\n watcher.stop().then(() => {\n storage.close();\n console.error('[ctxo] Watcher stopped');\n process.exit(0);\n });\n };\n\n process.on('SIGINT', cleanup);\n process.on('SIGTERM', cleanup);\n }\n\n private registerTreeSitterAdapters(registry: LanguageAdapterRegistry): void {\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { GoAdapter } = require('../adapters/language/go-adapter.js');\n registry.register(new GoAdapter());\n } catch {\n console.error('[ctxo] Go adapter unavailable (tree-sitter-go not installed)');\n }\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { CSharpAdapter } = require('../adapters/language/csharp-adapter.js');\n registry.register(new CSharpAdapter());\n } catch {\n console.error('[ctxo] C# adapter unavailable (tree-sitter-c-sharp not installed)');\n }\n }\n}\n","import { watch, type FSWatcher } from 'chokidar';\nimport type { IWatcherPort, FileChangeHandler } from '../../ports/i-watcher-port.js';\n\nconst DEFAULT_IGNORED = [\n '**/node_modules/**',\n '**/.git/**',\n '**/.ctxo/**',\n '**/dist/**',\n '**/coverage/**',\n];\n\nexport class ChokidarWatcherAdapter implements IWatcherPort {\n private readonly projectRoot: string;\n private readonly ignored: string[];\n private watcher: FSWatcher | undefined;\n\n constructor(projectRoot: string, ignored?: string[]) {\n this.projectRoot = projectRoot;\n this.ignored = ignored ?? DEFAULT_IGNORED;\n }\n\n start(handler: FileChangeHandler): void {\n if (this.watcher) {\n throw new Error('Watcher already started. Call stop() before starting again.');\n }\n\n this.watcher = watch(this.projectRoot, {\n ignored: this.ignored,\n persistent: true,\n ignoreInitial: true,\n });\n\n this.watcher.on('add', (path) => handler('add', path));\n this.watcher.on('change', (path) => handler('change', path));\n this.watcher.on('unlink', (path) => handler('unlink', path));\n }\n\n async stop(): Promise<void> {\n if (this.watcher) {\n await this.watcher.close();\n this.watcher = undefined;\n }\n }\n}\n","import { join } from 'node:path';\nimport { existsSync, readFileSync } from 'node:fs';\nimport initSqlJs from 'sql.js';\nimport { SessionRecorderAdapter } from '../adapters/stats/session-recorder-adapter.js';\nimport type { AggregatedStats } from '../ports/i-session-recorder-port.js';\nimport type { StatsReport } from '../core/stats/stats-types.js';\n\nexport class StatsCommand {\n private readonly ctxoRoot: string;\n\n constructor(projectRoot: string) {\n this.ctxoRoot = join(projectRoot, '.ctxo');\n }\n\n async run(options: { days?: number; json?: boolean; clear?: boolean }): Promise<void> {\n // Check if stats are enabled\n if (!this.isStatsEnabled()) {\n console.error('[ctxo] Stats collection is disabled in .ctxo/config.yaml');\n return;\n }\n\n const dbPath = join(this.ctxoRoot, '.cache', 'symbols.db');\n if (!existsSync(dbPath)) {\n if (options.json) {\n process.stdout.write(JSON.stringify(this.emptyReport(options.days)) + '\\n');\n } else {\n console.error('[ctxo] No usage data yet. Start using Ctxo MCP tools to collect stats.');\n }\n return;\n }\n\n // Open DB\n const SQL = await initSqlJs();\n const buffer = readFileSync(dbPath);\n const db = new SQL.Database(buffer);\n const recorder = new SessionRecorderAdapter(db);\n\n try {\n if (options.clear) {\n recorder.clear();\n // Persist cleared DB\n const data = db.export();\n const { writeFileSync } = await import('node:fs');\n writeFileSync(dbPath, Buffer.from(data));\n console.error('[ctxo] Session data cleared.');\n return;\n }\n\n // Validate --days\n if (options.days != null) {\n if (!Number.isInteger(options.days) || options.days <= 0) {\n console.error('[ctxo] --days must be a positive integer');\n process.exit(1);\n return;\n }\n }\n\n const stats = recorder.queryStats(options.days);\n\n if (stats.totalCalls === 0) {\n if (options.json) {\n process.stdout.write(JSON.stringify(this.emptyReport(options.days)) + '\\n');\n } else {\n console.error('[ctxo] No usage data yet. Start using Ctxo MCP tools to collect stats.');\n }\n return;\n }\n\n if (options.json) {\n process.stdout.write(JSON.stringify(this.buildReport(stats, options.days), null, 2) + '\\n');\n } else {\n this.printHumanReadable(stats, options.days);\n }\n } finally {\n db.close();\n }\n }\n\n private isStatsEnabled(): boolean {\n const configPath = join(this.ctxoRoot, 'config.yaml');\n if (!existsSync(configPath)) return true;\n\n try {\n const raw = readFileSync(configPath, 'utf-8');\n const match = raw.match(/stats:\\s*\\n\\s*enabled:\\s*(true|false)/);\n if (match) return match[1] !== 'false';\n return true;\n } catch {\n return true;\n }\n }\n\n private buildReport(stats: AggregatedStats, days?: number): StatsReport {\n const now = new Date().toISOString();\n const from = days != null\n ? new Date(Date.now() - days * 86400000).toISOString()\n : null;\n\n return {\n timeRange: { from, to: now, daysFilter: days ?? null },\n summary: {\n totalCalls: stats.totalCalls,\n totalTokensServed: stats.totalTokensServed,\n },\n topTools: stats.topTools,\n topSymbols: stats.topSymbols,\n detailLevelDistribution: stats.detailLevelDistribution.map((d) => ({\n level: d.level,\n count: d.count,\n percentage: d.percentage,\n })),\n };\n }\n\n private emptyReport(days?: number): StatsReport {\n return this.buildReport({\n totalCalls: 0,\n totalTokensServed: 0,\n topTools: [],\n topSymbols: [],\n detailLevelDistribution: [],\n }, days);\n }\n\n private printHumanReadable(stats: AggregatedStats, days?: number): void {\n const header = days != null ? `last ${days} days` : 'all time';\n\n console.error('');\n console.error(` Usage Summary (${header})`);\n console.error(' ────────────────────────────────────────');\n console.error(` Total tool calls: ${this.formatNumber(stats.totalCalls)}`);\n console.error(` Total tokens served: ${this.formatTokens(stats.totalTokensServed)}`);\n\n if (stats.topTools.length > 0) {\n console.error('');\n console.error(' Top Tools');\n console.error(' ────────────────────────────────────────');\n for (const t of stats.topTools) {\n const name = t.tool.padEnd(24);\n const calls = `${this.formatNumber(t.calls)} calls`.padEnd(14);\n console.error(` ${name}${calls}avg ${this.formatNumber(t.avgTokens)} tokens`);\n }\n }\n\n if (stats.topSymbols.length > 0) {\n console.error('');\n console.error(' Top Queried Symbols');\n console.error(' ────────────────────────────────────────');\n for (const s of stats.topSymbols) {\n const name = s.name.padEnd(32);\n console.error(` ${name}${this.formatNumber(s.queries)} queries`);\n }\n }\n\n if (stats.detailLevelDistribution.length > 0) {\n console.error('');\n console.error(' Detail Level Distribution');\n console.error(' ────────────────────────────────────────');\n for (const d of stats.detailLevelDistribution) {\n const bar = this.renderBar(d.percentage);\n const pct = `${d.percentage}%`.padStart(4);\n console.error(` ${d.level}: ${bar} ${pct}`);\n }\n }\n\n console.error('');\n }\n\n private renderBar(percentage: number): string {\n const filled = Math.round(percentage / 10);\n const empty = 10 - filled;\n return '█'.repeat(filled) + '░'.repeat(empty);\n }\n\n private formatNumber(n: number): string {\n return n.toLocaleString('en-US');\n }\n\n private formatTokens(n: number): string {\n if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;\n if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`;\n return String(n);\n }\n}\n","import { join } from 'node:path';\nimport { existsSync } from 'node:fs';\nimport type { IHealthCheck } from '../core/diagnostics/types.js';\nimport { JsonIndexReader } from '../adapters/storage/json-index-reader.js';\nimport { HealthChecker } from '../adapters/diagnostics/health-checker.js';\nimport { DoctorReporter } from '../adapters/diagnostics/doctor-reporter.js';\nimport { NodeVersionCheck, TsMorphCheck, TreeSitterCheck } from '../adapters/diagnostics/checks/runtime-check.js';\nimport { GitBinaryCheck, GitRepoCheck } from '../adapters/diagnostics/checks/git-check.js';\nimport {\n IndexDirectoryCheck,\n IndexFreshnessCheck,\n SymbolCountCheck,\n EdgeCountCheck,\n OrphanedFilesCheck,\n CoChangesCacheCheck,\n SchemaVersionCheck,\n} from '../adapters/diagnostics/checks/index-check.js';\nimport { SqliteCacheCheck } from '../adapters/diagnostics/checks/storage-check.js';\nimport { ConfigFileCheck } from '../adapters/diagnostics/checks/config-check.js';\nimport { DiskUsageCheck } from '../adapters/diagnostics/checks/disk-check.js';\n\nexport interface DoctorOptions {\n json?: boolean;\n quiet?: boolean;\n}\n\nexport class DoctorCommand {\n private readonly projectRoot: string;\n private readonly ctxoRoot: string;\n\n constructor(projectRoot: string) {\n this.projectRoot = projectRoot;\n this.ctxoRoot = join(projectRoot, '.ctxo');\n }\n\n async run(options: DoctorOptions = {}): Promise<void> {\n const checks: IHealthCheck[] = [\n new NodeVersionCheck(),\n new GitBinaryCheck(),\n new GitRepoCheck(),\n new IndexDirectoryCheck(),\n new IndexFreshnessCheck(),\n new SqliteCacheCheck(),\n new ConfigFileCheck(),\n new TsMorphCheck(),\n new TreeSitterCheck(),\n new DiskUsageCheck(),\n new SymbolCountCheck(),\n new EdgeCountCheck(),\n new OrphanedFilesCheck(),\n new CoChangesCacheCheck(),\n new SchemaVersionCheck(),\n ];\n\n // Pre-load index once — shared by all index-related checks (avoids 5x redundant readAll)\n const indexDir = join(this.ctxoRoot, 'index');\n const indices = existsSync(indexDir)\n ? new JsonIndexReader(this.ctxoRoot).readAll()\n : [];\n\n const checker = new HealthChecker(checks);\n const report = await checker.runAll({\n projectRoot: this.projectRoot,\n ctxoRoot: this.ctxoRoot,\n indices,\n });\n\n const reporter = new DoctorReporter();\n let output: string;\n\n if (options.json) {\n output = reporter.formatJson(report);\n process.stdout.write(output + '\\n');\n } else if (options.quiet) {\n output = reporter.formatQuiet(report);\n console.error(output);\n } else {\n output = reporter.formatHuman(report);\n console.error(output);\n }\n\n if (report.exitCode !== 0) {\n process.exitCode = 1;\n }\n }\n}\n","import { createLogger } from '../../core/logger.js';\nimport type { IHealthCheck, CheckContext, CheckResult, DoctorReport } from '../../core/diagnostics/types.js';\n\nconst log = createLogger('ctxo:doctor');\n\nexport class HealthChecker {\n private readonly checks: IHealthCheck[];\n\n constructor(checks: IHealthCheck[]) {\n this.checks = checks;\n }\n\n async runAll(ctx: CheckContext): Promise<DoctorReport> {\n const settled = await Promise.allSettled(\n this.checks.map(check => check.run(ctx)),\n );\n\n const results: CheckResult[] = settled.map((outcome, i) => {\n const check = this.checks[i]!;\n if (outcome.status === 'fulfilled') {\n const r = outcome.value;\n log.info(`${r.id}: ${r.status.toUpperCase()} (${r.message})`);\n return r;\n }\n const message = (outcome.reason as Error)?.message ?? 'Unknown error';\n log.error(`${check.id}: FAIL (${message})`);\n return {\n id: check.id,\n title: check.title,\n status: 'fail' as const,\n message: `Check crashed: ${message}`,\n };\n });\n\n const summary = {\n pass: results.filter(r => r.status === 'pass').length,\n warn: results.filter(r => r.status === 'warn').length,\n fail: results.filter(r => r.status === 'fail').length,\n };\n\n const exitCode = summary.fail > 0 ? 1 as const : 0 as const;\n\n return { checks: results, summary, exitCode };\n }\n}\n","import type { DoctorReport, CheckResult } from '../../core/diagnostics/types.js';\n\nconst ICONS: Record<string, string> = {\n pass: '✓',\n warn: '⚠',\n fail: '✗',\n};\n\nexport class DoctorReporter {\n formatHuman(report: DoctorReport): string {\n const lines: string[] = ['ctxo doctor — Health Check', ''];\n\n for (const check of report.checks) {\n lines.push(this.formatCheckLine(check));\n }\n\n lines.push('');\n lines.push(` Summary: ${report.summary.pass} passed, ${report.summary.warn} warnings, ${report.summary.fail} failures`);\n\n return lines.join('\\n');\n }\n\n formatQuiet(report: DoctorReport): string {\n const lines: string[] = [];\n\n for (const check of report.checks) {\n if (check.status === 'warn' || check.status === 'fail') {\n lines.push(this.formatCheckLine(check));\n }\n }\n\n if (lines.length > 0) lines.push('');\n lines.push(` Summary: ${report.summary.pass} passed, ${report.summary.warn} warnings, ${report.summary.fail} failures`);\n\n return lines.join('\\n');\n }\n\n formatJson(report: DoctorReport): string {\n return JSON.stringify({\n checks: report.checks.map(c => ({\n name: c.id,\n status: c.status,\n value: c.value ?? null,\n message: c.message,\n ...(c.fix ? { fix: c.fix } : {}),\n })),\n summary: report.summary,\n exitCode: report.exitCode,\n }, null, 2);\n }\n\n private formatCheckLine(check: CheckResult): string {\n const icon = ICONS[check.status] ?? '?';\n const title = check.title.padEnd(24);\n const suffix = check.fix ? ` (${check.fix})` : '';\n return ` ${icon} ${title} ${check.message}${suffix}`;\n }\n}\n","import { createRequire } from 'node:module';\nimport type { IHealthCheck, CheckResult, CheckContext } from '../../../core/diagnostics/types.js';\n\nconst require = createRequire(import.meta.url);\n\nfunction pass(id: string, title: string, message: string): CheckResult {\n return { id, title, status: 'pass', message };\n}\nfunction warn(id: string, title: string, message: string, fix: string): CheckResult {\n return { id, title, status: 'warn', message, fix };\n}\nfunction fail(id: string, title: string, message: string, fix: string): CheckResult {\n return { id, title, status: 'fail', message, fix };\n}\n\nexport function checkNodeVersion(version: string): CheckResult {\n const id = 'node_version';\n const title = 'Node.js version';\n const major = parseInt(version.slice(1).split('.')[0] ?? '0', 10);\n if (major >= 20) return { id, title, status: 'pass', message: `Node.js ${version} (required: ≥20)`, value: version };\n if (major >= 18) return { id, title, status: 'warn', message: `Node.js ${version} — v20+ recommended`, fix: 'Upgrade to Node.js 20 or later', value: version };\n return { id, title, status: 'fail', message: `Node.js ${version} — v20+ required`, fix: 'Upgrade to Node.js 20 or later', value: version };\n}\n\nexport class NodeVersionCheck implements IHealthCheck {\n readonly id = 'node_version';\n readonly title = 'Node.js version';\n\n async run(_ctx: CheckContext): Promise<CheckResult> {\n return checkNodeVersion(process.version);\n }\n}\n\nexport class TsMorphCheck implements IHealthCheck {\n readonly id = 'ts_morph';\n readonly title = 'ts-morph';\n\n async run(_ctx: CheckContext): Promise<CheckResult> {\n try {\n require.resolve('ts-morph');\n return pass(this.id, this.title, 'available');\n } catch {\n return fail(this.id, this.title, 'ts-morph not installed', 'Run \"npm install\"');\n }\n }\n}\n\nexport class TreeSitterCheck implements IHealthCheck {\n readonly id = 'tree_sitter';\n readonly title = 'tree-sitter';\n\n async run(_ctx: CheckContext): Promise<CheckResult> {\n try {\n require.resolve('tree-sitter');\n require.resolve('tree-sitter-language-pack');\n return pass(this.id, this.title, 'available');\n } catch {\n return warn(this.id, this.title, 'tree-sitter not found — Go/C# indexing disabled', 'Run \"npm install tree-sitter tree-sitter-language-pack\"');\n }\n }\n}\n","import { execFileSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { IHealthCheck, CheckResult, CheckContext } from '../../../core/diagnostics/types.js';\n\nexport class GitBinaryCheck implements IHealthCheck {\n readonly id = 'git_binary';\n readonly title = 'Git available';\n\n async run(_ctx: CheckContext): Promise<CheckResult> {\n try {\n const version = execFileSync('git', ['--version'], { encoding: 'utf-8' }).trim();\n return { id: this.id, title: this.title, status: 'pass', message: version, value: version };\n } catch {\n return { id: this.id, title: this.title, status: 'fail', message: 'git not found in PATH', fix: 'Install git and ensure it is in your PATH' };\n }\n }\n}\n\nexport class GitRepoCheck implements IHealthCheck {\n readonly id = 'git_repo';\n readonly title = 'Git repository';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n if (existsSync(join(ctx.projectRoot, '.git'))) {\n return { id: this.id, title: this.title, status: 'pass', message: ctx.projectRoot, value: ctx.projectRoot };\n }\n return { id: this.id, title: this.title, status: 'fail', message: 'Not a git repository', fix: 'Run \"git init\" or clone a repository' };\n }\n}\n","import { existsSync } from 'node:fs';\nimport { execFileSync } from 'node:child_process';\nimport { join } from 'node:path';\nimport type { IHealthCheck, CheckResult, CheckContext } from '../../../core/diagnostics/types.js';\nimport type { FileIndex } from '../../../core/types.js';\nimport { JsonIndexReader } from '../../storage/json-index-reader.js';\nimport { StalenessDetector } from '../../../core/staleness/staleness-detector.js';\nimport { SchemaManager } from '../../storage/schema-manager.js';\n\nfunction pass(id: string, title: string, message: string, value?: string): CheckResult {\n return { id, title, status: 'pass', message, value };\n}\nfunction warn(id: string, title: string, message: string, fix?: string, value?: string): CheckResult {\n return { id, title, status: 'warn', message, fix, value };\n}\nfunction fail(id: string, title: string, message: string, fix?: string, value?: string): CheckResult {\n return { id, title, status: 'fail', message, fix, value };\n}\n\n/** Use pre-loaded indices from context, or fall back to reading from disk */\nfunction getIndices(ctx: CheckContext): readonly FileIndex[] {\n return ctx.indices ?? new JsonIndexReader(ctx.ctxoRoot).readAll();\n}\n\nexport class IndexDirectoryCheck implements IHealthCheck {\n readonly id = 'index_directory';\n readonly title = 'Index directory';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n const indexDir = join(ctx.ctxoRoot, 'index');\n if (!existsSync(indexDir)) {\n return fail(this.id, this.title, 'No index directory', 'Run \"ctxo index\"');\n }\n const indices = getIndices(ctx);\n if (indices.length === 0) {\n return fail(this.id, this.title, 'Index directory empty', 'Run \"ctxo index\"');\n }\n return pass(this.id, this.title, `${indices.length} files indexed`, String(indices.length));\n }\n}\n\nexport class IndexFreshnessCheck implements IHealthCheck {\n readonly id = 'index_freshness';\n readonly title = 'Index freshness';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n const indices = getIndices(ctx);\n if (indices.length === 0) {\n return fail(this.id, this.title, 'No indexed files to check', 'Run \"ctxo index\"');\n }\n\n const indexedFiles = indices.map(idx => idx.file);\n const staleness = new StalenessDetector(ctx.projectRoot, ctx.ctxoRoot);\n const warning = staleness.check(indexedFiles);\n\n if (!warning) {\n return pass(this.id, this.title, `All ${indices.length} files fresh`, `0/${indices.length} stale`);\n }\n\n const staleCount = warning.staleFiles.length;\n const pct = staleCount / indices.length;\n const value = `${staleCount}/${indices.length} stale`;\n\n if (pct <= 0.1) {\n return warn(this.id, this.title, `${staleCount} of ${indices.length} files stale`, 'Run \"ctxo index\"', value);\n }\n return fail(this.id, this.title, `${staleCount} of ${indices.length} files stale (${Math.round(pct * 100)}%)`, 'Run \"ctxo index\"', value);\n }\n}\n\nexport class SymbolCountCheck implements IHealthCheck {\n readonly id = 'symbol_count';\n readonly title = 'Symbol count';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n const indices = getIndices(ctx);\n const total = indices.reduce((sum, idx) => sum + idx.symbols.length, 0);\n if (total > 0) {\n return pass(this.id, this.title, `${total.toLocaleString()} symbols`, String(total));\n }\n return fail(this.id, this.title, '0 symbols (index empty)', 'Run \"ctxo index\"', '0');\n }\n}\n\nexport class EdgeCountCheck implements IHealthCheck {\n readonly id = 'edge_count';\n readonly title = 'Edge count';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n const indices = getIndices(ctx);\n const total = indices.reduce((sum, idx) => sum + idx.edges.length, 0);\n if (total > 0) {\n return pass(this.id, this.title, `${total.toLocaleString()} edges`, String(total));\n }\n return warn(this.id, this.title, '0 edges (possible isolated files)', undefined, '0');\n }\n}\n\nexport class OrphanedFilesCheck implements IHealthCheck {\n readonly id = 'orphaned_files';\n readonly title = 'Orphaned index files';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n const indices = getIndices(ctx);\n if (indices.length === 0) {\n return pass(this.id, this.title, 'no index files to check');\n }\n\n const sourceFiles = this.getSourceFiles(ctx.projectRoot);\n if (sourceFiles.size === 0) {\n return pass(this.id, this.title, 'none (git ls-files unavailable)');\n }\n\n const orphaned = indices.filter(idx => !sourceFiles.has(idx.file));\n if (orphaned.length === 0) {\n return pass(this.id, this.title, 'none', '0');\n }\n if (orphaned.length <= 5) {\n return warn(this.id, this.title, `${orphaned.length} orphaned index files`, 'Delete orphaned files from .ctxo/index/', String(orphaned.length));\n }\n return fail(this.id, this.title, `${orphaned.length} orphaned index files`, 'Delete orphaned files from .ctxo/index/', String(orphaned.length));\n }\n\n private getSourceFiles(projectRoot: string): Set<string> {\n try {\n const output = execFileSync('git', ['ls-files', '--cached', '--others', '--exclude-standard'], {\n cwd: projectRoot,\n encoding: 'utf-8',\n });\n return new Set(output.split('\\n').map(l => l.trim()).filter(l => l.length > 0));\n } catch {\n return new Set();\n }\n }\n}\n\nexport class CoChangesCacheCheck implements IHealthCheck {\n readonly id = 'co_changes_cache';\n readonly title = 'Co-changes cache';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n const coChangesPath = join(ctx.ctxoRoot, 'index', 'co-changes.json');\n if (existsSync(coChangesPath)) {\n return pass(this.id, this.title, 'present');\n }\n return warn(this.id, this.title, 'missing (co-change analysis disabled)', 'Run \"ctxo index\" with git history');\n }\n}\n\nexport class SchemaVersionCheck implements IHealthCheck {\n readonly id = 'schema_version';\n readonly title = 'Schema version';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n const manager = new SchemaManager(ctx.ctxoRoot);\n const stored = manager.readStoredVersion();\n const current = manager.currentVersion();\n\n if (!stored) {\n return fail(this.id, this.title, 'No schema version found', 'Run \"ctxo index\"');\n }\n if (manager.isCompatible()) {\n return pass(this.id, this.title, `${stored} (current)`, stored);\n }\n return fail(this.id, this.title, `${stored} (expected ${current})`, 'Run \"ctxo index\" to re-index with current schema', stored);\n }\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { IHealthCheck, CheckResult, CheckContext } from '../../../core/diagnostics/types.js';\n\nexport class SqliteCacheCheck implements IHealthCheck {\n readonly id = 'sqlite_cache';\n readonly title = 'SQLite cache';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n const dbPath = join(ctx.ctxoRoot, '.cache', 'symbols.db');\n if (!existsSync(dbPath)) {\n return { id: this.id, title: this.title, status: 'warn', message: 'SQLite cache missing', fix: 'Run \"ctxo sync\" to rebuild' };\n }\n\n try {\n const { default: initSqlJs } = await import('sql.js');\n const SQL = await initSqlJs();\n const buffer = readFileSync(dbPath);\n const db = new SQL.Database(new Uint8Array(buffer));\n const result = db.exec('PRAGMA integrity_check');\n db.close();\n\n const firstRow = result[0]?.values[0];\n if (firstRow && firstRow[0] === 'ok') {\n return { id: this.id, title: this.title, status: 'pass', message: 'integrity_check passed' };\n }\n return { id: this.id, title: this.title, status: 'fail', message: `SQLite corrupt: ${String(firstRow?.[0])}`, fix: 'Run \"ctxo sync\" to rebuild' };\n } catch (err) {\n return { id: this.id, title: this.title, status: 'fail', message: `SQLite unreadable: ${(err as Error).message}`, fix: 'Run \"ctxo sync\" to rebuild' };\n }\n }\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { IHealthCheck, CheckResult, CheckContext } from '../../../core/diagnostics/types.js';\n\nexport class ConfigFileCheck implements IHealthCheck {\n readonly id = 'config_file';\n readonly title = 'Config file';\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n const configPath = join(ctx.ctxoRoot, 'config.yaml');\n if (!existsSync(configPath)) {\n return { id: this.id, title: this.title, status: 'warn', message: 'No config.yaml (using defaults)' };\n }\n\n try {\n const content = readFileSync(configPath, 'utf-8');\n if (content.trim().length === 0) {\n return { id: this.id, title: this.title, status: 'warn', message: 'config.yaml is empty (using defaults)' };\n }\n // Basic YAML structure check — tabs are invalid in YAML\n if (content.includes('\\t')) {\n return { id: this.id, title: this.title, status: 'fail', message: 'Invalid config.yaml: tabs are not allowed in YAML', fix: 'Replace tabs with spaces in .ctxo/config.yaml' };\n }\n return { id: this.id, title: this.title, status: 'pass', message: '.ctxo/config.yaml valid' };\n } catch (err) {\n return { id: this.id, title: this.title, status: 'fail', message: `Cannot read config.yaml: ${(err as Error).message}`, fix: 'Check file permissions for .ctxo/config.yaml' };\n }\n }\n}\n","import { existsSync, readdirSync, statSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { IHealthCheck, CheckResult, CheckContext } from '../../../core/diagnostics/types.js';\n\nexport interface DiskThresholds {\n readonly warnMb: number;\n readonly failMb: number;\n}\n\nconst DEFAULT_THRESHOLDS: DiskThresholds = { warnMb: 100, failMb: 500 };\n\nexport class DiskUsageCheck implements IHealthCheck {\n readonly id = 'disk_usage';\n readonly title = 'Disk usage';\n private readonly thresholds: DiskThresholds;\n\n constructor(thresholds: DiskThresholds = DEFAULT_THRESHOLDS) {\n this.thresholds = thresholds;\n }\n\n async run(ctx: CheckContext): Promise<CheckResult> {\n if (!existsSync(ctx.ctxoRoot)) {\n return { id: this.id, title: this.title, status: 'pass', message: 'no .ctxo/ directory', value: '0' };\n }\n\n const bytes = this.getDirSize(ctx.ctxoRoot);\n const mb = bytes / (1024 * 1024);\n const formatted = mb < 1 ? `${Math.round(bytes / 1024)} KB` : `${mb.toFixed(1)} MB`;\n\n if (mb < this.thresholds.warnMb) {\n return { id: this.id, title: this.title, status: 'pass', message: formatted, value: formatted };\n }\n if (mb < this.thresholds.failMb) {\n return { id: this.id, title: this.title, status: 'warn', message: `${formatted} — consider pruning orphaned index files`, value: formatted };\n }\n return { id: this.id, title: this.title, status: 'fail', message: `${formatted} — unusually large`, fix: 'Check for stale data in .ctxo/', value: formatted };\n }\n\n private getDirSize(dirPath: string): number {\n let total = 0;\n try {\n const entries = readdirSync(dirPath, { withFileTypes: true, recursive: true });\n for (const entry of entries) {\n if (entry.isFile()) {\n try {\n // parentPath available in Node 20.12+, path in earlier Node 20.x\n const parent = (entry as unknown as { parentPath?: string; path?: string }).parentPath\n ?? (entry as unknown as { path?: string }).path\n ?? dirPath;\n total += statSync(join(parent, entry.name)).size;\n } catch {\n // skip unreadable files\n }\n }\n }\n } catch {\n // skip unreadable directories\n }\n return total;\n }\n}\n","import { IndexCommand } from './index-command.js';\nimport { SyncCommand } from './sync-command.js';\nimport { StatusCommand } from './status-command.js';\nimport { VerifyCommand } from './verify-command.js';\nimport { InitCommand } from './init-command.js';\nimport { WatchCommand } from './watch-command.js';\nimport { StatsCommand } from './stats-command.js';\nimport { DoctorCommand } from './doctor-command.js';\n\nexport class CliRouter {\n private readonly projectRoot: string;\n\n constructor(projectRoot: string) {\n this.projectRoot = projectRoot;\n }\n\n async route(args: string[]): Promise<void> {\n const command = args[0];\n\n if (!command || command === '--help' || command === '-h') {\n this.printHelp();\n return;\n }\n\n switch (command) {\n case 'index': {\n const fileIdx = args.indexOf('--file');\n const fileArg = fileIdx !== -1 ? args[fileIdx + 1] : undefined;\n if (fileIdx !== -1 && (!fileArg || fileArg.startsWith('--'))) {\n console.error('[ctxo] --file requires a path argument');\n process.exit(1);\n return;\n }\n const checkArg = args.includes('--check');\n const skipHistory = args.includes('--skip-history');\n const maxHistoryIdx = args.indexOf('--max-history');\n const maxHistoryArg = maxHistoryIdx !== -1 ? Number(args[maxHistoryIdx + 1]) : undefined;\n if (maxHistoryIdx !== -1 && (!maxHistoryArg || isNaN(maxHistoryArg) || maxHistoryArg < 1)) {\n console.error('[ctxo] --max-history requires a positive integer');\n process.exit(1);\n return;\n }\n await new IndexCommand(this.projectRoot).run({ file: fileArg, check: checkArg, skipHistory, maxHistory: maxHistoryArg });\n break;\n }\n\n case 'sync':\n await new SyncCommand(this.projectRoot).run();\n break;\n\n case 'watch':\n await new WatchCommand(this.projectRoot).run();\n break;\n\n case 'verify-index':\n await new VerifyCommand(this.projectRoot).run();\n break;\n\n case 'status':\n new StatusCommand(this.projectRoot).run();\n break;\n\n case 'init': {\n const toolsIdx = args.indexOf('--tools');\n const toolsArg = toolsIdx !== -1 ? args[toolsIdx + 1] : undefined;\n const yesArg = args.includes('--yes') || args.includes('-y');\n const rulesOnly = args.includes('--rules');\n const dryRun = args.includes('--dry-run');\n const tools = toolsArg ? toolsArg.split(',').map(t => t.trim()) : undefined;\n await new InitCommand(this.projectRoot).run({ tools, yes: yesArg, rulesOnly, dryRun });\n break;\n }\n\n case 'stats': {\n const daysIdx = args.indexOf('--days');\n const daysArg = daysIdx !== -1 ? Number(args[daysIdx + 1]) : undefined;\n const jsonArg = args.includes('--json');\n const clearArg = args.includes('--clear');\n await new StatsCommand(this.projectRoot).run({ days: daysArg, json: jsonArg, clear: clearArg });\n break;\n }\n\n case 'doctor': {\n const jsonArg = args.includes('--json');\n const quietArg = args.includes('--quiet');\n await new DoctorCommand(this.projectRoot).run({ json: jsonArg, quiet: quietArg });\n break;\n }\n\n default:\n console.error(`[ctxo] Unknown command: \"${command}\". Run \"ctxo --help\" for usage.`);\n process.exit(1);\n return;\n }\n }\n\n private printHelp(): void {\n console.error(`\nctxo — MCP server for dependency-aware codebase context\n\nUsage:\n ctxo Start MCP server (stdio transport)\n ctxo index Build full codebase index (--max-history N, default 20)\n ctxo sync Rebuild SQLite cache from committed JSON index\n ctxo watch Start file watcher for incremental re-indexing\n ctxo verify-index CI gate: fail if index is stale\n ctxo status Show index manifest\n ctxo init Interactive setup (tools, rules, hooks)\n ctxo init --rules Regenerate AI tool rules only\n ctxo init --tools a,b -y Non-interactive (claude-code,cursor,...)\n ctxo init --dry-run Preview what would be created\n ctxo stats Show usage statistics (--json, --days N, --clear)\n ctxo doctor Health check all subsystems (--json, --quiet)\n ctxo --help Show this help message\n`.trim());\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,YAAY;AAGnB,SAAS,WAAAA,gBAAe;AAHxB,IAOsB;AAPtB;AAAA;AAAA;AAOO,IAAe,oBAAf,MAA6D;AAAA,MAEzD,OAAO;AAAA,MAEN;AAAA,MACA,iBAAiB,oBAAI,IAAwB;AAAA,MAEvD,YAAY,UAAoB;AAC9B,aAAK,SAAS,IAAI,OAAO;AACzB,aAAK,OAAO,YAAY,QAAQ;AAAA,MAClC;AAAA,MAEA,YAAY,UAA2B;AACrC,cAAM,MAAMA,SAAQ,QAAQ,EAAE,YAAY;AAC1C,eAAQ,KAAK,WAAiC,SAAS,GAAG;AAAA,MAC5D;AAAA,MAEA,kBAAkB,UAAyC;AACzD,aAAK,iBAAiB;AAAA,MACxB;AAAA,MAEU,MAAM,QAAsB;AACpC,eAAO,KAAK,OAAO,MAAM,MAAM;AAAA,MACjC;AAAA,MAEU,cAAc,UAAkB,MAAc,MAA0B;AAChF,eAAO,GAAG,QAAQ,KAAK,IAAI,KAAK,IAAI;AAAA,MACtC;AAAA,MAEU,gBAAgB,MAKxB;AACA,eAAO;AAAA,UACL,WAAW,KAAK,cAAc;AAAA,UAC9B,SAAS,KAAK,YAAY;AAAA,UAC1B,aAAa,KAAK;AAAA,UAClB,WAAW,KAAK;AAAA,QAClB;AAAA,MACF;AAAA,MAEU,0BAA0B,MAAkB,aAA+B;AACnF,YAAI,aAAa;AACjB,cAAM,QAAQ,CAAC,MAAkB;AAC/B,cAAI,YAAY,SAAS,EAAE,IAAI,GAAG;AAChC;AAAA,UACF;AACA,mBAAS,IAAI,GAAG,IAAI,EAAE,YAAY,KAAK;AACrC,kBAAM,EAAE,MAAM,CAAC,CAAE;AAAA,UACnB;AAAA,QACF;AACA,cAAM,IAAI;AACV,eAAO;AAAA,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AW,KAAK,SAAS,SAAS;AACxC,cAAM,IAAI,cAAc,KAAK,WAAW,EAAE,IAAI,EAAE,MAAM,SAAS,OAAO,SAAS,CAAC;AAChF;AAAA,MACF;AAAA,MAEA;AACE,gBAAQ,MAAM,4BAA4B,OAAO,iCAAiC;AAClF,gBAAQ,KAAK,CAAC;AACd;AAAA,IACJ;AAAA,EACF;AAAA,EAEQ,YAAkB;AACxB,YAAQ,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiBhB,KAAK,CAAC;AAAA,EACN;AACF;","names":["extname","readFileSync","writeFileSync","existsSync","join","extname","kind","extname","dirname","join","writeFileSync","existsSync","mkdirSync","join","dirname","join","readFileSync","GoAdapter","CSharpAdapter","existsSync","extname","writeFileSync","join","join","join","existsSync","execFileSync","join","existsSync","execFileSync","join","join","join","existsSync","readFileSync","writeFileSync","mkdirSync","existsSync","readFileSync","writeFileSync","mkdirSync","join","dirname","updated","join","mkdirSync","existsSync","readFileSync","createRequire","require","writeFileSync","join","extname","relative","readFileSync","join","relative","readFileSync","extname","GoAdapter","CSharpAdapter","join","existsSync","readFileSync","join","existsSync","readFileSync","writeFileSync","join","existsSync","require","execFileSync","existsSync","join","existsSync","execFileSync","join","pass","warn","fail","join","existsSync","execFileSync","existsSync","readFileSync","join","initSqlJs","existsSync","readFileSync","join","existsSync","readdirSync","statSync","join","join","existsSync"]}