feat(ai): W1-AI-CLOSURE 超级 Sprint — 9 APP 全链路收口 + chat 上下文真激活

Phase 2.3 chat 上下文捕获链路从未真正激活到完整工作:
- 14 处 ai-float-button 补 sourcePage,chat.ts 三分支同步设 pageFilters.contextId
- 后端 page_context 4 层 BUG 修(列名错位 + RLS site_id 未重设)
- xcx_chat filters.pop 破坏 body.page_context 引用 — dict() 浅拷贝隔离
- chat 流式 markdown 实时解析(表格/标题/列表/加粗 + KPI 富卡)
- reference_card KPI 富卡接入 SSE 路径,db 真写入
- 维客线索 source 显示规则:AI 来源用机器人 icon 替代长文字

数据库:
- public.member_retention_clue 加 emoji + runtime_mode + sandbox_instance_id
- biz.ai_run_logs 加 assistant_id + 复合索引
- chk_ai_cache_type CHECK 约束 8 类应用名
- cache_type / app_type 命名统一(app6_note / app7_customer / app8_consolidation)
- 历史 emoji 抽取脚本 44/44 成功

后端 silent failure 修:
- cleanup_service WHERE app_type → cache_type(90 天清理 + 20K 上限重新生效)
- _build_ai_insight 字段错位修复(app4 → app7 + 字段对齐 prompt schema)
- task_manager talkingPoints 改 app5_tactics + tactics 字段
- task_manager aiSuggestion 改取 one_line_summary
- cache_service.CACHE_EXPIRY_DAYS 加 app2a_finance_area
- WS /ws/ai-cache 加 token + JWT + site_id 校验(P0 信息泄露漏洞)
- internal_ai token 改 hmac.compare_digest

工具/文档:
- main.py 加 RotatingFileHandler logs/backend.log + uvicorn /health 过滤
- 新建 utils/clue_category.py(VI 6 类配色 + emoji fallback + source 显示规则)
- 新建 utils/markdown.ts(轻量 md 转 rich-text 解析 + streaming 容错)
- audit + 数据库变更说明 + backlog §七 #14 收口 + #15-#38 残余子任务
- backlog 追加 §十一 App1 参数/MCP/沙箱审计 + §十二 百炼/SQL MCP 主任务线

实地 MCP 走查:14 入口数据层 + 5 代表入口 sourcePage 注入 + customer-detail 全模块 + chat md 渲染 + reference_card 富卡 都已验证。9 项预先 BUG/UX 登记 §七 #29-#38 后续修复。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Neo
2026-05-06 16:39:07 +08:00
parent c9c2bce101
commit 2dfc926f96
56 changed files with 1983 additions and 278 deletions

View File

@@ -143,13 +143,13 @@ async def get_customer_detail(customer_id: int, site_id: int) -> dict:
# ── 扩展模块(独立 try/except 优雅降级)──
try:
ai_insight = _build_ai_insight(customer_id, conn)
ai_insight = _build_ai_insight(customer_id, site_id, conn)
except Exception:
logger.warning("构建 aiInsight 失败,降级为空", exc_info=True)
ai_insight = {"summary": "", "strategies": []}
try:
retention_clues = _build_retention_clues(customer_id, conn)
retention_clues = _build_retention_clues(customer_id, site_id, conn)
except Exception:
logger.warning("构建 retentionClues 失败,降级为空列表", exc_info=True)
retention_clues = []
@@ -223,24 +223,29 @@ async def get_customer_detail(customer_id: int, site_id: int) -> dict:
# ── 3.2 AI 洞察 / 维客线索 / 备注 ──────────────────────────
def _build_ai_insight(customer_id: int, conn) -> dict:
def _build_ai_insight(customer_id: int, site_id: int, conn) -> dict:
"""
构建 aiInsight 模块。
构建 aiInsight 模块(来自 App7 客户分析缓存)
查询 biz.ai_cache WHERE cache_type='app4_analysis' AND target_id=customerId
解析 result_json JSON。无缓存时返回空默认值。
查询 biz.ai_cache WHERE cache_type='app7_customer' AND target_id=customerId
AND site_id=site_id。无缓存时返回空默认值。
App7Result schema: {strategies: [{title, content}], summary: str}
"""
with conn.cursor() as cur:
cur.execute(
"""
SELECT result_json
FROM biz.ai_cache
WHERE cache_type = 'app4_analysis'
WHERE cache_type = 'app7_customer'
AND site_id = %s
AND target_id = %s
AND COALESCE(status, 'valid') = 'valid'
AND (expires_at IS NULL OR expires_at > now())
ORDER BY created_at DESC
LIMIT 1
""",
(str(customer_id),),
(site_id, str(customer_id)),
)
row = cur.fetchone()
@@ -255,37 +260,69 @@ def _build_ai_insight(customer_id: int, conn) -> dict:
summary = data.get("summary", "")
strategies_raw = data.get("strategies", [])
strategies = []
# App7Result schema: strategies = [{title, content}],但前端 demo 标杆 wxml 用单
# 字段 text(`{{item.text}}`)。在 service 层拼接成 demo 形态,前端保持 demo 一致。
for s in strategies_raw:
if isinstance(s, dict):
strategies.append({
"color": s.get("color", ""),
"text": s.get("text", ""),
})
t = (s.get("title") or "").strip()
c = (s.get("content") or "").strip()
text = f"{t}{c}" if t and c else (c or t)
strategies.append({"text": text})
return {"summary": summary, "strategies": strategies}
def _build_retention_clues(customer_id: int, conn) -> list[dict]:
def _build_retention_clues(customer_id: int, site_id: int, conn) -> list[dict]:
"""
构建 retentionClues 模块。
查询 public.member_retention_clue,按 recorded_at 倒序。
查询 public.member_retention_clue(含 emoji 独立列、source、detail
按 recorded_at 倒序,跨 source(manual / ai_consumption / ai_note)合并。
返回字段对齐 clue-card 组件契约 + xcx_customers.RetentionClue schema:
{tag, tag_color, emoji, text, source, desc}
"""
# CHANGE 2026-03-23 | BUG: clue_type/clue_text 列不存在,应为 category/summarycreated_at → recorded_at
from app.utils.clue_category import (
CATEGORY_TAG_COLOR,
SOURCE_DISPLAY_NAME,
format_category_tag,
)
with conn.cursor() as cur:
cur.execute(
"""
SELECT category, summary
SELECT category, summary, detail, emoji, source, recorded_by_name
FROM public.member_retention_clue
WHERE member_id = %s
AND site_id = %s
AND is_hidden = false
ORDER BY recorded_at DESC
""",
(customer_id,),
(customer_id, site_id),
)
rows = cur.fetchall()
return [{"type": r[0] or "", "text": r[1] or ""} for r in rows]
result: list[dict] = []
for category, summary, detail, emoji, source, recorded_by_name in rows:
category_str = category or ""
# source 显示规则(用户拍板:AI 来源用统一短标识 "AI",前端渲染 AI icon):
# - ai_consumption / ai_note → "AI"(舍弃 providers 详细文字,前端用 icon)
# - manual + recorded_by_name 非空 → 姓名(如"小燕")
# - manual + 空 → "系统"
src = source or "manual"
if src in ("ai_consumption", "ai_note"):
display_source = "AI"
else:
display_source = recorded_by_name or SOURCE_DISPLAY_NAME.get(src, "系统")
result.append({
"tag": format_category_tag(category_str),
"tag_color": CATEGORY_TAG_COLOR.get(category_str, "primary"),
"emoji": emoji or "",
"text": summary or "",
"source": display_source,
"desc": detail or "",
})
return result
NOTE_TYPE_LABELS = {"normal": "备注", "follow_up": "回访", "system": "系统", "ai": "AI"}