diff --git a/backend/app/api/internal_jobs.py b/backend/app/api/internal_jobs.py
index c67b900e..f773a8d9 100644
--- a/backend/app/api/internal_jobs.py
+++ b/backend/app/api/internal_jobs.py
@@ -38,6 +38,49 @@ def run_internal_job(name: str):
}
],
})
+ if key in {'faq-aggregate-hot', 'faq_hot_aggregate', 'faq-hot-aggregate'}:
+ from app.services.hot_faq_aggregator import HotFaqAggregator
+
+ schedule_task_id = data.get('schedule_task_id')
+ agent_id = data.get('agent_id')
+ if schedule_task_id:
+ task = db.session.get(ScheduleTask, int(schedule_task_id))
+ if task and task.dify_agent_id:
+ agent_id = task.dify_agent_id
+ result = HotFaqAggregator.aggregate_hot_faq_candidates(
+ agent_id=int(agent_id) if agent_id else None,
+ dry_run=False,
+ )
+ if not result.get('enabled'):
+ message = str(result.get('message') or 'FAQ_HOT_ENABLED is false')
+ return jsonify({
+ 'summary': {'total_count': 0, 'success_count': 0, 'failed_count': 0, 'skipped_count': 1},
+ 'details': [],
+ 'errors': [message],
+ 'step_logs': [{'step': 'faq_hot_aggregate', 'status': 'skipped', 'detail': {'message': message}}],
+ })
+ promoted = int(result.get('promoted_count') or 0)
+ skipped = int(result.get('skipped_count') or 0)
+ total = max(promoted + skipped, 1)
+ return jsonify({
+ 'summary': {
+ 'total_count': total,
+ 'success_count': promoted,
+ 'failed_count': 0,
+ 'skipped_count': skipped,
+ },
+ 'details': (result.get('candidates') or [])[:20],
+ 'errors': [],
+ 'step_logs': [{
+ 'step': 'faq_hot_aggregate',
+ 'status': 'success',
+ 'detail': {
+ 'scanned_logs': result.get('scanned_logs'),
+ 'promoted_count': promoted,
+ 'skipped_count': skipped,
+ },
+ }],
+ })
run_no = str(data.get('run_no') or '').strip()
schedule_task_id = data.get('schedule_task_id')
task = None
diff --git a/backend/app/api/schedule_admin.py b/backend/app/api/schedule_admin.py
index 2ee7c4b5..48f6971b 100644
--- a/backend/app/api/schedule_admin.py
+++ b/backend/app/api/schedule_admin.py
@@ -334,11 +334,14 @@ def post_schedule():
task.kb_sync_enabled = bool(data.get('kb_sync_enabled', False))
raw_kb_group_id = data.get('kb_group_id')
task.kb_group_id = int(raw_kb_group_id) if raw_kb_group_id not in (None, '', 0, '0') else None
- task.platform_api_path = f'/{task.id}'
+ if data_source_type == 'faq_hot_aggregate':
+ task.platform_api_path = 'faq-aggregate-hot'
+ else:
+ task.platform_api_path = f'/{task.id}'
db.session.commit()
db.session.refresh(task)
config_data = data.get('config')
- if config_data:
+ if config_data and data_source_type != 'faq_hot_aggregate':
upsert_schedule_task_config(task.id, config_data)
if not task.dify_agent_id:
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first()
diff --git a/backend/app/services/schedule/__init__.py b/backend/app/services/schedule/__init__.py
index 37fdc076..b2c9d209 100644
--- a/backend/app/services/schedule/__init__.py
+++ b/backend/app/services/schedule/__init__.py
@@ -273,6 +273,9 @@ def list_registered_api_paths() -> list[dict[str, str]]:
def resolve_schedule_executor(task: ScheduleTask) -> ScheduleExecutor:
dst = getattr(task, "data_source_type", None) or "database"
+ if dst == "faq_hot_aggregate":
+ from app.services.schedule.faq_hot_aggregate_job import run_faq_hot_aggregate_schedule
+ return run_faq_hot_aggregate_schedule
if dst in ("database", "external_api"):
return _run_generic_check_job
return _run_common_executor
diff --git a/backend/app/services/schedule/faq_hot_aggregate_job.py b/backend/app/services/schedule/faq_hot_aggregate_job.py
new file mode 100644
index 00000000..86ff3a46
--- /dev/null
+++ b/backend/app/services/schedule/faq_hot_aggregate_job.py
@@ -0,0 +1,70 @@
+"""
+backend/app/services/schedule/faq_hot_aggregate_job.py
+
+用途:排程管理触发的 FAQ 热点离线聚合执行器。
+依赖:HotFaqAggregator、ScheduleTask、ScheduleRun。
+逻辑:data_source_type=faq_hot_aggregate 时由 resolve_schedule_executor 调用。
+"""
+from __future__ import annotations
+
+from typing import Any
+
+from app.models import ScheduleRun, ScheduleTask
+from app.services.hot_faq_aggregator import HotFaqAggregator
+
+ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
+
+
+def run_faq_hot_aggregate_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
+ """
+ 执行 FAQ 热点离线聚合(等同 flask faq-aggregate-hot,非 dry-run)。
+ 核心逻辑:委托 HotFaqAggregator;可选 dify_agent_id 限定 Agent。
+ @param task - 排程任务;dify_agent_id 可选作 agent_id 过滤
+ @param run - 当前执行批次(未写入 run 字段,由 scheduler_service 汇总)
+ @returns ScheduleExecuteResult 元组
+ """
+ agent_id = int(task.dify_agent_id) if task.dify_agent_id else None
+ result = HotFaqAggregator.aggregate_hot_faq_candidates(agent_id=agent_id, dry_run=False)
+
+ step_logs: list[dict[str, Any]] = [
+ {
+ 'step': 'faq_hot_aggregate',
+ 'status': 'started',
+ 'detail': {'schedule_task_id': task.id, 'agent_id': agent_id},
+ }
+ ]
+
+ if not result.get('enabled'):
+ message = str(result.get('message') or 'FAQ_HOT_ENABLED is false')
+ step_logs.append({'step': 'faq_hot_aggregate', 'status': 'skipped', 'detail': {'message': message}})
+ return 0, 0, 0, 1, [], [message], step_logs
+
+ promoted = int(result.get('promoted_count') or 0)
+ skipped = int(result.get('skipped_count') or 0)
+ scanned = int(result.get('scanned_logs') or 0)
+ total = max(promoted + skipped, 1)
+
+ step_logs.append({
+ 'step': 'faq_hot_aggregate',
+ 'status': 'success',
+ 'detail': {
+ 'scanned_logs': scanned,
+ 'promoted_count': promoted,
+ 'skipped_count': skipped,
+ 'group_count': result.get('group_count'),
+ 'agent_id': agent_id,
+ },
+ })
+
+ details = [
+ {
+ 'canonical_query': item.get('canonical_query'),
+ 'ask_count_7d': item.get('ask_count_7d'),
+ 'user_count_7d': item.get('user_count_7d'),
+ 'answer_dominance': item.get('answer_dominance'),
+ }
+ for item in (result.get('candidates') or [])[:20]
+ if isinstance(item, dict)
+ ]
+
+ return total, promoted, 0, skipped, details, [], step_logs
diff --git a/backend/app/services/schedule/scheduler_service.py b/backend/app/services/schedule/scheduler_service.py
index 106dd206..4955cee9 100644
--- a/backend/app/services/schedule/scheduler_service.py
+++ b/backend/app/services/schedule/scheduler_service.py
@@ -226,7 +226,10 @@ def update_task(task: ScheduleTask, *, payload: dict[str, Any], actor_id: int |
task.kb_group_id = int(raw_group_id) if raw_group_id not in (None, "", 0, "0") else None
if not normalize_platform_api_path(task.platform_api_path):
- raise ValueError("platform_api_path is required for platform_app")
+ dst = str(getattr(task, "data_source_type", None) or "database")
+ if dst != "faq_hot_aggregate":
+ raise ValueError("platform_api_path is required for platform_app")
+ task.platform_api_path = "faq-aggregate-hot"
task.schedule_type = "platform_app"
if task.enabled and task.cron_expr:
diff --git a/docs/faq_cache_ops_manual.md b/docs/faq_cache_ops_manual.md
index f830ce52..18f6bf79 100644
--- a/docs/faq_cache_ops_manual.md
+++ b/docs/faq_cache_ops_manual.md
@@ -17,6 +17,142 @@
---
+## 1.1 架构总览
+
+### 整体分层
+
+```mermaid
+flowchart TB
+ subgraph online["在线对话(用户提问)"]
+ Q[用户问句] --> Match{FaqCacheService.try_match}
+ Match -->|命中 L1| SSE[SSE 直答预置答案]
+ Match -->|未命中| Dify[调用 Dify / HR / PLM 等]
+ Dify --> Log[写入 ChatLog]
+ SSE --> Log
+ end
+
+ subgraph offline["离线聚合(定时 / 手动)"]
+ Log --> Agg[HotFaqAggregator]
+ Agg --> PG[(faq_hot_candidates)]
+ end
+
+ subgraph admin["管理端审核"]
+ PG --> UI[热点发现 Tab]
+ UI -->|晋升| QQ[(quick_questions)]
+ UI -->|忽略| Deny[dismissed + deny_until]
+ QQ --> Match
+ end
+
+ subgraph kb["知识库更新(方案 B)"]
+ KBDoc[KB 文档 sync / 删除] --> Hook[faq_kb_invalidation]
+ Hook --> Stale[FAQ 待复审 stale_*
cache_enabled=false]
+ Stale --> UI2[常用问题 · 待复审]
+ UI2 -->|完成复审| QQ
+ end
+```
+
+| 层级 | 名称 | 存储 | 在线生效 |
+| --- | --- | --- | --- |
+| L1 | 人工 FAQ | `quick_questions` | ✅ 命中即 SSE 直答 |
+| L2 | 热点候选 | `faq_hot_candidates` | ❌ 须晋升后才进 L1 |
+| L3 | Dify 实时问答 | `chat_logs` | ✅ 默认兜底 |
+
+### 在线命中流程
+
+```mermaid
+flowchart TD
+ A[用户发消息 chat.py] --> B{有附件?}
+ B -->|是| Z[跳过 FAQ,走业务路由]
+ B -->|否| C[FaqCacheService.try_match]
+ C --> D{agent 全局 FAQ
cache_enabled=true
is_enabled=true
stale_at 为空
未过期?}
+ D -->|否| E[未命中 → Dify 等]
+ D -->|是| F{归一化问句匹配
question / title / aliases?}
+ F -->|否| E
+ F -->|是| G[SSE 直答 stream_chat]
+ G --> H[ChatLog: tokens=0
payload.source=faq_cache]
+ E --> I[ChatLog: tokens>0]
+```
+
+**匹配规则**:`normalize_faq_query` 归一化后精确匹配(见 `faq_text_utils.py`)。
+
+### 离线热点发现流程
+
+```mermaid
+flowchart TD
+ T[定时 cron / 管理端刷新] --> P[purge_expired 清理过期 candidate]
+ P --> S[扫描近 N 天 ChatLog]
+ S --> F1{tokens>0 且非 faq_cache 来源?}
+ F1 -->|否| Skip[跳过]
+ F1 -->|是| G[按 agent_id + q_norm 分组]
+ G --> F2{频次 / 用户数 / deny / 已有 FAQ?}
+ F2 -->|否| Skip
+ F2 -->|是| A[答案聚类 + 选最佳答案]
+ A --> F3{dominance ≥ 60%?}
+ F3 -->|否| Skip
+ F3 -->|是| U[UPSERT faq_hot_candidates]
+ U --> Admin[管理员审核]
+ Admin -->|晋升| QQ[quick_questions + cache_enabled]
+ Admin -->|忽略| D[dismissed + deny_until]
+```
+
+### KB 更新 → FAQ 待复审(方案 B)
+
+```mermaid
+sequenceDiagram
+ participant Admin as 管理员
+ participant KB as 知识库
+ participant Sync as dify_sync_service
+ participant Hook as faq_kb_invalidation
+ participant QQ as quick_questions
+ participant User as 用户
+ participant Dify as Dify
+
+ Note over Admin,QQ: 已晋升 FAQ 正常运行
+ User->>QQ: 提问
+ QQ->>User: L1 SSE 直答
+
+ Admin->>KB: 编辑文档并 sync
+ KB->>Sync: sync_hash 变化
+ Sync->>Hook: invalidate_faqs_for_kb_document
+ Hook->>QQ: stale_at=now, cache_enabled=false
+
+ User->>Dify: 再问同类问题(FAQ 不命中)
+ Dify->>User: 基于新 KB 回答
+
+ Admin->>QQ: 待复审 → 更新 answer → 完成复审
+ Note over QQ: clear_stale + cache_enabled=true
+ User->>QQ: 再问
+ QQ->>User: L1 直答新答案
+```
+
+### 数据表关系(简图)
+
+```mermaid
+erDiagram
+ chat_logs ||--o{ faq_hot_candidates : "source_chat_log_id"
+ faq_hot_candidates ||--o| quick_questions : "promoted_quick_question_id"
+ quick_questions }o--|| agents : "agent_id"
+ kb_documents ||--o{ kb_dify_sync_records : "document_id"
+ quick_questions }o--o| kb_documents : "stale_kb_document_id"
+ quick_questions {
+ int id
+ text answer
+ bool cache_enabled
+ json retriever_resources
+ json source_kb_document_ids
+ datetime stale_at
+ string stale_reason
+ }
+ faq_hot_candidates {
+ int id
+ string q_norm
+ string status
+ datetime expires_at
+ }
+```
+
+---
+
## 2. 首次部署 Checklist
### 2.1 数据库迁移
@@ -34,6 +170,8 @@ docker compose exec -T hxops-backend flask --app manage.py db upgrade
- `a1b2c3d4e5f7` — 扩展 `quick_questions`(answer、aliases、cache_enabled 等)
- `b2c3d4e5f6a8` — 新建 `faq_hot_candidates`
+- `c5d6e7f8a9b0` — 合并迁移 head(无 DDL)
+- `c6d7e8f9a0b1` — FAQ 待复审字段(`stale_*`、`source_kb_document_ids`)
### 2.2 环境变量
@@ -73,16 +211,33 @@ flask --app manage.py faq-aggregate-hot
## 3. 定时任务(推荐)
-热点发现 **无内置 cron**;过期 `candidate` 的物理清理也发生在聚合开始时。建议至少 **每天 1 次** 跑聚合。
+热点发现可通过 **排程管理** 配置 Cron,无需宿主机 crontab。
-### 3.1 Docker 环境(宿主机 crontab)
+### 3.1 排程管理(推荐)
+
+路径:**管理后台 → 排程管理 → 新增排程**
+
+| 配置项 | 建议值 |
+| --- | --- |
+| 数据源类型 | **FAQ 热点聚合** |
+| Cron | 例如每天 02:30(`0 2 * * *`) |
+| 限定应用 | 可选;留空=全部 Agent |
+| 所有者 | 必填 |
+
+创建并 **启用** 后,后端 `schedule-worker` 会按 Cron 自动执行,等同 `flask faq-aggregate-hot`。执行记录在排程工作台可查看(处理数 = 本次产出候选 + 跳过组数)。
+
+**前提**:`SCHEDULE_WORKER_ENABLED=true`(默认开启),后端进程需正常运行。
+
+### 3.2 Docker 环境(宿主机 crontab,备选)
+
+若不用排程管理,仍可用 crontab:
```cron
# 每天 02:30 聚合热点 FAQ(stdout 追加到日志)
30 2 * * * cd /path/to/hxops && docker compose exec -T hxops-backend flask --app manage.py faq-aggregate-hot >> /var/log/hxops/faq-aggregate-hot.log 2>&1
```
-### 3.2 裸机 / systemd timer
+### 3.3 裸机 / systemd timer
```bash
# 手动试跑
@@ -120,7 +275,7 @@ WantedBy=timers.target
sudo systemctl enable --now hxops-faq-aggregate.timer
```
-### 3.3 按 Agent 拆分(可选)
+### 3.4 按 Agent 拆分(可选)
大租户可分开跑,减轻单次扫描量:
@@ -128,9 +283,12 @@ sudo systemctl enable --now hxops-faq-aggregate.timer
flask --app manage.py faq-aggregate-hot --agent-id 12
```
-### 3.4 与「排程管理」的关系
+### 3.5 与 SQL 检核排程的区别
-管理端 **排程(Schedule)** 用于 Dify Workflow / 文件检核等,**不能**直接触发 `faq-aggregate-hot`。FAQ 聚合请用 crontab / systemd / CI 定时 Job。
+| 类型 | 用途 |
+| --- | --- |
+| 数据库直联 / 外部 API | SQL 拉数 + Dify 检核等业务排程 |
+| **FAQ 热点聚合** | ChatLog → `faq_hot_candidates`,无需 SQL/Dify Agent 配置 |
---
@@ -397,6 +555,7 @@ FAQ_HOT_ENABLED=false
| L1 在线匹配 | `backend/app/services/faq_cache.py` |
| 离线聚合 | `backend/app/services/hot_faq_aggregator.py` |
| PG 候选存储 | `backend/app/services/hot_faq_candidate_store.py` |
+| KB 失效标记 | `backend/app/services/faq_kb_invalidation.py` |
| CLI | `backend/app/cli/faq_commands.py` |
| 管理 API | `backend/app/api/admin.py` |
| 对话入口 | `backend/app/api/chat.py`(Dify 前 `try_match`) |
diff --git a/frontend/src/features/admin/modules/schedules/components/ScheduleCreateEditModal.vue b/frontend/src/features/admin/modules/schedules/components/ScheduleCreateEditModal.vue
index 78cce599..b78326ed 100644
--- a/frontend/src/features/admin/modules/schedules/components/ScheduleCreateEditModal.vue
+++ b/frontend/src/features/admin/modules/schedules/components/ScheduleCreateEditModal.vue
@@ -66,51 +66,61 @@ const showCreateModal = useScheduleCreateModalOpen();
{{ $t('admin.schedule.form.faqHotAggregateHint') }}
+{{ $t('admin.schedule.form.faqHotAgentFilterHelp') }}
+