HurairaMaqbool/CodeNavigator

GitHub: HurairaMaqbool/CodeNavigator

一个基于 Agentic RAG 的代码库理解平台,通过混合检索和 AST 调用图谱提供带有可靠文件与行号引用的代码级问答。

Stars: 0 | Forks: 0


提出任何关于代码库的问题。在几秒钟内获得有根据、有引用的答案 —— 而无需花费数小时使用 grep。

[![许可证](https://img.shields.io/badge/License-Proprietary-8A2BE2?style=for-the-badge&labelColor=0d1117)](#-许可证--知识产权) [![Python](https://img.shields.io/badge/Python-3.12-3776AB?style=for-the-badge&logo=python&logoColor=white&labelColor=0d1117)](#-技术栈) [![FastAPI](https://img.shields.io/badge/FastAPI-Backend-009688?style=for-the-badge&logo=fastapi&logoColor=white&labelColor=0d1117)](#-技术栈) [![Next.js](https://img.shields.io/badge/Next.js-Frontend-000000?style=for-the-badge&logo=next.js&logoColor=white&labelColor=0d1117)](#-技术栈) [![状态](https://img.shields.io/badge/Status-Active%20Development-F55036?style=for-the-badge&labelColor=0d1117)](#-路线图)
![ChromaDB](https://img.shields.io/badge/ChromaDB-Vector%20Store-6E57F7?style=flat-square) ![BM25](https://img.shields.io/badge/BM25-Sparse%20Retrieval-4ECDC4?style=flat-square) ![NetworkX](https://img.shields.io/badge/NetworkX-Call%20Graph-orange?style=flat-square) ![TreeSitter](https://img.shields.io/badge/Tree--sitter-AST%20Parsing-44A340?style=flat-square) ![Groq](https://img.shields.io/badge/Groq-LLM%20Inference-F55036?style=flat-square) ![PostgreSQL](https://img.shields.io/badge/PostgreSQL-Metadata%20Store-336791?style=flat-square&logo=postgresql&logoColor=white) ![RAGAS](https://img.shields.io/badge/RAGAS-Evaluation-6E57F7?style=flat-square)
Typing SVG

📋 目录
| # | 章节 | # | 章节 | |---|---------|---|---------| | 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) |
## 🧠 关于本项目 **接手一个陌生的代码库上手过程非常缓慢。** 工程师们常常需要花费数天时间去追踪调用链,阅读早已过时的文档,并打扰高级开发人员以获取上下文,这打断了所有人的工作流。 **CodeNavigator** 是一个 Agentic RAG 平台,旨在消除这种摩擦。只需将其指向一个代码仓库,它就会构建一个**三重索引** —— 包含稠密 embedding、稀疏关键词搜索和结构化 call graph —— 然后提供一个由 FSM 驱动的自主 agent,能够回答有关代码实际运行方式的精确且基于源码的问题。 这并非一个简单的 LLM 包装器。它是一个带有硬性验证阶段的确定性 agent 循环:模型生成的每一个引用在允许呈现给用户之前,都会与真实的文件系统进行比对检查。 | | 传统方式 | CodeNavigator | |---|---|---| | 📖 | 阅读与代码不同步的文档 | 直接从已索引的源码中实时生成答案 | | 🔍 | 手动使用 grep 并追踪函数调用 | Graph 引擎通过 NetworkX BFS 解析调用者/被调用者 | | 🙋 | 打断高级工程师询问“X 是在哪里发生的?” | 询问 agent —— 它会引用确切的文件和行号范围 | | 🤞 | 盲信 LLM 听起来自信但未经证实的答案 | 每一个引用都会与索引进行核对;低置信度的答案会被拦截 | ## ✨ 核心功能
| | 功能 | 描述 | |---|---|---| | 🤖 | **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 # 生产 frontend build cd frontend-next && npm run build ``` RAGAS 追踪 **Faithfulness**、**Answer Relevancy**、**Context Precision** 和 **Context Recall**,并具备针对速率限制强化的重试机制:`eval/run_eval.py` 会解析 Groq 自身的速率限制提示并进行指数退避(上限为 20 秒,最多尝试 5 次),同时 `eval/ragas_providers.py` 会配置评审模型自身的客户端级别重试处理,而不是将其禁用。 ## 📝 工程笔记 这里记录了在开发过程中解决的一些非同寻常的问题 —— 保留在这里,而不是深埋在 commit 历史中: | # | 问题 | 解决方案 | |---|---|---| | 1 | 长内容导致侧边栏垂直滚动失效 | 重构固定定位的容器结构 | | 2 | 符号搜索下拉菜单在其他面板下被遮挡 | 应用 `relative z-50` 堆叠层包裹器 | | 3 | RAGAS 图表 TypeScript 编译失败 | 在解析 Recharts 标签周围添加类型保护 | | 4 | 符号检查器中起始斜杠路径不一致 | 通过 `.lstrip('/')` 进行规范化处理 | | 5 | 速率限制重试循环无法终止 | 提高退避上限并调整休眠阈值 | | 6 | RAGAS 评审触发提供商速率限制 | 在 RAGAS `ChatGroq` 客户端上设置 `max_retries > 0` | | 7 | 评估的“比较运行”缺少较早的记录 | 改为通过 job ID 匹配缺少 `repo_id` 的旧版评估记录 | ## 🛣️ 路线图 ``` ✅ Phase 1 — Core Pipeline [x] Git ingestion + Tree-sitter AST chunking [x] Triple indexing — ChromaDB + BM25 + NetworkX [x] Hybrid search with Reciprocal Rank Fusion [x] Deterministic agentic FSM loop ✅ Phase 2 — Safety & Reliability [x] Hallucination Guard with citation validation [x] Semantic answer cache [x] IP-protected prompt loader with safe fallbacks [x] Rate-limit-hardened RAGAS evaluation 🔄 Phase 3 — Evaluation & Observability (in progress) [ ] Expanded RAGAS golden set [ ] Tracing / observability integration [ ] Automated regression detection 🔮 Phase 4 — Extensions [ ] Additional Tree-sitter language grammars [ ] Multi-repo cross-codebase queries [ ] Containerized deployment + CI/CD ``` ## 📄 许可证与知识产权 **版权所有 © 2026 Huraira Maqbool。保留所有权利。** 本仓库 —— 包括 Agentic FSM 循环、prompt 工程模板、置信度门控逻辑、检索算法和系统架构 —— 均为作者的专有作品,发布仅供**学习、演示和作品集评估之用**。 - 🚫 未经明确的书面许可,**不得用于商业用途** - 🚫 **严禁重新分发**或重新托管本代码库或其衍生作品 - 🚫 未经同意,**不得复用**其 prompt 结构或检索系统 有关许可或合作咨询,请联系:**hurairac37@gmail.com** ## 👤 作者
### **Huraira Maqbool** *AI 工程师 · Agentic RAG 系统 · LangChain · LangGraph* [![GitHub](https://img.shields.io/badge/GitHub-HurairaMaqbool-181717?style=for-the-badge&logo=github&logoColor=white)](https://github.com/HurairaMaqbool) [![LinkedIn](https://img.shields.io/badge/LinkedIn-Connect-0A66C2?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/huraira-maqbool-b696a5277/) [![Email](https://img.shields.io/badge/Email-Contact-EA4335?style=for-the-badge&logo=gmail&logoColor=white)](mailto:hurairac37@gmail.com)
*如果 CodeNavigator 节省了您理解代码库的时间,在 GitHub 上点个 ⭐ 可以帮助其他工程师发现它。*
使用 🐍 Python · ⚡ FastAPI · 🧠 Agentic RAG · 🕸️ NetworkX 构建
标签:AI智能体, 代码理解, 威胁情报, 开发者工具, 检索增强生成, 测试用例, 混合检索, 特权检测, 逆向工具