HurairaMaqbool/CodeNavigator
GitHub: HurairaMaqbool/CodeNavigator
一个基于 Agentic RAG 的代码库理解平台,通过混合检索和 AST 调用图谱提供带有可靠文件与行号引用的代码级问答。
Stars: 0 | Forks: 0
提出任何关于代码库的问题。在几秒钟内获得有根据、有引用的答案 —— 而无需花费数小时使用 grep。
[](#-许可证--知识产权) [](#-技术栈) [](#-技术栈) [](#-技术栈) [](#-路线图)
      
📋 目录
| # | 章节 | # | 章节 | |---|---------|---|---------| | 1 | [关于本项目](#-about-the-project) | 9 | [设计系统](#-design-system) | | 2 | [核心功能](#-features) | 10 | [目录结构](#-directory-map) | | 3 | [系统架构](#-system-architecture) | 11 | [安装与本地运行](#-setup--local-execution) | | 4 | [Agentic FSM 循环](#-the-agentic-fsm-loop) | 12 | [测试与评估](#-testing--evaluation) | | 5 | [混合检索引擎](#-hybrid-retrieval-engine-rrf) | 13 | [工程笔记](#-engineering-notes) | | 6 | [幻觉防御](#-hallucination-guard) | 14 | [路线图](#-roadmap) | | 7 | [受 IP 保护的 Prompt 加载器](#-ip-protected-prompt-loader) | 15 | [许可证与 IP](#-license--intellectual-property) | | 8 | [API 参考](#-api-reference) | 16 | [作者](#-author) |
| | 功能 | 描述 |
|---|---|---|
| 🤖 | **Agentic FSM 循环** | 一个确定性的 `PLAN → ACT → OBSERVE → DECIDE → VERIFY → RESPOND` 状态机 —— 由 LLM 决定下一步做什么,但循环结构可以防止失控或无根据的行为 |
| 🔀 | **混合检索** | ChromaDB 稠密向量 + BM25 稀疏关键词搜索,通过 Reciprocal Rank Fusion (RRF) 融合 |
| 🕸️ | **AST 关系图** | Tree-sitter 将代码库解析为包含类、方法和调用关系的 NetworkX 图谱 |
| 🛡️ | **幻觉防御** | 最终答案中的每一个 markdown 引用都会被验证 —— 包括文件是否存在、行范围界限 —— 并在发布给用户之前进行评分 |
| 📊 | **Mermaid 图表** | 调用子图将被遍历,并直接在聊天/画布 UI 中渲染为 Mermaid 流程图 |
| ⚡ | **语义化答案缓存** | 基于 embedding 的缓存可在同一 commit 版本内瞬间响应重复的问题 |
| 🔒 | **受 IP 保护的 Prompt** | 动态加载器在存在时从私有目录读取专有的 prompt 模板,否则回退到安全的默认操作配置 |
| 📈 | **RAGAS 评估** | 自动化 Faithfulness / Relevancy / Precision / Recall 评分,并针对 LLM 提供商的速率限制采取了强化的重试退避机制 |
| 🌐 | **REST + SSE API** | FastAPI 后端,支持 API key 认证、速率限制,以及用于流式传输 agent 轨迹和 token 的 Server-Sent Events (SSE) |
## 🏗️ 系统架构
CodeNavigator 运行解耦的客户端/服务器架构。Next.js 前端通过 REST 与 FastAPI 后端进行标准调用通信,并通过 SSE 流式传输 agent 的推理轨迹和 token。
```
graph TD
subgraph Frontend [Next.js Web Client — Port 3000]
UI[Workspace UI Shell]
Chat[RAG Chat Panel]
Canvas[Mermaid Diagram Canvas]
Eval[Evaluation Dashboard]
end
subgraph Backend [FastAPI Server — Port 8000]
API[API Gateway / Auth / Router]
Agent[Agentic RAG FSM Loop]
Retrieval[Hybrid Retrieval Engine]
Graph[AST Relation Graph Engine]
Ingestion[Repo Ingestion Pipeline]
end
subgraph Storage [Persistence & Indexes]
Chroma[ChromaDB Vector Index]
BM25[BM25 Sparse Index]
NetX[NetworkX Graph File]
Postgres[PostgreSQL Metadata]
Files[Local Repo Clones]
end
UI -->|API Requests| API
Chat -->|SSE Stream| API
API -->|Orchestrates| Agent
Agent -->|Queries| Retrieval
Retrieval -->|Dense Embeddings| Chroma
Retrieval -->|Sparse Match| BM25
Agent -->|AST Code Context| Files
API -->|Traverses Call Graph| Graph
Graph -->|NetworkX BFS| NetX
API -->|Triggers Job| Ingestion
Ingestion -->|Writes| Chroma
Ingestion -->|Writes| BM25
Ingestion -->|Writes| NetX
Ingestion -->|Clones| Files
API -->|CRUD| Postgres
```
### 数据接入 Pipeline
```
Repo URL Submitted
│
▼
Clone / Fetch (app/ingestion/clone.py)
│
▼
File Filter (app/ingestion/file_filter.py) — drops binaries, vendor packages, assets
│
▼
Tree-sitter Parse (app/parsing/tree_sitter_parser.py) — functions, classes, dependencies
│
▼
┌────────────────────────────────────────┐
│ Parallel Indexing │
│ → ChromaDB (dense embeddings) │
│ → BM25 store (sparse keyword index) │
│ → NetworkX (call graph) │
└────────────────────────────────────────┘
```
## 🔄 Agentic FSM 循环
CodeNavigator 的核心是一个**确定性有限状态机 (FSM)** —— 而非自由形式的 agent 循环 —— 专门设计用于保持模型有据可循,并限制其可执行的步骤数。
```
[PLAN] ──► [ACT (Search / Read)] ──► [OBSERVE] ──► [DECIDE: Iterate?]
│
├──► Yes ──► [PLAN]
└──► No ──► [VERIFY] ──► [RESPOND]
```
| 状态 | 职责 |
|---|---|
| **PLAN** | 根据用户查询和对话历史选择下一个逻辑步骤 |
| **ACT** | 调用 agent 工具之一 —— `search_code`、`view_file_snippet`、`list_calls` |
| **OBSERVE** | 收集并规范化原始工具的输出 |
| **DECIDE** | 决定是否已收集到足够的上下文(强制执行迭代次数上限) |
| **VERIFY** | 将生成的每一个引用与真实的文件/行边界进行交叉核对;剔除无效内容 |
| **RESPOND** | 将最终的、有根据的答案流式传输回客户端 |
该逻辑在 [`app/agent/loop.py`](file:///d:/github%20project/codebase-onboarding-agent/app/agent/loop.py) 中实现,每个状态的 prompt 由专用的格式化程序组装 —— [`plan_prompt.py`](file:///d:/github%20project/codebase-onboarding-agent/app/agent/prompts/plan_prompt.py)、[`decide_prompt.py`](file:///d:/github%20project/codebase-onboarding-agent/app/agent/prompts/decide_prompt.py)、[`finalize_prompt.py`](file:///d:/github%20project/codebase-onboarding-agent/app/agent/prompts/finalize_prompt.py) 和 [`compress_prompt.py`](file:///d:/github%20project/codebase-onboarding-agent/app/agent/prompts/compress_prompt.py) —— 它们全部由[受 IP 保护的 prompt 加载器](#-ip-protected-prompt-loader)提供支持。
## 🔀 混合检索引擎 (RRF)
检索过程利用 **Reciprocal Rank Fusion**,将来自 ChromaDB 的语义向量得分与来自 BM25 的关键词排名进行融合,该逻辑在 [`app/retrieval/hybrid_search.py`](file:///d:/github%20project/codebase-onboarding-agent/app/retrieval/hybrid_search.py) 中实现:
```
RRF_Score(d) = Σ (1 / (k + r_m(d))) for each retrieval model m in M
```
- **M** —— 检索模型集合(ChromaDB 稠密向量,BM25 稀疏索引)
- **r_m(d)** —— 文档 `d` 在模型 `m` 下的排名(从 1 开始计数)
- **k** —— 平滑常数,配置为 `60`
- 匹配测试文件模式(`/tests/`、`test_*.py`)的文档,其排名会受到惩罚,以便优先考虑实现源代码而非测试脚手架
## 🛡️ 幻觉防御
agent 生成的每一个答案在到达用户之前,都会经过一个确定性的验证阶段 —— 该逻辑在 [`app/agent/confidence.py`](file:///d:/github%20project/codebase-onboarding-agent/app/agent/confidence.py) 中实现:
```
Final LLM Answer
│
▼
Parse markdown citations (e.g. `src/auth.py:10-15`)
│
▼
For each citation:
• Does the file exist in the index? No → penalize score
• Are the line numbers within file bounds? No → penalize score
│
▼
Compute a deterministic confidence score
│
├── Passes threshold → return answer, citations intact
└── Fails threshold → strip answer, return a safe fallback
```
答案绝不会仅仅依靠模型自身的置信度来发布 —— 而是仅根据从实际索引文件中独立计算出的得分来决定。
## 🔒 受 IP 保护的 Prompt 加载器
为了将专有的系统 prompt 和用于提升答案质量的 few-shot 数据集保留在公开仓库之外,[`app/agent/prompts/loader.py`](file:///d:/github%20project/codebase-onboarding-agent/app/agent/prompts/loader.py) 实现了一种回退模式:
```
Loader → checks /private/prompts/
→ found → reads and injects the real templates into the agent loop
→ not found → loads safe, generic fallback strings baked into the code
```
这使得公开仓库能够以合理的默认配置端到端运行,而生产系统则在本地使用专有的 prompt 集。
## 🔌 API 参考
配置 API key 后,所有请求都需要包含 `X-API-Key` header。
| 方法 | Endpoint | 描述 | 请求 Payload | 响应 |
|---|---|---|---|---|
| `POST` | `/api/ingest` | 启动仓库数据接入 | `{ "url": "string" }` | `{ "job_id": "string", "status": "processing" }` |
| `GET` | `/api/ingest/status/{job_id}` | 轮询接入 pipeline 进度 | — | `{ "status": "ready\|processing\|failed", "files_parsed": 12, ... }` |
| `POST` | `/api/chat` | 查询 RAG FSM agent | `{ "message": "string", "repo_id": "string" }` | SSE 流 —— 事件包括: `state`、`token`、`done`、`error` |
| `GET` | `/api/symbols/{repo_id}` | 列出已索引的 AST 符号定义 | — | `[{ "name": "string", "path": "string", "start_line": 10 }]` |
| `GET` | `/api/diagram/{repo_id}` | 遍历方法调用并生成 Mermaid 图表 | Query: `symbol_name`、`depth` | `{ "mermaid_code": "string" }` |
| `GET` | `/api/file-snippet/{repo_id}` | 获取有边界的代码片段 | Query: `file_path`、`start_line`、`end_line` | `{ "code": "string", "start_line": 5, "end_line": 25 }` |
| `POST` | `/api/eval/run` | 触发 RAGAS 评估运行 | Query: `repo_id` | `{ "job_id": "string", "status": "started" }` |
## 🎨 设计系统
CodeNavigator 提供了定制的 **"Midnight Studio"** 暗黑主题,定义于 [`frontend-next/app/globals.css`](file:///d:/github%20project/codebase-onboarding-agent/frontend-next/app/globals.css):
```
:root {
--background: 240 10% 3.9%; /* Deep Charcoal */
--foreground: 0 0% 98%; /* Clean White */
--card: 240 10% 5.9%; /* Matte Gray */
--border: 240 5.9% 15%; /* Fine Border Accent */
--primary: 263.4 70% 50.4%; /* Royal Violet #8b5cf6 */
--primary-foreground: 210 20% 98%;
--success: 142.1 76.2% 36.3%; /* Forest Green */
--warning: 37.9 90.2% 50.2%; /* Warning Amber */
--destructive: 0 72.2% 50.6%; /* Alert Red */
}
```
## 🛠️ 技术栈
| 层级 | 技术 | 作用 |
|---|---|---|
| **后端** | FastAPI | REST API、SSE 流式传输、后台数据接入任务 |
| **前端** | Next.js | 聊天面板、Mermaid 图表画布、评估仪表板 |
| **LLM 推理** | Groq | agent 推理与答案生成 |
| **向量存储** | ChromaDB | 稠密 embedding 存储与语义搜索 |
| **关键词索引** | BM25 (自定义) | 精确匹配符号 / 关键词搜索 |
| **Graph 引擎** | NetworkX | Call graph 建模与 BFS 遍历 |
| **AST 解析器** | Tree-sitter | 支持多语言的函数/类提取 |
| **元数据数据库** | PostgreSQL | Job、repo 和评估元数据 |
| **评估** | RAGAS | Faithfulness、Relevancy、Precision、Recall 评分 |
| **图表** | Mermaid.js | Call graph 可视化 |
| **支付** | Stripe | 定价方案与计费表 (`app/platform/billing/`) |
## 📁 目录结构
```
codebase-onboarding-agent/
│
├── app/
│ ├── main.py ← FastAPI entry point, middleware, lifecycle
│ ├── config.py ← Pydantic Settings (env-driven config)
│ │
│ ├── api/
│ │ ├── router.py ← Ingestion / chat / graph / snippet / eval / billing routes
│ │ ├── auth.py ← API key + multi-tenant auth
│ │ ├── rate_limiter.py ← Slotted-bucket rate limiting
│ │ └── state_stream.py ← SSE generator for agent traces + tokens
│ │
│ ├── agent/
│ │ ├── loop.py ← FSM agent loop (PLAN→ACT→OBSERVE→DECIDE→VERIFY→RESPOND)
│ │ ├── tools.py ← search_code / view_file_snippet / list_calls
│ │ ├── confidence.py ← Hallucination Guard
│ │ ├── semantic_cache.py ← Embedding-based answer cache
│ │ └── prompts/
│ │ ├── loader.py ← IP-protected prompt loader
│ │ ├── plan_prompt.py
│ │ ├── decide_prompt.py
│ │ ├── finalize_prompt.py
│ │ ├── compress_prompt.py
│ │ └── answer_quality_dataset.py
│ │
│ ├── retrieval/
│ │ ├── embeddings.py ← SentenceTransformers dense embeddings
│ │ ├── vector_store.py ← ChromaDB client manager
│ │ ├── bm25_store.py ← BM25 sparse index
│ │ └── hybrid_search.py ← RRF fusion + test-file demotion
│ │
│ ├── graph/
│ │ └── builder.py ← NetworkX graph builder (classes, scopes, calls)
│ │
│ ├── diagrams/
│ │ └── mermaid_generator.py ← AST subgraph → Mermaid flowchart
│ │
│ ├── ingestion/
│ │ ├── clone.py ← Git URL resolution + auth + cloning
│ │ └── file_filter.py ← Source vs. vendor/asset filtering
│ │
│ ├── parsing/
│ │ └── tree_sitter_parser.py ← AST extraction (functions, classes, deps)
│ │
│ └── platform/
│ └── billing/ ← Stripe payment + subscription management
│
├── frontend-next/
│ └── app/
│ ├── layout.tsx ← Global shell, fonts, theme providers
│ ├── globals.css ← Midnight Studio theme
│ ├── onboarding/page.tsx ← Repo ingestion wizard
│ ├── chat/page.tsx ← Agent RAG dialog window
│ ├── architecture/page.tsx ← Call-graph canvas + inspector
│ └── evaluation/page.tsx ← RAGAS score history + CI checks
│
├── eval/
│ ├── run_eval.py ← RAGAS evaluation runner (429-hardened)
│ └── ragas_providers.py ← ChatGroq judge with retry-backoff
│
├── tests/ ← Full pytest suite
└── start.bat ← One-command local startup
```
## 🚀 安装与本地运行
### 前置条件
```
python --version # 3.12+
node --version # 18+
```
### 安装说明
```
# 克隆 repository
git clone https://github.com/HurairaMaqbool/codebase-onboarding-agent.git
cd codebase-onboarding-agent
# 创建并激活虚拟环境
python -m venv .venv
.venv\Scripts\activate # Windows
source .venv/bin/activate # macOS / Linux
# 安装 backend 依赖
pip install -r requirements.txt
# 安装 frontend 依赖
cd frontend-next && npm install && cd ..
# 配置环境变量
cp .env.example .env
```
使用你的密钥编辑 `.env`(如 `GROQ_API_KEY`、`POSTGRES_URI`、`REPOS_PATH`、模型选择、搜索阈值 —— 详情请参见 `app/config.py`)。
### 运行
```
# 单个命令(Windows)— 启动 backend (8000) + frontend (3000)
start.bat
# 或者手动执行,在两个终端中:
uvicorn app.main:app --host 0.0.0.0 --port 8000 # Terminal 1
cd frontend-next && npm run dev # Terminal 2
```
| 服务 | URL |
|---|---|
| FastAPI 后端 | http://localhost:8000 |
| API 文档 | http://localhost:8000/docs |
| Next.js 前端 | http://localhost:3000 |
## 🧪 测试与评估
```
# 完整测试套件
pytest
# 在 golden set 上进行 RAGAS 评估
python -m eval.run_eval
### **Huraira Maqbool**
*AI 工程师 · Agentic RAG 系统 · LangChain · LangGraph*
[](https://github.com/HurairaMaqbool)
[](https://www.linkedin.com/in/huraira-maqbool-b696a5277/)
[](mailto:hurairac37@gmail.com)
*如果 CodeNavigator 节省了您理解代码库的时间,在 GitHub 上点个 ⭐ 可以帮助其他工程师发现它。*
标签:AI智能体, 代码理解, 威胁情报, 开发者工具, 检索增强生成, 测试用例, 混合检索, 特权检测, 逆向工具