# rag-web-ui - Doramagic AI Context Pack

> 定位：安装前体验与判断资产。它帮助宿主 AI 有一个好的开始，但不代表已经安装、执行或验证目标项目。

## 充分原则

- **充分原则，不是压缩原则**：AI Context Pack 应该充分到让宿主 AI 在开工前理解项目价值、能力边界、使用入口、风险和证据来源；它可以分层组织，但不以最短摘要为目标。
- **压缩策略**：只压缩噪声和重复内容，不压缩会影响判断和开工质量的上下文。

## 给宿主 AI 的使用方式

你正在读取 Doramagic 为 rag-web-ui 编译的 AI Context Pack。请把它当作开工前上下文：帮助用户理解适合谁、能做什么、如何开始、哪些必须安装后验证、风险在哪里。不要声称你已经安装、运行或执行了目标项目。

## Claim 消费规则

- **事实来源**：Repo Evidence + Claim/Evidence Graph；Human Wiki 只提供显著性、术语和叙事结构。
- **事实最低状态**：`supported`
- `supported`：可以作为项目事实使用，但回答中必须引用 claim_id 和证据路径。
- `weak`：只能作为低置信度线索，必须要求用户继续核实。
- `inferred`：只能用于风险提示或待确认问题，不能包装成项目事实。
- `unverified`：不得作为事实使用，应明确说证据不足。
- `contradicted`：必须展示冲突来源，不得替用户强行选择一个版本。

## 它最适合谁

- **想在安装前理解开源项目价值和边界的用户**：当前证据主要来自项目文档。 证据：`README.md` Claim：`clm_0002` supported 0.86

## 它能做什么

- **命令行启动或安装流程**（需要安装后验证）：项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 证据：`README.md` Claim：`clm_0001` supported 0.86

## 怎么开始

- `git clone https://github.com/rag-web-ui/rag-web-ui.git` 证据：`README.md` Claim：`clm_0003` supported 0.86

## 继续前判断卡

- **当前建议**：需要管理员/安全审批
- **为什么**：继续前可能涉及密钥、账号、外部服务或敏感上下文，建议先经过管理员或安全审批。

### 30 秒判断

- **现在怎么做**：需要管理员/安全审批
- **最小安全下一步**：先跑 Prompt Preview；若涉及凭证或企业环境，先审批再试装
- **先别相信**：真实输出质量不能在安装前相信。
- **继续会触碰**：命令执行、本地环境或项目文件、环境变量 / API Key

### 现在可以相信

- **适合人群线索：想在安装前理解开源项目价值和边界的用户**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`README.md` Claim：`clm_0002` supported 0.86
- **能力存在：命令行启动或安装流程**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`README.md` Claim：`clm_0001` supported 0.86
- **存在 Quick Start / 安装命令线索**（supported）：可以相信项目文档出现过启动或安装入口；不要因此直接在主力环境运行。 证据：`README.md` Claim：`clm_0003` supported 0.86

### 现在还不能相信

- **真实输出质量不能在安装前相信。**（unverified）：Prompt Preview 只能展示引导方式，不能证明真实项目中的结果质量。
- **宿主 AI 版本兼容性不能在安装前相信。**（unverified）：Claude、Cursor、Codex、Gemini 等宿主加载规则和版本差异必须在真实环境验证。
- **不会污染现有宿主 AI 行为，不能直接相信。**（inferred）：Skill、plugin、AGENTS/CLAUDE/GEMINI 指令可能改变宿主 AI 的默认行为。
- **可安全回滚不能默认相信。**（unverified）：除非项目明确提供卸载和恢复说明，否则必须先在隔离环境验证。
- **真实安装后是否与用户当前宿主 AI 版本兼容？**（unverified）：兼容性只能通过实际宿主环境验证。
- **项目输出质量是否满足用户具体任务？**（unverified）：安装前预览只能展示流程和边界，不能替代真实评测。
- **安装命令是否需要网络、权限或全局写入？**（unverified）：这影响企业环境和个人环境的安装风险。 证据：`README.md`

### 继续会触碰什么

- **命令执行**：包管理器、网络下载、本地插件目录、项目配置或用户主目录。 原因：运行第一条命令就可能产生环境改动；必须先判断是否值得跑。 证据：`README.md`
- **本地环境或项目文件**：安装结果、插件缓存、项目配置或本地依赖目录。 原因：安装前无法证明写入范围和回滚方式，需要隔离验证。 证据：`README.md`
- **环境变量 / API Key**：项目入口文档明确出现 API key、token、secret 或账号凭证配置。 原因：如果真实安装需要凭证，应先使用测试凭证并经过权限/合规判断。 证据：`README.md`, `README.zh-CN.md`, `backend/app/api/api_v1/auth.py`, `backend/app/core/config.py` 等
- **宿主 AI 上下文**：AI Context Pack、Prompt Preview、Skill 路由、风险规则和项目事实。 原因：导入上下文会影响宿主 AI 后续判断，必须避免把未验证项包装成事实。

### 最小安全下一步

- **先跑 Prompt Preview**：用安装前交互式试用判断工作方式是否匹配，不需要授权或改环境。（适用：任何项目都适用，尤其是输出质量未知时。）
- **只在隔离目录或测试账号试装**：避免安装命令污染主力宿主 AI、真实项目或用户主目录。（适用：存在命令执行、插件配置或本地写入线索时。）
- **不要使用真实生产凭证**：环境变量/API key 一旦进入宿主或工具链，可能产生账号和合规风险。（适用：出现 API、TOKEN、KEY、SECRET 等环境线索时。）
- **安装后只验证一个最小任务**：先验证加载、兼容、输出质量和回滚，再决定是否深用。（适用：准备从试用进入真实工作流时。）

### 退出方式

- **保留安装前状态**：记录原始宿主配置和项目状态，后续才能判断是否可恢复。
- **记录安装命令和写入路径**：没有明确卸载说明时，至少要知道哪些目录或配置需要手动清理。
- **准备撤销测试 API key 或 token**：测试凭证泄露或误用时，可以快速止损。
- **如果没有回滚路径，不进入主力环境**：不可回滚是继续前阻断项，不应靠信任或运气继续。

## 哪些只能预览

- 解释项目适合谁和能做什么
- 基于项目文档演示典型对话流程
- 帮助用户判断是否值得安装或继续研究

## 哪些必须安装后验证

- 真实安装 Skill、插件或 CLI
- 执行脚本、修改本地文件或访问外部服务
- 验证真实输出质量、性能和兼容性

## 边界与风险判断卡

- **把安装前预览误认为真实运行**：用户可能高估项目已经完成的配置、权限和兼容性验证。 处理方式：明确区分 prompt_preview_can_do 与 runtime_required。 Claim：`clm_0004` inferred 0.45
- **命令执行会修改本地环境**：安装命令可能写入用户主目录、宿主插件目录或项目配置。 处理方式：先在隔离环境或测试账号中运行。 证据：`README.md` Claim：`clm_0005` supported 0.86
- **待确认**：真实安装后是否与用户当前宿主 AI 版本兼容？。原因：兼容性只能通过实际宿主环境验证。
- **待确认**：项目输出质量是否满足用户具体任务？。原因：安装前预览只能展示流程和边界，不能替代真实评测。
- **待确认**：安装命令是否需要网络、权限或全局写入？。原因：这影响企业环境和个人环境的安装风险。

## 开工前工作上下文

### 加载顺序

- 先读取 how_to_use.host_ai_instruction，建立安装前判断资产的边界。
- 读取 claim_graph_summary，确认事实来自 Claim/Evidence Graph，而不是 Human Wiki 叙事。
- 再读取 intended_users、capabilities 和 quick_start_candidates，判断用户是否匹配。
- 需要执行具体任务时，优先查 role_skill_index，再查 evidence_index。
- 遇到真实安装、文件修改、网络访问、性能或兼容性问题时，转入 risk_card 和 boundaries.runtime_required。

### 任务路由

- **命令行启动或安装流程**：先说明这是安装后验证能力，再给出安装前检查清单。 边界：必须真实安装或运行后验证。 证据：`README.md` Claim：`clm_0001` supported 0.86

### 上下文规模

- 文件总数：139
- 重要文件覆盖：40/139
- 证据索引条目：68
- 角色 / Skill 条目：8

### 证据不足时的处理

- **missing_evidence**：说明证据不足，要求用户提供目标文件、README 段落或安装后验证记录；不要补全事实。
- **out_of_scope_request**：说明该任务超出当前 AI Context Pack 证据范围，并建议用户先查看 Human Manual 或真实安装后验证。
- **runtime_request**：给出安装前检查清单和命令来源，但不要替用户执行命令或声称已执行。
- **source_conflict**：同时展示冲突来源，标记为待核实，不要强行选择一个版本。

## Prompt Recipes

### 适配判断

- 目标：判断这个项目是否适合用户当前任务。
- 预期输出：适配结论、关键理由、证据引用、安装前可预览内容、必须安装后验证内容、下一步建议。

```text
请基于 rag-web-ui 的 AI Context Pack，先问我 3 个必要问题，然后判断它是否适合我的任务。回答必须包含：适合谁、能做什么、不能做什么、是否值得安装、证据来自哪里。所有项目事实必须引用 evidence_refs、source_paths 或 claim_id。
```

### 安装前体验

- 目标：让用户在安装前感受核心工作流，同时避免把预览包装成真实能力或营销承诺。
- 预期输出：一段带边界标签的体验剧本、安装后验证清单和谨慎建议；不含真实运行承诺或强营销表述。

```text
请把 rag-web-ui 当作安装前体验资产，而不是已安装工具或真实运行环境。

请严格输出四段：
1. 先问我 3 个必要问题。
2. 给出一段“体验剧本”：用 [安装前可预览]、[必须安装后验证]、[证据不足] 三种标签展示它可能如何引导工作流。
3. 给出安装后验证清单：列出哪些能力只有真实安装、真实宿主加载、真实项目运行后才能确认。
4. 给出谨慎建议：只能说“值得继续研究/试装”“先补充信息后再判断”或“不建议继续”，不得替项目背书。

硬性边界：
- 不要声称已经安装、运行、执行测试、修改文件或产生真实结果。
- 不要写“自动适配”“确保通过”“完美适配”“强烈建议安装”等承诺性表达。
- 如果描述安装后的工作方式，必须使用“如果安装成功且宿主正确加载 Skill，它可能会……”这种条件句。
- 体验剧本只能写成“示例台词/假设流程”：使用“可能会询问/可能会建议/可能会展示”，不要写“已写入、已生成、已通过、正在运行、正在生成”。
- Prompt Preview 不负责给安装命令；如用户准备试装，只能提示先阅读 Quick Start 和 Risk Card，并在隔离环境验证。
- 所有项目事实必须来自 supported claim、evidence_refs 或 source_paths；inferred/unverified 只能作风险或待确认项。

```

### 角色 / Skill 选择

- 目标：从项目里的角色或 Skill 中挑选最匹配的资产。
- 预期输出：候选角色或 Skill 列表，每项包含适用场景、证据路径、风险边界和是否需要安装后验证。

```text
请读取 role_skill_index，根据我的目标任务推荐 3-5 个最相关的角色或 Skill。每个推荐都要说明适用场景、可能输出、风险边界和 evidence_refs。
```

### 风险预检

- 目标：安装或引入前识别环境、权限、规则冲突和质量风险。
- 预期输出：环境、权限、依赖、许可、宿主冲突、质量风险和未知项的检查清单。

```text
请基于 risk_card、boundaries 和 quick_start_candidates，给我一份安装前风险预检清单。不要替我执行命令，只说明我应该检查什么、为什么检查、失败会有什么影响。
```

### 宿主 AI 开工指令

- 目标：把项目上下文转成一次对话开始前的宿主 AI 指令。
- 预期输出：一段边界明确、证据引用明确、适合复制给宿主 AI 的开工前指令。

```text
请基于 rag-web-ui 的 AI Context Pack，生成一段我可以粘贴给宿主 AI 的开工前指令。这段指令必须遵守 not_runtime=true，不能声称项目已经安装、运行或产生真实结果。
```

## 角色 / Skill 索引

- 共索引 8 个角色 / Skill / 项目文档条目。

- **零基础入门：如何用 RAG 检索增强生成 打造知识库 QA 系统**（project_doc）：马上今年要过去了，这个项目是在 2025 年 1 月份闲暇时间发起一个类似于教育类的项目。 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/tutorial/README.md`
- **📖 Introduction**（project_doc）：Knowledge Base Management Based on RAG Retrieval-Augmented Generation 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`README.md`
- **Getting Started**（project_doc）：This is a Next.js https://nextjs.org project bootstrapped with create-next-app https://nextjs.org/docs/app/api-reference/cli/create-next-app . 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`frontend/README.md`
- **for javascript, npm install chromadb!**（project_doc）：Chroma - the open-source embedding database . The fastest way to build Python or JavaScript LLM apps with memory! 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`backend/uploads/README.md`
- **HuggingFace Embeddings Support**（project_doc）：This document explains how to use HuggingFace embedding models with RAG Web UI. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/HUGGINGFACE_EMBEDDINGS.md`
- **Troubleshooting Guide**（project_doc）：If you encounter "table not found" or similar database errors after starting your services, follow these steps: 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/troubleshooting.md`
- **🚀 十分钟搭建属于自己的 DeepSeek 知识库！完全开源、离线部署方案详解**（project_doc）：🚀 十分钟搭建属于自己的 DeepSeek 知识库！完全开源、离线部署方案详解 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/blog/deploy-local.md`
- **📖 简介**（project_doc）：基于 RAG Retrieval-Augmented Generation 的知识库管理 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`README.zh-CN.md`

## 证据索引

- 共索引 68 条证据。

- **零基础入门：如何用 RAG 检索增强生成 打造知识库 QA 系统**（documentation）：马上今年要过去了，这个项目是在 2025 年 1 月份闲暇时间发起一个类似于教育类的项目。 证据：`docs/tutorial/README.md`
- **📖 Introduction**（documentation）：Knowledge Base Management Based on RAG Retrieval-Augmented Generation 证据：`README.md`
- **Getting Started**（documentation）：This is a Next.js https://nextjs.org project bootstrapped with create-next-app https://nextjs.org/docs/app/api-reference/cli/create-next-app . 证据：`frontend/README.md`
- **for javascript, npm install chromadb!**（documentation）：Chroma - the open-source embedding database . The fastest way to build Python or JavaScript LLM apps with memory! 证据：`backend/uploads/README.md`
- **Package**（package_manifest）：{ "name": "rag-web-ui-frontend", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "node server.js", "lint": "next lint", "test": "jest --watch", "test:ci": "jest --ci" }, "dependencies": { "@radix-ui/react-accordion": "^1.2.2", "@radix-ui/react-alert-dialog": "^1.0.5", "@radix-ui/react-dialog": "^1.1.4", "@radix-ui/react-dropdown-menu": "^2.0.6", "@radix-ui/react-label": "^2.1.1", "@radix-ui/react-popover": "^1.1.4", "@radix-ui/react-progress": "^1.1.1", "@radix-ui/react-slot": "^1.1.1", "@radix-ui/react-switch": "^1.1.2", "@radix-ui/react-tabs": "^1.1.2", "@radix-ui/react-toast": "^1.2.4", "ai": "^4.0.1", "class-variance-authority": "^0.7… 证据：`frontend/package.json`
- **License**（source_file）：Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ 证据：`LICENSE`
- **HuggingFace Embeddings Support**（documentation）：This document explains how to use HuggingFace embedding models with RAG Web UI. 证据：`docs/HUGGINGFACE_EMBEDDINGS.md`
- **Troubleshooting Guide**（documentation）：If you encounter "table not found" or similar database errors after starting your services, follow these steps: 证据：`docs/troubleshooting.md`
- **🚀 十分钟搭建属于自己的 DeepSeek 知识库！完全开源、离线部署方案详解**（documentation）：🚀 十分钟搭建属于自己的 DeepSeek 知识库！完全开源、离线部署方案详解 证据：`docs/blog/deploy-local.md`
- **📖 简介**（documentation）：基于 RAG Retrieval-Augmented Generation 的知识库管理 证据：`README.zh-CN.md`
- **Components**（structured_config）：{ "$schema": "https://ui.shadcn.com/schema.json", "style": "default", "rsc": true, "tsx": true, "tailwind": { "config": "tailwind.config.ts", "css": "src/app/globals.css", "baseColor": "slate", "cssVariables": true, "prefix": "" }, "aliases": { "components": "@/components", "utils": "@/lib/utils" } } 证据：`frontend/components.json`
- **Tsconfig**（structured_config）：{ "compilerOptions": { "target": "ES2017", "lib": "dom", "dom.iterable", "esnext" , "allowJs": true, "skipLibCheck": true, "strict": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true, "plugins": { "name": "next" } , "paths": { "@/ ": "./src/ " } }, "include": "next-env.d.ts", " / .ts", " / .tsx", ".next/types/ / .ts", "next.config.js" , "exclude": "node modules" } 证据：`frontend/tsconfig.json`
- **Chat Provider, remember to set the api key / base url / model for the provider**（source_file）：Chat Provider, remember to set the api key / base url / model for the provider CHAT PROVIDER=openai 证据：`.env.example`
- **Set default behavior to automatically normalize line endings**（source_file）：Set default behavior to automatically normalize line endings text=auto 证据：`.gitattributes`
- **Python**（source_file）：Python pycache / .py cod $py.class .so .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib64/ parts/ sdist/ var/ wheels/ .egg-info/ .installed.cfg .egg .pytest cache/ .coverage htmlcov/ .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ chroma db/ 证据：`.gitignore`
- **Install system dependencies**（source_file）：Install system dependencies RUN apt-get update && apt-get install -y \ build-essential \ default-libmysqlclient-dev \ pkg-config \ netcat-traditional \ curl \ && rm -rf /var/lib/apt/lists/ 证据：`backend/Dockerfile`
- **Install system dependencies**（source_file）：Install system dependencies RUN apt-get update && apt-get install -y \ build-essential \ default-libmysqlclient-dev \ pkg-config \ netcat-traditional \ curl \ && rm -rf /var/lib/apt/lists/ 证据：`backend/Dockerfile.dev`
- **Alembic**（source_file）：alembic script location = alembic sqlalchemy.url = mysql+mysqlconnector://ragwebui:ragwebui@db/ragwebui 证据：`backend/alembic.ini`
- **Clean Db**（source_file）：def clean database ⋮---- engine = create engine settings.get database url 证据：`backend/clean_db.py`
- **Diff**（source_file）：@dataclass class Chunk ⋮---- index: int content hash: str chunk content: str uuid: str = None ⋮---- class SyncResult TypedDict ⋮---- to create: List Dict to update: List Dict to delete: List str ⋮---- old chunks = ⋮---- new chunks = ⋮---- def synchronize chunks old chunks: List Dict , new chunks: List Dict - SyncResult ⋮---- required fields = {'index', 'content hash', 'chunk content'} ⋮---- old chunks by hash = defaultdict list ⋮---- new chunks by hash = defaultdict list ⋮---- to create = to update = to delete = ⋮---- all hashes = set old chunks by hash.keys set new chunks by hash.keys ⋮---- threshold = 10 ⋮---- old list = sorted old chunks by hash content hash , key=lambda x: x 'index' new… 证据：`backend/diff.py`
- **Entrypoint**（source_file）：set -e echo "Waiting for MySQL..." while ! nc -z db 3306; do sleep 1 done echo "MySQL started" echo "Running migrations..." if alembic upgrade head; then echo "Migrations completed successfully" else echo "Migration failed" exit 1 fi echo "Starting application..." if "$ENVIRONMENT" = "development" ; then uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload else uvicorn app.main:app --host 0.0.0.0 --port 8000 fi 证据：`backend/entrypoint.sh`
- **Requirements**（source_file）：fastapi =0.104.1 uvicorn =0.24.0 python-jose =3.3.0 python-multipart =0.0.6 langchain =0.3.0 langchain-community =0.0.10 langchain-openai =0.3.3 langchain-chroma =0.0.5 chromadb =0.6.3 langchain-qdrant =0.2.0 chroma-hnswlib =0.7.3 BCrypt==4.0.1 SQLAlchemy =2.0.23 alembic =1.12.1 mysql-connector-python =8.0.33 minio =7.2.0 python-docx =0.8.11 pypdf =3.0.0 unstructured =0.10.30 markdown =3.0.0 unstructured md =0.10.0 openai =1.30.0 email-validator dashscope =1.13.6 langchain-deepseek==0.1.1 langchain-ollama==0.2.3 langchain-huggingface =0.1.0 sentence-transformers =2.2.0 docx2txt==0.8 证据：`backend/requirements.txt`
- **Docker Compose.Dev**（source_file）：services: nginx-dev: image: nginx:alpine ports: - "80:80" volumes: - ./nginx.dev.conf:/etc/nginx/nginx.conf:ro depends on: - frontend - backend - minio networks: - app network healthcheck: test: "CMD", "nginx", "-t" interval: 30s timeout: 10s retries: 3 restart: unless-stopped logging: driver: "json-file" options: max-size: "10m" max-file: "3" backend: build: context: ./backend dockerfile: Dockerfile.dev ports: - "8000:8000" env file: - .env extra hosts: - "host.docker.internal:host-gateway" environment: - DEBUG=1 - PYTHONUNBUFFERED=1 volumes: - ./backend:/app - ./uploads:/app/uploads networks: - app network depends on: - db - chromadb - minio restart: on-failure deploy: restart policy: con… 证据：`docker-compose.dev.yml`
- **Docker Compose**（source_file）：services: backend: build: ./backend env file: - .env extra hosts: - "host.docker.internal:host-gateway" volumes: - ./backend:/app - ./uploads:/app/uploads networks: - app network depends on: db: condition: service healthy chromadb: condition: service started minio: condition: service started restart: on-failure deploy: restart policy: condition: on-failure delay: 5s max attempts: 3 frontend: build: ./frontend volumes: - ./frontend:/app - /app/node modules networks: - app network db: image: mysql:8.0 command: --default-authentication-plugin=mysql native password environment: - MYSQL ROOT PASSWORD=root - MYSQL DATABASE=ragwebui - MYSQL USER=ragwebui - MYSQL PASSWORD=ragwebui - TZ=Asia/Shangha… 证据：`docker-compose.yml`
- **See https://help.github.com/articles/ignoring-files/ for more about ignoring files.**（source_file）：See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 证据：`frontend/.gitignore`
- **Dependencies**（source_file）：Dependencies FROM base AS deps RUN apk add --no-cache libc6-compat git 证据：`frontend/Dockerfile`
- **Install pnpm**（source_file）：Install pnpm RUN npm install -g pnpm@8 证据：`frontend/Dockerfile.dev`
- **Jest.Config**（source_file）：import type { Config } from 'jest' import nextJest from 'next/jest' 证据：`frontend/jest.config.ts`
- **Postcss.Config**（source_file）：/ @type {import 'postcss-load-config' .Config} / 证据：`frontend/postcss.config.mjs`
- **Tailwind.Config**（source_file）：import type { Config } from "tailwindcss" 证据：`frontend/tailwind.config.ts`
- **Default server block for both IP and nip.io access**（source_file）：events { worker connections 1024; } 证据：`nginx.conf`
- **开发环境的 CORS 设置**（source_file）：events { worker connections 1024; } 证据：`nginx.dev.conf`
- **Env**（source_file）：config = context.config ⋮---- target metadata = Base.metadata ⋮---- def get url ⋮---- def run migrations offline - None ⋮---- url = get url ⋮---- def run migrations online - None ⋮---- configuration = config.get section config.config ini section ⋮---- connectable = engine from config 证据：`backend/alembic/env.py`
- **revision identifiers, used by Alembic.**（source_file）：Revision ID: ${up revision} Revises: ${down revision comma,n} Create Date: ${create date} 证据：`backend/alembic/script.py.mako`
- **3580C0Dcd005 Increase Api Key Length**（source_file）：revision: str = '3580c0dcd005' down revision: Union str, None = 'e214adf7fb66' branch labels: Union str, Sequence str , None = None depends on: Union str, Sequence str , None = None ⋮---- def upgrade - None ⋮---- def downgrade - None 证据：`backend/alembic/versions/3580c0dcd005_increase_api_key_length.py`
- **59Cfa0F1361D Rename Metadata To Chunk Metadata**（source_file）：revision: str = '59cfa0f1361d' down revision: Union str, None = 'initial schema' branch labels: Union str, Sequence str , None = None depends on: Union str, Sequence str , None = None ⋮---- def upgrade - None ⋮---- def downgrade - None 证据：`backend/alembic/versions/59cfa0f1361d_rename_metadata_to_chunk_metadata.py`
- **5Be054Bd6587 Add Document Upload Id To Processing**（source_file）：revision: str = '5be054bd6587' down revision: Union str, None = 'fd73eebc87c1' branch labels: Union str, Sequence str , None = None depends on: Union str, Sequence str , None = None ⋮---- def upgrade - None ⋮---- def downgrade - None 证据：`backend/alembic/versions/5be054bd6587_add_document_upload_id_to_processing_.py`
- **E214Adf7Fb66 Add Api Keys Table**（source_file）：revision: str = 'e214adf7fb66' down revision: Union str, None = '5be054bd6587' branch labels: Union str, Sequence str , None = None depends on: Union str, Sequence str , None = None ⋮---- def upgrade - None ⋮---- def downgrade - None 证据：`backend/alembic/versions/e214adf7fb66_add_api_keys_table.py`
- **Fd73Eebc87C1 Add Document Uploads Table**（source_file）：revision = 'fd73eebc87c1' down revision = '59cfa0f1361d' branch labels = None depends on = None ⋮---- def upgrade - None ⋮---- def downgrade - None 证据：`backend/alembic/versions/fd73eebc87c1_add_document_uploads_table.py`
- **Initial Schema**（source_file）：revision: str = 'initial schema' down revision: Union str, None = None branch labels: Union str, Sequence str , None = None depends on: Union str, Sequence str , None = None ⋮---- def upgrade - None ⋮---- def downgrade - None 证据：`backend/alembic/versions/initial_schema.py`
- **Api**（source_file）：api router = APIRouter 证据：`backend/app/api/api_v1/api.py`
- **Api Keys**（source_file）：router = APIRouter logger = logging.getLogger name ⋮---- api keys = APIKeyService.get api keys ⋮---- api key = APIKeyService.create api key ⋮---- """ Update API key. """ api key = APIKeyService.get api key db=db, api key id=id ⋮---- api key = APIKeyService.update api key db=db, api key=api key, update data=api key in ⋮---- """ Delete API key. """ 证据：`backend/app/api/api_v1/api_keys.py`
- **Auth**（source_file）：router = APIRouter ⋮---- @router.post "/register", response model=UserResponse def register , db: Session = Depends get db , user in: UserCreate - Any ⋮---- user = db.query User .filter User.email == user in.email .first ⋮---- user = db.query User .filter User.username == user in.username .first ⋮---- user = User ⋮---- user = db.query User .filter User.username == form data.username .first ⋮---- access token expires = timedelta minutes=settings.ACCESS TOKEN EXPIRE MINUTES access token = security.create access token ⋮---- @router.post "/test-token", response model=UserResponse def test token current user: User = Depends get current user - Any 证据：`backend/app/api/api_v1/auth.py`
- **Chat**（source_file）：router = APIRouter ⋮---- knowledge bases = ⋮---- chat = Chat ⋮---- chats = ⋮---- chat = ⋮---- last message = messages "messages" -1 ⋮---- knowledge base ids = kb.id for kb in chat.knowledge bases ⋮---- async def response stream 证据：`backend/app/api/api_v1/chat.py`
- **Clean up external resources first**（source_file）：router = APIRouter ⋮---- logger = logging.getLogger name ⋮---- class TestRetrievalRequest BaseModel ⋮---- query: str kb id: int top k: int ⋮---- """ Create new knowledge base. """ kb = KnowledgeBase ⋮---- """ Retrieve knowledge bases. """ knowledge bases = ⋮---- """ Get knowledge base by ID. """ ⋮---- kb = ⋮---- kb = db.query KnowledgeBase .filter ⋮---- """ Delete knowledge base and all associated resources. """ ⋮---- document paths = doc.file path for doc in kb.documents ⋮---- minio client = get minio client embeddings = EmbeddingsFactory.create ⋮---- vector store = VectorStoreFactory.create ⋮---- Clean up external resources first cleanup errors = ⋮---- 1. Clean up MinIO files ⋮---- Delete… 证据：`backend/app/api/api_v1/knowledge_base.py`
- **Api**（source_file）：router = APIRouter 证据：`backend/app/api/openapi/api.py`
- **Knowledge**（source_file）：router = APIRouter ⋮---- kb = db.query models.KnowledgeBase .filter ⋮---- embeddings = EmbeddingsFactory.create ⋮---- vector store = VectorStoreFactory.create ⋮---- results = vector store.similarity search with score query, k=top k ⋮---- response = 证据：`backend/app/api/openapi/knowledge.py`
- **JWT settings**（source_file）：class Settings BaseSettings ⋮---- PROJECT NAME: str = "RAG Web UI" VERSION: str = "0.1.0" API V1 STR: str = "/api" ⋮---- MYSQL SERVER: str = os.getenv "MYSQL SERVER", "localhost" MYSQL PORT: int = int os.getenv "MYSQL PORT", "3306" MYSQL USER: str = os.getenv "MYSQL USER", "ragwebui" MYSQL PASSWORD: str = os.getenv "MYSQL PASSWORD", "ragwebui" MYSQL DATABASE: str = os.getenv "MYSQL DATABASE", "ragwebui" SQLALCHEMY DATABASE URI: Optional str = None ⋮---- @property def get database url self - str ⋮---- JWT settings SECRET KEY: str = os.getenv "SECRET KEY", "your-secret-key-here" ALGORITHM: str = "HS256" ACCESS TOKEN EXPIRE MINUTES: int = int os.getenv "ACCESS TOKEN EXPIRE MINUTES", "10080" ⋮-… 证据：`backend/app/core/config.py`
- **Minio**（source_file）：logger = logging.getLogger name ⋮---- def get minio client - Minio ⋮---- def init minio ⋮---- client = get minio client 证据：`backend/app/core/minio.py`
- **Security**（source_file）：oauth2 scheme = OAuth2PasswordBearer tokenUrl="/api/v1/auth/login/access-token" api key header = APIKeyHeader name="X-API-Key", auto error=False ⋮---- def verify password plain password: str, hashed password: str - bool ⋮---- def get password hash password: str - str ⋮---- def create access token data: dict, expires delta: Optional timedelta = None - str ⋮---- to encode = data.copy ⋮---- expire = datetime.utcnow + expires delta ⋮---- expire = datetime.utcnow + timedelta minutes=settings.ACCESS TOKEN EXPIRE MINUTES ⋮---- encoded jwt = jwt.encode to encode, settings.SECRET KEY, algorithm=settings.ALGORITHM ⋮---- credentials exception = HTTPException ⋮---- payload = jwt.decode token, settings.… 证据：`backend/app/core/security.py`
- **Session**（source_file）：engine = create engine settings.get database url SessionLocal = sessionmaker autocommit=False, autoflush=False, bind=engine ⋮---- def get db ⋮---- db = SessionLocal 证据：`backend/app/db/session.py`
- **Main**（source_file）：app = FastAPI ⋮---- @app.on event "startup" async def startup event ⋮---- migrator = DatabaseMigrator settings.get database url ⋮---- @app.get "/" def root ⋮---- @app.get "/api/health" async def health check 证据：`backend/app/main.py`
- **Init**（source_file）：all = 证据：`backend/app/models/__init__.py`
- **Api Key**（source_file）：class APIKey Base, TimestampMixin ⋮---- tablename = "api keys" ⋮---- id = Column Integer, primary key=True, index=True key = Column VARCHAR 128 , unique=True, index=True, nullable=False name = Column String 255 , nullable=False user id = Column Integer, ForeignKey "users.id" , nullable=False is active = Column Boolean, default=True, nullable=False last used at = Column DateTime timezone=True , nullable=True ⋮---- user = relationship "User", back populates="api keys" 证据：`backend/app/models/api_key.py`
- **Base**（source_file）：Base = declarative base ⋮---- class TimestampMixin ⋮---- created at = Column DateTime, default=datetime.utcnow, nullable=False updated at = Column DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False 证据：`backend/app/models/base.py`
- **Chat**（source_file）：chat knowledge bases = Table ⋮---- class Chat Base, TimestampMixin ⋮---- tablename = "chats" ⋮---- id = Column Integer, primary key=True, index=True title = Column String 255 , nullable=False user id = Column Integer, ForeignKey "users.id" , nullable=False ⋮---- messages = relationship "Message", back populates="chat", cascade="all, delete-orphan" user = relationship "User", back populates="chats" knowledge bases = relationship ⋮---- class Message Base, TimestampMixin ⋮---- tablename = "messages" ⋮---- content = Column LONGTEXT, nullable=False role = Column String 50 , nullable=False chat id = Column Integer, ForeignKey "chats.id" , nullable=False ⋮---- chat = relationship "Chat", back popu… 证据：`backend/app/models/chat.py`
- **Knowledge**（source_file）：class KnowledgeBase Base, TimestampMixin ⋮---- tablename = "knowledge bases" ⋮---- id = Column Integer, primary key=True, index=True name = Column String 255 , nullable=False description = Column LONGTEXT user id = Column Integer, ForeignKey "users.id" , nullable=False created at = Column DateTime, default=datetime.utcnow updated at = Column DateTime, default=datetime.utcnow, onupdate=datetime.utcnow ⋮---- documents = relationship "Document", back populates="knowledge base", cascade="all, delete-orphan" user = relationship "User", back populates="knowledge bases" processing tasks = relationship "ProcessingTask", back populates="knowledge base" chunks = relationship "DocumentChunk", back pop… 证据：`backend/app/models/knowledge.py`
- **User**（source_file）：class User Base, TimestampMixin ⋮---- tablename = "users" ⋮---- id = Column Integer, primary key=True, index=True email = Column String 255 , unique=True, index=True, nullable=False username = Column String 255 , unique=True, index=True, nullable=False hashed password = Column String 255 , nullable=False is active = Column Boolean, default=True is superuser = Column Boolean, default=False ⋮---- knowledge bases = relationship "KnowledgeBase", back populates="user" chats = relationship "Chat", back populates="user" api keys = relationship "APIKey", back populates="user", cascade="all, delete-orphan" 证据：`backend/app/models/user.py`
- **Api Key**（source_file）：class APIKeyBase BaseModel ⋮---- name: str is active: bool = True ⋮---- class APIKeyCreate APIKeyBase ⋮---- class APIKeyUpdate BaseModel ⋮---- name: Optional str = None is active: Optional bool = None ⋮---- class APIKey APIKeyBase ⋮---- id: int key: str user id: int last used at: Optional datetime = None created at: datetime updated at: datetime ⋮---- class Config ⋮---- from attributes = True ⋮---- class APIKeyInDB APIKey 证据：`backend/app/schemas/api_key.py`
- **Chat**（source_file）：class MessageBase BaseModel ⋮---- content: str role: str ⋮---- class MessageCreate MessageBase ⋮---- chat id: int ⋮---- class MessageResponse MessageBase ⋮---- id: int ⋮---- created at: datetime updated at: datetime ⋮---- class Config ⋮---- from attributes = True ⋮---- class ChatBase BaseModel ⋮---- title: str ⋮---- class ChatCreate ChatBase ⋮---- knowledge base ids: List int ⋮---- class ChatUpdate ChatBase ⋮---- knowledge base ids: Optional List int = None ⋮---- class ChatResponse ChatBase ⋮---- user id: int ⋮---- messages: List MessageResponse = knowledge base ids: List int = 证据：`backend/app/schemas/chat.py`
- 其余 8 条证据见 `AI_CONTEXT_PACK.json` 或 `EVIDENCE_INDEX.json`。

## 宿主 AI 必须遵守的规则

- **把本资产当作开工前上下文，而不是运行环境。**：AI Context Pack 只包含证据化项目理解，不包含目标项目的可执行状态。 证据：`docs/tutorial/README.md`, `README.md`, `frontend/README.md`
- **回答用户时区分可预览内容与必须安装后才能验证的内容。**：安装前体验的消费者价值来自降低误装和误判，而不是伪装成真实运行。 证据：`docs/tutorial/README.md`, `README.md`, `frontend/README.md`

## 用户开工前应该回答的问题

- 你准备在哪个宿主 AI 或本地环境中使用它？
- 你只是想先体验工作流，还是准备真实安装？
- 你最在意的是安装成本、输出质量、还是和现有规则的冲突？

## 验收标准

- 所有能力声明都能回指到 evidence_refs 中的文件路径。
- AI_CONTEXT_PACK.md 没有把预览包装成真实运行。
- 用户能在 3 分钟内看懂适合谁、能做什么、如何开始和风险边界。

---

## Doramagic Context Augmentation

下面内容用于强化 Repomix/AI Context Pack 主体。Human Manual 只提供阅读骨架；踩坑日志会被转成宿主 AI 必须遵守的工作约束。

## Human Manual 骨架

使用规则：这里只是项目阅读路线和显著性信号，不是事实权威。具体事实仍必须回到 repo evidence / Claim Graph。

宿主 AI 硬性规则：
- 不得把页标题、章节顺序、摘要或 importance 当作项目事实证据。
- 解释 Human Manual 骨架时，必须明确说它只是阅读路线/显著性信号。
- 能力、安装、兼容性、运行状态和风险判断必须引用 repo evidence、source path 或 Claim Graph。

- **项目概述与系统架构**：importance `high`
  - source_paths: README.md, README.zh-CN.md, backend/app/main.py, backend/app/core/config.py, backend/app/api/api_v1/api.py
- **后端核心系统：API、数据模型与服务层**：importance `high`
  - source_paths: backend/app/api/api_v1/auth.py, backend/app/api/api_v1/chat.py, backend/app/api/api_v1/knowledge_base.py, backend/app/api/api_v1/api_keys.py, backend/app/api/openapi/api.py
- **AI 与向量检索集成：LLM、Embedding 与向量库工厂**：importance `high`
  - source_paths: backend/app/services/llm/llm_factory.py, backend/app/services/embedding/embedding_factory.py, backend/app/services/vector_store/factory.py, backend/app/services/vector_store/base.py, backend/app/services/vector_store/chroma.py
- **前端、部署与运维：Docker、Next.js 与常见故障**：importance `high`
  - source_paths: docker-compose.yml, docker-compose.dev.yml, backend/Dockerfile, backend/Dockerfile.dev, backend/entrypoint.sh

## Repo Inspection Evidence / 源码检查证据

- repo_clone_verified: true
- repo_inspection_verified: true
- repo_commit: `905fb04669ae6f2a0cb3690d82a547b860e80dd4`
- inspected_files: `README.md`, `docker-compose.yml`, `docs/HUGGINGFACE_EMBEDDINGS.md`, `docs/blog/deploy-local.md`, `docs/troubleshooting.md`, `docs/tutorial/README.md`

宿主 AI 硬性规则：
- 没有 repo_clone_verified=true 时，不得声称已经读过源码。
- 没有 repo_inspection_verified=true 时，不得把 README/docs/package 文件判断写成事实。
- 没有 quick_start_verified=true 时，不得声称 Quick Start 已跑通。

## Doramagic Pitfall Constraints / 踩坑约束

这些规则来自 Doramagic 发现、验证或编译过程中的项目专属坑点。宿主 AI 必须把它们当作工作约束，而不是普通说明文字。

### Constraint 1: 来源证据：Backend combined with knowledge base Q&A reports an error, and the error message is as follows

- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Backend combined with knowledge base Q&A reports an error, and the error message is as follows
- Why it matters: 可能增加新用户试用和生产接入成本。
- Evidence: community_evidence:github | https://github.com/rag-web-ui/rag-web-ui/issues/70 | 来源类型 github_issue 暴露的待验证使用条件。
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 2: 能力证据存在缺口

- Trigger: Sandbox install result is missing.
- Host AI rule: 优先补证或在页面明确标记为未验证。
- Why it matters: 缺口未补前，Doramagic 不能把该能力当作可靠推荐卖点。
- Evidence: evidence.evidence_gaps | https://github.com/rag-web-ui/rag-web-ui | Sandbox install result is missing.
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 3: 沙箱验证已有失败原因

- Trigger: llm_blocked_sandbox_execution
- Why it matters: 失败原因未处理前，不应向用户暗示项目可顺利运行。
- Evidence: sandbox_validation_results | planner_decision=llm_blocked; planner_reason=The candidate command 'docker compose up -d' is not present in the deterministic allowlist (echo/python/node) and does not match any isolated_install_policy form (pip/npm/npx/uvx/docker run). 'docker compose up -d' would also start services persistently in the sandbox, whic…
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 4: 依赖 Docker 环境

- Trigger: 安装/运行入口包含 Docker 命令：docker compose up -d
- Host AI rule: 标注 Docker 前置条件，并提供非 Docker 路径或失败提示。
- Why it matters: 非工程用户可能没有 Docker，启动成本明显增加。
- Evidence: identity.distribution | https://github.com/rag-web-ui/rag-web-ui | docker compose up -d
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 5: 安装命令尚未沙箱验证

- Trigger: 当前 install_status=documented，还只是文档/元数据线索。
- Host AI rule: 在隔离环境执行最小安装路径，记录失败原因和修复步骤。
- Why it matters: 命令可能缺步骤、过期或依赖本地环境，不能直接作为用户承诺。
- Evidence: downstream_validation.install_status | https://github.com/rag-web-ui/rag-web-ui | install_status=documented; command=docker compose up -d
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 6: 来源证据：when process file get error "Failed to download temp file: S3 operation failed; code: NoSuchKey..."

- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：when process file get error "Failed to download temp file: S3 operation failed; code: NoSuchKey..."
- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- Why it matters: 可能增加新用户试用和生产接入成本。
- Evidence: community_evidence:github | https://github.com/rag-web-ui/rag-web-ui/issues/82 | 来源讨论提到 python 相关条件，需在安装/试用前复核。
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 7: 能力判断依赖假设

- Trigger: README/documentation is current enough for a first validation pass.
- Host AI rule: 将假设转成下游验证清单。
- Why it matters: 假设不成立时，用户拿不到承诺的能力。
- Evidence: capability.assumptions | https://github.com/rag-web-ui/rag-web-ui | README/documentation is current enough for a first validation pass.
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 8: Quick Start 尚未实际跑通

- Trigger: quickstart_status=not_attempted。
- Host AI rule: 执行最小 repro plan，记录命令、输入样例、输出样例和失败原因。
- Why it matters: 用户只能看到安装线索，不能确信 10 分钟内能形成最小可试路径。
- Evidence: downstream_validation.quickstart_status | https://github.com/rag-web-ui/rag-web-ui | quickstart_status=not_attempted; sandbox_quickstart_status=blocked
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 9: 来源证据：Front end bug

- Trigger: GitHub 社区证据显示该项目存在一个运行相关的待验证问题：Front end bug
- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- Why it matters: 可能增加新用户试用和生产接入成本。
- Evidence: community_evidence:github | https://github.com/rag-web-ui/rag-web-ui/issues/69 | 来源类型 github_issue 暴露的待验证使用条件。
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 10: 维护活跃度未知

- Trigger: 未记录 last_activity_observed。
- Host AI rule: 补 GitHub 最近 commit、release、issue/PR 响应信号。
- Why it matters: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- Evidence: evidence.maintainer_signals | https://github.com/rag-web-ui/rag-web-ui | last_activity_observed missing
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。
