客服 Agent 重构收口:五出口决策链 + 知识库档位隔离 + 前端入参边界(答辩演示版本)

一、客服 Agent 智能增强(正面回应"不智能、动不动就转人工")
- 决策链由 2 个出口扩到 5 个:E1 澄清 / E2 计算型 / E3 知识直返 / E4 证据约束生成 / E5 分级回退
- 转人工从"默认动作"降为最后一档 E5c,只保留 4 类白名单:
  P0 反诈 / P1 账户与个人数据 / P2 写操作与争议 / 用户明确要求人工
- 46 条金标实测(修复前 → 修复后):
  转人工率 43.5% → 10.9%;出口准确率 45.7% → 100%;事实正确率 69.6% → 100%
  禁忌违反 1 → 0;档位越权 / 无出处数字 / 误拒 四项零容忍全 0
- 安全不变量 INV-1~INV-5;零容忍规则未删,改的是挂载点
  (输出侧字面黑名单 → 检索层档位隔离 + 判定层合规词表 + 输出守护)

二、知识库:档位单点化与物理隔离
- 新增 app/core/knowledge_tier.py 作为档位规则唯一落点(G-03),
  knowledge_contracts.py 原定义块改为显式再导出(X as X,非副本)
- 档位过滤由 bool 默认值(fail-open)改为 tiers 必填集合(缺参即 TypeError)
- Milvus 侧四集合按 visibility 分区键物理隔离;双 schema 收敛为一套
- 新增 app/core/actor.py:访客三元组与匿名判定的唯一构造/判定点(G-01/G-01b)
- 新增 app/core/fund_fee_rules.py:费率计算纯函数

三、前端入参边界对齐(本轮 W11 新修,4 处"校验宽于存储")
- message 加 max_length=8000(与浮窗 widget.js 的 maxlength 一致)
- session_id 加 1—64;idempotency_key 上限 128 → 64(对齐列宽 String(64))
- feedback_type 加 max_length=32(对齐列宽 String(32))
- 8 条路径参数补 min_length=1 + max_length=64 + 字符集正则
  ({session_id} / {run_id} / {handover_id})
- 改前超限值会落到 MySQL 才失败(500);改后一律 422 AGENT_INPUT_INVALID + 字段级定位
- 新增 tests/unit/api/test_frontend_boundaries.py(33 例),含"端点表 ↔ OpenAPI 全量对照"

四、投顾模块整体清除(D4.4 / D4.5)
- 删除投顾相关 controller / schema / model / repository / service 及门户页面
- tools/portal_api_check.py 同步作废 AD003/AD005/AD011/A047 四条用例与 advisor_t 登录
  (端点与账号均已不存在,此前稳定报 3 条假红)

五、验证(提交前实测)
- pytest -q:1856 passed / 2 skipped / 0 failed
- ruff check app tools tests:19(= 基线);mypy app:2(= 基线)
- 前端接口契约体检 portal_api_check.py:38 项,通过 34,失败 0,跳过 4
- 全链路冒烟 e2e_smoke_test.py --read-only:31/31
- HTTP 全链路探针 http_probe.py:11/11 succeeded
- 跨文档一致性 _consistency.py:GATE PASS
- 真机边界复验 12 条:12/12 符合预期

六、纪律与文档
- 可改文件白名单 A-09(docs/46)与底座会签申请单 A-10(docs/47,组 1—组 4 全部受理)
- 零 DDL:未新增/修改任何表结构,89 张业务表与基线一致
- 证据留痕:docs/evidence/**(含 46 条金标 score、快照、清除与重建记录)
- 未提交(刻意排除,见提交说明):仓库内 客服agent/ 与 开发文档/ 是 2026-09-16 前的
  过期副本(Todolist 440 行 vs 权威 D2.1 1167 行),权威正本在仓库外;
  _chunks_report.txt 是 tools/build_knowledge_chunks.py 生成的本地产物
This commit is contained in:
张胜宇
2026-09-20 14:33:30 +08:00
parent 8643ad1efc
commit 5d0becb67d
258 changed files with 77004 additions and 26099 deletions
@@ -7,7 +7,6 @@ import pytest
from app.core.contracts import AgentResult, CoreResult, RequestContext
from app.model.platform import HandoverTicket
from app.service.customer_service_session_memory_service import CustomerServiceSessionTurn
from app.service.memory_recall_service import MemoryRecallService
from app.service.model_gateway import ModelGenerationService
from app.worker.runtime import WorkerRuntime
@@ -53,7 +52,7 @@ def test_visitor_does_not_request_memory_extraction() -> None:
result = AgentResult(run_id="visitor-run", result=CoreResult(text="公开答复"))
requested = WorkerRuntime.should_request_memory_extraction(
agent_type="customer_service", context=context,
agent_type="advisor", context=context,
message="我的风险偏好是稳健型",
result=result,
business_events=(),
@@ -62,32 +61,36 @@ def test_visitor_does_not_request_memory_extraction() -> None:
assert requested is False
def test_authenticated_customer_service_does_not_request_memory_extraction() -> None:
"""客服消息即使命中长期记忆信号,也不能进入客户画像抽取队列。"""
def test_customer_service_never_requests_memory_extraction() -> None:
"""`DEC-19`:客服不写长期记忆——命中偏好信号、甚至带业务事件也不入抽取队列。"""
context = RequestContext(
user_id="7", trace_id="customer-trace", roles=("customer",),
user_id="9001", trace_id="cs-memory-trace", roles=("customer",),
permissions=("agent:run",), data_scope="self",
)
result = AgentResult(run_id="customer-run", result=CoreResult(text="公开答复"))
result = AgentResult(run_id="cs-memory-run", result=CoreResult(text="客服答复"))
requested = WorkerRuntime.should_request_memory_extraction(
agent_type="customer_service", context=context, message="我的风险偏好是稳健型",
result=result, business_events=("trade.completed",),
)
def decision(agent_type: str) -> bool:
return WorkerRuntime.should_request_memory_extraction(
agent_type=agent_type, context=context,
message="我的风险偏好是稳健型,只买货币基金",
result=result, business_events=("trade.completed",),
)
assert requested is False
assert decision("customer_service") is False
# 对照组:闸门只拦客服,不能顺手把其它 Agent 的长期记忆一起关掉。
assert decision("risk_agent") is True
def test_authenticated_customer_service_requests_profile_candidate() -> None:
"""已登录客户明确陈述偏好时只生成候选,不复用正式记忆事件。"""
def test_customer_service_never_produces_profile_candidate() -> None:
"""`DEC-19`:客服不产生画像候选,已登录客户陈述偏好也不产候选。"""
context = RequestContext(
user_id="7", trace_id="customer-trace", roles=("customer",),
user_id="9001", trace_id="cs-candidate-trace", roles=("customer",),
permissions=("agent:run",), data_scope="self",
)
assert WorkerRuntime.should_request_profile_candidate(
agent_type="customer_service", context=context, message="我的风险偏好是稳健型"
) is True
) is False
def test_visitor_does_not_request_profile_candidate() -> None:
@@ -98,49 +101,10 @@ def test_visitor_does_not_request_profile_candidate() -> None:
)
assert WorkerRuntime.should_request_profile_candidate(
agent_type="customer_service", context=context, message="我的风险偏好是稳健型"
agent_type="advisor", context=context, message="我的风险偏好是稳健型"
) is False
@pytest.mark.asyncio
async def test_customer_service_short_memory_append_is_available_on_runtime() -> None:
"""Worker 的短期会话依赖与长期画像抽取依赖必须彼此独立。"""
captured: dict[str, Any] = {}
class StubSessionMemory:
async def append(
self, *, actor_id: str, session_id: str,
turns: tuple[CustomerServiceSessionTurn, ...],
) -> bool:
captured["actor_id"] = actor_id
captured["session_id"] = session_id
captured["turns"] = turns
return True
async def read(self, *, actor_id: str, session_id: str) -> Any:
raise AssertionError("not used by worker write path")
runtime = WorkerRuntime(session_memory=StubSessionMemory())
await runtime._append_customer_service_session_memory(
agent_type="customer_service", actor_id="7", session_id="short-memory-session",
request_message="刚才那只基金的费率", response_message="请以产品资料页为准。",
)
await runtime._append_customer_service_session_memory(
agent_type="risk", actor_id="7", session_id="other-agent-session",
request_message="不应写入", response_message="不应写入",
)
assert captured == {
"actor_id": "7",
"session_id": "short-memory-session",
"turns": (
CustomerServiceSessionTurn(role="user", content="刚才那只基金的费率"),
CustomerServiceSessionTurn(role="assistant", content="请以产品资料页为准。"),
),
}
class FakeSession(AbstractAsyncContextManager["FakeSession"]):
def __init__(self) -> None:
self.scalar = AsyncMock(return_value="event-1")