代码知识图谱检索系统

本地优先的混合RAG系统,通过AST解析、嵌入和关系图索引代码库,为AI编程助手提供精确上下文检索。

  • by david-franz
  • TypeScript
  • 本地部署
  • 15 星标
  • 更新于
在 GitHub 查看 david-franz/ctx-sys

使用说明

ctx系统

代码知识图上的本地混合RAG。 使用树状图AST+嵌入+关系图对代码库进行索引,并通过MCP为任何AI编码助手检索精确的上下文。本地优先,代码感知,专注于它擅长的一件事。

Alpha——尚未在npm上。 现在从源代码安装(请参阅 从源头构建) npm install -g ctx-sys 发布包后,以下路径适用。

为什么选择ctx-sys?

AI编码助手受到上下文窗口的限制。他们看不到你的整个代码库,也错过了文件之间的连接。ctx-sys充当 聪明的图书管理员 --它为代码建立索引,理解符号之间的关系,并通过MCP准确检索正确的上下文。

  • 混合动力RAG --将向量搜索、关键字/FTS5和图遍历与倒排融合相结合。
  • 本地优先 --你的代码永远不会离开你的机器。Ollama处理嵌入和(可选)摘要。
  • 代码感知 --树型AST解析使用Types/JavaScript、Python、C/C++和C#的专用提取器提取函数、类、导入和关系(Go、Rust和Java也使用树型进行解析,但使用更轻的通用提取器——请参阅 支持的语言).
  • MCP本地 --适用于Claude Desktop、Claude Code、Cursor或任何兼容MCP的客户端。

ctxsys专注于检索。会话/会话内存有意超出范围——如果需要,可以将其与lean ctx、mem0或助理的本地内存配对。

快速入门(5分钟)

1.安装

npm install -g ctx-sys   # once published; until then, build from source (see below)

# Install and start Ollama (for embeddings)
# macOS: brew install ollama
# Linux: curl -fsSL https://ollama.com/install.sh | sh
ollama serve &
ollama pull mxbai-embed-large:latest

或者让ctx-sys为您进行设置: ctx-sys setup 检测可用后端(Ollama、OpenAI兼容服务器、llamafile),在缺少Ollama时可选择在macOS/Linux上安装Ollama,提取所需的模型,编写启动配置,并运行 ctx-sys doctor 以确认。旗帜: --yes (非交互式), --install / --no-install, --backend ollama|openai-compatible|openai, --no-models, --json.

2.为你的项目建立索引

cd your-project
ctx-sys init
ctx-sys index

这将使用树形图解析您的代码,使用Ollama生成嵌入,并对文档进行索引——所有这些都在一个命令中完成。 ctx-sys init 还将MCP服务器注册到 .mcp.json, .cursor/mcp.json, ~/.codex/config.toml,以及 .github/copilot-instructions.md (选择退出 --no-mcp; --mcp-name X 对于并排索引),并安装git挂钩以保持索引在各个索引之间的同步 git checkout / pull / rebase (选择退出 --no-git-hooks).

3.搜索

ctx-sys search "how does authentication work"     # hybrid search (semantic + keyword)
ctx-sys context "error handling in the API layer" # assembled context with expansion
ctx-sys search "database connection pooling" --hyde

4.连接到您的AI助手

ctx-sys init 自动注册MCP服务器。用手把它连接起来——因为 克劳德桌面 (in ~/Library/Application Support/Claude/claude_desktop_config.json)或 克劳德代码 (在MCP设置中):

{
  "mcpServers": {
    "ctx-sys": {
      "command": "ctx-sys",
      "args": ["serve"]
    }
  }
}

你的人工智能助手现在有了跨代码库进行混合检索、实体检查和图遍历的工具。

运作原理

Your Code                  ctx-sys                         AI Assistant
─────────                  ───────                         ────────────
  .ts .py .rs    ──→   AST Parse (tree-sitter)
  .md .html      ──→   Document Chunking
                        ↓
                   Entity Extraction
                   (functions, classes, imports)
                        ↓
                   Embed with Ollama              ←──  "How does auth work?"
                   (mxbai-embed-large)                        ↓
                        ↓                              context_query
                   ┌─────────────┐                          ↓
                   │  SQLite DB  │               ┌─────────────────────┐
                   │  + FTS5     │──────────────→│  Hybrid Search      │
                   │  + vec0     │               │  • Vector similarity│
                   │  + Graph    │               │  • FTS5 keyword     │
                   └─────────────┘               │  • Graph traversal  │
                                                 └─────────┬───────────┘
                                                           ↓
                                                    Rank & Assemble
                                                           ↓
                                                  Relevant context with
                                                  source attribution

CLI参考

核心命令

ctx-sys init [directory]          # Initialize project config (+ MCP + git hooks)
ctx-sys index [directory]         # Index code + docs + embeddings
ctx-sys search <query>            # Hybrid search (semantic + keyword)
ctx-sys context <query>           # Assembled context with expansion
ctx-sys status [directory]        # Project info and health checks
ctx-sys serve                     # Start MCP server
ctx-sys watch [directory]         # Watch files and auto-reindex
ctx-sys doctor                    # Provider + native-module + Node version checks (PASS/WARN/FAIL)
ctx-sys setup                     # One-command bootstrap (backends, models, config)

关键标志

# Index
ctx-sys index --content docs      # Documentation only (skip code indexing)
ctx-sys index --content code      # Code only (alias: --no-doc)
ctx-sys index --git-sync          # Diff-driven re-sync since last indexed commit (also runs from git hooks)
ctx-sys index --no-embed          # Skip embedding generation
ctx-sys index --force             # Re-index everything from scratch

# Search
ctx-sys search "query" --hyde     # HyDE-enhanced conceptual search
ctx-sys search "query" --limit 20
ctx-sys search "query" --no-semantic  # Keyword-only

# Context
ctx-sys context "query" --max-tokens 8000
ctx-sys context "query" --no-expand
ctx-sys context "query" --hyde

# Status
ctx-sys status --check            # Full health diagnostics

子指令

# Entity management
ctx-sys entity list               # List indexed entities
ctx-sys entity stats              # Type breakdown
ctx-sys entity get <id>           # Entity details

# Relationship graph
ctx-sys graph query <entity>      # Traverse relationships
ctx-sys graph stats               # Graph statistics

# Embeddings
ctx-sys embed run                 # Generate/update embeddings
ctx-sys embed status              # Coverage report

# Summarization
ctx-sys summarize run             # Generate LLM summaries
ctx-sys summarize status          # Coverage report

# Configuration
ctx-sys config get <key>          # Read a config value
ctx-sys config set <key> <value>  # Set a config value
ctx-sys config list               # Show resolved configuration

# Knowledge bases
ctx-sys kb create <name>          # Package as shareable .ctx-kb
ctx-sys kb install <file>         # Install a knowledge base

# Team instructions (project-scoped guidance entities)
ctx-sys instruction add <name>    # Add an instruction
ctx-sys instruction list          # List instructions

# Debug
ctx-sys debug health              # System health check
ctx-sys debug inspect             # Database tables
ctx-sys debug export <file>       # Export project data

MCP工具

ctx-sys公开了5个基于动作的MCP工具,专注于混合检索:

工具 操作 它的作用
上下文查询 (独立) 具有源属性的混合RAG检索
实体 添加、获取、搜索、删除 管理代码和文档实体
索引 代码库、文档、同步、状态 解析和索引代码和文档
图 链接、查询、统计 导航实体关系
项目 创建、列出、设置活动、删除 多项目管理

配置

项目配置(.ctx-sys/config.yaml)

project:
  name: my-project

indexing:
  content: both          # both (default) | code | docs (documentation only)
  git_hooks: true        # install git-aware sync hooks; `index` reconciles to this
  # doc_extensions:      # override which extensions count as docs.
  #   - .md              # 'docs' mode defaults to prose (.md, .mdx, .txt, .rst, .pdf);
  #   - .txt             # 'both' mode otherwise indexes the full document set.
  ignore:
    - node_modules
    - dist
    - .git

embeddings:
  provider: ollama
  model: mxbai-embed-large:latest

summarization:           # optional, opt-in
  provider: ollama
  model: gemma3:270m

hyde:                    # optional, opt-in
  model: gemma3:270m

indexing.content 控制索引内容: both (默认,代码+文档), code (仅AST实体——与 --no-doc),或 docs (仅文档,跳过代码)。在 docs 模式文档集默认为散文(.md, .mdx, .txt, .rst, .pdf)--设置 indexing.doc_extensions 以任何方式扩大或缩小它。嵌入仍然在索引文档上运行。 index, index --git-sync,以及 watch 万分敬仰 content,将每个更改的文件路由到代码或文档索引器。 watch 也拒绝在git工作树中运行并排除 .yaao/ 工作台抖动。将现有项目切换到 docs 不会删除已索引的代码实体--delete .ctx-sys/ 并为干净的纯文档存储重新索引。这 --content <mode> 每次运行CLI标志都会覆盖配置。

indexing.git_hooks 声明是否支持git的同步挂钩(签出后/合并/重写/applypatch→ ctx-sys index --git-sync)已安装。 ctx-sys index 协调每次运行时的钩子匹配: true (默认)安装/更新它们, false 删除ctx-sys管理的。只有ctx-sys管理的钩子被触碰过; ctx-sys init --no-git-hooks 种子 git_hooks: false.

忽略规则。 ctx-sys init 写一个种子 .ctxignore (构建输出、依赖关系, .yaao/ / .lean-ctx/、锁文件、秘密)。 .gitignore 默认情况下不读取--选择加入 indexing.use_gitignore: true 在配置中,或传递 --use-gitignore 在CLI上。

全局配置(~/.ctx-sys/config.yaml)

database:
  path: ~/.ctx-sys/ctx-sys.db

providers:
  ollama:
    base_url: http://localhost:11434
  openai:
    api_key: ${OPENAI_API_KEY}  # Optional cloud fallback

提供者抽象还通过以下方式涵盖了与OpenAI兼容的服务器(vLLM、LM Studio、llamafile、LiteLLM、llama.cpp) openai-compatible 后端。

支持的语言

下面的一切都是用树保姆解析的。实体提取分为两层: 专用提取器 拉动丰富的、特定语言的符号,同时 通用提取器 是一种回退机制,在没有专用提取器的情况下,按节点类型(没有导入,也没有特定于语言的类型,如特征或接口)检测语法的函数和类/结构。

语言 提取器 提取的实体
types/JavaScript 专用 函数、类、方法、接口、类型、导入
Python 专用 函数、类、方法、导入
C/C++ 专用 函数、类、结构、枚举、命名空间, #includes
C# 专用 类、接口、结构、记录、枚举、方法、用法
Go 泛型 仅限函数、方法和结构
Rust 泛型 仅限于函数和结构
Java 泛型 仅类和方法

Go、Rust和Java都在专用提取器的路线图上(Rust的结构/内隐/特征,Go的接口/嵌入式类型,Java的泛型/注释)。所有语法都通过WASM捆绑在一起 @vscode/tree-sitter-wasm --没有每种语言的本地编译。

文档(Markdown、HTML、YAML、JSON、TOML、PDF、CSV、XML、纯文本)也使用语义分块进行索引。PDF提取可插在 PdfExtractor 界面分为两层:第一层(pdf解析,带有结构化标记+页面标题)和第二层(pdfjs-dist,带有基于字体高度的标题检测+稳定的每页阅读顺序)。内容寻址缓存使重新索引同一PDF成为不可能;具有结构感知的Docling层可以插入到同一接口后面。

需求

  • Node.js 20+ (engines.node: ">=20.0.0").
  • 奥拉玛 (对于本地嵌入;可选的云OpenAI回退可以在没有它的情况下工作)。
    • mxbai-embed-large:latest --嵌入模型(1024维,自动检测)。
    • gemma3:270m --摘要(可选)。
    • gemma3:270m --HyDE查询扩展(可选)。

建筑

ctx-sys将所有内容存储在一个SQLite数据库中(通过 better-sqlite3 --附带自己的SQLite,包括FTS5,因此无需系统级安装):

  • 实体 --代码符号和文档部分。
  • 关系 --包含、导入、调用、扩展、实现(从AST自动提取)。
  • 矢量 --嵌入通过 sqlite-vec 用于快速KNN搜索。
  • FTS5 --BM25排名的全文搜索。

搜索结合了向量+FTS+图检索,使用互逆秩融合(RRF)作为最终排名,并在融合路径的末尾应用一次分数归一化。高级功能包括HyDE查询扩展、查询分解、检索门控和智能上下文扩展。

ctx-sys适合的地方

caveman      → compresses model output + CLAUDE.md         (output side)
lean-ctx     → compresses tool I/O: file reads, shell      (input side, generic)
ctx-sys      → semantic + graph retrieval over codebase    (input side, intelligent)
yaao         → multi-agent orchestrator (uses ctx-sys as native retrieval peer)

姚 与ctx-sys原生集成:启用后,它为每个编排的代理提供自己的 ctx-sys serve MCP服务器,以便代理在编写代码之前查询您的代码库以获取上下文。

从源头构建

git clone https://github.com/david-franz/ctx-sys.git
cd ctx-sys
npm install
npm run build
npm link    # Makes ctx-sys available globally

贡献

欢迎捐款。请参阅 docs/ 实现规范目录(每个功能都有验收标准和范围外行)和架构原理白皮书。

许可证

麻省理工学院——见 许可证.