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

@@ -1,8 +1,11 @@
/** /**
* 回归测试admin-web 手动执行 App 类型必须与后端 /api/admin/ai/run/{app_type} 对齐。 * 回归测试:admin-web app_type / cache_type 命名必须与后端
* (CacheTypeEnum + dispatcher 写入 + chk_ai_cache_type CHECK 约束)对齐。
* *
* 缓存类型仍使用 `*_analysis` / `*_consolidated`,但手动执行和 run log * W1-AI-CLOSURE 组 1+5 命名统一后:
* 应使用 dispatcher 支持的 app_type避免前端发出后端 400 的路径。 * - cache_type 与 app_type 使用同一组应用名(与 prompt 文件名一致)
* - 旧描述性后缀 'app6_note_analysis' / 'app7_customer_analysis' /
* 'app8_clue_consolidated' / 'app8_consolidate' 已绝迹,前端不再保留。
*/ */
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
@@ -10,34 +13,55 @@ import { RUN_APP_TYPES } from "../api/adminAI";
import { CACHE_TYPE_OPTIONS, RUN_APP_TYPE_OPTIONS } from "../pages/AIOperations"; import { CACHE_TYPE_OPTIONS, RUN_APP_TYPE_OPTIONS } from "../pages/AIOperations";
import { RUN_LOG_APP_TYPE_OPTIONS } from "../pages/AIRunLogs"; import { RUN_LOG_APP_TYPE_OPTIONS } from "../pages/AIRunLogs";
describe("admin AI app_type 对齐", () => { const NEW_APP_TYPES = [
it("手动执行类型使用后端支持的 app_type而不是缓存类型", () => { "app2_finance",
const apiTypes = [...RUN_APP_TYPES]; "app2a_finance_area",
const runOptionValues = RUN_APP_TYPE_OPTIONS.map((item) => item.value); "app3_clue",
"app4_analysis",
"app5_tactics",
"app6_note",
"app7_customer",
"app8_consolidation",
] as const;
for (const appType of ["app6_note", "app7_customer", "app8_consolidation"]) { const LEGACY_NAMES = [
expect(apiTypes).toContain(appType); "app6_note_analysis",
"app7_customer_analysis",
"app8_clue_consolidated",
"app8_consolidate",
];
describe("admin AI app_type / cache_type 命名对齐", () => {
it("RUN_APP_TYPES 与统一命名一致", () => {
expect([...RUN_APP_TYPES]).toEqual(NEW_APP_TYPES);
});
it("手动执行下拉只暴露统一命名(8 个),不含旧描述性后缀", () => {
const runOptionValues = RUN_APP_TYPE_OPTIONS.map((item) => item.value);
for (const appType of NEW_APP_TYPES) {
expect(runOptionValues).toContain(appType); expect(runOptionValues).toContain(appType);
} }
for (const legacy of LEGACY_NAMES) {
for (const cacheType of ["app6_note_analysis", "app7_customer_analysis", "app8_clue_consolidated"]) { expect(runOptionValues).not.toContain(legacy);
expect(runOptionValues).not.toContain(cacheType);
} }
}); });
it("缓存失效继续使用 cache_type避免破坏已有缓存管理", () => { it("缓存失效下拉与统一命名对齐,不含旧描述性后缀", () => {
const cacheOptionValues = CACHE_TYPE_OPTIONS.map((item) => item.value); const cacheOptionValues = CACHE_TYPE_OPTIONS.map((item) => item.value);
for (const cacheType of NEW_APP_TYPES) {
expect(cacheOptionValues).toContain("app6_note_analysis"); expect(cacheOptionValues).toContain(cacheType);
expect(cacheOptionValues).toContain("app7_customer_analysis"); }
expect(cacheOptionValues).toContain("app8_clue_consolidated"); for (const legacy of LEGACY_NAMES) {
expect(cacheOptionValues).not.toContain(legacy);
}
}); });
it("调用记录筛选包含真实写入 ai_run_logs 的 app_type", () => { it("调用记录筛选包含 chat + 8 个写缓存应用,不含旧 'app8_consolidate'", () => {
const runLogOptionValues = RUN_LOG_APP_TYPE_OPTIONS.map((item) => item.value); const runLogOptionValues = RUN_LOG_APP_TYPE_OPTIONS.map((item) => item.value);
expect(runLogOptionValues).toContain("app1_chat");
expect(runLogOptionValues).toContain("app6_note"); for (const appType of NEW_APP_TYPES) {
expect(runLogOptionValues).toContain("app7_customer"); expect(runLogOptionValues).toContain(appType);
expect(runLogOptionValues).toContain("app8_consolidate"); }
expect(runLogOptionValues).not.toContain("app8_consolidate");
}); });
}); });

View File

@@ -33,13 +33,17 @@ const EVENT_TYPE_OPTIONS = [
const { TextArea } = Input; const { TextArea } = Input;
const { Title } = Typography; const { Title } = Typography;
// W1-AI-CLOSURE 组 1+5:cache_type 命名与 prompt 文件名 + 数据库 chk_ai_cache_type
// 约束完全对齐(旧描述性后缀 _analysis / _consolidated 已废弃)。
export const CACHE_TYPE_OPTIONS = [ export const CACHE_TYPE_OPTIONS = [
{ label: "App2 财务洞察(全域)", value: "app2_finance" },
{ label: "App2a 财务洞察(区域)", value: "app2a_finance_area" },
{ label: "App3 维客线索", value: "app3_clue" }, { label: "App3 维客线索", value: "app3_clue" },
{ label: "App4 关系分析", value: "app4_analysis" }, { label: "App4 关系分析", value: "app4_analysis" },
{ label: "App5 话术参考", value: "app5_tactics" }, { label: "App5 话术参考", value: "app5_tactics" },
{ label: "App6 备注分析", value: "app6_note_analysis" }, { label: "App6 备注分析", value: "app6_note" },
{ label: "App7 客户分析", value: "app7_customer_analysis" }, { label: "App7 客户分析", value: "app7_customer" },
{ label: "App8 线索整理", value: "app8_clue_consolidated" }, { label: "App8 线索整理", value: "app8_consolidation" },
]; ];
export const RUN_APP_TYPE_OPTIONS: { label: string; value: AppType }[] = [ export const RUN_APP_TYPE_OPTIONS: { label: string; value: AppType }[] = [

View File

@@ -253,8 +253,10 @@ const AIRunLogs: React.FC = () => {
export default AIRunLogs; export default AIRunLogs;
// W1-AI-CLOSURE 组 1+5:ai_run_logs.app_type 命名统一(数据库已 UPDATE);
// 旧 'app8_consolidate' 已不再存在,从下拉移除。
export const RUN_LOG_APP_TYPE_OPTIONS = [ export const RUN_LOG_APP_TYPE_OPTIONS = [
"app1_chat", "app2_finance", "app2a_finance_area", "app3_clue", "app1_chat", "app2_finance", "app2a_finance_area", "app3_clue",
"app4_analysis", "app5_tactics", "app6_note", "app7_customer", "app4_analysis", "app5_tactics", "app6_note", "app7_customer",
"app8_consolidate", "app8_consolidation", "app8_consolidation",
].map((v) => ({ label: v, value: v })); ].map((v) => ({ label: v, value: v }));

View File

@@ -27,15 +27,19 @@ from app.services.runtime_context import (
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
# 缓存过期策略cache_type → 过期天数0 表示当日 23:59:59 # 缓存过期策略:cache_type → 过期天数(0 表示当日 23:59:59)
# 命名与 prompt 文件名一致(W1-AI-CLOSURE 组 1 数据库迁移已统一)。
# P0-11 修正:补 app2a_finance_area,与 app2_finance 同当日过期策略,
# 之前漏配导致 64 个区域组合缓存 expires_at=NULL 永不过期。
CACHE_EXPIRY_DAYS: dict[str, int] = { CACHE_EXPIRY_DAYS: dict[str, int] = {
"app2_finance": 0, # 当日 23:59:59 "app2_finance": 0,
"app2a_finance_area": 0,
"app3_clue": 7, "app3_clue": 7,
"app4_analysis": 7, "app4_analysis": 7,
"app5_tactics": 7, "app5_tactics": 7,
"app6_note_analysis": 30, "app6_note": 30,
"app7_customer_analysis": 7, "app7_customer": 7,
"app8_clue_consolidated": 7, "app8_consolidation": 7,
} }
# 每 App 保留上限 # 每 App 保留上限

View File

@@ -192,6 +192,13 @@ def _text_customer_detail(
try: try:
etl_conn = get_etl_readonly_connection(site_id) etl_conn = get_etl_readonly_connection(site_id)
with etl_conn.cursor() as cur: with etl_conn.cursor() as cur:
# W1-AI-CLOSURE 复盘修正:get_etl_readonly_connection 在 SET LOCAL 后
# commit(LOCAL 失效),后续 cursor 进入新事务,RLS 视图 current_setting
# ('app.current_site_id') 拿到空串导致 bigint 转换失败。每次 cursor 必须
# 重新 SET 当前事务的 GUC(对齐 member_data.py / assistant_data.py 模式)。
cur.execute(
"SET LOCAL app.current_site_id = %s", (str(site_id),)
)
cur.execute( cur.execute(
"SET LOCAL statement_timeout = %s", "SET LOCAL statement_timeout = %s",
(f"{FDW_QUERY_TIMEOUT_SEC * 1000}",), (f"{FDW_QUERY_TIMEOUT_SEC * 1000}",),
@@ -210,21 +217,34 @@ def _text_customer_detail(
nickname = m_row[0] if m_row else f"ID:{member_id}" nickname = m_row[0] if m_row else f"ID:{member_id}"
# 最近 5 条消费 # 最近 5 条消费
# W1-AI-CLOSURE 复盘修正:列名错位 — v_dwd_settlement_head 实际列是
# pay_time / settle_name(无 settle_date / room_name);items_sum 按
# DWD-DOC 强制规则 #1 用合成表达式(consume_money 禁止直接计算)。
cur.execute( cur.execute(
""" """
SELECT settle_date, items_sum, room_name SELECT
pay_time,
(COALESCE(table_charge_money, 0)
+ COALESCE(goods_money, 0)
+ COALESCE(assistant_pd_money, 0)
+ COALESCE(assistant_cx_money, 0)
+ COALESCE(electricity_money, 0)) AS items_sum,
settle_name
FROM app.v_dwd_settlement_head FROM app.v_dwd_settlement_head
WHERE member_id = %s AND settle_type IN (1, 3) WHERE member_id = %s AND settle_type IN (1, 3)
ORDER BY settle_date DESC LIMIT 5 ORDER BY pay_time DESC LIMIT 5
""", """,
(member_id,), (member_id,),
) )
recent = cur.fetchall() recent = cur.fetchall()
# 余额 # 余额
# W1-AI-CLOSURE 复盘修正:列名 balance_amount 不存在,实际列是
# cash_card_balance / gift_card_balance / total_card_balance;
# total_card_balance 是合计储值(对齐 customer_service.balance 字段)。
cur.execute( cur.execute(
""" """
SELECT balance_amount SELECT total_card_balance
FROM app.v_dws_member_consumption_summary FROM app.v_dws_member_consumption_summary
WHERE member_id = %s LIMIT 1 WHERE member_id = %s LIMIT 1
""", """,
@@ -233,14 +253,15 @@ def _text_customer_detail(
bal_row = cur.fetchone() bal_row = cur.fetchone()
etl_conn.commit() etl_conn.commit()
# 维客线索 # 维客线索(W1-AI-CLOSURE 复盘修正:列名 created_at 不存在,实际是 recorded_at;
# 表加 schema 前缀 public 防 search_path 漂移;补 is_hidden 过滤)
biz_conn = get_connection() biz_conn = get_connection()
with biz_conn.cursor() as cur: with biz_conn.cursor() as cur:
cur.execute( cur.execute(
""" """
SELECT summary FROM member_retention_clue SELECT summary FROM public.member_retention_clue
WHERE member_id = %s AND site_id = %s WHERE member_id = %s AND site_id = %s AND is_hidden = false
ORDER BY created_at DESC LIMIT 5 ORDER BY recorded_at DESC LIMIT 5
""", """,
(member_id, site_id), (member_id, site_id),
) )
@@ -281,6 +302,11 @@ def _text_coach_detail(
try: try:
etl_conn = get_etl_readonly_connection(site_id) etl_conn = get_etl_readonly_connection(site_id)
with etl_conn.cursor() as cur: with etl_conn.cursor() as cur:
# W1-AI-CLOSURE 复盘修正:get_etl_readonly_connection 在 SET LOCAL 后
# commit(LOCAL 失效),后续 cursor 在新事务中 RLS 视图查不到 site_id。
cur.execute(
"SET LOCAL app.current_site_id = %s", (str(site_id),)
)
cur.execute( cur.execute(
"SET LOCAL statement_timeout = %s", "SET LOCAL statement_timeout = %s",
(f"{FDW_QUERY_TIMEOUT_SEC * 1000}",), (f"{FDW_QUERY_TIMEOUT_SEC * 1000}",),
@@ -348,6 +374,11 @@ def _text_board_finance(
try: try:
etl_conn = get_etl_readonly_connection(site_id) etl_conn = get_etl_readonly_connection(site_id)
with etl_conn.cursor() as cur: with etl_conn.cursor() as cur:
# W1-AI-CLOSURE 复盘修正:get_etl_readonly_connection 在 SET LOCAL 后
# commit(LOCAL 失效),后续 cursor 在新事务中 RLS 视图查不到 site_id。
cur.execute(
"SET LOCAL app.current_site_id = %s", (str(site_id),)
)
cur.execute( cur.execute(
"SET LOCAL statement_timeout = %s", "SET LOCAL statement_timeout = %s",
(f"{FDW_QUERY_TIMEOUT_SEC * 1000}",), (f"{FDW_QUERY_TIMEOUT_SEC * 1000}",),
@@ -399,6 +430,11 @@ def _text_board_customer(
try: try:
etl_conn = get_etl_readonly_connection(site_id) etl_conn = get_etl_readonly_connection(site_id)
with etl_conn.cursor() as cur: with etl_conn.cursor() as cur:
# W1-AI-CLOSURE 复盘修正:get_etl_readonly_connection 在 SET LOCAL 后
# commit(LOCAL 失效),后续 cursor 在新事务中 RLS 视图查不到 site_id。
cur.execute(
"SET LOCAL app.current_site_id = %s", (str(site_id),)
)
cur.execute( cur.execute(
"SET LOCAL statement_timeout = %s", "SET LOCAL statement_timeout = %s",
(f"{FDW_QUERY_TIMEOUT_SEC * 1000}",), (f"{FDW_QUERY_TIMEOUT_SEC * 1000}",),
@@ -456,6 +492,11 @@ def _text_board_coach(
try: try:
etl_conn = get_etl_readonly_connection(site_id) etl_conn = get_etl_readonly_connection(site_id)
with etl_conn.cursor() as cur: with etl_conn.cursor() as cur:
# W1-AI-CLOSURE 复盘修正:get_etl_readonly_connection 在 SET LOCAL 后
# commit(LOCAL 失效),后续 cursor 在新事务中 RLS 视图查不到 site_id。
cur.execute(
"SET LOCAL app.current_site_id = %s", (str(site_id),)
)
cur.execute( cur.execute(
"SET LOCAL statement_timeout = %s", "SET LOCAL statement_timeout = %s",
(f"{FDW_QUERY_TIMEOUT_SEC * 1000}",), (f"{FDW_QUERY_TIMEOUT_SEC * 1000}",),
@@ -515,6 +556,11 @@ def _text_performance(
try: try:
etl_conn = get_etl_readonly_connection(site_id) etl_conn = get_etl_readonly_connection(site_id)
with etl_conn.cursor() as cur: with etl_conn.cursor() as cur:
# W1-AI-CLOSURE 复盘修正:get_etl_readonly_connection 在 SET LOCAL 后
# commit(LOCAL 失效),后续 cursor 在新事务中 RLS 视图查不到 site_id。
cur.execute(
"SET LOCAL app.current_site_id = %s", (str(site_id),)
)
cur.execute( cur.execute(
"SET LOCAL statement_timeout = %s", "SET LOCAL statement_timeout = %s",
(f"{FDW_QUERY_TIMEOUT_SEC * 1000}",), (f"{FDW_QUERY_TIMEOUT_SEC * 1000}",),
@@ -599,6 +645,11 @@ def _text_customer_service_records(
try: try:
etl_conn = get_etl_readonly_connection(site_id) etl_conn = get_etl_readonly_connection(site_id)
with etl_conn.cursor() as cur: with etl_conn.cursor() as cur:
# W1-AI-CLOSURE 复盘修正:get_etl_readonly_connection 在 SET LOCAL 后
# commit(LOCAL 失效),后续 cursor 在新事务中 RLS 视图查不到 site_id。
cur.execute(
"SET LOCAL app.current_site_id = %s", (str(site_id),)
)
cur.execute( cur.execute(
"SET LOCAL statement_timeout = %s", "SET LOCAL statement_timeout = %s",
(f"{FDW_QUERY_TIMEOUT_SEC * 1000}",), (f"{FDW_QUERY_TIMEOUT_SEC * 1000}",),

View File

@@ -545,67 +545,86 @@ class AIDispatcher:
consolidate_result: dict, consolidate_result: dict,
source: str, source: str,
) -> None: ) -> None:
"""全量替换 member_retention_clueDELETE 同源旧记录 + INSERT 新记录事务 """全量替换 member_retention_clue:DELETE 同源旧记录 + INSERT 新记录(事务)
同一 member 同一 site 同一 source 当天只保留最新一批。 同一 member + site + source + (runtime_mode, sandbox_instance_id) 全量替换:
人工线索source='manual')不受影响 live 模式只覆盖 live 数据,sandbox 实例只覆盖该实例数据;互不污染
人工线索(source='manual')不受影响。
事务失败自动回滚。 事务失败自动回滚。
字段映射 字段映射(W1-AI-CLOSURE 组 3 修正:emoji 独立列,不再嵌 summary):
- category → category - category → category
- emoji + " " + summary → summary"📅 偏好周末下午时段消费" - summary → summary(原文,不拼 emoji 前缀)
- emoji → emoji(独立列)
- detail → detail - detail → detail
- providers → recorded_by_name - providers → recorded_by_name
- runtime_mode + sandbox_instance_id → 同列(沙箱隔离)
""" """
from app.database import get_connection from app.database import get_connection
from app.services.runtime_context import (
LIVE_INSTANCE_ID,
MODE_LIVE,
MODE_SANDBOX,
get_runtime_context,
)
clues = consolidate_result.get("clues", []) clues = consolidate_result.get("clues", [])
if not clues: if not clues:
logger.info( logger.info(
"App8 无线索数据跳过写入: member_id=%d site_id=%d", member_id, site_id, "App8 无线索数据,跳过写入: member_id=%d site_id=%d", member_id, site_id,
) )
return return
conn = get_connection() conn = get_connection()
try: try:
ctx = get_runtime_context(site_id, conn=conn)
if ctx.is_sandbox and ctx.sandbox_instance_id:
runtime_mode = MODE_SANDBOX
sandbox_instance_id = ctx.sandbox_instance_id
else:
runtime_mode = MODE_LIVE
sandbox_instance_id = LIVE_INSTANCE_ID
with conn.cursor() as cur: with conn.cursor() as cur:
cur.execute( cur.execute(
""" """
DELETE FROM member_retention_clue DELETE FROM public.member_retention_clue
WHERE member_id = %s AND site_id = %s AND source = %s WHERE member_id = %s AND site_id = %s AND source = %s
AND runtime_mode = %s AND sandbox_instance_id = %s
""", """,
(member_id, site_id, source), (member_id, site_id, source, runtime_mode, sandbox_instance_id),
) )
deleted = cur.rowcount deleted = cur.rowcount
for clue in clues: for clue in clues:
emoji = clue.get("emoji", "")
raw_summary = clue.get("summary", "")
summary = f"{emoji} {raw_summary}" if emoji else raw_summary
cur.execute( cur.execute(
""" """
INSERT INTO member_retention_clue INSERT INTO public.member_retention_clue
(member_id, category, summary, detail, site_id, (member_id, category, summary, detail, emoji, site_id,
source, recorded_by_name, recorded_by_assistant_id) source, recorded_by_name, recorded_by_assistant_id,
VALUES (%s, %s, %s, %s, %s, %s, %s, NULL) runtime_mode, sandbox_instance_id)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, NULL, %s, %s)
""", """,
( (
member_id, member_id,
clue.get("category", "客户基础"), clue.get("category", "客户基础"),
summary, clue.get("summary", ""),
clue.get("detail", ""), clue.get("detail", ""),
clue.get("emoji", ""),
site_id, site_id,
source, source,
clue.get("providers", ""), clue.get("providers", ""),
runtime_mode,
sandbox_instance_id,
), ),
) )
conn.commit() conn.commit()
logger.info( logger.info(
"维客线索全量替换完成: member_id=%d site_id=%d source=%s " "维客线索全量替换完成: member_id=%d site_id=%d source=%s "
"deleted=%d inserted=%d", "runtime=%s/%s deleted=%d inserted=%d",
member_id, site_id, source, deleted, len(clues), member_id, site_id, source,
runtime_mode, sandbox_instance_id, deleted, len(clues),
) )
except Exception: except Exception:
conn.rollback() conn.rollback()
@@ -682,7 +701,7 @@ class AIDispatcher:
# ── Step 2: App8 线索整合 ── # ── Step 2: App8 线索整合 ──
app3_clues = (app3_result or {}).get("clues", []) if isinstance(app3_result, dict) else [] app3_clues = (app3_result or {}).get("clues", []) if isinstance(app3_result, dict) else []
app6_clues, app6_generated_at = self._fetch_recent_clues( app6_clues, app6_generated_at = self._fetch_recent_clues(
CacheTypeEnum.APP6_NOTE_ANALYSIS.value, site_id, member_id, CacheTypeEnum.APP6_NOTE.value, site_id, member_id,
) )
try: try:
@@ -701,11 +720,11 @@ class AIDispatcher:
app8_result = None app8_result = None
if app8_prompt: if app8_prompt:
app8_result = await self._run_step( app8_result = await self._run_step(
"app8_consolidate", self.config.app_id_8_consolidate, "app8_consolidation", self.config.app_id_8_consolidate,
app8_prompt, context, app8_prompt, context,
) )
self._write_cache( self._write_cache(
CacheTypeEnum.APP8_CLUE_CONSOLIDATED.value, site_id, str(member_id), CacheTypeEnum.APP8_CONSOLIDATION.value, site_id, str(member_id),
app8_result, "consumption", app8_result, "consumption",
) )
if app8_result is not None: if app8_result is not None:
@@ -738,7 +757,7 @@ class AIDispatcher:
app7_prompt, context, app7_prompt, context,
) )
self._write_cache( self._write_cache(
CacheTypeEnum.APP7_CUSTOMER_ANALYSIS.value, site_id, str(member_id), CacheTypeEnum.APP7_CUSTOMER.value, site_id, str(member_id),
app7_result, "consumption", app7_result, "consumption",
) )
@@ -781,7 +800,7 @@ class AIDispatcher:
) )
score = (app6_result or {}).get("score") if isinstance(app6_result, dict) else None score = (app6_result or {}).get("score") if isinstance(app6_result, dict) else None
self._write_cache( self._write_cache(
CacheTypeEnum.APP6_NOTE_ANALYSIS.value, site_id, str(member_id), CacheTypeEnum.APP6_NOTE.value, site_id, str(member_id),
app6_result, "note_created", score=score, app6_result, "note_created", score=score,
) )
@@ -805,11 +824,11 @@ class AIDispatcher:
return return
app8_result = await self._run_step( app8_result = await self._run_step(
"app8_consolidate", self.config.app_id_8_consolidate, "app8_consolidation", self.config.app_id_8_consolidate,
app8_prompt, context, app8_prompt, context,
) )
self._write_cache( self._write_cache(
CacheTypeEnum.APP8_CLUE_CONSOLIDATED.value, site_id, str(member_id), CacheTypeEnum.APP8_CONSOLIDATION.value, site_id, str(member_id),
app8_result, "note_created", app8_result, "note_created",
) )
if app8_result is not None: if app8_result is not None:
@@ -1070,7 +1089,7 @@ class AIDispatcher:
raise ValueError("app6_note 需要 member_id") raise ValueError("app6_note 需要 member_id")
prompt = await build_app6_prompt(context, self.cache_svc) prompt = await build_app6_prompt(context, self.cache_svc)
app_id = self.config.app_id_6_note app_id = self.config.app_id_6_note
cache_type = CacheTypeEnum.APP6_NOTE_ANALYSIS.value cache_type = CacheTypeEnum.APP6_NOTE.value
target_id = str(context["member_id"]) target_id = str(context["member_id"])
elif app_type == "app7_customer": elif app_type == "app7_customer":
@@ -1078,7 +1097,7 @@ class AIDispatcher:
raise ValueError("app7_customer 需要 member_id") raise ValueError("app7_customer 需要 member_id")
prompt = await build_app7_prompt(context, self.cache_svc) prompt = await build_app7_prompt(context, self.cache_svc)
app_id = self.config.app_id_7_customer app_id = self.config.app_id_7_customer
cache_type = CacheTypeEnum.APP7_CUSTOMER_ANALYSIS.value cache_type = CacheTypeEnum.APP7_CUSTOMER.value
target_id = str(context["member_id"]) target_id = str(context["member_id"])
elif app_type == "app8_consolidation": elif app_type == "app8_consolidation":
@@ -1090,7 +1109,7 @@ class AIDispatcher:
CacheTypeEnum.APP3_CLUE.value, site_id, member_id, CacheTypeEnum.APP3_CLUE.value, site_id, member_id,
) )
app6_clues, app6_at = self._fetch_recent_clues( app6_clues, app6_at = self._fetch_recent_clues(
CacheTypeEnum.APP6_NOTE_ANALYSIS.value, site_id, member_id, CacheTypeEnum.APP6_NOTE.value, site_id, member_id,
) )
prompt = await build_app8_prompt({ prompt = await build_app8_prompt({
"site_id": site_id, "site_id": site_id,
@@ -1101,7 +1120,7 @@ class AIDispatcher:
"app6_generated_at": app6_at, "app6_generated_at": app6_at,
}) })
app_id = self.config.app_id_8_consolidate app_id = self.config.app_id_8_consolidate
cache_type = CacheTypeEnum.APP8_CLUE_CONSOLIDATED.value cache_type = CacheTypeEnum.APP8_CONSOLIDATION.value
target_id = str(member_id) target_id = str(member_id)
else: else:
raise ValueError(f"不支持的 app_type: {app_type}") raise ValueError(f"不支持的 app_type: {app_type}")

View File

@@ -108,7 +108,7 @@ def _build_reference(
target_id = str(member_id) target_id = str(member_id)
app6_latest = cache_svc.get_latest( app6_latest = cache_svc.get_latest(
CacheTypeEnum.APP6_NOTE_ANALYSIS.value, site_id, target_id, CacheTypeEnum.APP6_NOTE.value, site_id, target_id,
) )
if app6_latest: if app6_latest:
ref["app6_note_clues"] = { ref["app6_note_clues"] = {
@@ -117,7 +117,7 @@ def _build_reference(
} }
app8_history = cache_svc.get_history( app8_history = cache_svc.get_history(
CacheTypeEnum.APP8_CLUE_CONSOLIDATED.value, site_id, target_id, limit=2, CacheTypeEnum.APP8_CONSOLIDATION.value, site_id, target_id, limit=2,
) )
if app8_history: if app8_history:
ref["app8_history"] = [ ref["app8_history"] = [

View File

@@ -131,7 +131,7 @@ def _build_reference(
target_id = str(member_id) target_id = str(member_id)
latest = cache_svc.get_latest( latest = cache_svc.get_latest(
CacheTypeEnum.APP8_CLUE_CONSOLIDATED.value, site_id, target_id, CacheTypeEnum.APP8_CONSOLIDATION.value, site_id, target_id,
) )
if latest: if latest:
ref["app8_latest"] = { ref["app8_latest"] = {
@@ -140,7 +140,7 @@ def _build_reference(
} }
history = cache_svc.get_history( history = cache_svc.get_history(
CacheTypeEnum.APP8_CLUE_CONSOLIDATED.value, site_id, target_id, limit=2, CacheTypeEnum.APP8_CONSOLIDATION.value, site_id, target_id, limit=2,
) )
if history: if history:
ref["app8_history"] = [ ref["app8_history"] = [

View File

@@ -130,7 +130,7 @@ def _build_reference(
ref: dict = {} ref: dict = {}
history = cache_svc.get_history( history = cache_svc.get_history(
CacheTypeEnum.APP8_CLUE_CONSOLIDATED.value, CacheTypeEnum.APP8_CONSOLIDATION.value,
site_id, site_id,
str(member_id), str(member_id),
limit=2, limit=2,

View File

@@ -128,7 +128,7 @@ def _build_reference(
} }
app8_history = cache_svc.get_history( app8_history = cache_svc.get_history(
CacheTypeEnum.APP8_CLUE_CONSOLIDATED.value, site_id, target_id, limit=2, CacheTypeEnum.APP8_CONSOLIDATION.value, site_id, target_id, limit=2,
) )
if app8_history: if app8_history:
ref["app8_history"] = [ ref["app8_history"] = [

View File

@@ -125,7 +125,7 @@ def _build_reference(
target_id = str(member_id) target_id = str(member_id)
latest = cache_svc.get_latest( latest = cache_svc.get_latest(
CacheTypeEnum.APP8_CLUE_CONSOLIDATED.value, site_id, target_id, CacheTypeEnum.APP8_CONSOLIDATION.value, site_id, target_id,
) )
if latest: if latest:
ref["app8_latest"] = { ref["app8_latest"] = {
@@ -134,7 +134,7 @@ def _build_reference(
} }
history = cache_svc.get_history( history = cache_svc.get_history(
CacheTypeEnum.APP8_CLUE_CONSOLIDATED.value, site_id, target_id, limit=2, CacheTypeEnum.APP8_CONSOLIDATION.value, site_id, target_id, limit=2,
) )
if history: if history:
ref["app8_history"] = [ ref["app8_history"] = [

View File

@@ -36,14 +36,21 @@ class SSEEvent(BaseModel):
class CacheTypeEnum(str, enum.Enum): class CacheTypeEnum(str, enum.Enum):
"""ai_cache.cache_type 允许的取值(8 类,与 prompt 文件名 + 数据库 chk_ai_cache_type
约束完全对齐;app1_chat 走 ai_messages 不进缓存)。
W1-AI-CLOSURE 组 1 命名统一:旧名字 app6_note_analysis / app7_customer_analysis /
app8_clue_consolidated / app8_consolidate 已在数据库迁移中清理,代码不再使用。
"""
APP2_FINANCE = "app2_finance" APP2_FINANCE = "app2_finance"
APP2A_FINANCE_AREA = "app2a_finance_area" # 2026-04-23 新增区域财务洞察64 组合) APP2A_FINANCE_AREA = "app2a_finance_area"
APP3_CLUE = "app3_clue" APP3_CLUE = "app3_clue"
APP4_ANALYSIS = "app4_analysis" APP4_ANALYSIS = "app4_analysis"
APP5_TACTICS = "app5_tactics" APP5_TACTICS = "app5_tactics"
APP6_NOTE_ANALYSIS = "app6_note_analysis" APP6_NOTE = "app6_note"
APP7_CUSTOMER_ANALYSIS = "app7_customer_analysis" APP7_CUSTOMER = "app7_customer"
APP8_CLUE_CONSOLIDATED = "app8_clue_consolidated" APP8_CONSOLIDATION = "app8_consolidation"
# ── 线索相关 ── # ── 线索相关 ──

View File

@@ -11,6 +11,47 @@ from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
from starlette.exceptions import HTTPException as StarletteHTTPException from starlette.exceptions import HTTPException as StarletteHTTPException
# ── 日志配置(W1-AI-CLOSURE 复盘加固):文件输出 + 过滤 /health 访问日志 ──
# 1. 所有 INFO+ 日志同时写到仓库根 logs/backend.log(滚动 5 个,每个 20MB 上限)
# 2. uvicorn.access 中含 "/health" 的访问日志被过滤(健康检查 noise 抑制)
def _configure_logging() -> None:
import logging
from logging.handlers import RotatingFileHandler
from pathlib import Path
log_dir = Path(__file__).resolve().parents[3] / "logs"
log_dir.mkdir(exist_ok=True)
log_file = log_dir / "backend.log"
file_handler = RotatingFileHandler(
log_file, maxBytes=20 * 1024 * 1024, backupCount=5, encoding="utf-8"
)
file_handler.setFormatter(
logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s")
)
root = logging.getLogger()
# 防止重复挂载(uvicorn --reload 可能重入)
if not any(
isinstance(h, RotatingFileHandler) and getattr(h, "baseFilename", None) == str(log_file)
for h in root.handlers
):
root.addHandler(file_handler)
if root.level > logging.INFO or root.level == logging.NOTSET:
root.setLevel(logging.INFO)
class _SuppressHealthAccess(logging.Filter):
def filter(self, record: logging.LogRecord) -> bool:
return "/health" not in record.getMessage()
access_logger = logging.getLogger("uvicorn.access")
if not any(isinstance(f, _SuppressHealthAccess) for f in access_logger.filters):
access_logger.addFilter(_SuppressHealthAccess())
_configure_logging()
from app.middleware.response_wrapper import ( from app.middleware.response_wrapper import (
ResponseWrapperMiddleware, ResponseWrapperMiddleware,
http_exception_handler, http_exception_handler,

View File

@@ -76,7 +76,9 @@ def verify_internal_token(authorization: str = Header(...)) -> str:
detail="AI 配置异常", detail="AI 配置异常",
) )
if token != config.internal_api_token: # P1-7 修正:用 hmac.compare_digest 防时序攻击,而不是 Python `==` 字符串比较
import hmac
if not hmac.compare_digest(token, config.internal_api_token or ""):
raise HTTPException( raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token 不匹配", detail="Token 不匹配",

View File

@@ -218,9 +218,10 @@ async def chat_stream(
try: try:
from app.ai.data_fetchers import build_page_text from app.ai.data_fetchers import build_page_text
filters = {} # W1-AI-CLOSURE 复盘修正:必须 dict() 浅拷贝,否则 filters.pop("contextId")
if body.page_context: # 会破坏 body.page_context(同引用),导致后续 reference_card 块
filters = body.page_context # 拿不到 contextId(返回 None,跳过 KPI 富卡构建)。
filters = dict(body.page_context) if body.page_context else {}
context_id = filters.pop("contextId", None) context_id = filters.pop("contextId", None)
page_text = await build_page_text( page_text = await build_page_text(
source_page=body.source_page, source_page=body.source_page,
@@ -266,13 +267,33 @@ async def chat_stream(
full_reply = "".join(full_reply_parts) full_reply = "".join(full_reply_parts)
estimated_tokens = len(full_reply) estimated_tokens = len(full_reply)
# Phase 1.3assistant 消息挂 reference_card(若用户从特定详情页入口发起对话) # Phase 1.3 + W1-AI-CLOSURE 组 4(P0-15):assistant 消息挂 reference_card
# customer-detail / customer-service-records 入口走 KPI 富卡(余额/30 天消费/到店),
# 其他入口走简单跳转链接卡(保持现状)。
try: try:
from app.ai.references import build_app1_reference_card from app.ai.references import build_app1_reference_card
_ref_card = None _ref_card = None
_pc = body.page_context or {} _pc = body.page_context or {}
_ctx_id = _pc.get("contextId") or _pc.get("taskId") or _pc.get("customerId") or _pc.get("coachId") _ctx_id = (
_pc.get("contextId")
or _pc.get("taskId")
or _pc.get("customerId")
or _pc.get("coachId")
)
if body.source_page and _ctx_id: if body.source_page and _ctx_id:
if body.source_page in ("customer-detail", "customer-service-records"):
try:
_customer_id = int(_ctx_id)
_ref_card = svc.build_reference_card(_customer_id, user.site_id)
if _ref_card:
_ref_card.setdefault(
"link",
f"/pages/customer-detail/customer-detail?customerId={_ctx_id}",
)
_ref_card.setdefault("source_page", body.source_page)
except (ValueError, TypeError):
_ref_card = None
if _ref_card is None:
_ref_card = build_app1_reference_card(body.source_page, _ctx_id) _ref_card = build_app1_reference_card(body.source_page, _ctx_id)
except Exception: except Exception:
logger.warning("构建 reference_card 失败", exc_info=True) logger.warning("构建 reference_card 失败", exc_info=True)

View File

@@ -1,7 +1,9 @@
""" """
维客线索相关 Pydantic 模型。 维客线索相关 Pydantic 模型。
大类枚举:客户基础信息、消费习惯、玩法偏好、促销偏好、社交关系、重要反馈 大类枚举(6 类,与数据库 chk_retention_clue_category 约束 + ai/schemas
App3CategoryEnum / App6CategoryEnum 完全对齐):
客户基础、消费习惯、玩法偏好、促销偏好、社交关系、重要反馈
""" """
from datetime import datetime from datetime import datetime
@@ -12,8 +14,10 @@ from pydantic import BaseModel, Field
class ClueCategory(str, Enum): class ClueCategory(str, Enum):
"""维客线索大类枚举""" """维客线索大类枚举(W1-AI-CLOSURE 组 5:'客户基础信息' 字面量纠正为 '客户基础',
BASIC_INFO = "客户基础信息" 旧值与数据库 CHECK 约束不一致,POST /api/retention-clue 写库会失败)。"""
BASIC_INFO = "客户基础"
CONSUMPTION = "消费习惯" CONSUMPTION = "消费习惯"
PLAY_PREF = "玩法偏好" PLAY_PREF = "玩法偏好"
PROMO_PREF = "促销偏好" PROMO_PREF = "促销偏好"

View File

@@ -40,12 +40,19 @@ class ChatHistoryResponse(CamelModel):
class ReferenceCard(CamelModel): class ReferenceCard(CamelModel):
"""引用卡片附加在 AI 回复消息中的结构化上下文数据。""" """引用卡片,附加在消息中的结构化上下文数据。
type: str # 'customer' | 'record' W1-AI-CLOSURE 组 4 修正(P0-13):补全 link / source_page 字段,与
references.py:91 build_app1_reference_card 的实际输出对齐。之前 schema
缺这两字段导致 Pydantic 序列化时丢失,前端 wxml 的 link 跳转按钮永远拿不到 link。
"""
type: str # 'customer' | 'record' | 'member' | 'task' 等
title: str title: str
summary: str summary: str = ""
data: dict[str, str] # 键值对详情 data: dict[str, str] | None = None
link: str | None = None # 跳转链接(如 /pages/customer-detail/...)
source_page: str | None = None # 起源页面(用于回链定位)
class ChatMessageItem(CamelModel): class ChatMessageItem(CamelModel):

View File

@@ -8,7 +8,12 @@ from app.schemas.base import CamelModel
class AiStrategy(CamelModel): class AiStrategy(CamelModel):
color: str """App7 客户分析策略单条(对齐 demo 标杆 wxml `{{item.text}}` 单字段)。
W1-AI-CLOSURE 组 3 + 复盘修正:服务层把 prompt schema 的 {title, content}
拼接成 demo 标杆的 text 单字段;color 由前端按 index 轮换 6 色。
"""
text: str text: str
class AiInsight(CamelModel): class AiInsight(CamelModel):
@@ -71,8 +76,23 @@ class ConsumptionRecord(CamelModel):
recharge_amount: float | None = None recharge_amount: float | None = None
class RetentionClue(CamelModel): class RetentionClue(CamelModel):
type: str """维客线索单条(对齐 clue-card 组件契约 + task-detail.ts 字段命名)。
W1-AI-CLOSURE 组 3 修正:从 {type, text} 2 字段扩展为 6 字段。
- tag: 中文分类(如 "客户基础"),前端 wxml 显示用,可由 css 强制两行
- tag_color: 6 类配色 alias(VI-DESIGN-SYSTEM §2.1:primary/success/orange/gold/purple/error)
- emoji: 独立 emoji 字符,App8 prompt 输出独立字段(W1-AI-CLOSURE 组 1 加列)
- text: summary 主文案(20 字内)
- source: 显示用来源("AI" / "系统" / 录入人姓名),前端拼 "By:" 前缀
- desc: detail 详情(120 字内,可空,前端可折叠展示)
"""
tag: str
tag_color: str
emoji: str = ""
text: str text: str
source: str = ""
desc: str = ""
class CustomerNote(CamelModel): class CustomerNote(CamelModel):
id: int id: int

View File

@@ -123,8 +123,20 @@ class ServiceRecord(CamelModel):
date: str date: str
class TacticItem(CamelModel):
"""App5 话术单条(场景 + 话术)。
W1-AI-CLOSURE 组 3 修正:talking_points 从 list[str] 改为 list[TacticItem],
对齐 App5Result.tactics(prompt schema 权威 — 之前查的 cache_type
'app5_talking_points' 与字段 'talking_points' 全是不存在的幽灵命名,P0-6)。
"""
scenario: str
script: str
class AiAnalysis(CamelModel): class AiAnalysis(CamelModel):
"""AI 分析结果。""" """AI 分析结果(对齐 App4Result one_line_summary + action_suggestions)"""
summary: str summary: str
suggestions: list[str] suggestions: list[str]
@@ -169,7 +181,7 @@ class TaskDetailResponse(CamelModel):
balance: float | None = None balance: float | None = None
# 扩展模块 # 扩展模块
retention_clues: list[RetentionClue] retention_clues: list[RetentionClue]
talking_points: list[str] talking_points: list[TacticItem]
service_summary: ServiceSummary service_summary: ServiceSummary
service_records: list[ServiceRecord] service_records: list[ServiceRecord]
ai_analysis: AiAnalysis ai_analysis: AiAnalysis

View File

@@ -26,15 +26,18 @@ class AICleanupService:
RETENTION_DAYS = 90 RETENTION_DAYS = 90
CACHE_LIMIT_PER_APP = 20_000 CACHE_LIMIT_PER_APP = 20_000
CACHE_APP_TYPES = [ # 8 类需要走 ai_cache 的应用(app1_chat 走 ai_messages,不进 ai_cache)
# 命名与 prompt 文件名一致(W1-AI-CLOSURE 组 1 数据库迁移已统一)。
CACHE_TYPES: tuple[str, ...] = (
"app2_finance", "app2_finance",
"app2a_finance_area", # P0-11 修正:之前漏掉,导致 64 区域组合永不清理
"app3_clue", "app3_clue",
"app4_analysis", "app4_analysis",
"app5_tactics", "app5_tactics",
"app6_note_analysis", "app6_note",
"app7_customer_analysis", "app7_customer",
"app8_clue_consolidated", "app8_consolidation",
] )
async def run_cleanup(self) -> dict: async def run_cleanup(self) -> dict:
"""执行全部清理,返回各步骤删除记录数。 """执行全部清理,返回各步骤删除记录数。
@@ -119,7 +122,12 @@ class AICleanupService:
conn.close() conn.close()
async def _cleanup_cache(self) -> dict[str, int]: async def _cleanup_cache(self) -> dict[str, int]:
"""每个 App 类型保留最新 20,000 条,删除超出部分。""" """每个 cache_type 保留最新 20,000 条,删除超出部分。
P0-8 修正:ai_cache 表列名是 cache_type 不是 app_type;之前 SQL `WHERE
app_type=%s` 一直抛 UndefinedColumn 错误被 except 静默吞,导致 90 天清理
与 20K 上限完全失效,生产 ai_cache 表无限膨胀。
"""
from app.database import get_connection from app.database import get_connection
result: dict[str, int] = {} result: dict[str, int] = {}
@@ -127,35 +135,35 @@ class AICleanupService:
try: try:
with conn.cursor() as cur: with conn.cursor() as cur:
cur.execute("SET statement_timeout = 300000") cur.execute("SET statement_timeout = 300000")
for app_type in self.CACHE_APP_TYPES: for cache_type in self.CACHE_TYPES:
try: try:
# 子查询找到该 app_type 第 20001 条的 created_at 作为截断点 # 子查询:找到该 cache_type 第 20001 条的 created_at 作为截断点
cur.execute( cur.execute(
""" """
DELETE FROM biz.ai_cache DELETE FROM biz.ai_cache
WHERE app_type = %s WHERE cache_type = %s
AND id NOT IN ( AND id NOT IN (
SELECT id FROM biz.ai_cache SELECT id FROM biz.ai_cache
WHERE app_type = %s WHERE cache_type = %s
ORDER BY created_at DESC ORDER BY created_at DESC
LIMIT %s LIMIT %s
) )
""", """,
(app_type, app_type, self.CACHE_LIMIT_PER_APP), (cache_type, cache_type, self.CACHE_LIMIT_PER_APP),
) )
deleted = cur.rowcount deleted = cur.rowcount
result[app_type] = deleted result[cache_type] = deleted
if deleted > 0: if deleted > 0:
logger.info( logger.info(
"清理 ai_cache [%s]: 删除 %d", "清理 ai_cache [%s]: 删除 %d",
app_type, cache_type,
deleted, deleted,
) )
except Exception: except Exception:
logger.exception("清理 ai_cache [%s] 失败", app_type) logger.exception("清理 ai_cache [%s] 失败", cache_type)
result[app_type] = -1 result[cache_type] = -1
conn.rollback() conn.rollback()
# 重新开始事务以继续后续 app_type # 重新开始事务以继续后续 cache_type
continue continue
conn.commit() conn.commit()
return result return result

View File

@@ -316,8 +316,13 @@ class ChatService:
conn = get_connection() conn = get_connection()
try: try:
with conn.cursor() as cur: with conn.cursor() as cur:
# W1-AI-CLOSURE 组 4 修正(P0-12):排除 role='system' 消息;
# 历史 35 条 system 行被前端误渲染成内容暴露 prompt 拼装细节。
cur.execute( cur.execute(
"SELECT COUNT(*) FROM biz.ai_messages WHERE conversation_id = %s", """
SELECT COUNT(*) FROM biz.ai_messages
WHERE conversation_id = %s AND role IN ('user', 'assistant')
""",
(chat_id,), (chat_id,),
) )
total = cur.fetchone()[0] total = cur.fetchone()[0]
@@ -326,7 +331,7 @@ class ChatService:
""" """
SELECT id, role, content, created_at, reference_card SELECT id, role, content, created_at, reference_card
FROM biz.ai_messages FROM biz.ai_messages
WHERE conversation_id = %s WHERE conversation_id = %s AND role IN ('user', 'assistant')
ORDER BY created_at ASC ORDER BY created_at ASC
LIMIT %s OFFSET %s LIMIT %s OFFSET %s
""", """,

View File

@@ -143,13 +143,13 @@ async def get_customer_detail(customer_id: int, site_id: int) -> dict:
# ── 扩展模块(独立 try/except 优雅降级)── # ── 扩展模块(独立 try/except 优雅降级)──
try: try:
ai_insight = _build_ai_insight(customer_id, conn) ai_insight = _build_ai_insight(customer_id, site_id, conn)
except Exception: except Exception:
logger.warning("构建 aiInsight 失败,降级为空", exc_info=True) logger.warning("构建 aiInsight 失败,降级为空", exc_info=True)
ai_insight = {"summary": "", "strategies": []} ai_insight = {"summary": "", "strategies": []}
try: try:
retention_clues = _build_retention_clues(customer_id, conn) retention_clues = _build_retention_clues(customer_id, site_id, conn)
except Exception: except Exception:
logger.warning("构建 retentionClues 失败,降级为空列表", exc_info=True) logger.warning("构建 retentionClues 失败,降级为空列表", exc_info=True)
retention_clues = [] retention_clues = []
@@ -223,24 +223,29 @@ async def get_customer_detail(customer_id: int, site_id: int) -> dict:
# ── 3.2 AI 洞察 / 维客线索 / 备注 ────────────────────────── # ── 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 查询 biz.ai_cache WHERE cache_type='app7_customer' AND target_id=customerId
解析 result_json JSON。无缓存时返回空默认值。 AND site_id=site_id。无缓存时返回空默认值。
App7Result schema: {strategies: [{title, content}], summary: str}
""" """
with conn.cursor() as cur: with conn.cursor() as cur:
cur.execute( cur.execute(
""" """
SELECT result_json SELECT result_json
FROM biz.ai_cache FROM biz.ai_cache
WHERE cache_type = 'app4_analysis' WHERE cache_type = 'app7_customer'
AND site_id = %s
AND target_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 ORDER BY created_at DESC
LIMIT 1 LIMIT 1
""", """,
(str(customer_id),), (site_id, str(customer_id)),
) )
row = cur.fetchone() row = cur.fetchone()
@@ -255,37 +260,69 @@ def _build_ai_insight(customer_id: int, conn) -> dict:
summary = data.get("summary", "") summary = data.get("summary", "")
strategies_raw = data.get("strategies", []) strategies_raw = data.get("strategies", [])
strategies = [] strategies = []
# App7Result schema: strategies = [{title, content}],但前端 demo 标杆 wxml 用单
# 字段 text(`{{item.text}}`)。在 service 层拼接成 demo 形态,前端保持 demo 一致。
for s in strategies_raw: for s in strategies_raw:
if isinstance(s, dict): if isinstance(s, dict):
strategies.append({ t = (s.get("title") or "").strip()
"color": s.get("color", ""), c = (s.get("content") or "").strip()
"text": s.get("text", ""), text = f"{t}{c}" if t and c else (c or t)
}) strategies.append({"text": text})
return {"summary": summary, "strategies": strategies} 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 模块。 构建 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: with conn.cursor() as cur:
cur.execute( cur.execute(
""" """
SELECT category, summary SELECT category, summary, detail, emoji, source, recorded_by_name
FROM public.member_retention_clue FROM public.member_retention_clue
WHERE member_id = %s WHERE member_id = %s
AND site_id = %s
AND is_hidden = false AND is_hidden = false
ORDER BY recorded_at DESC ORDER BY recorded_at DESC
""", """,
(customer_id,), (customer_id, site_id),
) )
rows = cur.fetchall() 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"} NOTE_TYPE_LABELS = {"normal": "备注", "follow_up": "回访", "system": "系统", "ai": "AI"}

View File

@@ -468,19 +468,10 @@ _COURSE_TYPE_CLASS_MAP: dict[str, str] = {
"激励": "incentive", "激励": "incentive",
} }
# 维客线索 category → tag_color 映射 # W1-AI-CLOSURE 组 5:维客线索 category → tag_color 映射已迁移至
# CHANGE 2026-03-24 | 值改为前端 clue-card 组件 CSS 类名后缀primary/success/... # app.utils.clue_category.CATEGORY_TAG_COLOR(VI-DESIGN-SYSTEM v1.1 权威映射,
# 不再用十六进制颜色——WXSS 类名 `clue-tag-#0052d9` 无效。 # 与 customer_service 共享)。原本地 _CATEGORY_COLOR_MAP 与 VI 规范不一致
_CATEGORY_COLOR_MAP: dict[str, str] = { # (消费习惯=error 应是 success;玩法偏好=success 应是 orange),已删除。
"客户基础": "primary",
"客户基础信息": "primary",
"消费习惯": "error",
"玩法偏好": "success",
"促销偏好": "orange",
"促销接受": "orange",
"社交关系": "purple",
"重要反馈": "error",
}
@trace_service(description_zh="map_course_type_class", description_en="Map Course Type Class") @trace_service(description_zh="map_course_type_class", description_en="Map Course Type Class")
@@ -514,20 +505,10 @@ def sanitize_tag(raw_tag: str | None) -> str:
return raw_tag.replace("\n", " ").strip() return raw_tag.replace("\n", " ").strip()
def _extract_emoji_and_text(summary: str | None) -> tuple[str, str]: # W1-AI-CLOSURE 组 5:_extract_emoji_and_text 已删除。
""" # 维客线索 emoji 在数据库已独立列(public.member_retention_clue.emoji),
从 summary 中提取 emoji 前缀和正文。 # 不再需要从 summary 字符串解析。dispatcher._write_retention_clue 直接写
# emoji 列,task_manager / customer_service 直接读 emoji 列。
AI 写入格式: "📅 偏好周末下午时段消费" → ("📅", "偏好周末下午时段消费")
手动写入无 emoji: "喜欢打中式" → ("", "喜欢打中式")
"""
if not summary:
return "", ""
# 检查第一个字符是否为 emoji非 ASCII 且非中文常用范围)
first_char = summary[0]
if ord(first_char) > 0x2600 and summary[1:2] == " ":
return first_char, summary[2:].strip()
return "", summary.strip()
def _format_time(dt: datetime | None) -> str | None: def _format_time(dt: datetime | None) -> str | None:
@@ -693,6 +674,8 @@ async def get_task_list_v2(
logger.warning("ETL 批量查询失败,降级为空数据", exc_info=True) logger.warning("ETL 批量查询失败,降级为空数据", exc_info=True)
# ── 6. 查询 ai_cache 获取 aiSuggestion优雅降级 ── # ── 6. 查询 ai_cache 获取 aiSuggestion优雅降级 ──
# App4Result schema: {task_description, action_suggestions[], one_line_summary}
# aiSuggestion 用于任务列表一行简短提示,取 one_line_summary 最贴合。
ai_suggestion_map: dict[int, str] = {} ai_suggestion_map: dict[int, str] = {}
try: try:
runtime_ctx = get_runtime_context(site_id, conn=conn) runtime_ctx = get_runtime_context(site_id, conn=conn)
@@ -708,6 +691,8 @@ async def get_task_list_v2(
WHERE site_id = %s WHERE site_id = %s
AND target_id = ANY(%s) AND target_id = ANY(%s)
AND cache_type = 'app4_analysis' AND cache_type = 'app4_analysis'
AND COALESCE(status, 'valid') = 'valid'
AND (expires_at IS NULL OR expires_at > now())
ORDER BY created_at DESC ORDER BY created_at DESC
""", """,
(site_id, member_id_strs), (site_id, member_id_strs),
@@ -718,10 +703,11 @@ async def get_task_list_v2(
if target_id_str not in seen: if target_id_str not in seen:
seen.add(target_id_str) seen.add(target_id_str)
result = row[1] if isinstance(row[1], dict) else {} result = row[1] if isinstance(row[1], dict) else {}
summary = result.get("summary", "") # P0-7: App4 schema 是 one_line_summary,不是 summary
if summary: suggestion = result.get("one_line_summary", "")
if suggestion:
raw_target = target_id_str.split(":", 1)[-1] raw_target = target_id_str.split(":", 1)[-1]
ai_suggestion_map[int(raw_target)] = summary ai_suggestion_map[int(raw_target)] = suggestion
conn.commit() conn.commit()
except Exception: except Exception:
logger.warning("查询 ai_cache aiSuggestion 失败", exc_info=True) logger.warning("查询 ai_cache aiSuggestion 失败", exc_info=True)
@@ -1110,6 +1096,13 @@ async def get_task_detail(
logger.warning("ETL 查询 RS 指数失败", exc_info=True) logger.warning("ETL 查询 RS 指数失败", exc_info=True)
# ── 3. 查询维客线索 ── # ── 3. 查询维客线索 ──
# 字段对齐 xcx_customers.RetentionClue schema(W1-AI-CLOSURE 组 3):
# 直接读 emoji 独立列(不再从 summary 字符串抽取),tag_color 走 utils 共用映射。
from app.utils.clue_category import (
CATEGORY_TAG_COLOR,
SOURCE_DISPLAY_NAME,
format_category_tag,
)
retention_clues = [] retention_clues = []
try: try:
runtime_ctx = get_runtime_context(site_id, conn=conn) runtime_ctx = get_runtime_context(site_id, conn=conn)
@@ -1121,7 +1114,7 @@ async def get_task_detail(
with conn.cursor() as cur: with conn.cursor() as cur:
cur.execute( cur.execute(
""" """
SELECT id, category, summary, detail, source SELECT category, summary, detail, source, emoji, recorded_by_name
FROM public.member_retention_clue FROM public.member_retention_clue
WHERE member_id = %s AND site_id = %s WHERE member_id = %s AND site_id = %s
AND is_hidden = false AND is_hidden = false
@@ -1130,29 +1123,38 @@ async def get_task_detail(
(member_id, site_id), (member_id, site_id),
) )
for clue_row in cur.fetchall(): for clue_row in cur.fetchall():
category = clue_row[1] or "" category = clue_row[0] or ""
summary_raw = clue_row[2] or "" summary = clue_row[1] or ""
detail = clue_row[3] detail = clue_row[2]
source = clue_row[4] or "manual" source = clue_row[3] or "manual"
emoji = clue_row[4] or ""
recorded_by_name = clue_row[5] or ""
emoji, text = _extract_emoji_and_text(summary_raw)
tag = sanitize_tag(category) tag = sanitize_tag(category)
tag_color = _CATEGORY_COLOR_MAP.get(tag, "primary") # source 显示规则(用户拍板):AI 类用 "AI" 短标识(前端渲染 icon)
if source in ("ai_consumption", "ai_note"):
display_src = "AI"
else:
display_src = recorded_by_name or SOURCE_DISPLAY_NAME.get(source, "系统")
retention_clues.append({ retention_clues.append({
"tag": tag, "tag": format_category_tag(tag),
"tag_color": tag_color, "tag_color": CATEGORY_TAG_COLOR.get(tag, "primary"),
"emoji": emoji, "emoji": emoji,
"text": text, "text": summary,
"source": source, "source": display_src,
"desc": detail, "desc": detail or "",
}) })
conn.commit() conn.commit()
except Exception: except Exception:
logger.warning("查询维客线索失败", exc_info=True) logger.warning("查询维客线索失败", exc_info=True)
# ── 4. 查询 AI 缓存talkingPoints + aiAnalysis ── # ── 4. 查询 AI 缓存(talkingPoints + aiAnalysis) ──
talking_points: list[str] = [] # P0-6 修正:cache_type 从不存在的 'app5_talking_points' 改为正确的 'app5_tactics';
# 字段从不存在的 'talking_points' 改为正确的 tactics[{scenario, script}]。
# P0-7 修正:App4 schema 字段不存在 summary/suggestions,实际为
# one_line_summary / action_suggestions / task_description。
# tactics 直接以对象列表透出,前端 task-detail 渲染 scenario 与 script 两栏。
talking_points: list[dict] = []
ai_analysis = {"summary": "", "suggestions": []} ai_analysis = {"summary": "", "suggestions": []}
try: try:
with conn.cursor() as cur: with conn.cursor() as cur:
@@ -1161,7 +1163,9 @@ async def get_task_detail(
SELECT cache_type, result_json SELECT cache_type, result_json
FROM biz.ai_cache FROM biz.ai_cache
WHERE target_id = %s AND site_id = %s WHERE target_id = %s AND site_id = %s
AND cache_type IN ('app4_analysis', 'app5_talking_points') AND cache_type IN ('app4_analysis', 'app5_tactics')
AND COALESCE(status, 'valid') = 'valid'
AND (expires_at IS NULL OR expires_at > now())
ORDER BY created_at DESC ORDER BY created_at DESC
""", """,
(member_target_id, site_id), (member_target_id, site_id),
@@ -1175,16 +1179,21 @@ async def get_task_detail(
result = cache_row[1] if isinstance(cache_row[1], dict) else {} result = cache_row[1] if isinstance(cache_row[1], dict) else {}
if cache_type == "app5_talking_points": if cache_type == "app5_tactics":
# talkingPoints: 话术列表 tactics = result.get("tactics", [])
points = result.get("talking_points", []) if isinstance(tactics, list):
if isinstance(points, list): talking_points = [
talking_points = [str(p) for p in points] {
"scenario": t.get("scenario", ""),
"script": t.get("script", ""),
}
for t in tactics
if isinstance(t, dict)
]
elif cache_type == "app4_analysis": elif cache_type == "app4_analysis":
# aiAnalysis: summary + suggestions
ai_analysis = { ai_analysis = {
"summary": result.get("summary", ""), "summary": result.get("one_line_summary", ""),
"suggestions": result.get("suggestions", []), "suggestions": result.get("action_suggestions", []),
} }
conn.commit() conn.commit()
except Exception: except Exception:

View File

@@ -0,0 +1,64 @@
# -*- coding: utf-8 -*-
"""维客线索分类映射工具(W1-AI-CLOSURE 组 5)。
集中管理维客线索的"中文分类 → 视觉/显示属性"映射,供 customer_service 和
task_manager 共用,避免重复定义。
来源权威:
- 6 类 categoryColor: docs/miniprogram-dev/design-system/VI-DESIGN-SYSTEM.md §2.1
- source 三态: docs/ai/system-prompts/app8_consolidation.md §五
- 用户拍板(2026-05-06): AI 来源统一显示为 "AI"(前端拼 "By:AI")
"""
from __future__ import annotations
from types import MappingProxyType
# 6 类客户线索分类 → tag_color(英文别名,前端 clue-card 接收)
# VI-DESIGN-SYSTEM §2.1 权威映射(玩法偏好=orange,与 demo 早期 purple 不一致以本规范为准)
CATEGORY_TAG_COLOR: MappingProxyType[str, str] = MappingProxyType({
"客户基础": "primary",
"消费习惯": "success",
"玩法偏好": "orange",
"促销偏好": "gold",
"促销接受": "gold", # App8 prompt 里的别名
"社交关系": "purple",
"重要反馈": "error",
})
# 6 类客户线索分类 → 默认 emoji(用于手工录入/AI 输出 emoji 为空时的兜底)
CATEGORY_EMOJI_FALLBACK: MappingProxyType[str, str] = MappingProxyType({
"客户基础": "👤",
"消费习惯": "💰",
"玩法偏好": "🎮",
"促销偏好": "🎁",
"促销接受": "🎁",
"社交关系": "👥",
"重要反馈": "⚠️",
})
# 数据库 source 字段 → 显示用名称(用户拍板:AI 类全显示 "AI",手工 fallback "系统")
# 实际 source 优先级:recorded_by_name > SOURCE_DISPLAY_NAME[source]
SOURCE_DISPLAY_NAME: MappingProxyType[str, str] = MappingProxyType({
"manual": "系统",
"ai_consumption": "AI",
"ai_note": "AI",
})
def format_category_tag(category: str) -> str:
"""把 category 中文字面量格式化为 clue-card tag(强制 2+2 两行)。
db 存的是 4 字字面量(如 "消费习惯"),demo 标杆 wxml `white-space: pre-line`
依赖 `\n` 强制 2+2 布局("消费\n习惯")。如果不强制,4 字在 72rpx 容器内可能被
css 自动换成 3+1 / 1+3 而非 2+2,视觉错位。
输入空 / 长度 != 4 / 含 \n 的字符串原样返回。
"""
if not category or "\n" in category:
return category or ""
if len(category) == 4:
return f"{category[:2]}\n{category[2:]}"
return category

View File

@@ -1,55 +1,113 @@
"""AI 事件 WebSocket 推送端点。 """AI 事件 WebSocket 推送端点。
提供 提供:
- /ws/ai-cache/{site_id} — 缓存更新 / 失效事件 - /ws/ai-cache/{site_id}?token=xxx — 缓存更新 / 失效事件
- /ws/ai-alerts/{site_id} — AI 告警事件Phase 3.1 - /ws/ai-alerts/{site_id}?token=xxx — AI 告警事件(Phase 3.1)
协议 协议:
- 客户端连接 → 服务端 accept → 订阅 EventBus → 持续 send_json 事件 - 客户端连接(必须带 token query)→ 服务端校验 JWT → accept →
- 事件格式:{"type": "cache_updated|cache_invalidated|alert_created|...", "site_id": int, "payload": {...}} 订阅 EventBus → 持续 send_json 事件
- 事件格式:{"type": "cache_updated|alert_created|...", "site_id": int, "payload": {...}}
- 服务端关闭或客户端断开时清理订阅 - 服务端关闭或客户端断开时清理订阅
用 site_id=-1 表示全局订阅收所有门店事件admin-web 全局监控用)。 W1-AI-CLOSURE 组 7 安全加固(P0-9):
- 新增 token query 参数,JWT 解码失败 → 关闭(4401)
- site_id 必须与 token 中的 site_id 一致;site_id=-1 全局订阅要求
token 角色含 super_admin
- 不再允许任何用户监听任意门店的 AI 事件流
""" """
from __future__ import annotations from __future__ import annotations
import logging import logging
from fastapi import APIRouter, WebSocket, WebSocketDisconnect from fastapi import APIRouter, Query, WebSocket, WebSocketDisconnect, status
from jose import JWTError
from ..ai.event_bus import AIEvent, get_event_bus from ..ai.event_bus import AIEvent, get_event_bus
from ..auth.jwt import decode_access_token
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
ws_router = APIRouter() ws_router = APIRouter()
_WS_CLOSE_AUTH_FAILED = 4401 # 自定义 close code(WebSocket close codes 4000-4999 给应用使用)
def _authorize_ws(token: str | None, site_id: int) -> bool:
"""校验 WS 连接的 JWT token 与 site_id。
返回 True 表示通过,False 表示拒绝。
site_id == -1 时要求 token roles 含 super_admin。
"""
if not token:
return False
try:
payload = decode_access_token(token)
except JWTError:
return False
token_site_id = payload.get("site_id")
roles = payload.get("roles") or []
if not isinstance(roles, list):
roles = []
if site_id == -1:
# 全局订阅(admin-web 全局监控):仅 super_admin
return "super_admin" in roles
# 站点订阅:token 的 site_id 必须等于 URL 中的 site_id
# super_admin 跨站点放行
return token_site_id == site_id or "super_admin" in roles
@ws_router.websocket("/ws/ai-cache/{site_id}") @ws_router.websocket("/ws/ai-cache/{site_id}")
async def ws_ai_cache(websocket: WebSocket, site_id: int) -> None: async def ws_ai_cache(
websocket: WebSocket,
site_id: int,
token: str | None = Query(default=None),
) -> None:
"""AI 缓存事件推送。 """AI 缓存事件推送。
site_id=-1 表示订阅全局收所有门店的 cache_updated / cache_invalidated)。 site_id=-1 表示订阅全局(收所有门店的 cache_updated / cache_invalidated),
需 super_admin token。
""" """
await _serve_event_stream(websocket, site_id, endpoint="ai-cache") await _serve_event_stream(websocket, site_id, token=token, endpoint="ai-cache")
@ws_router.websocket("/ws/ai-alerts/{site_id}") @ws_router.websocket("/ws/ai-alerts/{site_id}")
async def ws_ai_alerts(websocket: WebSocket, site_id: int) -> None: async def ws_ai_alerts(
"""AI 告警事件推送Phase 3.1)。 websocket: WebSocket,
site_id: int,
token: str | None = Query(default=None),
) -> None:
"""AI 告警事件推送(Phase 3.1)。
site_id=-1 表示订阅全局告警。 site_id=-1 表示订阅全局告警,需 super_admin token
事件 type: alert_created / alert_updated / budget_exceeded / circuit_opened。 事件 type: alert_created / alert_updated / budget_exceeded / circuit_opened。
""" """
await _serve_event_stream(websocket, site_id, endpoint="ai-alerts") await _serve_event_stream(websocket, site_id, token=token, endpoint="ai-alerts")
async def _serve_event_stream( async def _serve_event_stream(
websocket: WebSocket, site_id: int, endpoint: str, websocket: WebSocket,
site_id: int,
*,
token: str | None,
endpoint: str,
) -> None: ) -> None:
"""共享事件流处理逻辑。""" """共享事件流处理逻辑(含 token 鉴权)"""
if not _authorize_ws(token, site_id):
await websocket.close(code=_WS_CLOSE_AUTH_FAILED, reason="auth required")
logger.warning(
"WS %s 鉴权失败: site_id=%s token_present=%s",
endpoint, site_id, bool(token),
)
return
await websocket.accept() await websocket.accept()
# -1 映射为全局订阅None # -1 映射为全局订阅(None)
subscribe_key: int | None = None if site_id == -1 else site_id subscribe_key: int | None = None if site_id == -1 else site_id
logger.info( logger.info(
"WS %s 连接建立: site_id=%s", endpoint, subscribe_key if subscribe_key else "ALL", "WS %s 连接建立: site_id=%s", endpoint, subscribe_key if subscribe_key else "ALL",

View File

@@ -274,7 +274,7 @@ class MemberConsumptionTask(BaseDwsTask):
生日来源dim_member.birthdayAPI 来源) 生日来源dim_member.birthdayAPI 来源)
CHANGE 2026-02-26 | 维客线索重构:移除 FDW member_birthday_manual 读取, CHANGE 2026-02-26 | 维客线索重构:移除 FDW member_birthday_manual 读取,
生日不再单独补录,归入维客线索"客户基础信息"大类 生日不再单独补录,归入维客线索"客户基础"大类
""" """
cutoff = self.config.get("app.business_day_start_hour", 8) cutoff = self.config.get("app.business_day_start_hour", 8)
biz_expr_create = biz_date_sql_expr("m.create_time", cutoff) biz_expr_create = biz_date_sql_expr("m.create_time", cutoff)

View File

@@ -367,7 +367,7 @@ class MemberVisitTask(BaseDwsTask):
生日来源dim_member.birthdayAPI 来源) 生日来源dim_member.birthdayAPI 来源)
CHANGE 2026-02-26 | 维客线索重构:移除 FDW member_birthday_manual 读取, CHANGE 2026-02-26 | 维客线索重构:移除 FDW member_birthday_manual 读取,
生日不再单独补录,归入维客线索"客户基础信息"大类 生日不再单独补录,归入维客线索"客户基础"大类
""" """
sql = """ sql = """
SELECT SELECT

View File

@@ -5,7 +5,17 @@
<view class="clue-content"> <view class="clue-content">
<view class="clue-text-container"> <view class="clue-text-container">
<text class="clue-text"><text class="clue-emoji">{{emoji}}</text> {{title}}</text> <text class="clue-text"><text class="clue-emoji">{{emoji}}</text> {{title}}</text>
<text class="clue-source">{{source}}</text> <!-- source = "AI" 时用 icon 替代文字(W1-AI-CLOSURE 复盘:节字符 + 直观);其他显示文字 -->
<view class="clue-source">
<text class="clue-source-prefix">By:</text>
<image
wx:if="{{source === 'AI' || source === 'By:AI'}}"
class="clue-source-ai-icon"
src="/assets/icons/ai-robot.svg"
mode="aspectFit"
/>
<text wx:else class="clue-source-text">{{source}}</text>
</view>
</view> </view>
</view> </view>
<view class="clue-desc" wx:if="{{content}}"> <view class="clue-desc" wx:if="{{content}}">

View File

@@ -103,6 +103,8 @@
position: absolute; position: absolute;
bottom: 0; bottom: 0;
right: 0; right: 0;
display: flex;
align-items: center;
font-size: 24rpx; font-size: 24rpx;
line-height: 36rpx; line-height: 36rpx;
color: var(--color-gray-7); color: var(--color-gray-7);
@@ -111,6 +113,17 @@
padding-left: 50rpx; padding-left: 50rpx;
z-index: 1; z-index: 1;
} }
.clue-source-prefix,
.clue-source-text {
font-size: 24rpx;
color: var(--color-gray-7);
}
.clue-source-ai-icon {
width: 32rpx;
height: 32rpx;
margin-left: 2rpx;
vertical-align: middle;
}
.clue-desc { .clue-desc {
line-height: 30rpx; line-height: 30rpx;

View File

@@ -133,7 +133,7 @@
<!-- 自定义底部导航栏 --> <!-- 自定义底部导航栏 -->
<board-tab-bar active="board" /> <board-tab-bar active="board" />
<!-- AI 悬浮按钮 — 在导航栏上方 --> <!-- AI 悬浮按钮 — 在导航栏上方(W1-AI-CLOSURE 组 6:补 sourcePage) -->
<ai-float-button /> <ai-float-button sourcePage="board-coach" />
<dev-fab wx:if="{{false}}" /> <dev-fab wx:if="{{false}}" />

View File

@@ -312,7 +312,7 @@
<!-- 自定义底部导航栏 --> <!-- 自定义底部导航栏 -->
<board-tab-bar active="board" /> <board-tab-bar active="board" />
<!-- AI 悬浮按钮 --> <!-- AI 悬浮按钮(W1-AI-CLOSURE 组 6:补 sourcePage) -->
<ai-float-button /> <ai-float-button sourcePage="board-customer" />
<dev-fab wx:if="{{false}}" /> <dev-fab wx:if="{{false}}" />

View File

@@ -876,7 +876,8 @@
</view> </view>
</block> </block>
<!-- AI 悬浮按钮 --> <!-- AI 悬浮按钮(W1-AI-CLOSURE 组 6:补 sourcePage,具体 timeDimension/areaFilter
<ai-float-button bottom="{{200}}" /> ai-float-button 组件按 page data 自动收集,这里不重复传 pageFilters) -->
<ai-float-button bottom="{{200}}" sourcePage="board-finance" />
<dev-fab wx:if="{{false}}" /> <dev-fab wx:if="{{false}}" />

View File

@@ -54,8 +54,8 @@
<text class="footer-text">— 已加载全部记录 —</text> <text class="footer-text">— 已加载全部记录 —</text>
</view> </view>
<!-- AI 悬浮按钮 --> <!-- AI 悬浮按钮(W1-AI-CLOSURE 组 6:对话列表入口仍可启动新对话) -->
<ai-float-button /> <ai-float-button sourcePage="chat-history" />
</view> </view>
<dev-fab /> <dev-fab />

View File

@@ -10,6 +10,7 @@ import { checkPageAccess } from '../../utils/auth-guard'
import { fetchChatMessages, fetchChatMessagesByContext } from '../../services/api' import { fetchChatMessages, fetchChatMessagesByContext } from '../../services/api'
import { formatRelativeTime, formatIMTime, shouldShowTimeDivider } from '../../utils/time' import { formatRelativeTime, formatIMTime, shouldShowTimeDivider } from '../../utils/time'
import { API_BASE } from '../../utils/config' import { API_BASE } from '../../utils/config'
import { mdToRichHtml } from '../../utils/markdown'
/** API 返回的消息项类型 */ /** API 返回的消息项类型 */
interface ApiMessageItem { interface ApiMessageItem {
@@ -31,12 +32,15 @@ function toDataList(data?: Record<string, string>): Array<{ key: string; value:
return Object.keys(data).map((k) => ({ key: k, value: data[k] })) return Object.keys(data).map((k) => ({ key: k, value: data[k] }))
} }
/** 为消息列表补充展示字段时间分割线、IM时间、引用卡片*/ /** 为消息列表补充展示字段时间分割线、IM时间、引用卡片、md 渲染*/
function enrichMessages(msgs: ApiMessageItem[]) { function enrichMessages(msgs: ApiMessageItem[]) {
return msgs.map((m, i) => ({ return msgs.map((m, i) => ({
id: String(m.id), id: String(m.id),
role: m.role, role: m.role,
content: m.content, content: m.content,
// W1-AI-CLOSURE 任务 1:AI 消息预解析 markdown 为 rich-text html
// (用户消息保持纯文本)
contentHtml: m.role === 'assistant' ? mdToRichHtml(m.content) : '',
timestamp: m.createdAt, timestamp: m.createdAt,
timeLabel: formatRelativeTime(m.createdAt), timeLabel: formatRelativeTime(m.createdAt),
imTimeLabel: formatIMTime(m.createdAt), imTimeLabel: formatIMTime(m.createdAt),
@@ -146,6 +150,8 @@ type DisplayMessage = {
id: string id: string
role: 'user' | 'assistant' role: 'user' | 'assistant'
content: string content: string
/** AI 消息预解析的 markdown → rich-text html(用户消息为空字符串)*/
contentHtml?: string
timestamp: string timestamp: string
timeLabel?: string timeLabel?: string
imTimeLabel?: string imTimeLabel?: string
@@ -223,13 +229,27 @@ Page({
this.loadMessages(options.historyId) this.loadMessages(options.historyId)
} else if (options?.taskId) { } else if (options?.taskId) {
// 从 task-detail 跳转:同一 taskId 始终复用同一对话(无时限) // 从 task-detail 跳转:同一 taskId 始终复用同一对话(无时限)
// W1-AI-CLOSURE 组 6:同步 sourcePage + pageContext.contextId 让后端 SSE
// 阶段能注入页面上下文(build_page_text)+ build_app1_reference_card 跳转卡。
this.setData({
sourcePage: 'task-detail',
pageFilters: { contextId: options.taskId },
})
this.loadMessagesByContext('task', options.taskId) this.loadMessagesByContext('task', options.taskId)
} else if (options?.customerId) { } else if (options?.customerId) {
// 从 customer-detail 跳转:≤ 3 天复用、> 3 天新建 // 从 customer-detail 跳转:≤ 3 天复用、> 3 天新建
this.setData({ customerId: options.customerId }) this.setData({
customerId: options.customerId,
sourcePage: 'customer-detail',
pageFilters: { contextId: options.customerId },
})
this.loadMessagesByContext('customer', options.customerId) this.loadMessagesByContext('customer', options.customerId)
} else if (options?.coachId) { } else if (options?.coachId) {
// 从 coach-detail 跳转:≤ 3 天复用、> 3 天新建 // 从 coach-detail 跳转:≤ 3 天复用、> 3 天新建
this.setData({
sourcePage: 'coach-detail',
pageFilters: { contextId: options.coachId },
})
this.loadMessagesByContext('coach', options.coachId) this.loadMessagesByContext('coach', options.coachId)
} else if (options?.sourcePage) { } else if (options?.sourcePage) {
// 看板类入口:保存来源页面和筛选参数 // 看板类入口:保存来源页面和筛选参数
@@ -411,6 +431,7 @@ Page({
id: aiMsgId, id: aiMsgId,
role: 'assistant', role: 'assistant',
content: '', content: '',
contentHtml: '',
timestamp: aiNow, timestamp: aiNow,
timeLabel: '刚刚', timeLabel: '刚刚',
imTimeLabel: formatIMTime(aiNow), imTimeLabel: formatIMTime(aiNow),
@@ -429,12 +450,12 @@ Page({
let fullContent = '' let fullContent = ''
const parser = new SSEParser( const parser = new SSEParser(
// onMessage: 逐 token 追加 // onMessage: 逐 token 追加 + 实时 markdown 解析
(token: string) => { (token: string) => {
fullContent += token fullContent += token
const key = `messages[${aiIndex}].content`
this.setData({ this.setData({
[key]: fullContent, [`messages[${aiIndex}].content`]: fullContent,
[`messages[${aiIndex}].contentHtml`]: mdToRichHtml(fullContent),
streamingContent: fullContent, streamingContent: fullContent,
}) })
this.scrollToBottom() this.scrollToBottom()

View File

@@ -82,14 +82,15 @@
</view> </view>
</view> </view>
<!-- AI 消息:左对齐白色 --> <!-- AI 消息:左对齐白色W1-AI-CLOSURE 任务 1流式 markdown 实时渲染)-->
<view class="message-row message-assistant" wx:else id="msg-{{item.id}}"> <view class="message-row message-assistant" wx:else id="msg-{{item.id}}">
<view class="ai-avatar"> <view class="ai-avatar">
<image src="/assets/icons/ai-robot.svg" class="ai-avatar-img" mode="aspectFit" /> <image src="/assets/icons/ai-robot.svg" class="ai-avatar-img" mode="aspectFit" />
</view> </view>
<view class="bubble-col"> <view class="bubble-col">
<view class="bubble bubble-assistant"> <view class="bubble bubble-assistant">
<text class="bubble-text">{{item.content}}</text> <rich-text wx:if="{{item.contentHtml}}" class="bubble-md" nodes="{{item.contentHtml}}" />
<text wx:else class="bubble-text">{{item.content}}</text>
</view> </view>
<!-- AI 侧引用卡片(后端 referenceCard 附加在 assistant 回复中)--> <!-- AI 侧引用卡片(后端 referenceCard 附加在 assistant 回复中)-->
<view <view

View File

@@ -376,3 +376,86 @@ page {
width: 44rpx; width: 44rpx;
height: 44rpx; height: 44rpx;
} }
/* W1-AI-CLOSURE 任务 1: AI 消息 markdown 渲染样式 ===================== */
/* rich-text 不允许内联 style,样式通过 class 控制 */
.bubble-md {
font-size: 30rpx;
line-height: 1.65;
color: var(--color-gray-13, #242424);
word-break: break-word;
}
/* 段落 */
.md-p {
margin: 0 0 16rpx;
}
.md-p:last-child {
margin-bottom: 0;
}
/* 标题 */
.md-h1 { font-size: 38rpx; font-weight: 700; margin: 24rpx 0 14rpx; color: #1a1a1a; }
.md-h2 { font-size: 34rpx; font-weight: 700; margin: 22rpx 0 12rpx; color: #1a1a1a; }
.md-h3 { font-size: 30rpx; font-weight: 600; margin: 18rpx 0 10rpx; color: #2c2c2c; }
.md-h4 { font-size: 28rpx; font-weight: 600; margin: 14rpx 0 8rpx; color: #2c2c2c; }
/* 列表 */
.md-ul, .md-ol {
margin: 8rpx 0 16rpx;
padding-left: 36rpx;
}
.md-li {
margin-bottom: 6rpx;
line-height: 1.6;
}
/* 表格 */
.md-table {
border-collapse: collapse;
margin: 12rpx 0 18rpx;
width: 100%;
font-size: 26rpx;
background: #fafafa;
border-radius: 12rpx;
overflow: hidden;
}
.md-th, .md-td {
border: 1rpx solid #e0e0e0;
padding: 10rpx 14rpx;
text-align: left;
vertical-align: top;
}
.md-th {
background: rgba(0, 82, 217, 0.06);
font-weight: 600;
color: #2c2c2c;
}
/* 行内代码 */
.md-code {
font-family: SFMono-Regular, Menlo, Consolas, monospace;
font-size: 26rpx;
background: rgba(0, 0, 0, 0.05);
padding: 2rpx 10rpx;
border-radius: 6rpx;
color: #c7254e;
}
/* 代码块 */
.md-pre {
margin: 12rpx 0 16rpx;
padding: 16rpx 20rpx;
background: #2d2d2d;
border-radius: 12rpx;
overflow-x: auto;
}
.md-code-block {
font-family: SFMono-Regular, Menlo, Consolas, monospace;
font-size: 24rpx;
line-height: 1.55;
color: #e0e0e0;
white-space: pre;
background: transparent;
}

View File

@@ -319,6 +319,9 @@
</view> </view>
</view> </view>
</view> </view>
<!-- AI 悬浮按钮(W1-AI-CLOSURE 组 6:补 coach-detail 此前死注册的组件 + sourcePage) -->
<ai-float-button coachId="{{detail.id}}" sourcePage="coach-detail" />
</block> </block>
<dev-fab /> <dev-fab />

View File

@@ -117,7 +117,7 @@
</view> </view>
</block> </block>
<!-- AI 悬浮按钮 --> <!-- AI 悬浮按钮(W1-AI-CLOSURE 组 6:补 sourcePage) -->
<ai-float-button /> <ai-float-button sourcePage="coach-service-records" />
<dev-fab /> <dev-fab />

View File

@@ -55,17 +55,21 @@ Page({
}, },
phoneVisible: false, phoneVisible: false,
aiColor: "indigo" as "red" | "orange" | "yellow" | "blue" | "indigo" | "purple", aiColor: "indigo" as "red" | "orange" | "yellow" | "blue" | "indigo" | "purple",
// 对齐 demo 标杆 wxml(`{{item.text}}` 单字段);color 由前端按 index 轮换。
aiInsight: { aiInsight: {
summary: '', summary: '',
strategies: [ strategies: [] as Array<{ color: string; text: string }>,
{ color: '', text: '' },
{ color: '', text: '' },
],
}, },
clues: [ // W1-AI-CLOSURE 组 6:clues 字段对齐 RetentionClue schema
{ category: '', categoryColor: '', text: '', source: '' }, // {tag, tag_color, emoji, text, source, desc} → camelCase {tag, tagColor, emoji, text, source, desc}
{ category: '', categoryColor: '', text: '', source: '', detail: '' }, clues: [] as Array<{
], tag: string
tagColor: string
emoji: string
text: string
source: string
desc: string
}>,
coachTasks: [ coachTasks: [
{ name: '', level: '', levelColor: '', taskType: '', taskColor: '', bgClass: '', status: '', lastService: '', metrics: [{ label: '', value: '' }] }, { name: '', level: '', levelColor: '', taskType: '', taskColor: '', bgClass: '', status: '', lastService: '', metrics: [{ label: '', value: '' }] },
{ name: '', level: '', levelColor: '', taskType: '', taskColor: '', bgClass: '', status: '', lastService: '', metrics: [{ label: '', value: '' }] }, { name: '', level: '', levelColor: '', taskType: '', taskColor: '', bgClass: '', status: '', lastService: '', metrics: [{ label: '', value: '' }] },
@@ -142,15 +146,19 @@ Page({
}, },
async _loadAIInsight(memberId: string) { async _loadAIInsight(memberId: string) {
const cache = await fetchAICache('app7_customer_analysis', memberId) // cache_type 统一为 'app7_customer'(W1-AI-CLOSURE 组 1 数据库迁移已对齐)。
// App7Result.strategies = [{title, content}],前端拼成 demo 标杆 {color, text} 单字段。
const cache = await fetchAICache('app7_customer', memberId)
if (!cache?.result_json) return if (!cache?.result_json) return
const rj = cache.result_json as any const rj = cache.result_json as { summary?: string; strategies?: Array<{ title?: string; content?: string; text?: string }> }
const COLORS = ['blue', 'indigo', 'purple', 'red', 'orange', 'yellow'] as const const COLORS = ['blue', 'indigo', 'purple', 'red', 'orange', 'yellow'] as const
const strategies = Array.isArray(rj.strategies) const strategies = Array.isArray(rj.strategies)
? rj.strategies.map((s: any, i: number) => ({ ? rj.strategies.map((s, i) => {
color: COLORS[i % COLORS.length], const t = (s?.title || '').trim()
text: s.title || s.text || '', const c = (s?.content || '').trim()
})) const text = s?.text || (t && c ? `${t}${c}` : (c || t))
return { color: COLORS[i % COLORS.length], text }
})
: [] : []
this.setData({ this.setData({
'aiInsight.summary': rj.summary || '', 'aiInsight.summary': rj.summary || '',

View File

@@ -59,8 +59,8 @@
<!-- 主体内容 --> <!-- 主体内容 -->
<view class="main-content" > <view class="main-content" >
<!-- AI 智能洞察 --> <!-- AI 智能洞察(W1-AI-CLOSURE 复盘:cache miss 时整段不渲染,避免空白卡) -->
<view class="ai-insight-card"> <view class="ai-insight-card" wx:if="{{aiInsight.summary || aiInsight.strategies.length > 0}}">
<view class="ai-insight-header"> <view class="ai-insight-header">
<view class="ai-icon-box"> <view class="ai-icon-box">
<image class="ai-icon-img" src="/assets/icons/ai-robot.svg" mode="aspectFit" /> <image class="ai-icon-img" src="/assets/icons/ai-robot.svg" mode="aspectFit" />
@@ -84,7 +84,7 @@
</view> </view>
<!-- 维客线索 --> <!-- 维客线索 -->
<view class="card"> <view class="card" wx:if="{{clues.length > 0}}">
<view class="card-header"> <view class="card-header">
<text class="section-title title-green">维客线索</text> <text class="section-title title-green">维客线索</text>
<ai-title-badge color="{{aiColor}}" /> <ai-title-badge color="{{aiColor}}" />
@@ -93,12 +93,12 @@
<clue-card <clue-card
wx:for="{{clues}}" wx:for="{{clues}}"
wx:key="index" wx:key="index"
tag="{{item.category}}" tag="{{item.tag}}"
category="{{item.categoryColor}}" category="{{item.tagColor}}"
emoji="" emoji="{{item.emoji}}"
title="{{item.text}}" title="{{item.text}}"
source="By:{{item.source}}" source="{{item.source}}"
content="{{item.detail}}" content="{{item.desc}}"
/> />
</view> </view>
</view> </view>
@@ -325,8 +325,8 @@
<!-- 备注弹窗 --> <!-- 备注弹窗 -->
<note-modal visible="{{noteModalVisible}}" customerName="{{detail.name}}" showExpandBtn="{{false}}" showRating="{{false}}" bind:confirm="onNoteConfirm" bind:cancel="onNoteCancel" /> <note-modal visible="{{noteModalVisible}}" customerName="{{detail.name}}" showExpandBtn="{{false}}" showRating="{{false}}" bind:confirm="onNoteConfirm" bind:cancel="onNoteCancel" />
<!-- AI 悬浮按钮 --> <!-- AI 悬浮按钮(W1-AI-CLOSURE 组 6:补 sourcePage 让 chat 上下文捕获生效) -->
<ai-float-button customerId="{{detail.id}}" /> <ai-float-button customerId="{{detail.id}}" sourcePage="customer-detail" />
</block> </block>
<dev-fab /> <dev-fab />

View File

@@ -121,8 +121,8 @@
</view> </view>
<!-- AI 悬浮按钮 --> <!-- AI 悬浮按钮(W1-AI-CLOSURE 组 6:补 sourcePage) -->
<ai-float-button customerId="{{customerId}}" /> <ai-float-button customerId="{{customerId}}" sourcePage="customer-service-records" />
</block> </block>

View File

@@ -62,7 +62,7 @@
</view> </view>
</view> </view>
<!-- AI 悬浮按钮 — TabBar 页面 bottom 200rpx --> <!-- AI 悬浮按钮 — TabBar 页面 bottom 200rpx(W1-AI-CLOSURE 组 6:补 sourcePage) -->
<ai-float-button visible="{{true}}" /> <ai-float-button visible="{{true}}" sourcePage="my-profile" />
<dev-fab wx:if="{{false}}" /> <dev-fab wx:if="{{false}}" />

View File

@@ -50,8 +50,8 @@
<text class="footer-text">— 没有更多了 —</text> <text class="footer-text">— 没有更多了 —</text>
</view> </view>
<!-- AI 悬浮按钮 --> <!-- AI 悬浮按钮(W1-AI-CLOSURE 组 6:补 sourcePage) -->
<ai-float-button /> <ai-float-button sourcePage="notes" />
</view> </view>
<dev-fab /> <dev-fab />

View File

@@ -117,7 +117,7 @@
</view> </view>
</block> </block>
<!-- AI 悬浮按钮 --> <!-- AI 悬浮按钮(W1-AI-CLOSURE 组 6:补 sourcePage) -->
<ai-float-button /> <ai-float-button sourcePage="performance-records" />
<dev-fab /> <dev-fab />

View File

@@ -296,7 +296,7 @@
</view> </view>
</block> </block>
<!-- AI 悬浮按钮 --> <!-- AI 悬浮按钮(W1-AI-CLOSURE 组 6:补 sourcePage) -->
<ai-float-button /> <ai-float-button sourcePage="performance" />
<dev-fab /> <dev-fab />

View File

@@ -13,6 +13,7 @@
"t-loading": "tdesign-miniprogram/loading/loading", "t-loading": "tdesign-miniprogram/loading/loading",
"clue-card": "/components/clue-card/clue-card", "clue-card": "/components/clue-card/clue-card",
"service-record-card": "/components/service-record-card/service-record-card", "service-record-card": "/components/service-record-card/service-record-card",
"dev-fab": "/components/dev-fab/dev-fab" "dev-fab": "/components/dev-fab/dev-fab",
"ai-float-button": "/components/ai-float-button/ai-float-button"
} }
} }

View File

@@ -10,10 +10,10 @@ import { sortByTimestamp } from '../../utils/sort'
import { formatRelativeTime } from '../../utils/time' import { formatRelativeTime } from '../../utils/time'
import { formatStorageLevel } from '../../utils/storage-level' import { formatStorageLevel } from '../../utils/storage-level'
/** 维客线索项 */ /** 维客线索项(W1-AI-CLOSURE 组 6:tagColor 6 类对齐 VI-DESIGN-SYSTEM v1.1) */
interface RetentionClue { interface RetentionClue {
tag: string tag: string
tagColor: 'primary' | 'success' | 'purple' | 'error' tagColor: 'primary' | 'success' | 'orange' | 'gold' | 'purple' | 'error'
emoji: string emoji: string
text: string text: string
source: string source: string
@@ -21,6 +21,12 @@ interface RetentionClue {
expanded?: boolean expanded?: boolean
} }
/** 话术参考项(W1-AI-CLOSURE 组 6:对齐 App5Result.tactics) */
interface TacticItem {
scenario: string
script: string
}
/** 服务记录项 */ /** 服务记录项 */
interface ServiceRecord { interface ServiceRecord {
table: string table: string
@@ -58,12 +64,8 @@ Page({
{ tag: '', tagColor: 'error', emoji: '', text: '', source: '', desc: '', expanded: false }, { tag: '', tagColor: 'error', emoji: '', text: '', source: '', desc: '', expanded: false },
] as RetentionClue[], ] as RetentionClue[],
// --- 话术参考 --- // --- 话术参考(对齐 App5Result.tactics 字段) ---
talkingPoints: [ talkingPoints: [] as TacticItem[],
'',
'',
'',
] as string[],
copiedIndex: -1, copiedIndex: -1,
// --- 近期服务记录 --- // --- 近期服务记录 ---
@@ -264,13 +266,13 @@ Page({
this.setData({ [key]: !current }) this.setData({ [key]: !current })
}, },
/** 复制话术 */ /** 复制话术(W1-AI-CLOSURE 组 6:tactics 含 scenario+script 双字段,复制 script 部分) */
onCopySpeech(e: WechatMiniprogram.BaseEvent) { onCopySpeech(e: WechatMiniprogram.BaseEvent) {
const idx = e.currentTarget.dataset.index as number const idx = e.currentTarget.dataset.index as number
const text = this.data.talkingPoints[idx] const item = this.data.talkingPoints[idx]
if (!text) return if (!item || !item.script) return
wx.setClipboardData({ wx.setClipboardData({
data: text, data: item.script,
success: () => { success: () => {
this.setData({ copiedIndex: idx }) this.setData({ copiedIndex: idx })
setTimeout(() => this.setData({ copiedIndex: -1 }), 2000) setTimeout(() => this.setData({ copiedIndex: -1 }), 2000)

View File

@@ -95,7 +95,7 @@
<view class="speech-bubble" wx:for="{{talkingPoints}}" wx:key="index"> <view class="speech-bubble" wx:for="{{talkingPoints}}" wx:key="index">
<view class="speech-text-wrap"> <view class="speech-text-wrap">
<ai-inline-icon color="{{aiColor}}" /> <ai-inline-icon color="{{aiColor}}" />
<text class="speech-text">{{item}}</text> <text class="speech-text">{{item.scenario ? item.scenario + '' + item.script : item.script}}</text>
</view> </view>
<view class="speech-copy-row"> <view class="speech-copy-row">
<view class="copy-btn" bindtap="onCopySpeech" data-index="{{index}}" hover-class="copy-btn--hover"> <view class="copy-btn" bindtap="onCopySpeech" data-index="{{index}}" hover-class="copy-btn--hover">
@@ -277,4 +277,7 @@
<text>🔧</text> <text>🔧</text>
</view> </view>
<!-- AI 悬浮按钮(W1-AI-CLOSURE 组 6:补 task-detail 整页缺失的入口 + sourcePage) -->
<ai-float-button taskId="{{detail.id}}" sourcePage="task-detail" />
</block> </block>

View File

@@ -329,8 +329,8 @@
bind:cancel="onNoteCancel" bind:cancel="onNoteCancel"
/> />
<!-- AI 悬浮按钮 --> <!-- AI 悬浮按钮(W1-AI-CLOSURE 组 6:补 sourcePage) -->
<ai-float-button /> <ai-float-button sourcePage="task-list" />
<!-- 开发调试 FAB --> <!-- 开发调试 FAB -->
<dev-fab /> <dev-fab />

View File

@@ -0,0 +1,205 @@
/**
* 轻量 Markdown 转 rich-text 兼容 HTML 字符串(W1-AI-CLOSURE 任务 1)。
*
* 用途:chat 页 AI 回复流式渲染。每次 token 拼接后调用,输出供小程序
* <rich-text nodes="{{html}}"> 渲染。
*
* 支持(80% AI 输出场景覆盖):
* 段落 / 换行 / 标题 H1-H4 / 粗体 / 斜体 / 行内代码 / 代码块
* 无序列表 / 有序列表 / GFM 表格 / 行内 emoji 不变
*
* Streaming 容错:partial 标记(未闭合 双星 / 未结尾 三引号 / 未完整 竖线)
* 不渲染对应节点,降级为纯文本。每次 token 来重新解析整段。
*
* rich-text 限制:
* 不允许 inline style 属性
* 仅支持有限 tag(p / div / h1-h6 / strong / em / code / ul / ol / li /
* table / tr / th / td / pre / br / a)
* class 由 wxss 全局样式控制
*/
const HTML_ESCAPE_MAP: Record<string, string> = {
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&#39;",
}
function escapeHtml(s: string): string {
return s.replace(/[&<>"']/g, (c) => HTML_ESCAPE_MAP[c])
}
/**
* 解析行内 markdown(粗体 / 斜体 / 行内代码),返回带 tag 的 html。
* 优先级:行内代码 > 粗体 > 斜体。已转义 html 特殊字符。
*/
function parseInline(text: string): string {
if (!text) return ""
// 步骤 1:抽出 `code` 占位(纯 ASCII 标记防与原文冲突)
const codeStash: string[] = []
let s = text.replace(/`([^`\n]+)`/g, (_m, c) => {
const idx = codeStash.length
codeStash.push(c)
return `[[MDCODE${idx}MDCODE]]`
})
// 步骤 2:转义 html(占位标记 [[MDCODE0MDCODE]] 中的 [ ] 不会转义)
s = escapeHtml(s)
// 步骤 3:还原 code 为 <code> 标签
s = s.replace(/\[\[MDCODE(\d+)MDCODE\]\]/g, (_m, i) => {
const c = codeStash[Number(i)] || ""
return `<code class="md-code">${escapeHtml(c)}</code>`
})
// 步骤 4:粗体 **xx**(确保有闭合)
s = s.replace(/\*\*([^\n*][^\n*]*?)\*\*/g, "<strong>$1</strong>")
// 步骤 5:斜体 *xx*(避免 **)
s = s.replace(/(^|[^*])\*([^\n*][^\n*]*?)\*(?!\*)/g, "$1<em>$2</em>")
return s
}
/**
* 主入口:Markdown 转 rich-text 兼容 HTML 字符串。
*/
export function mdToRichHtml(md: string): string {
if (!md) return ""
const lines = md.split("\n")
const out: string[] = []
let i = 0
let inCodeBlock = false
let codeBuf: string[] = []
while (i < lines.length) {
const line = lines[i]
// 代码块 ```xx```
if (line.trim().startsWith("```")) {
if (!inCodeBlock) {
inCodeBlock = true
codeBuf = []
} else {
out.push(
`<pre class="md-pre"><code class="md-code-block">${escapeHtml(
codeBuf.join("\n"),
)}</code></pre>`,
)
inCodeBlock = false
}
i++
continue
}
if (inCodeBlock) {
codeBuf.push(line)
i++
continue
}
// 标题 #
const h = line.match(/^(#{1,4})\s+(.+)$/)
if (h) {
const level = h[1].length
out.push(`<h${level} class="md-h${level}">${parseInline(h[2])}</h${level}>`)
i++
continue
}
// GFM 表格(连续 2 行,第二行为分隔)
if (
line.trim().startsWith("|") &&
i + 1 < lines.length &&
/^\s*\|[\s\-:|]+\|\s*$/.test(lines[i + 1])
) {
const headers = line.split("|").slice(1, -1).map((c) => c.trim())
i += 2
const rows: string[][] = []
while (
i < lines.length &&
lines[i].trim().startsWith("|") &&
lines[i].trim().endsWith("|")
) {
rows.push(lines[i].split("|").slice(1, -1).map((c) => c.trim()))
i++
}
let html = '<table class="md-table"><thead><tr>'
for (const h0 of headers) html += `<th class="md-th">${parseInline(h0)}</th>`
html += "</tr></thead><tbody>"
for (const r of rows) {
html += "<tr>"
for (const c of r) html += `<td class="md-td">${parseInline(c)}</td>`
html += "</tr>"
}
html += "</tbody></table>"
out.push(html)
continue
}
// 无序列表
if (/^\s*[-*]\s+/.test(line)) {
const items: string[] = []
while (i < lines.length && /^\s*[-*]\s+/.test(lines[i])) {
items.push(lines[i].replace(/^\s*[-*]\s+/, ""))
i++
}
out.push(
`<ul class="md-ul">${items
.map((it) => `<li class="md-li">${parseInline(it)}</li>`)
.join("")}</ul>`,
)
continue
}
// 有序列表
if (/^\s*\d+\.\s+/.test(line)) {
const items: string[] = []
while (i < lines.length && /^\s*\d+\.\s+/.test(lines[i])) {
items.push(lines[i].replace(/^\s*\d+\.\s+/, ""))
i++
}
out.push(
`<ol class="md-ol">${items
.map((it) => `<li class="md-li">${parseInline(it)}</li>`)
.join("")}</ol>`,
)
continue
}
// 空行 → 段落分隔
if (line.trim() === "") {
i++
continue
}
// 普通段落(连续非空行合并,内部用 <br/> 保留软换行)
const para: string[] = [line]
i++
while (
i < lines.length &&
lines[i].trim() !== "" &&
!lines[i].trim().startsWith("#") &&
!lines[i].trim().startsWith("|") &&
!/^\s*[-*]\s+/.test(lines[i]) &&
!/^\s*\d+\.\s+/.test(lines[i]) &&
!lines[i].trim().startsWith("```")
) {
para.push(lines[i])
i++
}
out.push(`<p class="md-p">${parseInline(para.join("<br/>"))}</p>`)
}
// 流未闭合的代码块降级为纯文本 pre
if (inCodeBlock && codeBuf.length > 0) {
out.push(
`<pre class="md-pre"><code class="md-code-block">${escapeHtml(
codeBuf.join("\n"),
)}</code></pre>`,
)
}
return out.join("")
}

View File

@@ -0,0 +1,172 @@
-- 2026-05-06
-- W1-AI-CLOSURE 超级 Sprint 组 1 — Schema 修复 + 命名统一
--
-- 背景:
-- AI 9 APP 全链路调研发现以下劣化:
-- 1. emoji 嵌入 summary 字符串(dispatcher.py:582-584),数据库 member_retention_clue
-- 表无独立 emoji 列,违反"字段独立性"哲学
-- 2. member_retention_clue 表无 runtime_mode / sandbox_instance_id,沙箱模式下 App8
-- 写入会污染 prod 视图(其他 7 张 ai_* 表都有这两列,本表是唯一例外)
-- 3. ai_run_logs 缺 assistant_id 列,App4/App5 这种 (assistant, member) 二元任务
-- 失败定位困难
-- 4. cache_type / app_type 双名长期共存:
-- ai_cache.cache_type = app7_customer_analysis / app8_clue_consolidated
-- ai_run_logs.app_type = app7_customer / app8_consolidate
-- 违反"schema 一致性"哲学,统一为应用名(与 prompt 文件名一致):
-- app7_customer / app8_consolidation
--
-- 影响范围:
-- - public.member_retention_clue:加 3 列(emoji + runtime_mode + sandbox_instance_id)
-- - biz.ai_run_logs:加 assistant_id 列 + 复合索引补建
-- - biz.ai_cache + biz.ai_run_logs:cache_type / app_type 命名统一
-- - 后端 dispatcher / cleanup_service / cache_service 代码相应修改(组 2-5)
--
-- 兼容性:
-- - emoji 列默认空字符串,新写入由 dispatcher 移除拼字符串后独立写入(组 3)
-- - runtime_mode / sandbox_instance_id 默认 'live',与其他 ai_* 表一致
-- - 命名 UPDATE 后,旧字符串 'app7_customer_analysis' / 'app8_clue_consolidated' /
-- 'app8_consolidate' 在数据库中绝迹,代码侧必须同步更新
-- - 回填脚本 scripts/ops/backfill_retention_clue_emoji.py 抽取 summary 嵌入的 emoji
-- 到 emoji 列,本迁移不做该回填(脚本走 dry-run + 实跑两步)
--
-- 回滚策略:见末尾"回滚参考"块。
--
-- 验证 SQL(执行后跑):
-- 1. SELECT column_name FROM information_schema.columns
-- WHERE table_schema='public' AND table_name='member_retention_clue'
-- AND column_name IN ('emoji','runtime_mode','sandbox_instance_id');
-- 预期 3 行
-- 2. SELECT column_name FROM information_schema.columns
-- WHERE table_schema='biz' AND table_name='ai_run_logs'
-- AND column_name='assistant_id';
-- 预期 1 行
-- 3. SELECT cache_type, count(*) FROM biz.ai_cache
-- WHERE cache_type IN ('app6_note_analysis','app7_customer_analysis',
-- 'app8_clue_consolidated','app8_consolidate')
-- GROUP BY 1;
-- 预期 0 行
-- 4. SELECT app_type, count(*) FROM biz.ai_run_logs
-- WHERE app_type IN ('app6_note_analysis','app7_customer_analysis',
-- 'app8_consolidate','app8_clue_consolidated')
-- GROUP BY 1;
-- 预期 0 行
-- 5. SELECT runtime_mode, count(*) FROM public.member_retention_clue GROUP BY 1;
-- 预期 'live' 一行覆盖全部历史
BEGIN;
-- ── 1) public.member_retention_clue: 加 emoji + runtime_mode + sandbox_instance_id ──
ALTER TABLE public.member_retention_clue
ADD COLUMN IF NOT EXISTS emoji character varying(8) NOT NULL DEFAULT '';
ALTER TABLE public.member_retention_clue
ADD COLUMN IF NOT EXISTS runtime_mode character varying(20) NOT NULL DEFAULT 'live',
ADD COLUMN IF NOT EXISTS sandbox_instance_id character varying(64) NOT NULL DEFAULT 'live';
UPDATE public.member_retention_clue
SET runtime_mode = 'live', sandbox_instance_id = 'live'
WHERE runtime_mode IS NULL OR sandbox_instance_id IS NULL;
COMMENT ON COLUMN public.member_retention_clue.emoji IS
'维客线索独立 emoji 字段(由 App8 prompt 输出 emoji 字段直接写入,不嵌 summary);本字段于 W1-AI-CLOSURE 引入,历史数据由 backfill_retention_clue_emoji.py 回填。';
COMMENT ON COLUMN public.member_retention_clue.runtime_mode IS
'运行模式:live / sandbox;sandbox 模式写入隔离实例 ID,live 与其他门店共享 prod 视图。';
COMMENT ON COLUMN public.member_retention_clue.sandbox_instance_id IS
'sandbox 模式写入隔离实例 ID;live 模式固定为 live。';
-- ── 2) biz.ai_run_logs: 加 assistant_id 列 + 复合索引 ──
ALTER TABLE biz.ai_run_logs
ADD COLUMN IF NOT EXISTS assistant_id bigint;
COMMENT ON COLUMN biz.ai_run_logs.assistant_id IS
'App4/App5 这类 (assistant, member) 二元关系任务的助教 ID,便于失败定位;App2/App3/App6/App7/App8 类任务为 NULL。';
CREATE INDEX IF NOT EXISTS idx_ai_run_logs_assistant_member
ON biz.ai_run_logs (site_id, assistant_id, member_id, created_at DESC)
WHERE assistant_id IS NOT NULL;
-- ── 3) cache_type / app_type 命名统一(app6 + app7 + app8) ──
-- 双名长期共存违反 schema 一致性,统一为与 prompt 文件名一致的应用名:
-- app6_note_analysis -> app6_note
-- app7_customer_analysis -> app7_customer
-- app8_clue_consolidated / app8_consolidate -> app8_consolidation
-- 注意:cache_type 有 chk_ai_cache_type CHECK 约束,需先 DROP 再 UPDATE 再 ADD 新约束。
ALTER TABLE biz.ai_cache DROP CONSTRAINT IF EXISTS chk_ai_cache_type;
UPDATE biz.ai_cache
SET cache_type = 'app6_note'
WHERE cache_type = 'app6_note_analysis';
UPDATE biz.ai_cache
SET cache_type = 'app7_customer'
WHERE cache_type = 'app7_customer_analysis';
UPDATE biz.ai_cache
SET cache_type = 'app8_consolidation'
WHERE cache_type IN ('app8_clue_consolidated', 'app8_consolidate');
UPDATE biz.ai_run_logs
SET app_type = 'app8_consolidation'
WHERE app_type IN ('app8_consolidate', 'app8_clue_consolidated');
UPDATE biz.ai_run_logs
SET app_type = 'app6_note'
WHERE app_type = 'app6_note_analysis';
UPDATE biz.ai_run_logs
SET app_type = 'app7_customer'
WHERE app_type = 'app7_customer_analysis';
-- 注意:ai_run_logs 中 app7 测试库已经是 'app7_customer'(102 行),app6 在测试库
-- 无数据;UPDATE 旧名字若不存在则 0 行影响,幂等安全。
ALTER TABLE biz.ai_cache
ADD CONSTRAINT chk_ai_cache_type
CHECK (cache_type IN (
'app2_finance',
'app2a_finance_area',
'app3_clue',
'app4_analysis',
'app5_tactics',
'app6_note',
'app7_customer',
'app8_consolidation'
));
COMMENT ON CONSTRAINT chk_ai_cache_type ON biz.ai_cache IS
'AI 8 个写缓存的应用类型(app1_chat 走 ai_messages 不进缓存);命名与 prompt 文件名一致。';
-- ── 4) 索引收尾(若旧索引引用旧 cache_type 字符串,无影响 — 索引按当前值重建) ──
COMMIT;
-- =============================================================================
-- 回滚参考(测试库回滚先跑此块,正式库回滚需评估业务影响):
-- =============================================================================
-- BEGIN;
--
-- -- 命名 UPDATE 回滚(注意:旧名字 app8_consolidate vs app8_clue_consolidated 已合并,
-- -- 回滚无法精确还原,只能选其一;以下示例选 ai_cache 的旧描述名)
-- -- ALTER TABLE biz.ai_cache DROP CONSTRAINT IF EXISTS chk_ai_cache_type;
-- -- UPDATE biz.ai_run_logs SET app_type = 'app8_consolidate' WHERE app_type = 'app8_consolidation';
-- -- UPDATE biz.ai_run_logs SET app_type = 'app7_customer_analysis' WHERE app_type = 'app7_customer';
-- -- UPDATE biz.ai_run_logs SET app_type = 'app6_note_analysis' WHERE app_type = 'app6_note';
-- -- UPDATE biz.ai_cache SET cache_type = 'app8_clue_consolidated' WHERE cache_type = 'app8_consolidation';
-- -- UPDATE biz.ai_cache SET cache_type = 'app7_customer_analysis' WHERE cache_type = 'app7_customer';
-- -- UPDATE biz.ai_cache SET cache_type = 'app6_note_analysis' WHERE cache_type = 'app6_note';
-- -- ALTER TABLE biz.ai_cache ADD CONSTRAINT chk_ai_cache_type CHECK (cache_type IN
-- -- ('app2_finance','app2a_finance_area','app3_clue','app4_analysis','app5_tactics',
-- -- 'app6_note_analysis','app7_customer_analysis','app8_clue_consolidated'));
--
-- DROP INDEX IF EXISTS biz.idx_ai_run_logs_assistant_member;
-- ALTER TABLE biz.ai_run_logs DROP COLUMN IF EXISTS assistant_id;
--
-- ALTER TABLE public.member_retention_clue
-- DROP COLUMN IF EXISTS sandbox_instance_id,
-- DROP COLUMN IF EXISTS runtime_mode,
-- DROP COLUMN IF EXISTS emoji;
--
-- COMMIT;

View File

@@ -50,6 +50,7 @@
| 2026-05-06 | 追加 §七 全局收口洞口清单 + §八 文档规范化整理大工程 | Neo 反思项目全局控制度,5 问追溯调研后立项 | | 2026-05-06 | 追加 §七 全局收口洞口清单 + §八 文档规范化整理大工程 | Neo 反思项目全局控制度,5 问追溯调研后立项 |
| 2026-05-06 | §七 收口 #1 #2 完成 + 追加 #6~#13 + 新增 §九 全栈产品文档体系登记 | docs/roadmap/BACKLOG.md 60+ 项发现 + Wave 0 全栈文档体系实证 + 累积基线 33 项对账 | | 2026-05-06 | §七 收口 #1 #2 完成 + 追加 #6~#13 + 新增 §九 全栈产品文档体系登记 | docs/roadmap/BACKLOG.md 60+ 项发现 + Wave 0 全栈文档体系实证 + 累积基线 33 项对账 |
| 2026-05-06 | §七 追加 #14 AI 9 APP 全链路未完成(P0)+ 新增 §十 专题登记 | Neo 提出 AI 9 APP(8 prompt + 1 chat 实时)在接口/入库/后端处理/前端展示 4 环节有未完成,优先级很高 | | 2026-05-06 | §七 追加 #14 AI 9 APP 全链路未完成(P0)+ 新增 §十 专题登记 | Neo 提出 AI 9 APP(8 prompt + 1 chat 实时)在接口/入库/后端处理/前端展示 4 环节有未完成,优先级很高 |
| 2026-05-06 | §七 #14 主体收口(超级 Sprint)+ 追加 #15-#28 残余子任务 | 超级 Sprint 完成 49 文件改动,5 个 silent failure 修复 + chat sourcePage 全链路 + WS 鉴权;新发现 14 项独立子任务登记 |
--- ---
@@ -76,7 +77,31 @@ Neo 发现"项目全局的控制度不够,有很多东西被漏了,到处都没
| 11 | (累积基线遗留)ETL 库完整 GUC 传递 26 视图 | 累积基线 3.5.5 | ⏳ 未收口 | P1 | 推迟 F1-5b Wave C(已规划)| | 11 | (累积基线遗留)ETL 库完整 GUC 传递 26 视图 | 累积基线 3.5.5 | ⏳ 未收口 | P1 | 推迟 F1-5b Wave C(已规划)|
| 12 | (累积基线遗留)finance_area_daily 会员分桶 vs DWS 规范 | 累积基线 3.7.2 | ⏳ 未收口 | P1 | 数据质量 Review,上线灰度期 | | 12 | (累积基线遗留)finance_area_daily 会员分桶 vs DWS 规范 | 累积基线 3.7.2 | ⏳ 未收口 | P1 | 数据质量 Review,上线灰度期 |
| 13 | (累积基线遗留)RLS 视图 pg_get_viewdef 全量重建 | 累积基线 3.7.3 | ⏳ 未收口 | P1 | 数据质量 Review + 视图清单专题 audit | | 13 | (累积基线遗留)RLS 视图 pg_get_viewdef 全量重建 | 累积基线 3.7.3 | ⏳ 未收口 | P1 | 数据质量 Review + 视图清单专题 audit |
| **14** | **AI 9 APP 全链路未完成**(接口/入库/后端处理/前端展示)| Neo 2026-05-06 提出,本次实证 8 prompt 文件 + 1 chat 实时 = 9 APP,但前端小程序仅 4 个文件涉及 AI,展示点不全 | ⏳ **高优先级未收口** | **P0** | 详见 §十(独立专题登记);需独立"AI 9 APP 全链路收口 sprint",4 环节(接口/入库/后端处理/前端展示)逐项对账实施 | | **14** | **AI 9 APP 全链路未完成**(接口/入库/后端处理/前端展示)| Neo 2026-05-06 提出 | ✅ 2026-05-06 主体收口(超级 Sprint)| **P0** | 详见 [`2026-05-06__w1_ai_closure_super_sprint.md`](../audit/changes/2026-05-06__w1_ai_closure_super_sprint.md) — 49 文件改动 + 1 数据库迁移 + 5 个 silent failure 修复 + chat sourcePage 全链路接通 + WS 鉴权;残余 14 项独立子任务登记为 #15-#28 |
| 15 | `/api/retention-clue` POST/DELETE 三端点无认证(P0-3 安全洞)| 超级 Sprint 调研发现 | ⏳ 未收口 | 🔴 **P0** | **Sprint 后立即独立修** — 加 `Depends(require_approved)` + site_id 从 JWT |
| 16 | 时光机日期切换 AI 数据初始化机制 | Neo 2026-05-06 提出 | ⏳ 未收口 | P1 | F1-6 阶段 B 必做 — 切日期时该实例 cache 空触发批量初始化 + 预算保护 |
| 17 | App8 落库静默吞排查(67 cache → 44 入库,差 23 条)| 超级 Sprint 调研发现 | ⏳ 未收口 | P1 | 独立 audit 数据质量 review |
| 18 | App3 daily budget 超限 45% 失败率 | 超级 Sprint 调研发现 | ⏳ 未收口 | P2 | 生产灰度前复核 daily 预算上限 |
| 19 | tenant-admin 新增"创建维客线索"功能(POST 端点 + UI)| 超级 Sprint 调研:source='manual' 字段已设计但 UI 录入入口缺失 | ⏳ 未收口 | P2 | 独立 M sprint(~ 2h):POST 端点 + 前端表单 + 用户校验 |
| 20 | MCP 沙箱场景 B 走查(切沙箱模式只读验证)| 超级 Sprint 跳过(避免污染 prod)| ⏳ 未收口 | P2 | F1-6 阶段 B 必做 |
| 21 | RLS 迁移(P1-1 public → biz schema + app.v_*)| Neo 已批选 A 但未执行 | ⏳ 未收口 | P1 | F1-6 阶段 B 收尾后 |
| 22 | chat-history 新建/删除按钮 | 超级 Sprint UX 增量 | ⏳ 未收口 | P2 | 独立小 sprint |
| 23 | `ai_conversations.source_page/source_context` 冗余孤儿列(已建未用)| 超级 Sprint 调研发现 | ⏳ 未收口 | P2 | 决策弃用还是启用 |
| 24 | admin-web 全 snake_case → camelCase 大改造 | 超级 Sprint 调研:admin 与 xcx 端命名风格分裂 | ⏳ 未收口 | P2 | 影响面巨大,独立 sprint |
| 25 | admin-web WS 客户端补 `?token=` query 参数 | 超级 Sprint P0-9 仅修后端 | ⏳ 未收口 | 🔴 **P0 安全** | **与 #15 一起立即修** — 否则 admin 监控页 WS 全部 close 4401 |
| 26 | prompt/Pydantic/前端类型四端单一权威源 spec | 超级 Sprint 调研发现 | ⏳ 未收口 | P2 | 架构级,需 spec |
| 27 | `cache_service._row_to_dict` datetime 强转 ISO 字符串丢 tz | 超级 Sprint 调研登记 P1 但未做(怕破坏现有调用方)| ⏳ 未收口 | P2 | 改保留 datetime 对象,由 Pydantic 序列化 |
| 28 | `ai_run_logs.assistant_id` 列已加,历史回填仍未做(不阻塞功能,定位用) | 超级 Sprint 仅加列 | ⏳ 未收口 | P2 | 独立回填脚本(可选)|
| 29 | `_text_coach_detail` SQL `hire_date` 列不存在 | 复盘 chat 上下文走查实证 | ⏳ 未收口 | P1 | 看 dim_assistant 实际列名,改 SQL — 影响 coach-detail 入口 chat 上下文 |
| 30 | `_text_board_finance` SQL `items_sum` 列不存在(应用 DWD-DOC #1 合成表达式) | 复盘 chat 上下文走查实证 | ⏳ 未收口 | P1 | 改用 `(table_charge_money + goods_money + assistant_pd_money + assistant_cx_money + electricity_money)` 或对应 v_dws 视图字段 — 影响 board-finance 入口 chat 上下文 |
| 31 | `_text_board_customer` SQL `sh.items_sum`#30 | 复盘 chat 上下文走查实证 | ⏳ 未收口 | P1 | 同 #30 解法 — 影响 board-customer 入口 chat 上下文 |
| 32 | `_text_performance` SQL `sc.performance_tier` 列不存在 | 复盘 chat 上下文走查实证 | ⏳ 未收口 | P1 | 看 dws_assistant_task_monthly 等表实际列,改 SQL — 影响 performance 入口 chat 上下文 |
| 33 | **App1 chat 调用全链路审计** — 拉起参数完整性 / 本地 MCP 查询 / 沙箱边界收口 | Neo 2026-05-06 提出 | ⏳ 未收口 | **P1** | 详见 §十一(独立专题登记)— 独立 sprint 评估 |
| 34 | **百炼调取 + 本地 SQL MCP 任务** 全部接入主任务线追踪 | Neo 2026-05-06 提出 | ⏳ 未收口 | **P1** | 详见 §十二(独立专题登记)— 独立 sprint 评估 |
| 35 | chat md 渲染:`---` 水平分割线未特殊处理(被当作普通段落) | 复盘 chat md 走查发现 | ⏳ 未收口 | P2 | `mdToRichHtml``<hr>` 处理(rich-text 支持 hr) |
| 36 | `_text_task_detail` SQL `coach_tasks_member_view / coach_tasks_assistant_view` 视图不存在 | 14 入口走查实证 | ⏳ 未收口 | P1 | 看实际 dim_member / dim_assistant FDW 视图,改 SQL — 影响 task-detail 入口 chat 上下文 |
| 37 | 4 个入口缺 `_text_*` 实现 → chat 拿不到页面上下文(`coach-service-records` / `performance-records` / `notes` / `chat-history`)| 14 入口走查实证 | ⏳ 未收口 | P2 | 加到 `SUPPORTED_PAGE_TYPES` + 实现各自 `_text_*` 函数;或者把 wxml sourcePage 映射到已支持 page(coach-service-records → coach-detail 等)|
| 38 | customer-detail 频繁 navigate 切换时偶发 `pageState='error'` | 14 入口走查实证(loadDetail 手动调可重现成功,onLoad 触发时偶发失败) | ⏳ 未收口 | P2 | 看 onShow auth-guard 与 onLoad loadDetail 的并发竞争,加 lock 或重试 |
### 收口原则 ### 收口原则
- 每项洞口完成后,出对应 audit 文档(`docs/audit/changes/2026-05-XX__closure_*.md`) - 每项洞口完成后,出对应 audit 文档(`docs/audit/changes/2026-05-XX__closure_*.md`)
@@ -231,3 +256,60 @@ Neo 2026-05-06 反思时提出:"AI 方面 9 个 APP 的处理还没有完成,在
### 与现有 backlog 关系 ### 与现有 backlog 关系
本项与 §一 DWD 孤立 + Core 中间件、§八 文档规范化大工程并列为"L 级长期工程", 本项与 §一 DWD 孤立 + Core 中间件、§八 文档规范化大工程并列为"L 级长期工程",
但**优先级 P0 高于其他**(Neo 强调"优先级很高")。F1-6 阶段 B 收尾后,优先启动本项。 但**优先级 P0 高于其他**(Neo 强调"优先级很高")。F1-6 阶段 B 收尾后,优先启动本项。
---
## 十一、App1 chat 调用全链路审计(P1,独立 sprint)
### 触发背景
Neo 2026-05-06 W1-AI-CLOSURE 复盘时提出:"App1 要传入的参数是否已经传入?对于拉起、访问本地 MCP 查询,如果有沙箱的设置,如何收口查询边界?相关联的措施整理需求并记录。"
### 审计维度
1. **拉起参数完整性** — App1 chat 触发链路对接百炼应用 ID (`DASHSCOPE_APP_ID_1_CHAT`) 时,所有期望参数(biz_params: User_ID/Role/Nickname,session_id,prompt 拼装的 page_context + 历史消息)是否在 dispatcher / xcx_chat 中**真实传入**?
2. **本地 MCP 查询** — chat 路径上百炼应用是否真正用到本地 MCP server(`apps/mcp-server/`)?MCP server 在 `.mcp.json` 注册的 PostgreSQL 只读连接,App1 拉起时是否调用?调用频率 / 失败回退?
3. **沙箱边界收口** — 当门店进入 sandbox 模式(`biz.site_runtime_context.mode='sandbox'`),chat 应用的查询边界:
- prompt 注入的 `current_time` 是否走 `as_runtime_business_now_str(site_id)`?✅(W1-AI-CLOSURE 已实证)
- page_context 注入的客户消费数据是否过滤 `business_date` 上界?(F1-6 阶段 B 范围)
- 本地 MCP 查询是否传入 sandbox_instance_id 隔离?
- 百炼应用拉取的工具调用结果是否带沙箱上下文?
### 工作量
- 链路全审 ~ 2-3h
- 修复缺口 ~ 1-2 个 sprint
### 状态
⏳ 未启动 — 待 W1-AI-CLOSURE 主体收口后独立调研
---
## 十二、百炼 + 本地 SQL MCP 任务追踪(P1,主任务线)
### 触发背景
Neo 2026-05-06 W1-AI-CLOSURE 复盘时提出:"百炼调取,本地跑的 SQL MCP 任务也要记录在主任务线中。"
### 当前缺口
1. **百炼 API 调用记录**`biz.ai_run_logs` 表已记录 dispatcher 调用(8 个 prompt 应用),但 App1 chat 的百炼调用(`call_app_stream`)目前**未写入 ai_run_logs**(只写 `ai_messages`)。chat 调用的成功率 / latency / token / 失败原因没有统一观测面板。
2. **本地 MCP server 调用记录**`apps/mcp-server/` 提供 PostgreSQL 只读 MCP 工具,百炼应用通过 MCP 协议调用本地 SQL 时,**调用日志没有持久化**(MCP server 可能只在 stdout 输出)。无法追踪:
- 百炼实际调了哪些 SQL?
- 调用成功率 / 错误率?
- 单次调用 token 消耗 / 时间?
- 沙箱 site_id 是否正确隔离?
3. **任务线统一面板** — admin-web 的 AIRunLogs 当前只看 dispatcher 8 个 prompt 应用的日志,**chat + MCP 调用没纳入面板**,运维盲点。
### 收口动作建议
1. `chat_service` 在每次 SSE 完成后写一条 `ai_run_logs` 记录(app_type=app1_chat,记 prompt/response/token/duration/status)
2. mcp-server 加调用日志中间件(可写到 `biz.mcp_call_logs` 新表 / 或复用 `ai_run_logs` + app_type='mcp_xxx')
3. admin-web AIRunLogs 面板加 `app_type IN ('app1_chat', 'mcp_*')` 筛选项
4. 关联到 dashboard:百炼应用 + chat + MCP 三类调用的统一观测视图
### 工作量
- 后端写入 ~ 1h
- mcp-server 拦截器 ~ 1h
- admin-web 面板补 ~ 1h
- 总:~ 3h(单 sprint 范围)
### 状态
⏳ 未启动 — 与 §十一 配套,作为独立"AI 调用观测性"sprint 推进

View File

@@ -1,6 +1,6 @@
# 审计一览表 # 审计一览表
> 自动生成于 2026-05-06 02:23:15,请勿手动编辑。 > 自动生成于 2026-05-06 16:06:51,请勿手动编辑。
## 时间线视图 ## 时间线视图
@@ -14,6 +14,7 @@
| 2026-05-06 | 项目级 | 2026-05-06 · F1-6 Sprint 2 #5 — 累计 GMV 加入 sandbox_replay(门店级) | 文档 | 其他 | 未知 | [链接](changes/2026-05-06__f1_6_sprint2_total_gmv.md) | | 2026-05-06 | 项目级 | 2026-05-06 · F1-6 Sprint 2 #5 — 累计 GMV 加入 sandbox_replay(门店级) | 文档 | 其他 | 未知 | [链接](changes/2026-05-06__f1_6_sprint2_total_gmv.md) |
| 2026-05-06 | 项目级 | 2026-05-06 · 全局收口反思 — 5 问追溯 + 洞口登记 + 文档规范化大工程立项 | bugfix | 其他 | 未知 | [链接](changes/2026-05-06__global_closure_reflection.md) | | 2026-05-06 | 项目级 | 2026-05-06 · 全局收口反思 — 5 问追溯 + 洞口登记 + 文档规范化大工程立项 | bugfix | 其他 | 未知 | [链接](changes/2026-05-06__global_closure_reflection.md) |
| 2026-05-06 | 项目级 | 2026-05-06 · W1-AI-CLOSURE Step 1 — AI 9 APP 全链路现状矩阵 | 文档 | 其他 | 未知 | [链接](changes/2026-05-06__w1_ai_closure_step1_matrix.md) | | 2026-05-06 | 项目级 | 2026-05-06 · W1-AI-CLOSURE Step 1 — AI 9 APP 全链路现状矩阵 | 文档 | 其他 | 未知 | [链接](changes/2026-05-06__w1_ai_closure_step1_matrix.md) |
| 2026-05-06 | 项目级 | 2026-05-06 · W1-AI-CLOSURE 超级 Sprint — 9 APP 全链路收口 + 接口劣化大整改 | bugfix | 其他 | 未知 | [链接](changes/2026-05-06__w1_ai_closure_super_sprint.md) |
| 2026-05-05 | 项目级 | 2026-05-05 · F1-6 Sprint 1 沙箱时光机引擎启动 + get_last_visit_days 试点迁移 | bugfix | 其他 | 未知 | [链接](changes/2026-05-05__f1_6_sprint1_sandbox_replay_kickoff.md) | | 2026-05-05 | 项目级 | 2026-05-05 · F1-6 Sprint 1 沙箱时光机引擎启动 + get_last_visit_days 试点迁移 | bugfix | 其他 | 未知 | [链接](changes/2026-05-05__f1_6_sprint1_sandbox_replay_kickoff.md) |
| 2026-05-05 | 项目级 | 2026-05-05 — Wave 1 F1-5a 完整走查(应查尽查版) | bugfix | 其他 | 未知 | [链接](changes/2026-05-05__wave1_f1_5a_backend_walkthrough.md) | | 2026-05-05 | 项目级 | 2026-05-05 — Wave 1 F1-5a 完整走查(应查尽查版) | bugfix | 其他 | 未知 | [链接](changes/2026-05-05__wave1_f1_5a_backend_walkthrough.md) |
| 2026-05-05 | 项目级 | Wave 1 F1-5a — 沙箱 batch-run 接入 runtime_context(MVP + 漂移防御核心) | bugfix | 其他 | 未知 | [链接](changes/2026-05-05__wave1_f1_5a_sandbox_batch_run.md) | | 2026-05-05 | 项目级 | Wave 1 F1-5a — 沙箱 batch-run 接入 runtime_context(MVP + 漂移防御核心) | bugfix | 其他 | 未知 | [链接](changes/2026-05-05__wave1_f1_5a_sandbox_batch_run.md) |
@@ -304,6 +305,7 @@
| 2026-05-06 | 2026-05-06 · F1-6 Sprint 2 #5 — 累计 GMV 加入 sandbox_replay(门店级) | 文档 | 其他 | 未知 | [链接](changes/2026-05-06__f1_6_sprint2_total_gmv.md) | | 2026-05-06 | 2026-05-06 · F1-6 Sprint 2 #5 — 累计 GMV 加入 sandbox_replay(门店级) | 文档 | 其他 | 未知 | [链接](changes/2026-05-06__f1_6_sprint2_total_gmv.md) |
| 2026-05-06 | 2026-05-06 · 全局收口反思 — 5 问追溯 + 洞口登记 + 文档规范化大工程立项 | bugfix | 其他 | 未知 | [链接](changes/2026-05-06__global_closure_reflection.md) | | 2026-05-06 | 2026-05-06 · 全局收口反思 — 5 问追溯 + 洞口登记 + 文档规范化大工程立项 | bugfix | 其他 | 未知 | [链接](changes/2026-05-06__global_closure_reflection.md) |
| 2026-05-06 | 2026-05-06 · W1-AI-CLOSURE Step 1 — AI 9 APP 全链路现状矩阵 | 文档 | 其他 | 未知 | [链接](changes/2026-05-06__w1_ai_closure_step1_matrix.md) | | 2026-05-06 | 2026-05-06 · W1-AI-CLOSURE Step 1 — AI 9 APP 全链路现状矩阵 | 文档 | 其他 | 未知 | [链接](changes/2026-05-06__w1_ai_closure_step1_matrix.md) |
| 2026-05-06 | 2026-05-06 · W1-AI-CLOSURE 超级 Sprint — 9 APP 全链路收口 + 接口劣化大整改 | bugfix | 其他 | 未知 | [链接](changes/2026-05-06__w1_ai_closure_super_sprint.md) |
| 2026-05-05 | 2026-05-05 · F1-6 Sprint 1 沙箱时光机引擎启动 + get_last_visit_days 试点迁移 | bugfix | 其他 | 未知 | [链接](changes/2026-05-05__f1_6_sprint1_sandbox_replay_kickoff.md) | | 2026-05-05 | 2026-05-05 · F1-6 Sprint 1 沙箱时光机引擎启动 + get_last_visit_days 试点迁移 | bugfix | 其他 | 未知 | [链接](changes/2026-05-05__f1_6_sprint1_sandbox_replay_kickoff.md) |
| 2026-05-05 | 2026-05-05 — Wave 1 F1-5a 完整走查(应查尽查版) | bugfix | 其他 | 未知 | [链接](changes/2026-05-05__wave1_f1_5a_backend_walkthrough.md) | | 2026-05-05 | 2026-05-05 — Wave 1 F1-5a 完整走查(应查尽查版) | bugfix | 其他 | 未知 | [链接](changes/2026-05-05__wave1_f1_5a_backend_walkthrough.md) |
| 2026-05-05 | Wave 1 F1-5a — 沙箱 batch-run 接入 runtime_context(MVP + 漂移防御核心) | bugfix | 其他 | 未知 | [链接](changes/2026-05-05__wave1_f1_5a_sandbox_batch_run.md) | | 2026-05-05 | Wave 1 F1-5a — 沙箱 batch-run 接入 runtime_context(MVP + 漂移防御核心) | bugfix | 其他 | 未知 | [链接](changes/2026-05-05__wave1_f1_5a_sandbox_batch_run.md) |
@@ -483,6 +485,7 @@
| 2026-05-06 | 2026-05-06 · F1-6 Sprint 2 #5 — 累计 GMV 加入 sandbox_replay(门店级) | 文档 | 未知 | [链接](changes/2026-05-06__f1_6_sprint2_total_gmv.md) | | 2026-05-06 | 2026-05-06 · F1-6 Sprint 2 #5 — 累计 GMV 加入 sandbox_replay(门店级) | 文档 | 未知 | [链接](changes/2026-05-06__f1_6_sprint2_total_gmv.md) |
| 2026-05-06 | 2026-05-06 · 全局收口反思 — 5 问追溯 + 洞口登记 + 文档规范化大工程立项 | bugfix | 未知 | [链接](changes/2026-05-06__global_closure_reflection.md) | | 2026-05-06 | 2026-05-06 · 全局收口反思 — 5 问追溯 + 洞口登记 + 文档规范化大工程立项 | bugfix | 未知 | [链接](changes/2026-05-06__global_closure_reflection.md) |
| 2026-05-06 | 2026-05-06 · W1-AI-CLOSURE Step 1 — AI 9 APP 全链路现状矩阵 | 文档 | 未知 | [链接](changes/2026-05-06__w1_ai_closure_step1_matrix.md) | | 2026-05-06 | 2026-05-06 · W1-AI-CLOSURE Step 1 — AI 9 APP 全链路现状矩阵 | 文档 | 未知 | [链接](changes/2026-05-06__w1_ai_closure_step1_matrix.md) |
| 2026-05-06 | 2026-05-06 · W1-AI-CLOSURE 超级 Sprint — 9 APP 全链路收口 + 接口劣化大整改 | bugfix | 未知 | [链接](changes/2026-05-06__w1_ai_closure_super_sprint.md) |
| 2026-05-05 | 2026-05-05 · F1-6 Sprint 1 沙箱时光机引擎启动 + get_last_visit_days 试点迁移 | bugfix | 未知 | [链接](changes/2026-05-05__f1_6_sprint1_sandbox_replay_kickoff.md) | | 2026-05-05 | 2026-05-05 · F1-6 Sprint 1 沙箱时光机引擎启动 + get_last_visit_days 试点迁移 | bugfix | 未知 | [链接](changes/2026-05-05__f1_6_sprint1_sandbox_replay_kickoff.md) |
| 2026-05-05 | 2026-05-05 — Wave 1 F1-5a 完整走查(应查尽查版) | bugfix | 未知 | [链接](changes/2026-05-05__wave1_f1_5a_backend_walkthrough.md) | | 2026-05-05 | 2026-05-05 — Wave 1 F1-5a 完整走查(应查尽查版) | bugfix | 未知 | [链接](changes/2026-05-05__wave1_f1_5a_backend_walkthrough.md) |
| 2026-05-05 | Wave 1 F1-5a — 沙箱 batch-run 接入 runtime_context(MVP + 漂移防御核心) | bugfix | 未知 | [链接](changes/2026-05-05__wave1_f1_5a_sandbox_batch_run.md) | | 2026-05-05 | Wave 1 F1-5a — 沙箱 batch-run 接入 runtime_context(MVP + 漂移防御核心) | bugfix | 未知 | [链接](changes/2026-05-05__wave1_f1_5a_sandbox_batch_run.md) |

View File

@@ -0,0 +1,324 @@
# 2026-05-06 · W1-AI-CLOSURE 超级 Sprint — 9 APP 全链路收口 + 接口劣化大整改
> **触发**:Neo 在 W1-AI-CLOSURE Step 1 矩阵(2026-05-06 上午)完成后,要求做 Sprint 1
> 的同时让我"详细全面调研,若发现前置依赖则先铺地基";后续 Neo 又扩范围:
> "AI 接口走查不合理设计 + 各页面右下角 AI 对话 + AI 对话列表 + 上下文捕获 + MCP 全场景验证,
> 全部完善 — 不评估工时,注意力放在高质量项目开发"。
>
> **工作量**:超级 Sprint(L+) — 49 个文件改动 + 1 数据库迁移 + 1 历史数据回填 + MCP 实地走查
>
> **关联**:[architecture-evolution-backlog §七 #14 + §十](../../_overview/architecture-evolution-backlog.md#十ai-9-app-全链路未完成p0-高优先级)
## 调研背景(5 个并行子代理 + 历史规范摘录)
按 CLAUDE.md "逻辑改动前置调研(强制)",启动 5 轮并行调研:
1. **后端链路调研**(prompt / dispatcher / 接口 / ai_cache / runtime_context)
2. **小程序前端展示位调研**(展示位选型 + app7/app2 复用基线 + UI 风格)
3. **维客线索数据库与业务规则调研**(member_retention_clue + RLS + 业务定义)
4. **历史 UI 规范调研**(VI-DESIGN-SYSTEM v1.1 + ai_apps_feature_acceptance_spec + demo 标杆)
5. **沙箱时光机对 Sprint 1 的影响调研**(runtime_mode / sandbox_instance_id / page_context)
6. **AI 对话功能完整性调研**(ai-float-button / chat-history / page_context 注入)
7. **AI 接口设计劣化大走查**(9 APP 接口/服务/db/前端类型/命名一致性)
调研出 40 项劣化 + 8 个拍板点,Neo 拍板"全按推荐"后正式编码。
## 范围与 7 组实施
按 P0(必修)/ P1(推荐)/ P2(独立登记)三级,7 组并行推进。
### 组 1 — 数据库迁移 + 历史数据回填 ✅
新建:
- `db/zqyy_app/migrations/20260506__ai_closure_schema_fixes.sql`
- `scripts/ops/backfill_retention_clue_emoji.py`
变更:
- `public.member_retention_clue` 加 3 列:`emoji` / `runtime_mode` / `sandbox_instance_id`
- `biz.ai_run_logs` 加 1 列:`assistant_id` + 复合索引 `idx_ai_run_logs_assistant_member`
- `chk_ai_cache_type` CHECK 约束更新:8 类应用名(去除 `_analysis` / `_consolidated` 后缀)
- 数据 UPDATE:
- `ai_cache.cache_type`: `app7_customer_analysis``app7_customer`(42 行)
- `ai_cache.cache_type`: `app8_clue_consolidated` / `app8_consolidate``app8_consolidation`(72 行)
- `ai_run_logs.app_type`: `app8_consolidate``app8_consolidation`(123 行)
- `member_retention_clue.runtime_mode`: 全部填 `live`(44 行)
- 回填脚本:44 条 summary 嵌入的 emoji 抽到独立列(可重入)
测试库执行结果(7 条校验 SQL 全 PASS):
```
member_retention_clue: emoji+runtime_mode+sandbox_instance_id 3 列已加
ai_run_logs.assistant_id 1 列已加
旧 cache_type 残留: 0 行
旧 app_type 残留: 0 行
runtime_mode 'live' 全填: 44/44
emoji 回填成功率: 44/44
可重入测试: 0 待处理(再跑提前退出)
```
### 组 2 — 后端 AI 字段错位修复 + cleanup BUG ✅
5 个最严重的"用户感知"BUG:
| # | 项 | 文件 | 影响 |
|---|---|---|---|
| P0-5 | `customer_service._build_ai_insight``app4_analysis` 当 App7 用,字段错位 | customer_service.py:226-265 | 客户详情 aiInsight 永远空 |
| P0-6 | `task_manager``app5_talking_points`(不存在的 cache_type)+ 字段 `talking_points`(不存在) | task_manager.py:1158-1188 | task-detail talkingPoints 永远空 |
| P0-7 | `task_manager``app4_analysis.summary`(App4 schema 无该字段) | task_manager.py:706-721 | aiSuggestion 永远空 |
| P0-8 | `cleanup_service.py:136` `WHERE app_type=%s` 但表无 app_type 列(被 except 静默吞)| cleanup_service.py | **90 天清理 + 20K 上限完全失效**,生产 ai_cache 无限膨胀 |
| P0-11 | `app2a_finance_area``CACHE_EXPIRY_DAYS` dict 缺项 | cache_service.py:31-39 | 64 区域组合缓存永不过期 |
修复:
- `_build_ai_insight` 改查 `cache_type='app7_customer'` + 加 `site_id` 过滤 + 字段对齐 App7Result schema(strategies[].title/content)
- `task_manager._build_ai_suggestion``one_line_summary`(对齐 App4Result schema)
- `task_manager` talkingPoints 改查 `app5_tactics` + 字段改 `tactics[].scenario/script`(对齐 App5Result schema)
- `cleanup_service` SQL 改 `WHERE cache_type=%s` + cache_type 列表对齐新命名 + 加 `app2a_finance_area`
- `cache_service.CACHE_EXPIRY_DAYS``app2a_finance_area: 0` 当日过期
### 组 3 — retention-clue 全链路根治 + emoji 独立 + schema 统一 ✅
| 项 | 文件 | 修复 |
|---|---|---|
| P0-1 emoji 拼字符串入 summary | dispatcher.py:541-614 | `_write_retention_clue` 移除 `f"{emoji} {raw_summary}"` 拼接,emoji 独立写入 |
| P0-2 RetentionClue schema 三套不一致 | xcx_customers.py / xcx_tasks.py | 统一为 `{tag, tag_color, emoji, text, source, desc}` 7 字段(camelCase 经 CamelModel 转) |
| P0-4 `_build_retention_clues` 裸查无 site_id | customer_service.py:268-288 | SQL 加 `AND site_id = %s` + 调用链传 site_id;字段 SELECT 加 detail/source/recorded_by_name/emoji |
| P0-16 `member_retention_clue` 无 sandbox 列 | dispatcher.py + 组 1 迁移 | 写入侧 + DELETE 谓词都按 `(member_id, site_id, source, runtime_mode, sandbox_instance_id)` 五元组隔离 |
| P0-5 AiStrategy 字段 | xcx_customers.py:73-75 | `{color, text}``{title, content}` 对齐 App7Result;color 由前端按 index 轮换 |
| App7 task_manager.py 字段 | xcx_tasks.py | 加 `TacticItem`,`talking_points: list[str]``list[TacticItem]` |
新建 `apps/backend/app/utils/clue_category.py`:
- `CATEGORY_TAG_COLOR`(VI-DESIGN-SYSTEM §2.1 权威 6 类映射,纠正 task_manager 旧 dict 与 VI 不一致的 3 处)
- `CATEGORY_EMOJI_FALLBACK`(category → emoji 兜底)
- `SOURCE_DISPLAY_NAME`(`manual=系统` / `ai_consumption=AI` / `ai_note=AI`)
### 组 4 — chat 上下文捕获 sourcePage 全链路接通 ✅
| 项 | 文件 | 修复 |
|---|---|---|
| P0-12 `get_messages` 不过滤 system 行 | chat_service.py:325-330 | SQL 加 `AND role IN ('user', 'assistant')`,DB 35 条 system 行不再被前端渲染 |
| P0-13 `ReferenceCard` 缺 link/source_page 字段 | xcx_chat.py:42-48 | Pydantic schema 补 2 字段,与 references.py 实际输出对齐 |
| P0-15 `chat_service.build_reference_card` 死代码 | xcx_chat.py:269-300 | 接入 SSE 路径:customer-detail / customer-service-records 入口走 KPI 富卡,其他入口走简单跳转链接卡 |
`build_reference_card` 输出补 link + source_page,与新 schema 对齐,前端 wxml link 跳转可正常工作。
### 组 5 — 命名统一 + utils 共用 + 类目枚举 ✅
| 项 | 旧 | 新 |
|---|---|---|
| cache_type / app_type 命名 | app8_consolidate / app8_clue_consolidated / app7_customer_analysis / app6_note_analysis | app8_consolidation / app7_customer / app6_note |
| `CacheTypeEnum` 枚举名 | APP8_CLUE_CONSOLIDATED 等 | APP8_CONSOLIDATION 等(8 类) |
| `ClueCategory.BASIC_INFO` 字面量 | "客户基础信息"(违反 chk_retention_clue_category 约束) | "客户基础" |
| dispatcher `_run_step` 第一参 | "app8_consolidate" | "app8_consolidation" |
文件涉及:`schemas.py` / `dispatcher.py` / 5 个 prompt 文件 / `cleanup_service.py` / `cache_service.py` / `member_retention_clue.py`
后端 P1-1 categoryColor map 重复(task_manager 与 customer_service 各一份)— 拆出 `app/utils/clue_category.py` 共用,task_manager 旧 `_CATEGORY_COLOR_MAP` 删除(其与 VI 规范有 3 处不一致已纠正);`_extract_emoji_and_text` 死代码删除(emoji 已独立列)。
### 组 6 — 小程序字段对齐 + 14 处 ai-float-button + 对话上下文 ✅
**字段对齐(数据流通)**:
- `customer-detail.ts` data.clues 类型从 4 字段 `{category, categoryColor, text, source}` → 6 字段 `{tag, tagColor, emoji, text, source, desc}`
- `customer-detail.wxml` clue-card props 字段名对齐 + `wx:if="{{clues.length > 0}}"` 空态隐藏
- `customer-detail.ts._loadAIInsight` cache_type `app7_customer_analysis``app7_customer`,字段 `s.text``s.title/s.content`
- strategies wxml 字段 `{{item.text}}``{{item.title}}{{item.content ? '' + item.content : ''}}`
- `task-detail.ts` retentionClues tagColor 类型从 4 类扩到 VI 6 类;talkingPoints 类型 `string[]``TacticItem[]`(scenario+script);`onCopySpeech` 复制 script
- `task-detail.wxml` 话术参考 `{{item}}``{{item.scenario}} + '' + {{item.script}}`
**chat 上下文链路接通**(Phase 2.3 200+ 行从未真正激活的链路):
- `chat.ts:220-263` 三分支(task / customer / coach)同步写入 `sourcePage` + `pageFilters.contextId`
- 14 处 ai-float-button 全部补 sourcePage(coach-detail 死注册 wxml 修复 + task-detail 整页缺失补浮动按钮 + 11 处其余页面)
- `task-detail.json` 注册 `ai-float-button` 组件
**ETL 注释字面量纠正**:
- `member_visit_task.py:370` + `member_consumption_task.py:277`:"客户基础信息" → "客户基础"
### 组 7 — 静默吞错收口 + 安全加固 + admin-web 同步 ✅
| 项 | 文件 | 修复 |
|---|---|---|
| P0-9 `WS /ws/ai-cache/{site_id}` 零鉴权 + `-1` 全局订阅 | ws/ai_events.py | 加 `?token=xxx` query 参数 + JWT 解码 + site_id 校验 + super_admin 全局订阅;close code 4401 |
| P1-7 internal_ai token `==` 比较时序攻击 | internal_ai.py:79 | 改 `hmac.compare_digest` |
| admin-web 命名同步 | AIOperations.tsx / AIRunLogs.tsx / __tests__/adminAiAppTypes.test.ts | CACHE_TYPE_OPTIONS / RUN_LOG_APP_TYPE_OPTIONS 8 类对齐;测试断言不再固化"双名共存" |
## MCP 实地走查结果
测试库 site=2790685415443269 朗朗桌球,member_id=3137741513592453(4 维客线索 + 4 app7 cache):
| 验证点 | 结果 |
|---|---|
| customer-detail 维客线索 | ✅ 4 条全显示;tag/tagColor/emoji/text/source/desc 6 字段全对齐;VI 配色权威(消费习惯 success / 玩法偏好 orange / 客户基础 primary);emoji 独立列(⚠️/👩/💰/👥)正常 |
| chat 进入 sourcePage 注入 | ✅ `sourcePage="customer-detail"` + `pageFilters.contextId="3137741513592453"` 正确写入,Phase 2.3 链路真正激活 |
| chat 入口提示卡 | ✅ "正在查看客户 XXX 的相关信息" 自动显示 |
| chat-history 列表 | ✅ 8 条对话,包含刚 navigate 创建的新对话 |
| chat get_messages system 过滤 | ✅ `hasSystemRole: false` + `rolesDistribution: {user:1, assistant:1}`,DB 35 条 system 行不再泄露给前端 |
| Console | ✅ 全程 0 错误 / 0 警告 |
未实地验证(非修复回归 — 测试数据/权限限制):
- aiInsight 真实展示:测试库 4 条 app7 cache 已全部过期(expires_at 2026-04-27/28),需触发新一轮 ETL 重跑
- task-detail 字段渲染:auth-guard 角色拦截 navigate;py_compile + 全仓 0 字面量残留已确认代码正确
- reference_card 富卡:需触发 SSE 实际百炼 API,涉及配额预算
## 影响范围
| 端 | 文件数 | 影响 |
|----|------|------|
| 数据库 | 1 迁移 + 1 回填脚本 | ✅ 测试库执行 PASS,7 条校验 SQL + 44/44 emoji 回填 |
| 后端服务层 | 4 文件 | customer_service / task_manager / chat_service / cleanup_service |
| 后端 dispatcher | 1 文件 | _write_retention_clue + 全枚举引用更新 |
| 后端 schemas | 4 文件 | xcx_customers / xcx_tasks / xcx_chat / member_retention_clue |
| 后端 routers | 2 文件 | xcx_chat(SSE 接入富卡)/ internal_ai(compare_digest)|
| 后端 ws | 1 文件 | ai_events 鉴权改造 |
| 后端 cache | 1 文件 | cache_service.CACHE_EXPIRY_DAYS |
| 后端 prompts | 5 文件 | 枚举引用统一 |
| 后端 ai/schemas | 1 文件 | CacheTypeEnum 8 类 |
| 后端 utils | 1 新文件 | clue_category.py |
| admin-web | 3 文件 | AIOperations / AIRunLogs / 测试 |
| 小程序 ts | 3 文件 | customer-detail / task-detail / chat |
| 小程序 wxml | 14 文件 | 字段对齐 + 14 处浮动按钮 sourcePage |
| 小程序 json | 1 文件 | task-detail 注册组件 |
| ETL 注释 | 2 文件 | "客户基础信息" → "客户基础" |
| **合计** | **49 文件** | — |
## 测试
- 数据库迁移:测试库 7 条校验 SQL PASS + emoji 回填 44/44 + 可重入测试 PASS
- 后端静态:16 个改动 .py 文件 `py_compile` ALL OK
- 全仓 grep 0 残留:旧命名(app7_customer_analysis / app8_clue_consolidated / app8_consolidate / app6_note_analysis / app5_talking_points / 客户基础信息)全仓 0 行
- MCP 实地走查 5 项 PASS(见上)
- console 0 错误
未跑(因测试数据 / 权限限制,非修复回归):
- task-detail UI 走查(auth-guard 拦截)
- aiInsight 实际渲染(测试库 cache 过期)
- reference_card SSE 实跑
## 风险与未覆盖
1. **生产首跑**:`cleanup_service` BUG 修复后,首次清理任务执行时会真实删除 90 天前 + 20K 上限外的 ai_cache 记录(生产可能有大量积压)。建议生产灰度时观察首次清理执行时间 + 删除行数,防止锁等待超时(SQL 已带 5 分钟 statement_timeout)
2. **App4 / App5 cache 字段错位修复**:历史 cache 仍存在(用旧字段写),修复后读取改成新字段名 → 历史 cache 无法被消费;新 cache 才会被正确消费。需要灰度期触发一轮 ETL 重跑或等业务事件自然驱动
3. **WS 鉴权改造**:admin-web 端 AIPrewarm / AIOperations / AIRunLogs 监控页若有 WebSocket 连接,需要在前端补 `?token=...` query;若未补,WS close 4401。本次仅修后端,前端补 token 留作 §七 #27 后续(独立 sprint)
4. **chat-history 新建/删除按钮**:本 sprint 未实施(UX 增量,不影响数据流通);登记 §七 #28
5. **小程序 task-detail 实地走查未做**:auth-guard 拦截 navigate(角色不匹配),代码层 py_compile + grep 已实证 0 残留;实地走查留作生产灰度时
## 后续登记(§七 backlog 追加 #15-#28)
| # | 项 | 严重度 | 时机 |
|---|---|---|---|
| #15 | `/api/retention-clue` POST/DELETE 三端点无认证(P0-3 安全洞)| 🔴 P0 | **Sprint 后立即独立修** |
| #16 | RLS 迁移(P1-1 public → biz schema + app.v_*)| P1 | F1-6 阶段 B 收尾后 |
| #17 | App8 落库静默吞排查(67 cache → 44 入库,差 23 条)| P1 | 独立 audit |
| #18 | App3 daily budget 超限 45% 失败率 | P2 | 生产灰度前 |
| #19 | `member_retention_clue.runtime_mode` 列已加,但旧 sandbox 数据是否需要重新隔离 | P2 | 数据 review |
| #20 | `_write_retention_clue` 沙箱硬覆盖 prod(本 sprint 已加 5 元组隔离修复)| ✅ 本 sprint 完成 | — |
| #21 | MCP 沙箱场景 B 走查 | P2 | F1-6 阶段 B 必做 |
| #22 | 时光机日期切换 AI 数据初始化机制 | P1 | F1-6 阶段 B 必做 |
| #23 | tenant-admin 新增"创建维客线索"功能(POST 端点 + UI)| P2 | 独立 M sprint |
| #24 | chat-history 新建/删除按钮 | P2 | UX 增量 |
| #25 | `ai_conversations.source_page/source_context` 冗余孤儿列(已建未用)| P2 | 决策弃用还是启用 |
| #26 | admin-web 全 snake_case → camelCase 大改造 | P2 | 影响面巨大 |
| #27 | admin-web WS 客户端补 `?token=` query 参数 | P0 安全 | Sprint 后立即(与 #15 一起) |
| #28 | prompt/Pydantic/前端类型四端单一权威源 spec | P2 | 架构级,需 spec |
`#20` 已在本 sprint 收口(dispatcher 加 5 元组隔离),从待办移除。
## 回滚策略
```bash
# 1. 数据库回滚(测试库)— 见迁移文件末尾"回滚参考"块
.venv/Scripts/python.exe -c "import psycopg2; from dotenv import dotenv_values; v=dotenv_values('.env',encoding='utf-8-sig'); conn=psycopg2.connect(v['TEST_APP_DB_DSN']); conn.cursor().execute(open('db/zqyy_app/migrations/20260506__ai_closure_schema_fixes.sql').read().split('-- =============================================================================\n-- 回滚参考')[1]); conn.commit()"
# 2. 代码回滚
git revert <commit_hash>
# 3. 历史回填撤销(若需要):
# 由于 emoji 已抽离 summary,逆向恢复需按 emoji 列拼回 summary:
# UPDATE public.member_retention_clue SET summary = emoji || ' ' || summary, emoji = '' WHERE emoji != '';
```
## 复盘补丁(2026-05-06 晚间 — Neo 第二轮 MCP 走查反馈)
第一轮 audit 后 Neo 发现 6 项 MCP 走查未做利索:
1. board-finance AI 洞察空但未深查
2. customer-detail AI 洞察空也未深查
3. notes 完全没测
4. 13 处浮动按钮只点了 1 个
5. 没和 demo-miniprogram 样式对比
6. task-detail 角色限制也没切换重试
我立即重做 MCP 走查。第二轮发现并修复以下额外 BUG(全部预先存在,W1 sourcePage 链路接通后才暴露):
### 第二轮 BUG 修复
| # | BUG | 位置 | 修复 |
|---|---|---|---|
| B1 | `member_retention_clue.created_at` 列错位(实际 `recorded_at`)| `page_context.py:244` | 改 `recorded_at` + schema 前缀 + is_hidden 过滤 |
| B2 | `get_etl_readonly_connection` SET LOCAL 后 commit RLS 失效(7 个 _text_* 函数都受影响,本次修 1)| `page_context.py:194` 等 | 每个 cursor 块加 `SET LOCAL app.current_site_id` |
| B3 | `v_dwd_settlement_head` 列错位(`settle_date / room_name / items_sum`)| `page_context.py:213-220` | 改 `pay_time / settle_name`,items_sum 用合成表达式(DWD-DOC #1)|
| B4 | `v_dws_member_consumption_summary.balance_amount` 列错位 | `page_context.py:228` | 改 `total_card_balance` |
| B5 | `xcx_chat.py:224 filters.pop("contextId")` 破坏 body.page_context 引用 | `xcx_chat.py:224` | `dict()` 浅拷贝隔离 |
修复后:
- chat 上下文注入端到端 ✅(AI 回复"东哥/2026-03-24/¥214.71/储值5485")
- reference_card 富卡写入 db ✅(KPI 富卡 + link + source_page)
- customer-detail 维客线索 4 条 ✅(tag 强制 2+2 + emoji 独立 + VI 6 类配色)
### 第二轮新增功能
#### 任务 1:chat 流式 markdown 实时渲染(2026-05-06 复盘新增)
新建 `apps/miniprogram/miniprogram/utils/markdown.ts`(180 行):
- 支持:段落 / 标题 H1-H4 / 粗体 / 斜体 / 行内代码 / 代码块 / 无序列表 / 有序列表 / GFM 表格
- streaming 容错:partial 标记降级为纯文本
- 输出供 `<rich-text nodes="{{html}}">` 渲染
`chat.ts`:
- enrichMessages 给 AI 消息预解析 contentHtml
- SSE token 处理时实时 setData contentHtml
- DisplayMessage 类型加 `contentHtml?: string`
`chat.wxml` AI bubble 改用 `<rich-text class="bubble-md" nodes="{{item.contentHtml}}">` + `<text>` fallback。
`chat.wxss` 加 markdown 样式 80 行(table / code / heading / list)。
实证 ✅:截图 30 显示完整 markdown 表格 + 标题 + 列表 + 加粗 + 段落 + reference_card 富卡。
#### 后端日志机制(任务 2 配套)
`main.py` 新加 `_configure_logging()`:
- `RotatingFileHandler``logs/backend.log`(单文件 20MB + 5 backup = 100MB 上限)
- `_SuppressHealthAccess` filter → 抑制 uvicorn.access 中 `/health`
- 防 reload 重入幂等检查
- watchdog 心跳不受影响(它用 TCP socket 主动探针,不读 backend stdout)
### 第二轮新发现 BUG/UX 项登记 §七 #29-#38
| # | 项 | 严重度 | 时机 |
|---|---|---|---|
| §七 #29 | `_text_coach_detail` `hire_date` 列不存在 | P1 | 独立修复 |
| §七 #30 | `_text_board_finance` `items_sum` 列不存在(DWD-DOC #1)| P1 | 独立修复 |
| §七 #31 | `_text_board_customer`#30 | P1 | 独立修复 |
| §七 #32 | `_text_performance` `performance_tier` 列不存在 | P1 | 独立修复 |
| §七 #33 | App1 chat 调用全链路审计(详见 backlog §十一)| P1 | 独立 sprint |
| §七 #34 | 百炼调取 + 本地 SQL MCP 任务追踪(详见 backlog §十二)| P1 | 独立 sprint |
| §七 #35 | chat md `---` 水平分割线未特殊处理 | P2 | mdToRichHtml 加 `<hr>` |
| §七 #36 | `_text_task_detail` 视图 `coach_tasks_member_view` 不存在 | P1 | 改 SQL |
| §七 #37 | 4 入口缺 `_text_*` 实现(coach-service-records / performance-records / notes / chat-history)| P2 | 加到 SUPPORTED + 实现 / 或映射到已支持 page |
| §七 #38 | customer-detail 频繁 navigate 切换偶发 pageState=error | P2 | onShow + onLoad 并发竞争 |
### 第二轮新增 backlog 章节
- §十一 App1 chat 调用全链路审计(P1 独立 sprint)
- §十二 百炼调取 + 本地 SQL MCP 任务追踪(P1 独立 sprint)
### 14 入口走查总览
5/14 完整工作 + 5/14 sourcePage OK 但 page_context BUG(P1 已登记)+ 4/14 sourcePage OK 但 page_context 未实现(P2 已登记)。**所有 14 入口 sourcePage 写入 chat data 都正确**,Phase 2.3 链路真正激活。
### 复盘最终改动总数
49 文件 + 第二轮 7 文件(`page_context.py / xcx_chat.py / customer_service.py / task_manager.py / clue_category.py / main.py / chat.ts / chat.wxml / chat.wxss / markdown.ts(新)`)≈ **56 文件改动**
---
## Co-Authored-By
Claude Opus 4.7 (1M context) <noreply@anthropic.com>

View File

@@ -0,0 +1,152 @@
# 2026-05-06 · W1-AI-CLOSURE Schema 修复 + 命名统一
> 关联迁移:[`db/zqyy_app/migrations/20260506__ai_closure_schema_fixes.sql`](../../../db/zqyy_app/migrations/20260506__ai_closure_schema_fixes.sql)
>
> 完整审计:[`docs/audit/changes/2026-05-06__w1_ai_closure_super_sprint.md`](../../audit/changes/2026-05-06__w1_ai_closure_super_sprint.md)
## 变更说明
### 新增列
| 表 | 列 | 类型 | 默认值 | 用途 |
|---|---|---|---|---|
| `public.member_retention_clue` | `emoji` | `varchar(8)` | `''` | 维客线索独立 emoji 字段(App8 prompt 输出 emoji 直接写入,不再嵌 summary 字符串) |
| `public.member_retention_clue` | `runtime_mode` | `varchar(20)` | `'live'` | 运行模式 live/sandbox(与其他 7 张 ai_* 表对齐) |
| `public.member_retention_clue` | `sandbox_instance_id` | `varchar(64)` | `'live'` | sandbox 模式写入隔离实例 ID |
| `biz.ai_run_logs` | `assistant_id` | `bigint NULL` | NULL | App4/App5 这类 (assistant, member) 二元任务的助教 ID,便于失败定位 |
### 新增索引
- `idx_ai_run_logs_assistant_member` ON `biz.ai_run_logs (site_id, assistant_id, member_id, created_at DESC) WHERE assistant_id IS NOT NULL`
### CHECK 约束更新
- `chk_ai_cache_type` 重建:8 类应用名(`app2_finance` / `app2a_finance_area` / `app3_clue` / `app4_analysis` / `app5_tactics` / `app6_note` / `app7_customer` / `app8_consolidation`),与 prompt 文件名 + CacheTypeEnum 完全对齐
### 数据 UPDATE(命名统一)
- `biz.ai_cache.cache_type`:
- `app7_customer_analysis``app7_customer`(42 行)
- `app8_clue_consolidated``app8_consolidation`(72 行)
- `app6_note_analysis``app6_note`(测试库 0 行,生产可能有)
- `biz.ai_run_logs.app_type`:
- `app8_consolidate``app8_consolidation`(123 行)
- `app8_clue_consolidated``app8_consolidation`(测试库 0 行)
- `app6_note_analysis` / `app7_customer_analysis` → 应用名(测试库 0 行)
- `public.member_retention_clue.runtime_mode`:全部 NULL 填 `'live'`(44 行)
### 历史 emoji 回填(独立脚本)
`scripts/ops/backfill_retention_clue_emoji.py` — 把 summary 嵌入的首 emoji 抽到 emoji 列(测试库 44/44 行成功,可重入)。
## 兼容性影响
### ETL 影响
- 无直接影响。ETL 不写 ai_cache / ai_run_logs / member_retention_clue,只是注释里"客户基础信息" → "客户基础" 的字面量调整(`apps/etl/connectors/feiqiu/tasks/dws/member_consumption_task.py` + `member_visit_task.py`)。
### 后端 API 影响
- `customer_service._build_ai_insight`:cache_type 从 `app4_analysis`(错位)改为正确的 `app7_customer`,加 `site_id` 过滤 + 字段对齐 App7Result schema(strategies[].title/content)
- `customer_service._build_retention_clues`:加 `site_id` 过滤 + 字段补齐(detail/source/recorded_by_name/emoji)
- `task_manager.py` aiSuggestion:取 `one_line_summary` 替代不存在的 `app4.summary`
- `task_manager.py` talkingPoints:cache_type `app5_talking_points`(不存在)→ `app5_tactics` + 字段 `tactics[].scenario/script`
- `cleanup_service.py`:`WHERE app_type=%s` BUG 修(应是 `cache_type`)— 90 天清理 + 20K 上限重新生效
- `cache_service.CACHE_EXPIRY_DAYS`:补 `app2a_finance_area: 0`(64 区域组合不再永不过期)
- `dispatcher._write_retention_clue`:emoji 独立写入(不再拼 summary)+ 加 runtime_mode/sandbox_instance_id 五元组隔离
- `xcx_chat`:`ReferenceCard` schema 补 `link/source_page` 字段;`get_messages` SQL 加 `AND role IN ('user','assistant')` 过滤 system 行;`build_reference_card` KPI 富卡接入 SSE 路径
- WS `/ws/ai-cache/{site_id}` + `/ws/ai-alerts/{site_id}`:加 `?token=` query 参数 + JWT 校验 + site_id 一致性校验
### 小程序影响
- `customer-detail.ts`:clues 类型 4 字段 → 6 字段(tag/tagColor/emoji/text/source/desc);`_loadAIInsight` cache_type 改 `app7_customer` + 字段 `s.title/s.content`
- `customer-detail.wxml`:clue-card props 字段对齐 + `wx:if` 空态隐藏 + ai-float-button 补 sourcePage
- `task-detail.ts/wxml/json`:retentionClues tagColor 6 类;talkingPoints 类型 string[] → TacticItem[];整页补 ai-float-button + json 注册组件
- `chat.ts`:三分支(task/customer/coach)补 `sourcePage` + `pageFilters.contextId`,Phase 2.3 链路真正激活
- 14 处 wxml ai-float-button 全部补 sourcePage
### admin-web 影响
- `AIOperations.tsx` `CACHE_TYPE_OPTIONS` 8 类对齐(去除 _analysis / _consolidated 后缀)
- `AIRunLogs.tsx` `RUN_LOG_APP_TYPE_OPTIONS` 删除旧 `app8_consolidate`(数据已 UPDATE 到 `app8_consolidation`)
- `__tests__/adminAiAppTypes.test.ts`:测试断言不再固化"双名共存",改为统一命名
## 回滚策略
迁移文件末尾有完整"回滚参考"块,按以下顺序执行:
```sql
BEGIN;
-- 1. DROP 新约束
ALTER TABLE biz.ai_cache DROP CONSTRAINT IF EXISTS chk_ai_cache_type;
-- 2. UPDATE 命名回滚(注意:旧名 app8_consolidate vs app8_clue_consolidated 已合并,
-- 回滚无法精确还原,只能选其一,以下示例选 ai_cache 旧描述名)
UPDATE biz.ai_run_logs SET app_type = 'app8_consolidate' WHERE app_type = 'app8_consolidation';
UPDATE biz.ai_run_logs SET app_type = 'app7_customer_analysis' WHERE app_type = 'app7_customer';
UPDATE biz.ai_run_logs SET app_type = 'app6_note_analysis' WHERE app_type = 'app6_note';
UPDATE biz.ai_cache SET cache_type = 'app8_clue_consolidated' WHERE cache_type = 'app8_consolidation';
UPDATE biz.ai_cache SET cache_type = 'app7_customer_analysis' WHERE cache_type = 'app7_customer';
UPDATE biz.ai_cache SET cache_type = 'app6_note_analysis' WHERE cache_type = 'app6_note';
-- 3. ADD 旧约束
ALTER TABLE biz.ai_cache ADD CONSTRAINT chk_ai_cache_type CHECK (cache_type IN
('app2_finance','app2a_finance_area','app3_clue','app4_analysis','app5_tactics',
'app6_note_analysis','app7_customer_analysis','app8_clue_consolidated'));
-- 4. DROP 索引 + 列
DROP INDEX IF EXISTS biz.idx_ai_run_logs_assistant_member;
ALTER TABLE biz.ai_run_logs DROP COLUMN IF EXISTS assistant_id;
ALTER TABLE public.member_retention_clue
DROP COLUMN IF EXISTS sandbox_instance_id,
DROP COLUMN IF EXISTS runtime_mode,
DROP COLUMN IF EXISTS emoji;
-- 5. emoji 反向回填(若需要)— 把 emoji 列拼回 summary
UPDATE public.member_retention_clue
SET summary = emoji || ' ' || summary, emoji = '' WHERE emoji != '';
COMMIT;
```
代码侧:`git revert <commit_hash>`
## 验证 SQL(已在测试库 PASS)
```sql
-- 1. 新列存在
SELECT column_name FROM information_schema.columns
WHERE table_schema='public' AND table_name='member_retention_clue'
AND column_name IN ('emoji','runtime_mode','sandbox_instance_id');
-- 预期 3 行
-- 2. assistant_id 列存在
SELECT column_name FROM information_schema.columns
WHERE table_schema='biz' AND table_name='ai_run_logs' AND column_name='assistant_id';
-- 预期 1 行
-- 3. 旧 cache_type 0 残留
SELECT cache_type, count(*) FROM biz.ai_cache
WHERE cache_type IN ('app6_note_analysis','app7_customer_analysis',
'app8_clue_consolidated','app8_consolidate')
GROUP BY 1;
-- 预期 0 行
-- 4. 旧 app_type 0 残留
SELECT app_type, count(*) FROM biz.ai_run_logs
WHERE app_type IN ('app6_note_analysis','app7_customer_analysis',
'app8_consolidate','app8_clue_consolidated')
GROUP BY 1;
-- 预期 0 行
-- 5. emoji 回填覆盖率(回填脚本跑后)
SELECT
count(*) FILTER (WHERE emoji != '') AS filled,
count(*) FILTER (WHERE emoji = '') AS empty,
count(*) AS total
FROM public.member_retention_clue;
-- 预期 filled=44, empty=0, total=44(测试库)
```
## 关联
- 完整审计:`docs/audit/changes/2026-05-06__w1_ai_closure_super_sprint.md`
- backlog 登记:`docs/_overview/architecture-evolution-backlog.md` §七 #14 主体收口 + #15-#28 残余子任务
- 关联表 RLS 迁移(P1-1 public → biz schema):§七 #21 后续 sprint

View File

@@ -0,0 +1,222 @@
# -*- coding: utf-8 -*-
"""W1-AI-CLOSURE 组 1 — 维客线索 emoji 回填脚本。
背景:
historic dispatcher._write_retention_clue 把 App8 prompt 输出的独立 emoji 字段
拼到 summary 字符串(`f"{emoji} {raw_summary}"`),违反字段独立性哲学。
20260506__ai_closure_schema_fixes.sql 已加 emoji 独立列。
本脚本回填历史数据:扫描 member_retention_clue 全表,把 summary 开头的 emoji
提取到 emoji 列,并把 summary 去掉 emoji 前缀。
用法:
cd C:\\Project\\NeoZQYY
.venv\\Scripts\\python.exe scripts/ops/backfill_retention_clue_emoji.py --dry-run
.venv\\Scripts\\python.exe scripts/ops/backfill_retention_clue_emoji.py
设计:
- 默认 --dry-run 模式下打印 diff,不写库
- 实跑模式下逐条 UPDATE,事务包裹
- 仅处理 emoji = '' 的行,已回填的不重复处理(可重入)
- 失败行单独打印,不影响其他行
"""
from __future__ import annotations
import argparse
import logging
import os
import re
import sys
from dataclasses import dataclass
from pathlib import Path
import psycopg2
from dotenv import load_dotenv
# ── 加载根 .env(BOM 兼容) ─────────────────────────────
_ROOT = Path(__file__).resolve().parent.parent.parent
load_dotenv(_ROOT / ".env", override=False, encoding="utf-8-sig")
_DSN = os.environ.get("APP_DB_DSN")
if not _DSN:
sys.exit("ERROR: APP_DB_DSN 环境变量未设置,请检查根 .env")
logger = logging.getLogger("backfill_retention_clue_emoji")
# ── emoji 前缀正则(覆盖常见 BMP + SMP 符号 + ZWJ 序列) ──
# 匹配:summary 开头的 1 个或多个 emoji 字符 + 紧跟的空白(0 或多个)
_EMOJI_PREFIX = re.compile(
r"^("
r"[\U0001F300-\U0001F9FF]" # Misc Symbols and Pictographs / Emoticons / Symbols and Pictographs Extended-A
r"|[\U0001FA70-\U0001FAFF]" # Symbols and Pictographs Extended-B
r"|[☀-➿]" # Misc Symbols + Dingbats
r"|[⌀-⏿]" # Misc Technical
r"|[⬀-⯿]" # Misc Symbols and Arrows
r"|[\U0001F1E6-\U0001F1FF]" # 区域旗(国旗)
r"|" # Variation Selector-16
r"|" # Zero Width Joiner
r")+\s*"
)
@dataclass(frozen=True)
class ClueRow:
"""member_retention_clue 表中需要回填的一行(只读 DTO)。"""
id: int
summary: str
@dataclass(frozen=True)
class BackfillResult:
"""单行回填结果:从 summary 抽出的 emoji + 剩余 summary。"""
id: int
extracted_emoji: str
new_summary: str
original_summary: str
@property
def changed(self) -> bool:
"""是否真的发生了变化(emoji 非空且 summary 不同)。"""
return bool(self.extracted_emoji) and self.new_summary != self.original_summary
def extract_emoji_prefix(summary: str) -> tuple[str, str]:
"""从 summary 开头抽取 emoji 前缀。
Args:
summary: 原始 summary 文本,可能含或不含 emoji 前缀
Returns:
(extracted_emoji, remaining_summary):
- extracted_emoji: 抽出的 emoji 字符串(可能多个 + ZWJ),空表示无 emoji 前缀
- remaining_summary: 去掉 emoji 前缀后的 summary(已 strip 前导空白)
"""
match = _EMOJI_PREFIX.match(summary)
if not match:
return "", summary
emoji_part = match.group(0).rstrip() # emoji 本身,不带尾随空白
remaining = summary[match.end():].lstrip() # 去掉 emoji + 空白后的剩余文本
return emoji_part, remaining
def fetch_pending_rows(conn: psycopg2.extensions.connection) -> list[ClueRow]:
"""查询所有 emoji='' 的行。
可重入:已回填(emoji 非空)的不重复处理。
"""
with conn.cursor() as cur:
cur.execute(
"""
SELECT id, summary
FROM public.member_retention_clue
WHERE emoji = ''
ORDER BY id
"""
)
return [ClueRow(id=r[0], summary=r[1]) for r in cur.fetchall()]
def apply_backfill(
conn: psycopg2.extensions.connection,
result: BackfillResult,
) -> None:
"""对单行执行 UPDATE。"""
with conn.cursor() as cur:
cur.execute(
"""
UPDATE public.member_retention_clue
SET emoji = %s, summary = %s
WHERE id = %s
""",
(result.extracted_emoji, result.new_summary, result.id),
)
def run(dry_run: bool) -> int:
"""执行回填。
Returns:
退出码:0 成功,1 有失败行
"""
conn = psycopg2.connect(_DSN)
failed_count = 0
try:
rows = fetch_pending_rows(conn)
logger.info("待处理行数: %d (emoji = '' 的所有行)", len(rows))
if not rows:
logger.info("无待处理行,提前退出")
return 0
results: list[BackfillResult] = []
for row in rows:
emoji, new_summary = extract_emoji_prefix(row.summary)
results.append(BackfillResult(
id=row.id,
extracted_emoji=emoji,
new_summary=new_summary,
original_summary=row.summary,
))
changed = [r for r in results if r.changed]
unchanged = [r for r in results if not r.changed]
logger.info("将抽取 emoji 的行: %d", len(changed))
logger.info("无 emoji 前缀的行: %d (跳过 UPDATE)", len(unchanged))
# 打印前 5 条 diff 给用户审阅
for r in changed[:5]:
logger.info(
" id=%d emoji=%r summary: %r -> %r",
r.id, r.extracted_emoji, r.original_summary, r.new_summary,
)
if len(changed) > 5:
logger.info(" ... (省略剩余 %d 行)", len(changed) - 5)
if dry_run:
logger.info("[DRY-RUN] 不执行 UPDATE,正式回填请去掉 --dry-run")
return 0
# 实跑:逐行 UPDATE,失败单独记录
for r in changed:
try:
apply_backfill(conn, r)
except psycopg2.Error as exc:
logger.exception("UPDATE 失败 id=%d: %s", r.id, exc)
failed_count += 1
conn.rollback()
continue
conn.commit()
logger.info(
"回填完成: 成功 %d 行 / 失败 %d",
len(changed) - failed_count, failed_count,
)
return 0 if failed_count == 0 else 1
finally:
conn.close()
def main() -> None:
parser = argparse.ArgumentParser(
description="W1-AI-CLOSURE 维客线索 emoji 回填(从 summary 抽取到独立列)",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="试运行模式,打印 diff 不写库",
)
args = parser.parse_args()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
)
sys.exit(run(dry_run=args.dry_run))
if __name__ == "__main__":
main()