Commit b728565f by 黄南光

- 调整文件上传生命周期:上传仅保存文件,不再同步抽取文本或生成 PPT 预览

- 新增 PPT/PPTX 预览缓存检查,未生成预览时返回非阻塞状态
- 更新前端上传与预览状态文案,区分“已保存”和“预览未就绪”
- 新增 Wiki + RAG 双路查询接口,支持 JSON 与 SSE 汇总回答
- 将 ingest/lint 的 schema、品牌基线、type 归一化收口到统一 ingest contract
- 优化 RAG 意图识别、检索日志和分类型回答提示词
- 新增轻改谈客知识库参考资料、开发计划、学习记录与相关测试覆盖
1 parent dd9cc291
Showing 48 changed files with 1448 additions and 292 deletions
.git
.gitignore
.pytest_cache
__pycache__
*.py[cod]
.env
.env.*
!.env_example
logs
ware
frontend/.next
frontend/node_modules
node_modules
.agents
.claude
.codex
.idea
#DASHSCOPE_API_KEY=sk-4ed2da3f27d34f5692b39ed7c113efb0
DASHSCOPE_API_KEY=sk-107dd26bca184e39bd1744af7d634488
app_key = "48e5e13229b82c1b4e6e8c96151f0637"
secret = "c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b"
#DASHSCOPE_API_KEY=sk-107dd26bca184e39bd1744af7d634488
DASHSCOPE_API_KEY=sk-ws-H.EMRRMDI.ENrv.MEUCIC0bmrHgRBloIBAOnfTsqDG5IPuH7jhlEgIh2HmCVDNcAiEA1c-jXCFBKbq5BJJxCeELfhlrLt05a85zjOB45cV_vt4
# 核心文件状态管理 MySQL 配置
DB_HOST=192.168.3.92
......@@ -9,9 +7,3 @@ DB_PORT=3308
DB_NAME=ai_multi_agentic_dev
DB_USER=biz_multi_agentic
DB_PASSWORD=JEIjHeLT
# API 接口地址
API_MERCHANT_SEARCH=http://llm-middleware.glsx.com.cn/ask_data/api/findMerchantIdByFt5
API_STAFF_SEARCH=https://gsc-agent.glsx.com.cn/gsc-agent-manage-biz/bus/api/findStaff
API_ROP_ROUTER=https://dj.glsx.com.cn/rop-dj-pe-analysis/router
API_DATA_QUERY=http://dc.glsx.com.cn/data
# Errors
Command failures and integration errors.
---
## [ERR-20260710-001] local-skill-read
**Logged**: 2026-07-10T16:20:00+08:00
**Priority**: low
**Status**: resolved
**Area**: config
### Summary
沙箱内首次读取已安装的 self-improvement 技能说明失败。
### Error
```text
Access is denied; the reported SKILL.md path could not be read in the default sandbox.
```
### Context
- 尝试只读访问 `C:\Users\admin\.codex\skills\self-improving-agent\SKILL.md`。
- 目录存在,但默认沙箱未允许读取文件内容。
### Suggested Fix
使用只读权限提升重新执行该命令。
### Metadata
- Reproducible: unknown
- Related Files: none
### Resolution
- **Resolved**: 2026-07-10T16:21:00+08:00
- **Notes**: 使用只读权限提升后成功读取技能说明。
---
## [ERR-20260710-002] repository-file-discovery
**Logged**: 2026-07-10T16:19:00+08:00
**Priority**: low
**Status**: resolved
**Area**: docs
### Summary
文件发现命令将尚不存在的 `docs` 目录作为搜索根,导致 `rg` 返回错误。
### Error
```text
rg: docs: 系统找不到指定的文件。 (os error 2)
```
### Context
- 调查项目结构时运行了包含 `docs` 的多根目录 `rg --files`。
- 其余目标目录的文件列表仍正常返回。
### Suggested Fix
搜索前先用 `Test-Path` 判断可选目录,或只对已存在目录运行 `rg`。
### Metadata
- Reproducible: yes
- Related Files: docs
### Resolution
- **Resolved**: 2026-07-10T16:20:00+08:00
- **Notes**: 后续调查不再假设 `docs` 已存在。
---
# Feature Requests
Capabilities requested by the user.
---
# Learnings
Corrections, insights, and knowledge gaps captured during development.
**Categories**: correction | insight | knowledge_gap | best_practice
---
# Wiki Upload Lifecycle Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Make Wiki file upload return as soon as the file is stored, and move parsing/preview generation into separate states and actions.
**Architecture:** Keep upload, ingest, and preview as separate lifecycle concerns. Backend exposes a single Wiki file status contract and explicit preview readiness; frontend treats upload queue status separately from database ingest status.
**Tech Stack:** FastAPI, SQLAlchemy async sessions, Next.js React client, Python unittest/static tests.
## Global Constraints
- Answer and UI-facing behavior should use Chinese wording where existing UI does.
- Do not run PDF VLM parsing from upload endpoints.
- Do not generate PPT/PPTX preview PDFs from the GET preview endpoint.
- Keep changes scoped to Wiki file upload/preview plus minimal shared status typing.
---
### Task 1: Backend Upload Contract
**Files:**
- Modify: `src/api/routes/files.py`
- Test: `tests/api/test_upload_word_count_static.py`
**Interfaces:**
- Produces: `/upload/{file_id}` returns after disk save with `status: "success"` and file status `Pending`.
- [ ] Write a failing test proving `upload_file_chunk` does not call `extract_text_from_file`.
- [ ] Run the test and verify it fails on current code.
- [ ] Remove upload-time text extraction and keep `word_count` at `0`.
- [ ] Run the test and verify it passes.
### Task 2: PPT Preview Readiness
**Files:**
- Modify: `src/api/routes/files.py`
- Modify: `src/tools/document_parser.py`
- Test: `tests/api/test_files_preview.py`
**Interfaces:**
- Produces: `GET /files/view/{file_id}` returns an existing PPT/PPTX preview PDF only when cache is ready.
- Produces: Missing PPT/PPTX preview returns HTTP 202 with JSON detail instead of blocking conversion.
- [ ] Write a failing test proving missing PPT cache returns a non-blocking status and does not call conversion.
- [ ] Run the test and verify it fails on current code.
- [ ] Add cache lookup helper and change `view_file` to avoid conversion.
- [ ] Run the test and verify it passes.
### Task 3: Frontend Preview and Upload UX
**Files:**
- Modify: `frontend/src/app/page.tsx`
- Test: `tests/frontend/test_wiki_upload_preview_static.py`
**Interfaces:**
- Produces: upload modal uses saved/upload failed wording for disk save.
- Produces: PPT/PPTX preview uses controlled fetch state and user-facing message when preview PDF is not ready.
- [ ] Write static tests for upload wording and iframe gating.
- [ ] Run the tests and verify they fail on current code.
- [ ] Update frontend state handling and preview rendering.
- [ ] Run the tests and verify they pass.
### Task 4: Verification
**Files:**
- Test: targeted backend/frontend static tests.
- [ ] Run all targeted tests.
- [ ] Run a broader test subset if imports are healthy.
- [ ] Report exact commands and outcomes.
......@@ -50,9 +50,16 @@ interface TreeFile {
path: string;
}
const canIframePreview = (name: string) => {
type PreviewStatus = "idle" | "loading" | "ready" | "missing" | "error";
const canDirectIframePreview = (name: string) => {
const lowerName = name.toLowerCase();
return lowerName.endsWith(".pdf");
};
const needsControlledPreview = (name: string) => {
const lowerName = name.toLowerCase();
return lowerName.endsWith(".pdf") || lowerName.endsWith(".ppt") || lowerName.endsWith(".pptx");
return lowerName.endsWith(".ppt") || lowerName.endsWith(".pptx");
};
const buildTree = (links: string[]) => {
......@@ -131,6 +138,7 @@ export default function EnterpriseWiki() {
const [selectedFileId, setSelectedFileId] = useState<string | null>(null);
const [wikiContent, setWikiContent] = useState<string>("");
const [previewContent, setPreviewContent] = useState<string>("");
const [previewStatus, setPreviewStatus] = useState<PreviewStatus>("idle");
const [isPreviewLoading, setIsPreviewLoading] = useState(false);
const [viewMode, setViewMode] = useState<"raw" | "wiki_tree">("raw");
const [selectedWikiPath, setSelectedWikiPath] = useState<string | null>(null);
......@@ -548,15 +556,21 @@ export default function EnterpriseWiki() {
const fetchPreview = async (id: string) => {
const targetFile = files.find(f => f.id === id);
if (targetFile && canIframePreview(targetFile.name)) return;
if (targetFile && canDirectIframePreview(targetFile.name)) {
setPreviewStatus("ready");
setPreviewContent("");
setIsPreviewLoading(false);
return;
}
setIsPreviewLoading(true);
setPreviewStatus("loading");
setPreviewContent("正在加载预览...");
try {
const res = await fetch(`${API_BASE}/files/view/${encodeURIComponent(id)}`);
if (res.ok) {
const contentType = res.headers.get("content-type");
if (contentType && contentType.includes("application/json")) {
const contentType = res.headers.get("content-type") || "";
if (contentType.includes("application/json")) {
const data = await res.json();
if (data.type === "text_preview") {
setPreviewContent(data.content);
......@@ -564,13 +578,19 @@ export default function EnterpriseWiki() {
setPreviewContent(data.content || "无法解析文档内容");
}
} else {
const text = await res.text();
setPreviewContent(text);
setPreviewContent("");
}
setPreviewStatus("ready");
} else if (res.status === 202) {
const data = await res.json().catch(() => null);
setPreviewStatus("missing");
setPreviewContent(data?.detail?.message || "预览 PDF 尚未生成,请稍后刷新或先发起摄入。");
} else {
setPreviewStatus("error");
setPreviewContent("预览加载失败");
}
} catch {
setPreviewStatus("error");
setPreviewContent("预览请求发生错误");
} finally {
setIsPreviewLoading(false);
......@@ -579,6 +599,9 @@ export default function EnterpriseWiki() {
const onSelectFile = async (id: string) => {
setSelectedFileId(id);
setPreviewStatus("idle");
setPreviewContent("");
setIsPreviewLoading(false);
// 强制跳转到原始文档预览模式
setViewMode("raw");
setIsModalOpen(true);
......@@ -1543,12 +1566,49 @@ export default function EnterpriseWiki() {
{viewMode === "raw" ? (
<div className="flex w-full h-full">
<div className="flex-1 w-full h-full p-8">
{selectedFileObj && canIframePreview(selectedFileObj.name) ? (
{selectedFileObj && canDirectIframePreview(selectedFileObj.name) ? (
<iframe
key={selectedFileId}
src={`${API_BASE}/files/view/${encodeURIComponent(selectedFileId || '')}`}
className="w-full h-full rounded-3xl border border-slate-200 bg-white shadow-xl"
/>
) : selectedFileObj && needsControlledPreview(selectedFileObj.name) ? (
previewStatus === "ready" ? (
<iframe
key={selectedFileId}
src={`${API_BASE}/files/view/${encodeURIComponent(selectedFileId || '')}`}
className="w-full h-full rounded-3xl border border-slate-200 bg-white shadow-xl"
/>
) : (
<div className="w-full h-full bg-white rounded-3xl border border-slate-200 p-12 shadow-xl flex items-center justify-center">
<div className="max-w-md text-center">
{isPreviewLoading || previewStatus === "loading" ? (
<>
<Loader2 className="w-10 h-10 animate-spin text-blue-600 mx-auto mb-4" />
<h3 className="text-base font-bold text-slate-800">正在加载预览...</h3>
</>
) : previewStatus === "missing" ? (
<>
<AlertCircle className="w-10 h-10 text-amber-500 mx-auto mb-4" />
<h3 className="text-base font-bold text-slate-800">预览 PDF 尚未生成</h3>
<p className="text-sm text-slate-500 mt-2">{previewContent || "请稍后刷新,或先发起摄入生成预览资源。"}</p>
</>
) : (
<>
<AlertCircle className="w-10 h-10 text-red-500 mx-auto mb-4" />
<h3 className="text-base font-bold text-slate-800">预览加载失败</h3>
<p className="text-sm text-slate-500 mt-2">{previewContent || "预览请求发生错误"}</p>
</>
)}
<button
onClick={() => selectedFileId && fetchPreview(selectedFileId)}
className="mt-5 inline-flex items-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-sm font-bold text-white hover:bg-blue-700"
>
<RefreshCw className="w-4 h-4" /> 刷新预览
</button>
</div>
</div>
)
) : (
<div className="w-full h-full bg-white rounded-3xl border border-slate-200 p-12 overflow-auto shadow-xl relative custom-scrollbar">
{isPreviewLoading && (
......@@ -1860,11 +1920,13 @@ export default function EnterpriseWiki() {
</div>
{item.status === 'uploading' ? (
<div className="flex items-center gap-1.5 mt-1 text-xs font-bold text-blue-600">
<Loader2 className="w-3.5 h-3.5 animate-spin" /> 上传中...
<Loader2 className="w-3.5 h-3.5 animate-spin" /> 保存中...
</div>
) : item.status === 'success' ? (
<div className="flex items-center gap-1.5 mt-1 text-xs font-bold text-emerald-600">
<CheckCircle2 className="w-3.5 h-3.5" /> 上传成功
<div className="mt-1">
<div className="flex items-center gap-1.5 text-xs font-bold text-emerald-600">
<CheckCircle2 className="w-3.5 h-3.5" /> 已保存到文件库
</div>
</div>
) : item.status === 'error' ? (
<div className="flex items-center gap-1.5 mt-1 text-xs font-bold text-red-600" title={item.errorMsg}>
......
......@@ -329,12 +329,18 @@ export default function RagWorkspace() {
};
const clearHistoryV2 = async () => {
const sessionToClear = sessionId;
chatAbortRef.current?.abort();
chatAbortRef.current = null;
await runAction(() => clearRagHistory(sessionId));
setLoading(false);
setMessages([]);
setPreviewChunk(null);
setSessionId(`rag-${Date.now()}-${Math.random().toString(36).slice(2)}`);
try {
await clearRagHistory(sessionToClear);
} catch (error) {
alert(error instanceof Error ? error.message : "清空对话失败");
}
};
const openSourcePreview = async (source: RagChunk) => {
......@@ -1044,6 +1050,7 @@ export default function RagWorkspace() {
function updateLastMessage(messages: RagMessage[], patch: { contentAppend?: string; thinkingAppend?: string; sources?: RagChunk[]; reasoningStep?: RagReasoningStep; meta?: Record<string, unknown>; endTime?: number }) {
const next = [...messages];
const last = next[next.length - 1];
if (!last) return messages;
const reasoning = [...(last.reasoning || [])];
if (patch.reasoningStep) {
const existing = reasoning.findIndex((item) => item.id === patch.reasoningStep!.id);
......@@ -1067,7 +1074,7 @@ function updateLastMessage(messages: RagMessage[], patch: { contentAppend?: stri
function toWikiReasoning(message: RagMessage): ReasoningStep[] {
const steps: ReasoningStep[] = [];
for (const step of message.reasoning || []) {
steps.push({ id: step.id, type: "thought", content: ragStepText(step) });
steps.push({ id: step.id, type: "thought", content: ragStepText(step), time: formatElapsedSeconds(step.elapsed_ms) });
}
if (message.thinking?.trim()) {
steps.push({ id: "thinking", type: "thought", content: message.thinking });
......@@ -1075,6 +1082,12 @@ function toWikiReasoning(message: RagMessage): ReasoningStep[] {
return steps;
}
function formatElapsedSeconds(elapsedMs?: number): string | undefined {
if (typeof elapsedMs !== "number" || elapsedMs < 0) return undefined;
const seconds = elapsedMs / 1000;
return `耗时 ${seconds < 10 ? seconds.toFixed(1) : Math.round(seconds)}s`;
}
// 单条 RAG 推理步骤 → 一行可读文本(标题 + 关键信息)。
function ragStepText(step: RagReasoningStep): string {
const data = (step.data || {}) as Record<string, unknown>;
......
......@@ -107,7 +107,10 @@ export function streamRagQuery(
}
}
})
.catch((error) => onEvent({ type: "error", content: error.message }));
.catch((error) => {
if (error instanceof Error && error.name === "AbortError") return;
onEvent({ type: "error", content: error instanceof Error ? error.message : String(error) });
});
return controller;
}
......
......@@ -24,6 +24,7 @@ from src.api.routes.ingest import router as ingest_router
from src.api.routes.query import router as query_router
from src.api.routes.wiki import router as wiki_router
from src.api.routes.lint import router as lint_router
from src.api.routes.multi_path_search import router as multi_path_router
from src.rag.routes import router as rag_router
app = FastAPI(
......@@ -70,6 +71,7 @@ app.include_router(ingest_router)
app.include_router(query_router)
app.include_router(wiki_router)
app.include_router(lint_router)
app.include_router(multi_path_router)
app.include_router(rag_router)
if __name__ == "__main__":
......
wiki系统:
最主要是有3个skills:
摄入ingest,查询query,维护lint
摄入
###版本一
---
**直接用现有的业务提供的摄入skills,交给大模型react,由它自己根据skills对文件进行摄入**
优势:
​ a.开发方便,系统快速成型
问题:
​ a.消耗token极其高,比如1个文件需要react生成10份wiki摄入文件,由于Agentscoup框架react模型的特点,第2份生成的wiki文件过程会有第1生成wiki文件的上下文记忆,第10分文件会有前9分文件的上下文记忆,token消耗异常高,一份2k字文件可以消耗大几十万token
​ b.摄入速度慢,自带的react模式一次只能生成一份wiki文件
​ c.摄入质量差,随着模型持续输出wiki文件,后生成的wiki文件质量显著差于前几份文件,且有严重的幻觉
​ d.wiki文件的formatter头没有按照skills定义的标准生成
​
#### 版本二
---
**将摄入拆为三阶段摄入**
- **Phase 1: 规划阶段 (Planning)**:由大模型对整份文件进行分析,输出需要生成wiki文件的规划,包括路径,文件名等,头标签等。
- **Phase 2: 并发写作**:由phase1阶段拿到大模型所规划的页面之后,将文件+规划+skills提示词送入第二阶段的agent,由Agent并发地写各自的wiki页面
- **Phase 3: 文件入库**:拿到phase2各自的wiki写作页面后,一次性写入wiki仓库,并更新索引。
优点:
​ a.token消耗显著降低
​ b.摄入时间显著减少
问题:
​ a.摄入wiki文件需要支持摄出,摄出需要干净,不能影响wiki仓库
​ b.formatter头由大模型生成,输出不稳定,并发生成文件时,由概率会生成失败
​ c.多个文件摄入生成一份wiki,要考虑合并问题
#### 版本三
------
**Wiki支持摄出,引入Formatter头并发校验**
1. 对摄入文件的formatter头加入field_sources列表,用于追踪formatter头的来源
```
title: 轻改综合异议处理话术
series:
- 鸿蒙智行
- 通用品牌
# 引入field_sources列表,用于追踪wiki文件formatter头来源
field_sources:
title:
轻改综合异议处理话术:
- ware/raw/KB_施工流程.md
- ware/raw/KB_产品技术.md
series:
鸿蒙智行:
- ware/raw/KB_施工流程.md
通用品牌:
- ware/raw/KB_产品技术.md
```
​
2. Wiki文件内容加入 <!-- SOURCE_START: ... -->, <!-- SOURCE_END: ... --> 标签,用于追踪Wiki文件正文内容来源
```
<!-- SOURCE_START: ware/raw/KB_施工流程.md -->
# 轻改综合异议处理话术
本页汇总了轻改综合业务中关于流程合规、质保风险、价格透明度及施工时间统筹等核心场景的优秀异议处理话术。更多案例与背景信息可参考 [[轻改优秀客户异议处理汇总]]。
---
## 条目 24:带电改装与整车质保风险
- **车型**:问界M7
- **销售员**:吴静娴
- **标签**:
**客户异议**:
这位客户此时此刻真正在对抗的不是产品功能,而是对‘私自改装是否会影响整车质保’的风险认知不足,认为外部安装只要便宜且不出故障即可。
**优秀话术**:
那个车也挺贵的,不要因为接一根线拿给你接错了,接坏了影响你本身的四年的一个质保哦。哪怕你不装都行。因为m六的话,那个质保是毕竟你本身车就带四年的那个质保的那样。但是你但是问件所有的东西,如果是因为我们自己私自改装哦带尤其带电的东西产生了就是其他的问题。假如说你的电吸门失灵,你的车机产生故障。这种是因为你通过自己外面私自改装的话,这个可能会有影响啊,我们就慎重带电的东西慎重。
<!-- SOURCE_END: ware/raw/KB_施工流程.md -->
```
​
3. 对于大模型生成的formatter头格式不符合规范,引入python脚本代码校验的方式,强制校验大模型生成的formatter头,不符合规范则从重试
4. 将formatter头的规划移动到pharse1,由phase1进行规划,phase2只进行并发生成正文
优点:
​ a.显著提升摄入质量
​ b.由于减少了Agent输出formatter头输出错误导致重试,摄入速度大幅增快
问题:
​ a.多文件并发可能会生成同一份wiki文件,导致冲突
​ b.生成wiki文件在phase2并发执行过程中并发数太高导致百炼API接口异常
​ c.摄入formatter头不规范统一,原skills的formatter头太过异想天开,认为所有的wiki文件可能都会有一个concept页或者entity页,用于关联其子产品或者子wiki文件,再用标签对该wiki文件进行打标,实测文件下来,发现以下问题:
​ a1. 该头设计容易给LLM忽略
​ a2. Tags从8维度打标太过随意,Tags标签和formatter头严重重合,失去打标意义
​ a3. LLM标签由8维度组成,大模型往往会将每个维度的标签都只打一两个,或者标签过多导致不打
#### 版本四
------
**1.文件摄入操作同一时间端内只允许一份文件执行,限制phase2并发写作线程数**
解决并发执行带来的接口异常和写入冲突
**2.重构Formatter头**
弱化Tags标签作用,将Tags字段里面的内容固定到Fomatter头中,与原formatter头进行合并
**3.slug路径扁平化,归一化**
原先路径下,slug保存的是全路径,允许一个WikiType文件下支持多份重名的Wiki文件,按照品牌隔离,带来问题:
​ a.一份文件可能有多个品牌,但是归为一个品牌路径下
​ b.当大模型从A品牌slug中查不到想要的数据,会去读B品牌slug路径,同时会去读相关的related路径文件
现改为,WikiType路径下不会有重名文件,减少大模型工具调用,提升检索速度
**4.将摄入slug和查询slug路径对齐,进一步提高检索效率**
优势:
​ 进一步改进摄入质量
​ 减少查询执行兜底次数,大幅提升检索速度
问题:
​ a. 回答速度不够快
​ b. 业务发来话术相关的长文档,最长一份有30w字+,摄入消耗token大,速度和质量上需要和产品平衡,预构建Rag系统
#### 版本五
------
**1.优化index.md 读取**
将查询skills里面的Index.md 读取放到系统提示词中,减少一次模型思考和工具调用
**2.修改回答模型**
模型将qwen-plus改为deepseek-v4-flash,答复提升回答速度
**3.构建Rag系统**
为适配业务对长达数十万字话术文档的摄入需求,构建Rag系统,使得文档数据支持全量检索
优势
​ 解决大部分wiki现有问题,对检索的准确性和速度上有了质的飞跃
问题
​ a. 话术文档若由wiki摄入,需要针对性地对话术文档摄入进行优化
​ b. 现有的摄入skills品牌标准,基线,schema定义高度重合,提示词分散,后续需重点优化
​ c. rag系统与wiki系统检索策略和调优问题:需业务决定使用哪种策略对话术类文档进行检索
​ d.针对不同场景下的wiki,在formatter头设计和skills设计上还有很大的改进空间
# 品牌基线(受控枚举 · 唯一权威)
> 品牌枚举的**唯一权威**:摄入(ingest)与健康检查(lint)共用本文件(反引号包裹的 token 即基线集合)。
> 本文件由 Python 层静态注入 Planner 上下文(ingest)并被 lint 读取做品牌枚举校验;LLM 无需主动 Read。
## 鸿蒙智行体系(5 个)
`问界`、`享界`、`智界`、`尊界`、`尚界` — 均同时打 `鸿蒙智行` 品牌系列标签。
## 通用品牌(按首字母)
`岚图`、`零跑`、`理想`、`iCAR`、`MINI`、`smart`、`阿维塔`、`阿斯顿马丁`、`埃安`、`奥迪`、`宝骏`、`宝马`、`北京汽车`、`北京越野`、`北汽新能源`、`本田`、`比亚迪`、`别克`、`标致`、`长城`、`长安`、`长安启源`、`长安欧尚`、`长安凯程`、`东风`、`东风奕派`、`东风纳米`、`东风风神`、`东风风行`、`大众`、`方程豹`、`飞凡`、`丰田`、`福特`、`广汽传祺`、`广汽集团`、`哈弗`、`红旗`、`吉利汽车`、`吉利银河`、`吉利几何`、`极氪`、`极越`、`捷豹`、`捷达`、`捷途`、`捷途山海`、`凯迪拉克`、`领克`、`领汇`、`欧拉`、`起亚`、`启辰`、`奇瑞`、`奇瑞QQ`、`奇瑞新能源`、`奇瑞风云`、`日产`、`荣威`、`深蓝`、`斯柯达`、`坦克`、`腾势`、`五菱`、`魏牌`、`星途`、`仰望`、`智己`
> `理想` 一期标注「即将展业」,已纳入基线,可正常摄入。
## 合作生态与公司名称(非车品牌,无需审批)
`嘀加`、`广联数科`
> 上述用于标注产品/服务的出品公司、合作生态等,摄入时可直接使用,无需向管理员发起审批;不作为车辆 `brand` 字段值。
## 未知品牌规则(自动标记,不中断摄入)
摄入时遇到不在基线内的品牌:**不中断、不询问**,按以下方式自动标记后继续摄入,留待事后人工审批:
1. 能确认是新品牌名 → 在标签值后附 `[待审批]`(如 `某新品牌[待审批]`)。
2. 无法确认归属 → 填 `未知[待确认]`。
3. 在 `ware/wiki/log.md` 记录 `⚠️ 新品牌待确认:[品牌名]`。
> lint 在品牌枚举校验时会跳过含 `待审批`/`待确认`/`[` 的值,不误报;管理员事后审批通过的品牌再补入本基线。
## 审批记录区
<!-- 管理员按时间倒序追加:YYYY-MM-DD | 品牌名 | 鸿蒙智行/通用品牌 | 审批人 -->
# 黄金示例 (Golden Examples)
本文档提供 3 个标准的 wiki 页面生成示例。在创建页面时,**必须严格锚定以下示例的结构、篇幅和粒度**。
---
## 示例 1:Product 页面 (产品介绍)
**输入片段**:
> "鸿蒙智行辅助驾驶无忧服务产品包含整车延保服务。在原厂质保期满后,提供额外1年或3万公里的保修服务。除外责任包括:1. 易损件正常磨损;2. 人为损坏;3. 未在授权中心保养导致的故障... (共17条)。"
**输出页面** (`ware/wiki/products/鸿蒙智行辅助驾驶无忧延保.md`):
```markdown
---
schema_version: v1.3
type: products
title: 鸿蒙智行辅助驾驶无忧延保
series: 鸿蒙智行
brand:
- 问界
business_category: 权益类
sub_business: 售前延保
role:
- 驻店销售
related:
- 鸿蒙智行辅助驾驶无忧服务产品手册
- 鸿蒙智行延保免责条款
sources:
- ware/raw/鸿蒙智行辅助驾驶无忧服务产品手册260121.pdf
created: 2026-06-09
updated: 2026-06-09
tags:
- 产品参数
---
# 鸿蒙智行辅助驾驶无忧延保
整车延保是鸿蒙智行辅助驾驶无忧服务产品之一,旨在原厂质保期满后,为车主提供延长保修服务。
## 核心保障
| 保障项目 | 说明 |
|---------|------|
| 延长保修期 | 提供额外 1 年或 3 万公里(以先到者为准)的保修服务 |
## 除外责任
> 本产品存在 17 条除外责任(如易损件正常磨损、人为损坏等)。
> **详细条款请参见:** [[鸿蒙智行延保免责条款]]
```
*(注意:① 单一信息源——产品页不铺陈 17 条除外责任,而用 slug wikilink 引用 policy 页;价格/年限/里程等核心数值与表格必须 100% 全量保留。② slug 用「作用域+产品线」命名,避免裸名「整车延保」;wikilink 一律 slug 简写。)*
---
## 示例 2:Sources 摘要页 (导航入口)
**输入片段**:整个《鸿蒙智行辅助驾驶无忧服务产品手册260121.pdf》
**输出页面** (`ware/wiki/sources/鸿蒙智行/鸿蒙智行辅助驾驶无忧服务产品手册.md`):
```markdown
---
schema_version: v1.3
type: sources
title: 鸿蒙智行辅助驾驶无忧服务产品手册
series: 鸿蒙智行
brand:
- 问界
business_category: 权益类
sub_business: 售前延保
role:
- 通用
related:
- 鸿蒙智行辅助驾驶无忧延保
- 鸿蒙智行延保免责条款
- 辅助驾驶功能定义与分类
sources:
- ware/raw/鸿蒙智行辅助驾驶无忧服务产品手册260121.pdf
created: 2026-06-09
updated: 2026-06-09
tags: []
---
# 鸿蒙智行辅助驾驶无忧服务产品手册 — 来源摘要
## 来源基本信息
- 来源标题:鸿蒙智行辅助驾驶无忧服务产品手册
- 品牌系列:鸿蒙智行
- 业务大类:权益类
- 发布日期:2026-01-21
## 文档概述
本文档详细介绍了鸿蒙智行针对辅助驾驶系统推出的无忧服务产品,涵盖了整车延保的核心权益、功能定义分类以及相关的免责政策,旨在为终端销售提供标准化的产品说明和合规要求。
## 下游页面导航
| type | 页面 | 一句话描述 |
|------|------|-----------|
| products | [[鸿蒙智行辅助驾驶无忧延保]] | 介绍延保服务的保障期限与范围 |
| policies | [[鸿蒙智行延保免责条款]] | 罗列 17 条延保服务的除外责任与合规红线 |
| concepts | [[辅助驾驶功能定义与分类]] | 梳理辅助驾驶的核心功能定义 |
## 关键数据速查
| 数据项 | 数值 |
|--------|------|
| 延保期限 | 1年/3万公里 |
> 原始依据:`ware/raw/鸿蒙智行辅助驾驶无忧服务产品手册260121.pdf`
```
*(注意:Sources 页仅做极简摘要和导航表,绝不将源文件逐字展开,限制在 80 行以内;导航链接一律 slug 简写。)*
---
## 示例 3:Concepts 页面 (概念定义)
**输入片段**:
> "辅助驾驶功能主要分为主动安全功能和巡航辅助功能。主动安全包含 AEB (自动紧急制动) 和 FCW (前向碰撞预警)。此功能仅为辅助,不能替代驾驶员控制。"
**输出页面** (`ware/wiki/concepts/辅助驾驶功能定义与分类.md`):
```markdown
---
schema_version: v1.3
type: concepts
title: 辅助驾驶功能定义与分类
series: 鸿蒙智行
brand:
- 问界
business_category: 权益类
sub_business: 售前延保
role:
- 驻店销售
related:
- 鸿蒙智行辅助驾驶无忧服务产品手册
sources:
- ware/raw/鸿蒙智行辅助驾驶无忧服务产品手册260121.pdf
created: 2026-06-09
updated: 2026-06-09
tags:
- 产品参数
---
# 辅助驾驶功能定义与分类
辅助驾驶功能主要划分为以下两大类别,旨在提升行车安全性与舒适度:
## 1. 主动安全功能
主要用于在紧急情况下干预或提醒驾驶员,包括:
- **AEB (自动紧急制动)**
- **FCW (前向碰撞预警)**
## 2. 巡航辅助功能
*(注:原文未提及具体包含的子功能)*
> **重要提示**:辅助驾驶功能仅为驾驶辅助系统,不能完全替代驾驶员的人工控制。
```
*(注意:只定义核心概念。原文没细说的部分诚实标注"原文未提及",不编造。)*
......@@ -24,7 +24,7 @@ description: |
| Frontmatter 合规 | 12 个必填字段齐全:`schema_version, type, title, series, brand, business_category, sub_business, role, related, sources, created, updated`;type 合法;`business_category` 枚举;`brand/role` 为列表;日期格式 | 🔴 | ❌ 报告 |
| 断链 | wikilink `[[x]]` 目标 slug 不存在 | 🔴/🟡 | ✅ 转纯文本 + 从 `related[]` 移除 |
| 重复 slug | 跨目录同名 slug(`[[slug]]` 无法唯一解析) | 🔴 | ❌ 人工合并/改名 |
| 品牌枚举违规 | `brand` 字段值不在共享基线 `../llm-ingest/references/brand-baseline.md` 内(跳过 `[待审批]/[待确认]` 标记) | 🔴 | ❌ 管理员审批 |
| 品牌枚举违规 | `brand` 字段值不在共享 contract `../llm-ingest/references/schema.md` 的车辆品牌基线内(跳过 `[待审批]/[待确认]` 标记) | 🔴 | ❌ 管理员审批 |
| 话术字段 | `type: script` 页面缺 `script_type`,或 `违规话术` 缺 `violation_type` | 🔴 | ❌ 报告 |
| frontmatter 级矛盾 | 同 `title` 的多页面 `business_category` 不一致 | 🔴 | ❌ 人工 |
| LLM 残留 | 正文含 `<think>/<thinking>` 标签 | 🔴 | ✅ 删除残留块 |
......@@ -61,8 +61,7 @@ ReActAgent(`max_iters=6`,工具仅 `read_local_file/write_wiki_file/append_w
## 基线与参考(与 ingest 共用同一份权威,不维护两套)
- 品牌基线:`../llm-ingest/references/brand-baseline.md`(反引号包裹的品牌 token 即基线集合)。
- Schema 定义:`../llm-ingest/references/schema.md`(`schema_version` 从此读取)。
- 品牌基线与 Schema 定义:`../llm-ingest/references/schema.md`(`INGEST_CONTRACT` 块是唯一权威,包含 `schema_version`、type、品牌、业务枚举与合并字段)。
- Phase 2 提示词内联于 `lint.py`(`sys_prompt`),随代码维护。
- lint 自身不再持有 references 副本;确定性检查的方法学以本文件 Phase 1 表 + `lint.py` 实现为权威。
......
import os
import shutil
import re
import json
from datetime import datetime
from urllib.parse import quote
......@@ -20,8 +19,7 @@ from config import RAW_DIR
from src.tools.document_parser import (
delete_office_preview_pdf,
extract_text_from_file,
get_or_create_office_preview_pdf,
is_presentation_file,
get_existing_office_preview_pdf,
)
router = APIRouter()
......@@ -222,15 +220,12 @@ async def upload_file_chunk(file_id: str, file: UploadFile = File(...)):
file_size = os.path.getsize(file_path)
word_count = 0
if is_presentation_file(file_path):
logger.info(f"Skip PPT/PPTX upload word count to avoid converting during upload: {file.filename}")
else:
try:
text = extract_text_from_file(file_path)
pure_text = re.sub(r'\s+', '', text)
word_count = len(pure_text)
except Exception as e:
logger.warning(f"计算字数失败 [{file.filename}]: {e}")
logger.info(
"[Upload] File saved; skip upload-time text extraction: file_id=%s, name=%s, size=%s",
file_id,
file.filename,
file_size,
)
db_file.size = file_size
db_file.word_count = word_count
......@@ -246,7 +241,13 @@ async def upload_file_chunk(file_id: str, file: UploadFile = File(...)):
await session.commit()
logger.info(f"文件上传完成: {file.filename}, size={file_size}, word_count={word_count}")
return {"status": "success"}
return {
"status": "success",
"file_id": file_id,
"file_status": "Pending",
"size": file_size,
"word_count": word_count,
}
@router.delete("/files/{file_id}")
......@@ -364,24 +365,28 @@ async def view_file(file_id: str):
logger.info("[Preview] 返回 PDF 原文件: file_id=%s, media_type=application/pdf", file_id)
return FileResponse(file_path, media_type='application/pdf')
if ext in ('.ppt', '.pptx'):
try:
preview_pdf_path = await run_in_threadpool(get_or_create_office_preview_pdf, file_path, file_id)
preview_pdf_path = get_existing_office_preview_pdf(file_path, file_id)
if not preview_pdf_path:
logger.info(
"[Preview] 返回 PPT/PPTX PDF 预览: file_id=%s, cache_path=%s, media_type=application/pdf",
file_id,
preview_pdf_path,
)
return FileResponse(preview_pdf_path, media_type='application/pdf')
except Exception as e:
logger.error(
"[Preview] PPT/PPTX PDF 预览失败: file_id=%s, name=%s, path=%s, error=%s",
"[Preview] PPT/PPTX preview PDF missing: file_id=%s, name=%s, path=%s",
file_id,
db_file.name,
file_path,
e,
exc_info=True,
)
raise HTTPException(status_code=500, detail=f"PPT/PPTX 预览生成失败: {str(e)}")
raise HTTPException(
status_code=202,
detail={
"type": "preview_status",
"preview_status": "missing",
"message": "预览 PDF 尚未生成,请稍后刷新或先发起摄入。",
},
)
logger.info(
"[Preview] Return cached PPT/PPTX PDF preview: file_id=%s, cache_path=%s, media_type=application/pdf",
file_id,
preview_pdf_path,
)
return FileResponse(preview_pdf_path, media_type='application/pdf')
try:
content = extract_text_from_file(file_path)
......
......@@ -13,8 +13,9 @@ from fastapi.responses import StreamingResponse
logger = logging.getLogger(__name__)
from config import WIKI_DIR, BASE_DIR, LINT_MODEL_NAME, SKILLS_DIR
from config import WIKI_DIR, BASE_DIR, LINT_MODEL_NAME
from src.utils.llm_tracker import get_llm_formatter, get_llm_model, token_counter_context
from src.utils.ingest_contract import as_value_list, brand_baseline_set, canonicalize_type, load_ingest_contract
from src.tools.wiki_tools import read_local_file, write_wiki_file, append_wiki_file, rebuild_index, normalize_br_tags
from agentscope.agent import ReActAgent
......@@ -69,40 +70,13 @@ def run_lint_phase1(wiki_dir: str, base_dir: str, mode: str = "full", changed_pa
"wikilink_count": 0,
}
VALID_TYPES = {"entity", "product", "concept", "procedure", "script", "policy",
"comparison", "troubleshooting", "source", "synthesis",
# 兼容 ingest 生成的复数形式
"entities", "products", "concepts", "procedures", "scripts",
"policies", "comparisons", "sources", "syntheses"}
REQUIRED_FIELDS = ["schema_version", "type", "title",
"series", "brand", "business_category", "sub_business", "role",
"related", "sources", "created", "updated"]
VALID_BUSINESS_CATEGORIES = {"轻改类", "权益类", "二手车类", "未知业务[待确认]"}
STALE_TYPES = {"policy", "script", "procedure", "policies", "scripts", "procedures"}
# --- 读取当前 schema_version ---
# 与 ingest 共用同一份权威 spec(不维护两套):品牌基线与 schema 均取自 llm-ingest 的 references
refs_dir = os.path.join(SKILLS_DIR, "llm-ingest", "references")
current_schema_version = None
schema_path = os.path.join(refs_dir, "schema.md")
if os.path.exists(schema_path):
with open(schema_path, "r", encoding="utf-8", errors="replace") as sf:
for line in sf:
m = re.search(r'schema_version[:\s]+([\w.]+)', line)
if m:
current_schema_version = m.group(1).strip()
break
# --- 读取品牌基线集合(反引号包裹的 token)---
brand_baseline = set()
brand_baseline_path = os.path.join(refs_dir, "brand-baseline.md")
if os.path.exists(brand_baseline_path):
with open(brand_baseline_path, "r", encoding="utf-8", errors="replace") as bf:
for tok in re.findall(r'`([^`]+)`', bf.read()):
tok = tok.strip()
# 排除明显非品牌的占位/示例 token
if tok and not tok.startswith(("^", "ware/")) and ":" not in tok:
brand_baseline.add(tok)
contract = load_ingest_contract()
VALID_TYPES = set(contract.canonical_types.keys())
REQUIRED_FIELDS = list(contract.required_fields)
VALID_BUSINESS_CATEGORIES = set(contract.business_categories)
STALE_TYPES = {"policies", "scripts", "procedures"}
current_schema_version = contract.schema_version
brand_baseline = brand_baseline_set()
# --- P1-A: 全量页面扫描 ---
all_md_files = []
......@@ -171,7 +145,9 @@ def run_lint_phase1(wiki_dir: str, base_dir: str, mode: str = "full", changed_pa
if field not in md:
errors["missing_fields"].append(field)
page_type = md.get("type", "")
if page_type and page_type not in VALID_TYPES:
try:
page_type = canonicalize_type(page_type, contract) if page_type else ""
except ValueError:
errors["invalid_type"] = page_type
if current_schema_version and md.get("schema_version") is not None:
if str(md.get("schema_version")) != str(current_schema_version):
......@@ -182,8 +158,12 @@ def run_lint_phase1(wiki_dir: str, base_dir: str, mode: str = "full", changed_pa
errors["date_format_errors"].append(date_field)
# 维度合规:business_category 枚举;brand/role 应为列表
bc = md.get("business_category")
if bc is not None and str(bc) not in VALID_BUSINESS_CATEGORIES:
errors["extra_errors"].append(f"business_category 非法值: {bc}")
invalid_bcs = [
item for item in as_value_list(bc)
if str(item) not in VALID_BUSINESS_CATEGORIES
]
if invalid_bcs:
errors["extra_errors"].append(f"business_category 非法值: {invalid_bcs}")
for list_dim in ("brand", "role"):
if list_dim in md and not isinstance(md.get(list_dim), list):
errors["extra_errors"].append(f"{list_dim} 应为列表")
......@@ -289,11 +269,7 @@ def run_lint_phase1(wiki_dir: str, base_dir: str, mode: str = "full", changed_pa
# 全部基于全量页面 metadata,单次 frontmatter.load 收集后复用。
# ==================================================================================
def _as_list(v):
if isinstance(v, list):
return [x for x in v if x not in (None, "")]
if v in (None, ""):
return []
return [v]
return [x for x in as_value_list(v) if x not in (None, "")]
def _clean_to_slug(raw):
s = str(raw).strip()
......@@ -310,9 +286,13 @@ def run_lint_phase1(wiki_dir: str, base_dir: str, mode: str = "full", changed_pa
try:
post = frontmatter.load(fpath)
md = post.metadata
try:
page_type = canonicalize_type(md.get("type", ""), contract)
except ValueError:
page_type = str(md.get("type", ""))
page_meta[slug] = {
"rel": rel,
"type": str(md.get("type", "")),
"type": page_type,
"title": str(md.get("title", slug)),
"brand": _as_list(md.get("brand")),
"business_category": md.get("business_category"),
......@@ -350,7 +330,7 @@ def run_lint_phase1(wiki_dir: str, base_dir: str, mode: str = "full", changed_pa
# 话术字段合规:script 页面 script_type / violation_type(有字段才校验,避免新模板误报)
for slug, meta in page_meta.items():
if meta["type"] not in ("script", "scripts"):
if meta["type"] != "scripts":
continue
if meta.get("script_type") is None:
result["script_issues"].append({"file": meta["rel"], "issue": "script_type 缺失"})
......@@ -379,7 +359,7 @@ def run_lint_phase1(wiki_dir: str, base_dir: str, mode: str = "full", changed_pa
CLAIM_RE = re.compile(r'\d[\d,\.]*\s*(?:元|万元|万|年|公里|万公里|折|%)|覆盖|不含|不包括|包含|三电|保修|质保')
_cand_groups = {}
for slug, meta in page_meta.items():
if meta["type"] not in ("entity", "entities", "product", "products"):
if meta["type"] not in ("entities", "products"):
continue
claims = []
for line in meta["content"].splitlines():
......@@ -402,7 +382,10 @@ def run_lint_phase1(wiki_dir: str, base_dir: str, mode: str = "full", changed_pa
rel = os.path.relpath(fpath, base_dir).replace("\\", "/")
try:
post = frontmatter.load(fpath)
page_type = str(post.metadata.get("type", ""))
try:
page_type = canonicalize_type(post.metadata.get("type", ""), contract)
except ValueError:
page_type = str(post.metadata.get("type", ""))
if page_type not in STALE_TYPES:
continue
updated_val = post.metadata.get("updated")
......
......@@ -28,7 +28,14 @@ QDRANT_COLLECTION = os.environ.get("QDRANT_COLLECTION", "rag_chunks")
RAG_ANSWER_MODEL = os.environ.get("RAG_ANSWER_MODEL", "deepseek-v4-flash")
RAG_INTENT_MODEL = os.environ.get("RAG_INTENT_MODEL", "deepseek-v4-flash")
RAG_REWRITE_MODEL = os.environ.get("RAG_REWRITE_MODEL", "deepseek-v4-flash")
#
# RAG_ANSWER_MODEL = os.environ.get("RAG_ANSWER_MODEL", "qwen3.7-plus")
# RAG_INTENT_MODEL = os.environ.get("RAG_INTENT_MODEL", "qwen3.7-plus")
# RAG_REWRITE_MODEL = os.environ.get("RAG_REWRITE_MODEL", "qwen3.7-plus")
# 意图识别优先走低延迟路径:默认显式关闭支持该参数模型的 thinking/reasoning 模式。
RAG_INTENT_ENABLE_THINKING = os.environ.get("RAG_INTENT_ENABLE_THINKING", "false")
os.environ.setdefault("RAG_INTENT_ENABLE_THINKING", RAG_INTENT_ENABLE_THINKING)
# 用于将文本转换为高维向量的 Embedding 模型,默认 text-embedding-v4
RAG_EMBEDDING_MODEL = os.environ.get("RAG_EMBEDDING_MODEL", "text-embedding-v4")
......
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
......@@ -203,6 +203,21 @@ def delete_office_preview_pdf(file_path: str, file_id: str, preview_dir: str | N
)
return str(cache_path)
def get_existing_office_preview_pdf(file_path: str, file_id: str, preview_dir: str | None = None) -> str | None:
"""Return a fresh cached PPT/PPTX preview PDF path without creating it."""
source_path = Path(file_path)
if not source_path.exists():
raise FileNotFoundError(f"File not found: {file_path}")
cache_path = get_office_preview_pdf_path(file_path, file_id, preview_dir)
if not cache_path.exists():
return None
if cache_path.stat().st_mtime < source_path.stat().st_mtime:
return None
return str(cache_path)
def get_or_create_office_preview_pdf(file_path: str, file_id: str, preview_dir: str | None = None) -> str:
"""Create or reuse a cached PDF preview for PPT/PPTX files without running VLM parsing."""
source_path = Path(file_path)
......
from __future__ import annotations
import functools
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import yaml
CONTRACT_START = "<!-- INGEST_CONTRACT_START -->"
CONTRACT_END = "<!-- INGEST_CONTRACT_END -->"
@dataclass(frozen=True)
class IngestContract:
schema_version: str
required_fields: tuple[str, ...]
canonical_types: dict[str, dict[str, Any]]
type_aliases: dict[str, str]
source_tracked_exclude: tuple[str, ...]
list_merge_fields: tuple[str, ...]
business_categories: tuple[str, ...]
vehicle_brands: tuple[str, ...]
ecosystem_names: tuple[str, ...]
prompt_text: str
def _default_schema_path() -> Path:
return Path(__file__).resolve().parents[2] / "skills" / "llm-ingest" / "references" / "schema.md"
def _extract_contract_yaml(schema_text: str) -> str:
if CONTRACT_START not in schema_text or CONTRACT_END not in schema_text:
raise ValueError("schema.md 缺少 INGEST_CONTRACT 标记")
block = schema_text.split(CONTRACT_START, 1)[1].split(CONTRACT_END, 1)[0].strip()
if block.startswith("```"):
lines = block.splitlines()
if lines and lines[0].startswith("```"):
lines = lines[1:]
if lines and lines[-1].strip() == "```":
lines = lines[:-1]
block = "\n".join(lines).strip()
return block
def _flatten_vehicle_brands(raw: dict[str, Any]) -> tuple[str, ...]:
out: list[str] = []
for values in raw.values():
if not isinstance(values, list):
continue
for item in values:
if item and item not in out:
out.append(str(item))
return tuple(out)
def _build_type_aliases(canonical_types: dict[str, dict[str, Any]]) -> dict[str, str]:
aliases: dict[str, str] = {}
for canonical, spec in canonical_types.items():
aliases[canonical] = canonical
for alias in spec.get("aliases", []) or []:
aliases[str(alias)] = canonical
return aliases
@functools.lru_cache(maxsize=None)
def load_ingest_contract(schema_path: str | None = None) -> IngestContract:
path = Path(schema_path) if schema_path else _default_schema_path()
schema_text = path.read_text(encoding="utf-8")
raw = yaml.safe_load(_extract_contract_yaml(schema_text)) or {}
canonical_types = raw.get("canonical_types") or {}
if not canonical_types:
raise ValueError("schema contract 缺少 canonical_types")
return IngestContract(
schema_version=str(raw.get("schema_version") or "").strip(),
required_fields=tuple(raw.get("required_fields") or ()),
canonical_types=canonical_types,
type_aliases=_build_type_aliases(canonical_types),
source_tracked_exclude=tuple(raw.get("source_tracked_exclude") or ()),
list_merge_fields=tuple(raw.get("list_merge_fields") or ()),
business_categories=tuple(raw.get("business_categories") or ()),
vehicle_brands=_flatten_vehicle_brands(raw.get("vehicle_brands") or {}),
ecosystem_names=tuple(raw.get("ecosystem_names") or ()),
prompt_text=schema_text,
)
def current_schema_version() -> str:
return load_ingest_contract().schema_version
def canonicalize_type(raw_type: Any, contract: IngestContract | None = None) -> str:
value = str(raw_type or "").strip()
active_contract = contract or load_ingest_contract()
canonical = active_contract.type_aliases.get(value)
if not canonical:
raise ValueError(f"非法页面 type: {value}")
return canonical
def brand_baseline_set() -> set[str]:
return set(load_ingest_contract().vehicle_brands)
def ecosystem_name_set() -> set[str]:
return set(load_ingest_contract().ecosystem_names)
def contract_prompt_text() -> str:
return load_ingest_contract().prompt_text
def as_value_list(value: Any) -> list[Any]:
if isinstance(value, list):
return list(value)
if value in (None, ""):
return []
return [value]
def merge_field_sources(
target_md: dict[str, Any],
new_md: dict[str, Any],
canonical_source: str,
contract: IngestContract | None = None,
) -> None:
active_contract = contract or load_ingest_contract()
exclude = set(active_contract.source_tracked_exclude)
list_fields = set(active_contract.list_merge_fields)
fs = target_md.get("field_sources", {}) or {}
for key, value in new_md.items():
if key in exclude:
continue
new_values = as_value_list(value)
if not new_values:
continue
is_list = key in list_fields or isinstance(value, list) or isinstance(target_md.get(key), list)
fs.setdefault(key, {})
for item in new_values:
fs[key].setdefault(item, [])
if canonical_source not in fs[key][item]:
fs[key][item].append(canonical_source)
if is_list:
merged = as_value_list(target_md.get(key))
for item in new_values:
if item not in merged:
merged.append(item)
target_md[key] = merged
elif target_md.get(key) in (None, ""):
target_md[key] = new_values[0]
target_md["field_sources"] = fs
def recompute_after_source_removal(
md: dict[str, Any],
removed_source: str,
contract: IngestContract | None = None,
) -> None:
active_contract = contract or load_ingest_contract()
list_fields = set(active_contract.list_merge_fields)
fs = md.get("field_sources", {}) or {}
for field, srcmap in list(fs.items()):
for item in list(srcmap.keys()):
if removed_source in srcmap.get(item, []):
srcmap[item] = [s for s in srcmap[item] if s != removed_source]
if not srcmap.get(item):
srcmap.pop(item, None)
surviving = list(srcmap.keys())
if not surviving:
fs.pop(field, None)
md.pop(field, None)
elif isinstance(md.get(field), list) or field in list_fields:
md[field] = surviving
elif md.get(field) not in surviving:
md[field] = surviving[0]
if fs:
md["field_sources"] = fs
else:
md.pop("field_sources", None)
from pathlib import Path
import ast
import unittest
def _function_source(path: str, name: str) -> str:
source = Path(path).read_text(encoding="utf-8")
tree = ast.parse(source)
for node in tree.body:
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == name:
return ast.get_source_segment(source, node) or ""
raise AssertionError(f"Function not found: {name}")
class FilesPreviewStaticTest(unittest.TestCase):
def test_pptx_view_uses_existing_preview_without_generating(self):
view_source = _function_source("src/api/routes/files.py", "view_file")
self.assertIn("get_existing_office_preview_pdf", view_source)
self.assertNotIn("get_or_create_office_preview_pdf", view_source)
self.assertIn("preview_status", view_source)
self.assertIn("missing", view_source)
self.assertIn("status_code=202", view_source)
def test_document_parser_exposes_existing_preview_helper(self):
parser_source = Path("src/tools/document_parser.py").read_text(encoding="utf-8")
self.assertIn("def get_existing_office_preview_pdf", parser_source)
self.assertIn("return str(cache_path)", parser_source)
if __name__ == "__main__":
unittest.main()
from pathlib import Path
import unittest
class IngestContractStaticTest(unittest.TestCase):
def test_ingest_uses_schema_contract_instead_of_split_reference_files(self):
source = Path("src/api/routes/ingest.py").read_text(encoding="utf-8")
self.assertIn("def build_planner_system_prompt", source)
self.assertIn("def build_writer_system_prompt", source)
self.assertNotIn("src.utils.ingest_prompts", source)
self.assertFalse(Path("src/utils/ingest_prompts.py").exists())
self.assertIn("contract_prompt_text", source)
self.assertIn("current_schema_version", source)
self.assertIn("canonicalize_type", source)
self.assertIn("merge_field_sources", source)
self.assertIn("recompute_after_source_removal", source)
self.assertNotIn("brand-baseline.md", source)
self.assertNotIn("golden-examples.md", source)
self.assertNotIn('"v1.3"', source)
hardcoded_prompt_fragments = [
"轻改类 | 权益类 | 二手车类",
"杜绝同义碎片化",
"按主题完整归集",
"数值零丢失",
"作用域实体 + 产品线/主题",
]
for fragment in hardcoded_prompt_fragments:
self.assertNotIn(fragment, source)
def test_lint_uses_schema_contract_instead_of_markdown_regex_baselines(self):
source = Path("src/api/routes/lint.py").read_text(encoding="utf-8")
self.assertIn("brand_baseline_set", source)
self.assertIn("canonicalize_type", source)
self.assertIn("load_ingest_contract", source)
self.assertNotIn("brand-baseline.md", source)
self.assertNotIn("schema_version[:\\s]+", source)
def test_llm_ingest_skill_has_single_reference_document(self):
references = sorted(p.name for p in Path("skills/llm-ingest/references").glob("*.md"))
skill = Path("skills/llm-ingest/SKILL.md").read_text(encoding="utf-8")
self.assertEqual(references, ["schema.md"])
self.assertNotIn("brand-baseline.md", skill)
self.assertNotIn("golden-examples.md", skill)
self.assertNotIn("v1.3", skill)
if __name__ == "__main__":
unittest.main()
from pathlib import Path
import unittest
class IngestFileLocksStaticTest(unittest.TestCase):
def test_ingest_is_global_serial_but_egress_only_uses_file_lock(self):
source = Path("src/api/routes/ingest.py").read_text(encoding="utf-8")
self.assertIn("ingest_global_lock = asyncio.Lock()", source)
self.assertIn("async with ingest_global_lock:", source)
self.assertIn("file_operation_locks", source)
self.assertIn("def _get_file_operation_lock(file_id: str)", source)
self.assertIn("async with _get_file_operation_lock(file_id):", source)
self.assertIn("[Egress] waiting_for_file_lock", source)
self.assertNotIn("[Egress] waiting_for_ingest_global_lock", source)
self.assertNotIn("[Egress] acquired_ingest_global_lock", source)
self.assertIn("[IngestTask] waiting_for_file_lock", source)
self.assertIn("[IngestTask] waiting_for_ingest_global_lock", source)
if __name__ == "__main__":
unittest.main()
from pathlib import Path
import ast
import unittest
class UploadWordCountStaticTest(unittest.TestCase):
def test_upload_does_not_extract_text_or_run_vlm(self):
source = Path("src/api/routes/files.py").read_text(encoding="utf-8")
tree = ast.parse(source)
upload_fn = next(
node for node in tree.body
if isinstance(node, ast.AsyncFunctionDef) and node.name == "upload_file_chunk"
)
upload_source = ast.get_source_segment(source, upload_fn) or ""
self.assertNotIn("extract_text_from_file", upload_source)
self.assertNotIn("_load_pdf", upload_source)
self.assertIn("word_count = 0", upload_source)
self.assertIn('db_file.status = "Pending"', upload_source)
if __name__ == "__main__":
unittest.main()
from pathlib import Path
import unittest
RAG_PAGE = Path("frontend/src/app/rag/page.tsx")
RAG_API = Path("frontend/src/lib/rag-api.ts")
class RagChatStaticTest(unittest.TestCase):
def test_clear_history_does_not_enter_chat_loading_state(self):
source = RAG_PAGE.read_text(encoding="utf-8")
clear_start = source.index("const clearHistoryV2 = async () => {")
clear_end = source.index("const openSourcePreview", clear_start)
clear_block = source[clear_start:clear_end]
self.assertNotIn("runAction", clear_block)
self.assertIn("setLoading(false)", clear_block)
self.assertIn("setMessages([])", clear_block)
self.assertIn("const sessionToClear = sessionId", clear_block)
self.assertIn("clearRagHistory(sessionToClear)", clear_block)
def test_aborted_rag_stream_is_not_rendered_as_an_error_message(self):
source = RAG_API.read_text(encoding="utf-8")
self.assertIn('error.name === "AbortError"', source)
self.assertIn("return;", source[source.index('error.name === "AbortError"'):])
def test_rag_reasoning_steps_render_elapsed_time_per_step(self):
source = RAG_PAGE.read_text(encoding="utf-8")
self.assertIn("function formatElapsedSeconds", source)
self.assertIn("time: formatElapsedSeconds(step.elapsed_ms)", source)
self.assertIn("`耗时 ${", source)
if __name__ == "__main__":
unittest.main()
from pathlib import Path
import unittest
class WikiUploadPreviewStaticTest(unittest.TestCase):
def setUp(self):
self.source = Path("frontend/src/app/page.tsx").read_text(encoding="utf-8")
def test_ppt_preview_uses_controlled_state_not_direct_iframe(self):
self.assertIn("const canDirectIframePreview", self.source)
self.assertIn('return lowerName.endsWith(".pdf");', self.source)
self.assertIn("预览 PDF 尚未生成", self.source)
self.assertIn("previewStatus", self.source)
def test_upload_modal_distinguishes_file_saved_from_processing_done(self):
self.assertIn("保存中", self.source)
self.assertIn("已保存到文件库", self.source)
self.assertNotIn("稍后可在列表中发起摄入", self.source)
if __name__ == "__main__":
unittest.main()
import unittest
import sys
import types
sqlalchemy_stub = types.ModuleType("sqlalchemy")
sqlalchemy_stub.select = lambda *_args, **_kwargs: None
sys.modules["sqlalchemy"] = sqlalchemy_stub
config_stub = types.ModuleType("src.rag.config")
config_stub.RAG_ANSWER_MODEL = "answer-model"
config_stub.RAG_INTENT_MODEL = "intent-model"
config_stub.RAG_MAX_CONTEXT_CHARS = 4000
config_stub.RAG_MIN_RERANK_SCORE = 0.0
config_stub.RAG_NEIGHBOR_WINDOW = 1
config_stub.RAG_PARENT_FINAL_TOP_K = 5
config_stub.RAG_RERANKER_TOP_K = 20
config_stub.RAG_VECTOR_TOP_K = 20
sys.modules["src.rag.config"] = config_stub
llm_stub = types.ModuleType("src.rag.llm")
llm_stub.chat_once = None
llm_stub.chat_stream = None
sys.modules["src.rag.llm"] = llm_stub
reranker_stub = types.ModuleType("src.rag.reranker")
reranker_stub.rerank_chunks = lambda _query, chunks: chunks
sys.modules["src.rag.reranker"] = reranker_stub
stores_stub = types.ModuleType("src.rag.stores")
stores_stub.vector_store = object()
sys.modules["src.rag.stores"] = stores_stub
models_stub = types.ModuleType("src.database.models")
models_stub.RagChunk = object
sys.modules["src.database.models"] = models_stub
session_stub = types.ModuleType("src.database.session")
session_stub.AsyncSessionLocal = object
sys.modules["src.database.session"] = session_stub
from src.rag.retrieval import _answer_system_prompt
class AnswerPromptStaticTest(unittest.TestCase):
def test_prompt_aligns_with_llm_query_answer_templates(self):
prompt = _answer_system_prompt()
required_phrases = [
"【差异化回答格式】",
"scripts(话术类)",
"troubleshooting(系统排障类)",
"policies(政策/合规红线类)",
"products(产品类)",
"procedures(流程/SOP 类)",
"comparisons / synthesis(对比分析/综合类)",
"concepts(概念类)",
"当前知识库中暂无关于「{关键词}」的 {意图类型} 信息。",
"类型:{推荐的页面 type,如 scripts / products / policies}",
"路径建议:raw/sources/{品牌}/{文档名}.md",
]
for phrase in required_phrases:
with self.subTest(phrase=phrase):
self.assertIn(phrase, prompt)
if __name__ == "__main__":
unittest.main()
import importlib
import os
import sys
import unittest
class RagConfigTest(unittest.TestCase):
def test_intent_thinking_defaults_to_disabled(self):
original = os.environ.pop("RAG_INTENT_ENABLE_THINKING", None)
config_stub = type(sys)("config")
config_stub.BASE_DIR = os.getcwd()
original_config_module = sys.modules.get("config")
sys.modules["config"] = config_stub
sys.modules.pop("src.rag.config", None)
try:
rag_config = importlib.import_module("src.rag.config")
self.assertEqual(rag_config.RAG_INTENT_ENABLE_THINKING, "false")
self.assertEqual(os.environ["RAG_INTENT_ENABLE_THINKING"], "false")
finally:
sys.modules.pop("src.rag.config", None)
if original_config_module is None:
sys.modules.pop("config", None)
else:
sys.modules["config"] = original_config_module
if original is None:
os.environ.pop("RAG_INTENT_ENABLE_THINKING", None)
else:
os.environ["RAG_INTENT_ENABLE_THINKING"] = original
if __name__ == "__main__":
unittest.main()
import sys
import types
import unittest
sqlalchemy_stub = types.ModuleType("sqlalchemy")
sqlalchemy_stub.select = lambda *_args, **_kwargs: None
sys.modules["sqlalchemy"] = sqlalchemy_stub
config_stub = types.ModuleType("src.rag.config")
config_stub.RAG_ANSWER_MODEL = "answer-model"
config_stub.RAG_INTENT_MODEL = "intent-model"
config_stub.RAG_MAX_CONTEXT_CHARS = 4000
config_stub.RAG_MIN_RERANK_SCORE = 0.0
config_stub.RAG_NEIGHBOR_WINDOW = 1
config_stub.RAG_PARENT_FINAL_TOP_K = 5
config_stub.RAG_RERANKER_TOP_K = 20
config_stub.RAG_VECTOR_TOP_K = 20
sys.modules["src.rag.config"] = config_stub
llm_stub = types.ModuleType("src.rag.llm")
async def _unused_chat_once(*_args, **_kwargs):
raise AssertionError("chat_once should be patched in tests")
async def _unused_chat_stream(*_args, **_kwargs):
raise AssertionError("chat_stream should be patched in tests")
yield {}
llm_stub.chat_once = _unused_chat_once
llm_stub.chat_stream = _unused_chat_stream
sys.modules["src.rag.llm"] = llm_stub
reranker_stub = types.ModuleType("src.rag.reranker")
reranker_stub.rerank_chunks = lambda _query, chunks: chunks
sys.modules["src.rag.reranker"] = reranker_stub
stores_stub = types.ModuleType("src.rag.stores")
stores_stub.vector_store = object()
sys.modules["src.rag.stores"] = stores_stub
models_stub = types.ModuleType("src.database.models")
class RagChunk:
status = "active"
chunk_id = "chunk_id"
models_stub.RagChunk = RagChunk
sys.modules["src.database.models"] = models_stub
session_stub = types.ModuleType("src.database.session")
session_stub.AsyncSessionLocal = object
sys.modules["src.database.session"] = session_stub
from src.rag import retrieval
class RetrievalIntentNormalizationTest(unittest.IsolatedAsyncioTestCase):
async def test_classify_intent_prompt_aligns_with_ingest_and_query_routing(self):
captured = {}
async def fake_chat_once(_model, prompt, **_kwargs):
captured["prompt"] = prompt
return '{"intent":"chitchat","intents":["chitchat"],"standalone_query":"你好"}'
original_chat_once = retrieval.chat_once
retrieval.chat_once = fake_chat_once
try:
await retrieval.classify_intent("你好", [])
finally:
retrieval.chat_once = original_chat_once
prompt = captured["prompt"]
self.assertLess(len(prompt), 2400)
required_phrases = [
"角色",
"输出 JSON",
"Canonical intent 取值",
"products/scripts/policies/procedures/troubleshooting/comparisons/concepts/synthesis/sources/entities",
"优先级",
"troubleshooting > policies > scripts > products > procedures > comparisons > synthesis > concepts",
"能不能说/违规/合规/能不能做 → policies",
"怎么说/怎么回/话术/应对 → scripts",
"参数/价格/质保/保障 → products",
"综合分析/趋势/跨资料归纳 → synthesis",
"价格和免责怎么跟客户说",
'"intents":["scripts","products","policies"]',
"brand 只填车辆品牌",
"嘀加/广联数科不是车辆品牌",
"business_category 仅限",
"sub_business 尽量用业务口径",
"字段约束",
"禁止 Markdown",
"<think>",
]
for phrase in required_phrases:
with self.subTest(phrase=phrase):
self.assertIn(phrase, prompt)
async def test_classify_intent_normalizes_legacy_singular_intents_to_canonical_plural(self):
async def fake_chat_once(*_args, **_kwargs):
return (
'{"intent":["product","policy"],'
'"intents":["product","policy"],'
'"standalone_query":"价格和免责"}'
)
original_chat_once = retrieval.chat_once
retrieval.chat_once = fake_chat_once
try:
result = await retrieval.classify_intent("价格和免责", [])
finally:
retrieval.chat_once = original_chat_once
self.assertEqual(result.intent, "products")
self.assertEqual(result.intents, ["products", "policies"])
self.assertEqual(result.standalone_query, "价格和免责")
async def test_classify_intent_accepts_canonical_plural_results(self):
cases = [
("能不能这么说,合规吗", '{"intent":"policies","intents":["policies"],"standalone_query":"能不能这么说,合规吗"}', "policies", ["policies"]),
("客户嫌贵怎么回", '{"intent":"scripts","intents":["scripts"],"standalone_query":"客户嫌贵怎么回"}', "scripts", ["scripts"]),
(
"太阳膜价格和免责",
'{"intent":"products","intents":["products","policies"],"business_category":"轻改类","sub_business":"太阳膜","standalone_query":"太阳膜价格和免责"}',
"products",
["products", "policies"],
),
]
original_chat_once = retrieval.chat_once
try:
for query, response, expected_intent, expected_intents in cases:
async def fake_chat_once(*_args, _response=response, **_kwargs):
return _response
retrieval.chat_once = fake_chat_once
with self.subTest(query=query):
result = await retrieval.classify_intent(query, [])
self.assertEqual(result.intent, expected_intent)
self.assertEqual(result.intents, expected_intents)
finally:
retrieval.chat_once = original_chat_once
if __name__ == "__main__":
unittest.main()
from types import SimpleNamespace
from src.rag.retrieval import Candidate, _candidate_log_items, _chunk_log_items
def test_candidate_log_items_include_source_score_and_metadata():
candidate = Candidate(
child_chunk_id="child-1",
parent_chunk_id="parent-1",
file_id="file-1",
retrieval_type="direct",
hybrid_score=0.87654,
payload={
"source_name": "source.pdf",
"chunk_index": 12,
"page_start": 3,
"page_end": 4,
"section_title": "features",
"brand": "brand-a",
"business_category": "vehicle",
"content_kind": "text",
},
)
items = _candidate_log_items([candidate], limit=5)
assert items == [
{
"rank": 1,
"type": "direct",
"score": 0.8765,
"child": "child-1",
"parent": "parent-1",
"file_id": "file-1",
"source": "source.pdf",
"chunk_index": 12,
"page": "3-4",
"section": "features",
"kind": "text",
"brand": "brand-a",
"category": "vehicle",
}
]
def test_chunk_log_items_include_scores_location_and_preview():
chunk = SimpleNamespace(
chunk_id="parent-1",
child_chunk_id="child-1",
file_id="file-1",
source_name="source.pdf",
chunk_index=12,
page_start=3,
page_end=3,
row_start=None,
row_end=None,
title_path="features > cockpit",
section_title="features",
content_kind="text",
brand_series="brand-a",
business_category="vehicle",
retrieval_type="direct",
vector_score=0.45678,
final_score=0.45678,
rerank_score=0.81234,
is_neighbor=False,
metadata_json={},
content="line one\nline two",
)
items = _chunk_log_items([chunk], limit=5, include_preview=True)
assert items == [
{
"rank": 1,
"chunk_id": "parent-1",
"child": "child-1",
"file_id": "file-1",
"source": "source.pdf",
"chunk_index": 12,
"page": "3",
"title": "features > cockpit",
"section": "features",
"kind": "text",
"brand": "brand-a",
"category": "vehicle",
"type": "direct",
"vector_score": 0.4568,
"final_score": 0.4568,
"rerank_score": 0.8123,
"neighbor": False,
"chars": 17,
"preview": "line one line two",
}
]
import unittest
from pathlib import Path
import frontmatter
class IngestContractTest(unittest.TestCase):
def test_schema_contract_exposes_version_types_and_brand_baseline(self):
from src.utils.ingest_contract import (
brand_baseline_set,
canonicalize_type,
current_schema_version,
ecosystem_name_set,
load_ingest_contract,
)
contract = load_ingest_contract()
self.assertEqual(current_schema_version(), "v1.0")
self.assertEqual(contract.schema_version, "v1.0")
self.assertEqual(canonicalize_type("product"), "products")
self.assertEqual(canonicalize_type("products"), "products")
self.assertEqual(canonicalize_type("source"), "sources")
self.assertEqual(canonicalize_type("sources"), "sources")
with self.assertRaises(ValueError):
canonicalize_type("not-a-type")
self.assertIn("问界", brand_baseline_set())
self.assertIn("尚界", brand_baseline_set())
self.assertNotIn("嘀加", brand_baseline_set())
self.assertIn("嘀加", ecosystem_name_set())
for field in ("series", "brand", "business_category", "sub_business", "role"):
self.assertIn(field, contract.list_merge_fields)
def test_merge_field_sources_unions_all_filter_dimensions(self):
from src.utils.ingest_contract import merge_field_sources
target = {
"schema_version": "v1.0",
"type": "products",
"title": "嘀加太阳膜",
"series": "鸿蒙智行",
"brand": ["问界"],
"business_category": "轻改类",
"sub_business": "太阳膜",
"role": ["驻店销售"],
"tags": ["产品参数"],
"field_sources": {
"series": {"鸿蒙智行": ["ware/raw/a.pdf"]},
"brand": {"问界": ["ware/raw/a.pdf"]},
"business_category": {"轻改类": ["ware/raw/a.pdf"]},
"sub_business": {"太阳膜": ["ware/raw/a.pdf"]},
"role": {"驻店销售": ["ware/raw/a.pdf"]},
},
}
new = {
"schema_version": "v1.0",
"type": "products",
"title": "嘀加太阳膜",
"series": "通用品牌",
"brand": ["智界", "问界"],
"business_category": "权益类",
"sub_business": "售后延保",
"role": ["通用"],
"tags": ["FAQ", "产品参数"],
}
merge_field_sources(target, new, "ware/raw/b.pdf")
self.assertEqual(target["series"], ["鸿蒙智行", "通用品牌"])
self.assertEqual(target["brand"], ["问界", "智界"])
self.assertEqual(target["business_category"], ["轻改类", "权益类"])
self.assertEqual(target["sub_business"], ["太阳膜", "售后延保"])
self.assertEqual(target["role"], ["驻店销售", "通用"])
self.assertEqual(target["tags"], ["产品参数", "FAQ"])
self.assertEqual(
target["field_sources"]["brand"]["问界"],
["ware/raw/a.pdf", "ware/raw/b.pdf"],
)
self.assertEqual(
target["field_sources"]["sub_business"]["售后延保"],
["ware/raw/b.pdf"],
)
def test_existing_wiki_pages_use_current_schema_version(self):
from src.utils.ingest_contract import current_schema_version
expected = current_schema_version()
mismatches = []
for path in Path("ware/wiki").rglob("*.md"):
if path.name in {"index.md", "log.md"} or "lint_reports" in path.parts or "metadata" in path.parts:
continue
post = frontmatter.load(path)
if post.metadata.get("schema_version") != expected:
mismatches.append(str(path))
self.assertEqual(mismatches, [])
if __name__ == "__main__":
unittest.main()
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!