Procházet zdrojové kódy

test(e2e): 补 D-04/SC-P-40·41 + D-06/SC-H-06 三流 e2e 契约用例

D-04 plan.ai.generate (SC-P-40/41):
- POST /api/ai/plan/generate + /api/ai/plan/regenerate-section
- 功能: 会员一键生成 overview+nutrition/diet/exercise 三板块(非空/标题); 逐板块重生成不丢其他板块 + overview 保留 + 幂等不漂移; 未知 sectionKey 不破坏三板块
- 异常·超时降级不500: HTTP200+code=200+结构完整+非空兜底+fallback_used(boolean); 真实 fallback_used=true 分支对 python.base-url 不可达实例实测
- 权限: 未购会员 46003; 无效 token 401; 实测无 token code=500 承袭; G-304-1 跨家庭 memberId 放行 承袭·真实缺陷未修(fixme)
- 会员构造不走坏掉的 /api/membership/trial; 走 /api/membership/orders + /api/membership/notify(payMethod=wechat); 支持 AI_TEST_TOKEN

D-06 butler.ai.collaborate (SC-H-06):
- POST /api/butler/collaborate/{close,feedback,notify}
- 功能: 闭环留痕(结论/处置/时长+CLOSED+closedAt); 反哺待审(PENDING_REVIEW+去重+继承); 未审不入库(notify 409); 审核通过可检索(APPROVED+reviewer+移出待审+notify); 审计可读(HTTP 代理 + butler_ai_collaboration_audit_log 落库 CLOSE_ORDER/SUBMIT_FEEDBACK/AUDIT_FEEDBACK/NOTIFY_PARENT); 反馈原家长 DTO+sourceWorkorderId+notified
- 异常: 隐私脱敏(手机号1**********/身份证******************/邮箱***@***,原文不入库)+空400; 未审不入库 409; 重复反哺去重 409; 已审核不可重复 409; 工单不存在404; 反哺不存在/不匹配404; 参数缺失400; 已闭环再 close 409
- 权限: 管家自审核403(审核权归运营); 非运营待审403; 家长直接写kb403; 跨家庭 close/feedback 403; 匿名协作403 + admin 匿名401
- 「隐私脱敏 403」真实契约核实: 隐私内容脱敏+200(非以明文入库),403 为越权/越界/非运营审核; 不伪造
- 工单 seed 用 mysql CLI(后端无 HTTP 创建 butler_escalation_orders); 审计表无 HTTP 读端点 + 审核通过可检索未独立kb-insert 承袭差距登记(非放水)
- 探针 _probe_*.spec.js gitignore

只改 tests/e2e/**; 不改生产源码/不改台账.
QA-orchestration před 13 hodinami
rodič
revize
837a3a0c46

+ 1 - 0
tests/e2e/api/.gitignore

@@ -0,0 +1 @@
+_probe_*.spec.js

+ 412 - 0
tests/e2e/api/ai-plan-generate-contract.spec.js

@@ -0,0 +1,412 @@
+// ============================================================================
+// [D-04 · SC-P-40 / SC-P-41 · 能力键 plan.ai.generate]
+// 三流(功能 / 异常 / 权限)e2e 契约用例
+// ----------------------------------------------------------------------------
+// 接口(docs/tdd/orchestration/discovery-2026-11-30-1008.md §2;D8 AIChatController L955/L976):
+//   POST /api/ai/plan/generate            选成员 + 目标 → AiGateway(LangGraph) → overview + 三板块
+//   POST /api/ai/plan/regenerate-section  仅重生成 sectionKey 对应板块,其余两板块原样保留(不丢)
+//
+// 三板块键(AiGateway GROWTH_SECTION_KEYS):nutrition / diet / exercise
+//   标题:营养补充建议 / 饮食建议 / 运动计划(GROWTH_SECTION_TITLES)
+//
+// 契约来源(已逐条核对后端实现,只读,不改生产源码):
+//   cfc-backend/.../controller/ai/AIChatController.java
+//     L955 @PostMapping("/plan/generate")            checkGate(userId) → 46003;aiGateway.generateGrowthPlan;
+//                                                   needPurchase → Result.error(46003,...);否则 Result.success(data)
+//     L976 @PostMapping("/plan/regenerate-section") checkGate(userId) → 46003;aiGateway.regenerateGrowthPlanSection
+//     ERR_AI_COACH_MEMBER_ONLY = 46003(未购会员/会员过期拦截;会员过期=46004)
+//     @RequestAttribute("userId") / @RequestAttribute("familyId")(JwtInterceptor 注入;匿名 userId=-1/familyId=null)
+//   cfc-backend/.../service/AiGateway.java
+//     generateGrowthPlan(...):       {overview, sections:[{key,title,content}×3], fallback_used}
+//     regenerateGrowthPlanSection:   仅 section.put(content) 目标 key;其余两板块 + overview 原样保留;
+//                                    sectionKey 非法 → 不匹配、三板块不变;幂等(连点同板块不漂移其它板块)
+//     LangGraph 超时 / 熔断 / 解析失败 → 非空模板 Fallback + fallback_used=true;禁止抛异常 / 不 500
+//   Result<T>: success code=200;error code 在 body,HTTP 仍 200;JwtInterceptor 匿名/无效 token → 401 code=401
+//
+// 鉴权契约(实测,见本任务探针 _probe_ai_plan.spec.js,gitignore):
+//   ① 带「无效/格式错误 Bearer token」→ HTTP 401 {code:401,message:"请先登录"}
+//   ② 「完全不带 Authorization」→ HTTP 200 {code:500,message:"服务器内部错误"} ⚠ 见下方承袭缺陷(应为 401,非 46003/500)
+//   ③ 已登录非会员 → HTTP 200 code=46003(不泄露内部错误,不 500)
+//
+// 长期 blocker(只标「承袭·真实缺陷未修」,不造绿、不写放水断言):
+//   ✦ G-304-1(跨家庭越权拒绝缺失):本端点只 checkGate(userId),@RequestAttribute("familyId") 未用于归属校验,
+//     params.memberId 未做家庭归属校验。已实测:会员 A(familyA) 传 memberId=B(familyB 成员) → code=200 生成,未 403。
+//     按「权限三流」本应跨家庭 memberId → 403。test.fixme + 严格断言保留,转绿需后端补归属守卫(非本任务)。
+//   ✦ 承袭缺陷(鉴权口径):完全不带 token → code=500(缺 familyId → ServletRequestBindingException),
+//     而非 401/46003。真实契约已严格断言(code=500),并保留「应 401」fixme。
+//   ✦ 另:POST /api/membership/trial(自助开通试用)在部分库 payment_method ENUM('wechat','alipay','card')
+//     下 Data truncated → code=400/500(见 butler-fallback.spec.js 既有登记)。本用例改走
+//     POST /api/membership/orders + POST /api/membership/notify(payMethod=wechat)构造会员,不依赖 trial;
+//     或注入已是会员账号的 AI_TEST_TOKEN(与 butler-fallback.spec.js 约定一致)。
+//
+// 运行:
+//   CFC_API_BASE=http://127.0.0.1:9082 npx playwright test api/ai-plan-generate-contract.spec.js \
+//     -c tests/playwright.config.api.js --project=desktop
+// 安全约定:不打印 token / 手机号;测试数据全部自建 direct-register,不改动存量业务数据。
+// ============================================================================
+
+const { test, expect } = require('@playwright/test');
+const { apiPost } = require('../helpers/api');
+
+const API_TIMEOUT_MS = 120000;
+
+/** 三板块键顺序(AiGateway GROWTH_SECTION_KEYS) */
+const SECTION_KEYS = ['nutrition', 'diet', 'exercise'];
+/** 三板块标题(AiGateway GROWTH_SECTION_TITLES) */
+const SECTION_TITLES = { nutrition: '营养补充建议', diet: '饮食建议', exercise: '运动计划' };
+/** 未购会员业务码(AIChatController ERR_AI_COACH_MEMBER_ONLY) */
+const ERR_AI_COACH_MEMBER_ONLY = 46003;
+
+// ---------------------------------------------------------------------------
+// helpers(禁可选链 ?.;时间用 parseDate 不用 new Date(string) —— 本文件不涉及时间解析)
+// ---------------------------------------------------------------------------
+
+/** 注册账号:direct-register 冷启动可达 16s+,显式 60s + 重试 */
+async function register(request, role, tag) {
+  const phone = '13' + String(Math.floor(Math.random() * 900000000) + 100000000);
+  let lastErr;
+  for (let i = 0; i < 3; i++) {
+    try {
+      const r = await request.post('/api/auth/direct-register', {
+        data: { phone, role, nickname: 'QA-' + tag },
+        timeout: 60000,
+      });
+      const body = await r.json().catch(() => ({}));
+      if (body.code === 200 && body.data && body.data.token) {
+        return { token: body.data.token, userId: body.data.userId, familyId: body.data.familyId, role: role };
+      }
+      lastErr = body;
+    } catch (e) {
+      lastErr = e && e.message ? e.message : String(e);
+    }
+  }
+  throw new Error('register(' + role + ') 失败: ' + JSON.stringify(lastErr));
+}
+
+/**
+ * 构造已购会员(BASIC 及以上 + 有效期):
+ *   POST /api/membership/orders(levelCode=FAMILY)→ POST /api/membership/notify(payMethod=wechat 模拟支付回调)
+ * 不依赖 POST /api/membership/trial(该端点在部分库 payment_method ENUM 下 code=400/500,见登记)。
+ * 或:注入已是会员账号 token(AI_TEST_TOKEN),与 butler-fallback.spec.js 约定一致。
+ */
+async function makeMember(request, tag) {
+  if (process.env.AI_TEST_TOKEN) {
+    return { token: process.env.AI_TEST_TOKEN, userId: null, familyId: null, injected: true };
+  }
+  const u = await register(request, 'parent', tag);
+  const order = await apiPost(
+    request,
+    '/api/membership/orders',
+    { levelCode: 'FAMILY', paymentType: 'yearly', period: 'yearly' },
+    u.token,
+  );
+  expect(order.code, '创建会员订单应成功 code=200, 实际=' + order.code + ' msg=' + order.message).toBe(200);
+  const orderNo = order.data && order.data.orderNo;
+  expect(typeof orderNo, '订单应返回 orderNo').toBe('string');
+  const notify = await apiPost(
+    request,
+    '/api/membership/notify',
+    { orderNo: orderNo, transactionId: 'QA-' + Date.now() + '-' + Math.floor(Math.random() * 1e6), payMethod: 'wechat' },
+    u.token,
+  );
+  expect(notify.code, '支付回调应成功 code=200').toBe(200);
+  expect(notify.data, '支付回调应返回 success=true').toBe(true);
+  return { token: u.token, userId: u.userId, familyId: u.familyId, injected: false };
+}
+
+/** 断言「生成/重生成」数据结构完整(overview + 三板块 + fallback 标记),不 500 */
+function assertPlanShape(data, label) {
+  expect(data, label + ': data 不能为空').toBeTruthy();
+  expect(typeof data.overview === 'string' && data.overview.trim().length > 0, label + ': overview 应为非空字符串').toBe(true);
+  expect(Array.isArray(data.sections), label + ': sections 应为数组').toBe(true);
+  expect(data.sections.length, label + ': 应恰好三板块').toBe(3);
+  const keys = data.sections.map(function (s) { return s.key; });
+  expect(keys, label + ': 板块键应为 ' + SECTION_KEYS.join(',')).toEqual(SECTION_KEYS);
+  for (const s of data.sections) {
+    expect(SECTION_TITLES[s.key], label + ': 板块 ' + s.key + ' 标题应为 ' + SECTION_TITLES[s.key] + ', 实际=' + s.title).toBe(s.title);
+    expect(typeof s.content === 'string' && s.content.trim().length > 0, label + ': 板块 ' + s.key + ' content 应非空').toBe(true);
+  }
+  expect(typeof data.fallback_used === 'boolean', label + ': fallback_used 应为 boolean').toBe(true);
+}
+
+function sectionByKey(sections, key) {
+  return (sections || []).find(function (s) { return s.key === key; }) || null;
+}
+
+// ---------------------------------------------------------------------------
+// SC-P-40 · 生成 AI 方案
+// ---------------------------------------------------------------------------
+
+test.describe('SC-P-40 · POST /api/ai/plan/generate(三流)', () => {
+  test.setTimeout(180000);
+
+  test('[功能] 已购会员一键生成:HTTP200 + code=200 + overview + nutrition/diet/exercise 三板块 + 不500', async ({ request }) => {
+    const member = await makeMember(request, 'sc-p40-fn');
+    const memberId = member.userId != null ? member.userId : undefined;
+
+    const r = await apiPost(
+      request,
+      '/api/ai/plan/generate',
+      { goal: '提升孩子专注力', memberId: memberId },
+      member.token,
+    );
+
+    expect(r.status, 'HTTP 不应为 5xx').toBe(200);
+    expect(r.status, '超时/降级也不 500').not.toBe(500);
+    expect(r.code, '业务 code 应为 200, 实际=' + r.code + ' msg=' + r.message).toBe(200);
+    assertPlanShape(r.data, 'SC-P-40 generate');
+  });
+
+  test('[异常·超时降级不500] LangGraph 上游超时/不可用 → 仍 HTTP200+code=200 + 完整三板块 + 非空兜底 + fallback_used=boolean,不抛 500', async ({ request }) => {
+    // 契约:AiGateway 超时/熔断/解析失败 → 非空模板 Fallback + fallback_used=true,禁止抛异常/500。
+    // 本用例断言「无论上游是否可用都不 500 + 结构完整」这一可机器校验的契约面;
+    // 真实 fallback_used=true 分支已在本任务对「python.base-url 指向不可达地址 / python.enabled=false 的后端实例」
+    // 实测验证(探针 + 独立实例),见汇报。测试侧不强断 fallback_used===true(远端上游是否可用不可控)。
+    const member = await makeMember(request, 'sc-p40-timeout');
+    const memberId = member.userId != null ? member.userId : undefined;
+
+    const r = await apiPost(
+      request,
+      '/api/ai/plan/generate',
+      { goal: '提升孩子专注力', memberId: memberId },
+      member.token,
+    );
+
+    expect(r.status, '超时降级也不 HTTP500').not.toBe(500);
+    expect(r.status).toBe(200);
+    expect(r.code, '超时降级仍业务成功 code=200, 实际=' + r.code + ' msg=' + r.message).toBe(200);
+    expect(r.message, '不泄露内部错误').not.toBe('服务器内部错误');
+    assertPlanShape(r.data, 'SC-P-40 timeout-fallback');
+    // fallback_used 是明确的降级标记(true=走兜底;false=上游可用),必须存在且为 boolean
+    expect(typeof r.data.fallback_used === 'boolean').toBe(true);
+  });
+
+  test('[权限·未购会员拦截] 已登录但非会员 → code=46003(该功能为会员专享),不500,不返回方案', async ({ request }) => {
+    const free = await register(request, 'parent', 'sc-p40-free');
+
+    const r = await apiPost(
+      request,
+      '/api/ai/plan/generate',
+      { goal: '提升孩子专注力', memberId: free.userId },
+      free.token,
+    );
+
+    expect(r.status, '未购会员不 500').not.toBe(500);
+    expect(r.status).toBe(200);
+    expect(r.code, '未购会员拦截 code=46003, 实际=' + r.code + ' msg=' + r.message).toBe(ERR_AI_COACH_MEMBER_ONLY);
+    expect(r.message, '应提示会员专享').toContain('会员');
+    expect(r.data == null, '拦截时不返回方案数据').toBe(true);
+  });
+
+  test('[权限·鉴权] 无效/格式错误 Bearer token → HTTP401 code=401 请先登录', async ({ request }) => {
+    const res = await request.post('/api/ai/plan/generate', {
+      data: { goal: 'x', memberId: 1 },
+      headers: { Authorization: 'Bearer invalid.token.here' },
+      timeout: 30000,
+    });
+    expect(res.status(), '无效 token → HTTP 401').toBe(401);
+    const body = await res.json().catch(() => ({}));
+    expect(body.code).toBe(401);
+    expect(body.message).toBe('请先登录');
+  });
+
+  test('[权限·鉴权 承袭·真实缺陷未修] 完全不带 token → 实测 code=500(缺 familyId),非 401/46003', async ({ request }) => {
+    // ⚠ 承袭·真实缺陷未修:无 Authorization → 匿名 familyId=null → @RequestAttribute("familyId") required
+    //   → ServletRequestBindingException → HTTP200 + code=500「服务器内部错误」;本应与「无效 token」一致 401。
+    // 严格断言「真实现状」,不写放水断言;不造绿。修复属生产源码改动,非本任务范围。
+    const res = await request.post('/api/ai/plan/generate', { data: { goal: 'x', memberId: 1 }, timeout: 30000 });
+    expect(res.status(), '实测 HTTP 200').toBe(200);
+    const body = await res.json().catch(() => ({}));
+    expect(body.code, '实测 code=500').toBe(500);
+    expect(body.code, '非 46003 会员拦截').not.toBe(ERR_AI_COACH_MEMBER_ONLY);
+    expect(body.code, '非 401 鉴权').not.toBe(401);
+    expect(body.data == null).toBe(true);
+  });
+
+  test.fixme(
+    '[权限·越权 G-304-1 承袭·真实缺陷未修] 跨家庭 memberId 应 403,但当前 checkGate 仅查 caller、memberId 未做家庭归属校验 → 已实测放行 code=200',
+    async ({ request }) => {
+      const a = await makeMember(request, 'sc-p40-famA');
+      const b = await register(request, 'parent', 'sc-p40-famB');
+      // 期望契约(按 sc-key-map/API 权限三流 + G-304-1 口径):跨家庭 memberId → 403
+      const r = await apiPost(
+        request,
+        '/api/ai/plan/generate',
+        { goal: 'x', memberId: b.userId },
+        a.token,
+      );
+      expect(r.code, '跨家庭 memberId 应 403(G-304-1 承袭,当前实测 code=200 放行)').toBe(403);
+    },
+  );
+});
+
+// ---------------------------------------------------------------------------
+// SC-P-41 · 分板块重生成(不丢其他板块)
+// ---------------------------------------------------------------------------
+
+test.describe('SC-P-41 · POST /api/ai/plan/regenerate-section(三流)', () => {
+  test.setTimeout(180000);
+
+  test('[功能] 逐板块重生成 diet:仅目标板块重生成,nutrition/exercise 与 overview 原样保留,不丢其他板块', async ({ request }) => {
+    const member = await makeMember(request, 'sc-p41-fn');
+    const memberId = member.userId != null ? member.userId : undefined;
+    const goal = '提升孩子专注力';
+
+    const gen = await apiPost(request, '/api/ai/plan/generate', { goal: goal, memberId: memberId }, member.token);
+    expect(gen.code, '先生成应成功').toBe(200);
+    assertPlanShape(gen.data, 'SC-P-41 baseline');
+
+    const before = gen.data.sections;
+    const othersBefore = before.filter(function (s) { return s.key !== 'diet'; }).map(function (s) {
+      return { key: s.key, title: s.title, content: s.content };
+    });
+    const dietBefore = sectionByKey(before, 'diet');
+
+    const regen = await apiPost(
+      request,
+      '/api/ai/plan/regenerate-section',
+      {
+        sectionKey: 'diet',
+        content: dietBefore ? dietBefore.content : '',
+        memberId: memberId,
+        goal: goal,
+      },
+      member.token,
+    );
+
+    expect(regen.status, '不 500').toBe(200);
+    expect(regen.code, '重生成 code=200, 实际=' + regen.code + ' msg=' + regen.message).toBe(200);
+    assertPlanShape(regen.data, 'SC-P-41 regen diet');
+
+    // overview 保留
+    expect(regen.data.overview, 'overview 原样保留').toBe(gen.data.overview);
+    // 其余两板块原样保留(key/title/content 全等),不丢其他板块
+    const othersAfter = regen.data.sections.filter(function (s) { return s.key !== 'diet'; }).map(function (s) {
+      return { key: s.key, title: s.title, content: s.content };
+    });
+    expect(othersAfter, '未重生成的两板块不丢、不变').toEqual(othersBefore);
+    // 目标板块仍是 diet + 标题不变 + content 非空
+    const dietAfter = sectionByKey(regen.data.sections, 'diet');
+    expect(dietAfter, 'diet 板块仍在').toBeTruthy();
+    expect(dietAfter.title).toBe('饮食建议');
+    expect(typeof dietAfter.content === 'string' && dietAfter.content.trim().length > 0).toBe(true);
+  });
+
+  test('[功能·幂等] 连续重生成同一板块,其余两板块始终不漂移、不丢', async ({ request }) => {
+    const member = await makeMember(request, 'sc-p41-idem');
+    const memberId = member.userId != null ? member.userId : undefined;
+    const goal = '提升孩子专注力';
+
+    const gen = await apiPost(request, '/api/ai/plan/generate', { goal: goal, memberId: memberId }, member.token);
+    expect(gen.code).toBe(200);
+    const keepNutrition = sectionByKey(gen.data.sections, 'nutrition');
+    const keepExercise = sectionByKey(gen.data.sections, 'exercise');
+
+    for (let i = 0; i < 2; i++) {
+      const regen = await apiPost(
+        request,
+        '/api/ai/plan/regenerate-section',
+        { sectionKey: 'exercise', content: sectionByKey(gen.data.sections, 'exercise').content, memberId: memberId, goal: goal },
+        member.token,
+      );
+      expect(regen.code, '第' + (i + 1) + '次重生成 code=200').toBe(200);
+      assertPlanShape(regen.data, 'SC-P-41 idempotent ' + i);
+      expect(sectionByKey(regen.data.sections, 'nutrition'), 'nutrition 不漂移').toEqual(keepNutrition);
+      expect(regen.data.sections.filter(function (s) { return s.key === 'exercise'; }).length, 'exercise 仅一条').toBe(1);
+      // nutrition 与未触动的 diet 不丢
+      expect(sectionByKey(regen.data.sections, 'diet') != null, 'diet 不丢').toBe(true);
+      expect(keepExercise.key).toBe('exercise');
+    }
+  });
+
+  test('[异常] 未知 sectionKey → 不500、三板块不丢、overview 不变(不匹配任何板块不破坏结构)', async ({ request }) => {
+    const member = await makeMember(request, 'sc-p41-badkey');
+    const memberId = member.userId != null ? member.userId : undefined;
+    const goal = '提升孩子专注力';
+
+    const gen = await apiPost(request, '/api/ai/plan/generate', { goal: goal, memberId: memberId }, member.token);
+    expect(gen.code).toBe(200);
+    const before = gen.data.sections.map(function (s) { return { key: s.key, title: s.title, content: s.content }; });
+
+    const regen = await apiPost(
+      request,
+      '/api/ai/plan/regenerate-section',
+      { sectionKey: 'nonexistent-section', content: 'x', memberId: memberId, goal: goal },
+      member.token,
+    );
+
+    expect(regen.status, '未知 sectionKey 不 500').not.toBe(500);
+    expect(regen.code, '未知 sectionKey 仍业务成功(不破坏三板块) code=200, 实际=' + regen.code).toBe(200);
+    assertPlanShape(regen.data, 'SC-P-41 unknown sectionKey');
+    expect(regen.data.overview, 'overview 不变').toBe(gen.data.overview);
+    // 未匹配 key → 不替换任何板块;其余/全部板块不丢
+    const afterKeys = regen.data.sections.map(function (s) { return s.key; });
+    expect(afterKeys, '三板块不丢').toEqual(SECTION_KEYS);
+  });
+
+  test('[异常·超时降级不500] 上游超时/不可用 → 重生成仍 HTTP200+code=200 + 三板块不丢 + fallback_used=boolean,不 500', async ({ request }) => {
+    const member = await makeMember(request, 'sc-p41-timeout');
+    const memberId = member.userId != null ? member.userId : undefined;
+    const goal = '提升孩子专注力';
+
+    const gen = await apiPost(request, '/api/ai/plan/generate', { goal: goal, memberId: memberId }, member.token);
+    expect(gen.code).toBe(200);
+
+    const regen = await apiPost(
+      request,
+      '/api/ai/plan/regenerate-section',
+      { sectionKey: 'nutrition', content: sectionByKey(gen.data.sections, 'nutrition').content, memberId: memberId, goal: goal },
+      member.token,
+    );
+
+    expect(regen.status, '超时降级也不 HTTP500').not.toBe(500);
+    expect(regen.code, '超时降级仍 code=200').toBe(200);
+    assertPlanShape(regen.data, 'SC-P-41 timeout-fallback');
+    // 目标板块重生成失败时 Fallback 填充默认内容,其余两板块仍保留
+    const others = regen.data.sections.filter(function (s) { return s.key !== 'nutrition'; });
+    expect(others.length, '其余两板块不丢').toBe(2);
+  });
+
+  test('[权限·未购会员拦截] 已登录非会员 → code=46003,不500,不重生成', async ({ request }) => {
+    const free = await register(request, 'parent', 'sc-p41-free');
+
+    const r = await apiPost(
+      request,
+      '/api/ai/plan/regenerate-section',
+      { sectionKey: 'diet', content: 'x', memberId: free.userId, goal: 'x' },
+      free.token,
+    );
+
+    expect(r.status, '不500').not.toBe(500);
+    expect(r.code, '未购会员拦截 46003, 实际=' + r.code).toBe(ERR_AI_COACH_MEMBER_ONLY);
+    expect(r.data == null).toBe(true);
+  });
+
+  test('[权限·鉴权] 无效 token → HTTP401 code=401', async ({ request }) => {
+    const res = await request.post('/api/ai/plan/regenerate-section', {
+      data: { sectionKey: 'diet', memberId: 1, goal: 'x' },
+      headers: { Authorization: 'Bearer invalid.token.here' },
+      timeout: 30000,
+    });
+    expect(res.status()).toBe(401);
+    const body = await res.json().catch(() => ({}));
+    expect(body.code).toBe(401);
+  });
+
+  test.fixme(
+    '[权限·越权 G-304-1 承袭·真实缺陷未修] 跨家庭 memberId 重生成应 403,但当前未做家庭归属校验 → 已实测放行',
+    async ({ request }) => {
+      const a = await makeMember(request, 'sc-p41-famA');
+      const b = await register(request, 'parent', 'sc-p41-famB');
+      const r = await apiPost(
+        request,
+        '/api/ai/plan/regenerate-section',
+        { sectionKey: 'diet', content: 'x', memberId: b.userId, goal: 'x' },
+        a.token,
+      );
+      expect(r.code, '跨家庭 memberId 应 403(G-304-1 承袭,当前实测放行)').toBe(403);
+    },
+  );
+});
+
+// 安全约定:本文件不打印 token / 手机号。

+ 492 - 0
tests/e2e/api/butler-collaborate-contract.spec.js

@@ -0,0 +1,492 @@
+// ============================================================================
+// [D-06 · SC-H-06 · 能力键 butler.ai.collaborate · TC-H-06 / TC-H-06-E / TC-H-06-P]
+// 三流(功能 / 异常 / 权限)e2e 契约用例 —— AI 管家协同闭环
+// ----------------------------------------------------------------------------
+// 接口(docs/tdd/orchestration/discovery-2026-11-30-1008.md §3;D8 ButlerController L376/L391/L403):
+//   POST /api/butler/collaborate/close     闭环标记:结论/处置/时长完整保存 + 工单置 CLOSED + 审计
+//   POST /api/butler/collaborate/feedback  提炼可复用结论 + 反哺:脱敏 + 幂等去重 → 入待审队列(PENDING_REVIEW),非直接入库
+//   POST /api/butler/collaborate/notify    反馈原家长 + 关闭升级链路:仅「审核通过」的反哺可通知
+//
+// 闭环完整链路(sc-key-map SC-H-06 / TC-H-06):
+//   闭环标记 → 知识反哺(脱敏+去重) → 入待审 → 运营审核(APPROVED 入库 / REJECTED 退回) → 可检索 → 反馈家长 → 全程审计
+//
+// 契约来源(已逐条核对后端实现,只读,不改生产源码):
+//   cfc-backend/.../controller/butler/ButlerController.java L376/L391/L403
+//   cfc-backend/.../service/ButlerAiCollaborationService.java
+//     closeOrder:      workorderId/userId 空→400;工单不存在→404「工单不存在」;非本家庭→403「仅本家庭工单可操作」;
+//                      已 CLOSED→409「工单已闭环」;保存 resolution/reviewConclusion/durationMinutes + status=CLOSED + closedAt;
+//                      审计 ACTION_CLOSE_ORDER(actor_role=butler);成功 code=200 message「工单已闭环」
+//     submitFeedback:  workorderId/userId 空→400;脱敏后空→400「反哺内容不能为空或不合规」;工单不存在→404;
+//                      非本家庭→403;同工单+同内容指纹重复→409「该结论已反哺,请勿重复提交」;
+//                      status=PENDING_REVIEW + dedupeKey(WO-{id}-{hash}) + notified=0;继承工单 conclusion/disposition/duration;
+//                      审计 ACTION_SUBMIT_FEEDBACK;code=200 message「反哺已提交待审队列」
+//     sanitizeFeedback: 手机号→1**********;身份证→******************;邮箱→***@***(脱敏,不以 403 拒绝隐私内容)
+//     notifyParent:    workorderId/feedbackId 空→400;反哺不存在或工单不匹配→404;
+//                      !isApprovedForKnowledge→409「反哺未审核通过,不得反馈家长」(未审不入库/不可反馈);
+//                      通过→ set notified=1;DTO{workorderId,feedbackId,familyId,conclusion,disposition,durationMinutes,
+//                      sourceWorkorderId,notifiedAt};审计 ACTION_NOTIFY_PARENT(actor_role=operator);code=200「已反馈原家长」
+//   审核(运营侧,非本任务 3 端点,用于驱动闭环至「审核通过」):
+//     POST /api/admin/knowledge-base/unified/feedback/pending  运营待审队列;非运营→403「仅运营角色可审核反哺」;匿名→401
+//     POST /api/admin/knowledge-base/unified/feedback/audit    {feedbackId,decision:APPROVED|REJECTED,remark}
+//         仅 admin/operator/knowledge_admin;非运营→403;PENDING_REVIEW→APPROVED+reviewerId+reviewedAt;
+//         已审核→409;写入审计 ACTION_AUDIT_FEEDBACK(actor_role=operator)
+//   家庭隔离 familyMatches(user.familyId == order.familyId) → 跨家庭 403
+//   Result<T>: success code=200;error code 在 body、HTTP 仍 200;JwtInterceptor 匿名→401;
+//     /api/admin/** 匿名→401、非 admin/operator→403
+//
+// 鉴权 / 真实契约(实测,见本任务探针 _probe_*.spec.js gitignore):
+//   ① 协作端点「完全不带 token」:close/feedback → 403「仅本家庭工单可操作」(匿名 userId=-1,familyId=null→不匹配);
+//      非本家庭→403;非运营审核→403。(协作端点不强制 401;admin 端点匿名→401。)
+//   ② 管家自审核 → 403「仅运营角色可审核反哺」;审核权归运营(TC-H-06-P)。
+//   ③ 跨家庭读/写工单/反哺 → 403;SC-H-06 本组实现家庭隔离(对比 G-304-1 只涉本组 A,本组不承袭)。
+//
+// 隐私脱敏 + 403(任务口径核实,真实契约):
+//   ✦「隐私脱敏」:反哺含家长隐私(手机号/身份证/邮箱)→ sanitizeFeedback 脱敏后入待审/入库;
+//      原文不入库、不下发;不以 403 拒绝隐私内容(真实为 code=200 + 脱敏)。TC-H-06-E「拦截并提示脱敏,不允许带隐私入库」
+//      在本实现 = 「脱敏后才入待审」;仅「脱敏后为空」→ 400。
+//   ✦「403」:越界/越权 —— 管家读/写他人家庭工单/反哺→403;管家自行审核→403;家长直接写入 AI 知识库(非运营审核)→403;
+//      审核权归运营。(TC-H-06-P)
+//   两者合并断言:隐私内容不以明文入库/下发 + 越权 403。
+//
+// 「未审不入库」(TC-H-06-E):PENDING_REVIEW 反哺不得反馈家长(notify→409)、不得计入已批准知识;
+//   仅 APPROVED 且 content 非空(isApprovedForKnowledge)才可 notify / 可检索。
+//   本任务 3 端点无「未审入库」路径;notify 是未审→已审的硬闸门。
+//
+// 「审核通过可检索」(TC-H-06 步骤 4/5 / SC-H-06):审核通过 → status=APPROVED + reviewerId + reviewedAt,
+//   从待审队列移除,isApprovedForKnowledge=true(ButlerAiCollaborationService.verifyKnowledgeHit),notify 放行。
+//   ⚠ 承袭差距(真实契约核实,非放水):本实现「审核通过」= butler_ai_feedback.status=APPROVED + isApprovedForKnowledge;
+//     但**未观测到把反哺写入 AI 知识库正文的独立 insert**,且 ButlerAiCollaborationService.verifyKnowledgeHit /
+//     isApprovedForKnowledge / pendingFeedbacks 的「可检索」判定**未暴露 HTTP 查询端点**(仅运营 /feedback/pending 可见状态)。
+//     故本用例断言真实可检索代理(APPROVED + 移出待审 + notify 放行 + 脱敏内容保留),并标注承袭差距,不伪造 kb-hit 绿。
+//     「AI 再问同类问题能命中新知识」需 kb 检索端点,本组 3 端点不覆盖(见 SC-H-06 登记 / discovery O-03)。
+//
+// 「审计可读」(SC-H-06 可审计 / TC-H-06):close/feedback/audit/notify 全程写 butler_ai_collaboration_audit_log;
+//   ButlerAiCollaborationService.auditLog(workorderId[,familyId]) 只读查询存在,但**未暴露 HTTP 端点**。
+//   本用例:① 断言 HTTP 可读审计代理(已闭环字段、待审/已审状态、reviewerId、reviewedAt、notified、来源追溯 sourceWorkorderId);
+//   ② 直接查 butler_ai_collaboration_audit_log 校验 CLOSE_ORDER/SUBMIT_FEEDBACK/AUDIT_FEEDBACK/NOTIFY_PARENT 落库(需 mysql CLI)。
+//   并标注「审计表无 HTTP 读端点」承袭差距,不伪造。
+//
+// 工单构造:后端**无 HTTP 创建 butler_escalation_orders 的端点**(ButlerEscalationOrderMapper 无 insert 路径;
+//   /api/butler/escalation/* 只 claim/list/detail/...已存在工单)。本用例用 mysql CLI 直接 seed 一条 PROCESSING 工单
+//   (与 tests/e2e/reset-db.sh / flow-l1-tests.js 的 mysql 直连约定一致),不改生产源码、不改台账。
+//   mysql CLI 不可用时本用例明确失败(不造绿)。DB 连接用 MYSQL_HOST/MYSQL_USER/MYSQL_PASS/MYSQL_DB(默认对齐本地 cfc-backend)。
+//
+// 运行:
+//   CFC_API_BASE=http://127.0.0.1:9082 MYSQL_HOST=192.168.16.251 MYSQL_USER=zxyj MYSQL_PASS=zxyj@123 MYSQL_DB=zxyj \
+//     npx playwright test api/butler-collaborate-contract.spec.js -c tests/playwright.config.api.js --project=desktop
+// 安全约定:不打印 token / 手机号;测试数据全部自建 direct-register + seed,不改动存量业务数据。
+// ============================================================================
+
+const { test, expect } = require('@playwright/test');
+const { execFileSync } = require('child_process');
+const { apiPost } = require('../helpers/api');
+
+const API_TIMEOUT_MS = 120000;
+
+// ---------------------------------------------------------------------------
+// helpers(禁可选链 ?.;不用 new Date(string);中文内容经参数传入 SQL,不拼接裸值)
+// ---------------------------------------------------------------------------
+
+/** 注册账号(direct-register),返回 token/userId/familyId */
+async function register(request, role, tag) {
+  const phone = '13' + String(Math.floor(Math.random() * 900000000) + 100000000);
+  let lastErr;
+  for (let i = 0; i < 3; i++) {
+    try {
+      const r = await request.post('/api/auth/direct-register', {
+        data: { phone, role, nickname: 'QA-' + tag },
+        timeout: 60000,
+      });
+      const body = await r.json().catch(() => ({}));
+      if (body.code === 200 && body.data && body.data.token) {
+        return { token: body.data.token, userId: body.data.userId, familyId: body.data.familyId, role: role };
+      }
+      lastErr = body;
+    } catch (e) {
+      lastErr = e && e.message ? e.message : String(e);
+    }
+  }
+  throw new Error('register(' + role + ') 失败: ' + JSON.stringify(lastErr));
+}
+
+// ---------- mysql CLI(与 reset-db.sh / flow-l1-tests.js 约定一致;环境变量对齐 cfc-backend 数据源) ----------
+const MYSQL_CLI = process.env.MYSQL_CLI || 'mysql';
+const MYSQL_HOST = process.env.MYSQL_HOST || '192.168.16.251';
+const MYSQL_PORT = process.env.MYSQL_PORT || '3306';
+const MYSQL_USER = process.env.MYSQL_USER || 'zxyj';
+const MYSQL_PASS = process.env.MYSQL_PASS != null ? process.env.MYSQL_PASS : 'zxyj@123';
+const MYSQL_DB = process.env.MYSQL_DB || 'zxyj';
+
+/** 转义 SQL 字符串字面量(单引号翻倍 + 去 NUL/反斜杠处理),仅用于本测试构造的受控值 */
+function sqlStr(s) {
+  return "'" + String(s == null ? '' : s).replace(/\\/g, '\\\\').replace(/'/g, "''").replace(/\0/g, '') + "'";
+}
+
+/** 执行 SQL(经 stdin 传入,返回原始输出;mysql CLI 不可用即抛错,不造绿) */
+function mysqlExec(sql) {
+  const args = ['-h', MYSQL_HOST, '-P', MYSQL_PORT, '-u', MYSQL_USER];
+  if (MYSQL_PASS !== '') args.push('-p' + MYSQL_PASS);
+  // -N --skip-column-names -B --batch:tab 分隔、无表头/无边框,便于机器解析(真实 mysql CLI 支持)
+  args.push('-N', '-B', '--default-character-set=utf8mb4', MYSQL_DB);
+  return execFileSync(MYSQL_CLI, args, { input: sql + ';\n', encoding: 'utf8', timeout: 30000 });
+}
+
+/**
+ * seed 一条 butler_escalation_orders(status=PROCESSING),返回 workorderId。
+ * 后端无 HTTP 创建路径;不改生产源码。
+ */
+function seedWorkorder(familyId, butlerUserId, parentDemand, aiConclusion) {
+  mysqlExec(
+    'INSERT INTO butler_escalation_orders ' +
+    '(family_id, butler_user_id, source_type, risk_level, status, parent_demand, ai_conclusion, escalation_level, created_at, updated_at) ' +
+    'VALUES (' + Number(familyId) + ', ' + Number(butlerUserId) + ', ' + sqlStr('AI_ESCALATION') + ', ' +
+    sqlStr('MEDIUM') + ', ' + sqlStr('PROCESSING') + ', ' + sqlStr(parentDemand || 'QA 家长诉求') + ', ' +
+    sqlStr(aiConclusion || 'QA AI 已给结论') + ', 1, NOW(), NOW())',
+  );
+  // 回退/主路径:mysql CLI 每次独立连接,LAST_INSERT_ID() 跨进程不可靠 → 按家庭取最新一条(workers=1,本测试自建数据)
+  const out = mysqlExec('SELECT id FROM butler_escalation_orders WHERE family_id=' + Number(familyId) + " AND status='PROCESSING' ORDER BY id DESC LIMIT 1").trim();
+  const lines = out.split('\n').map(function (l) { return l.trim(); }).filter(function (l) { return l !== ''; });
+  let id = null;
+  for (const line of lines) { if (/^\d+$/.test(line)) id = Number(line); }
+  if (id == null) throw new Error('seedWorkorder 取不到工单 id, raw=' + JSON.stringify(out));
+  return id;
+}
+
+/** 查审计表某工单的 action 集合(审计可读;无 HTTP 读端点时的真实落库校验) */
+function auditActionsFor(workorderId) {
+  const out = mysqlExec('SELECT action FROM butler_ai_collaboration_audit_log WHERE workorder_id=' + Number(workorderId)).trim();
+  // -N -B:无表头无边框;仅保留非空、已知 ACTION_* 形态行
+  return out.split('\n').map(function (l) { return l.trim(); }).filter(function (l) {
+    return l !== '' && l !== 'action' && !/^[-+|]/.test(l);
+  });
+}
+
+const ACTION_CLOSE_ORDER = 'CLOSE_ORDER';
+const ACTION_SUBMIT_FEEDBACK = 'SUBMIT_FEEDBACK';
+const ACTION_AUDIT_FEEDBACK = 'AUDIT_FEEDBACK';
+const ACTION_NOTIFY_PARENT = 'NOTIFY_PARENT';
+
+// ---------------------------------------------------------------------------
+// SC-H-06 · 与 AI 管家协同闭环(三流)
+// ---------------------------------------------------------------------------
+
+test.describe.serial('SC-H-06 · /api/butler/collaborate/{close,feedback,notify}(三流)', () => {
+  test.setTimeout(180000);
+
+  test('[功能 全链路] 闭环留痕→反哺待审→未审不入库→审核通过可检索→反馈家长→审计可读', async ({ request }) => {
+    const butler = await register(request, 'parent', 'sc-h06-fn-butler'); // 管家操作者(本家庭)
+    const operator = await register(request, 'admin', 'sc-h06-fn-op');    // 运营(审核权)
+
+    const workorderId = seedWorkorder(butler.familyId, butler.userId, 'QA 家长诉求', 'QA AI 已给结论');
+
+    // ---- 1. 闭环标记 close:结论/处置/时长完整保存 + 工单 CLOSED ----
+    const close = await apiPost(
+      request,
+      '/api/butler/collaborate/close',
+      { workorderId: workorderId, conclusion: '睡眠调整建议有效', disposition: '电话随访', durationMinutes: 25 },
+      butler.token,
+    );
+    expect(close.status, 'close 不500').toBe(200);
+    expect(close.code, 'close code=200, 实际=' + close.code + ' msg=' + close.message).toBe(200);
+    expect(close.message).toBe('工单已闭环');
+
+    // 闭环留痕可读(audit/readable):经 /api/butler/escalation/detail 读回已保存字段
+    const detail = await apiPost(request, '/api/butler/escalation/detail', { workorderId: workorderId }, butler.token);
+    expect(detail.code, '读工单 code=200').toBe(200);
+    expect(detail.data.status, '工单置为已闭环 CLOSED').toBe('CLOSED');
+    expect(detail.data.resolution, '闭环结论完整保存').toBe('睡眠调整建议有效');
+    expect(detail.data.reviewConclusion, '处置方式完整保存').toBe('电话随访');
+    expect(detail.data.durationMinutes, '处置时长完整保存').toBe(25);
+    expect(detail.data.closedAt != null, 'closedAt 留痕').toBe(true);
+
+    // 已闭环再 close → 409
+    const reclose = await apiPost(
+      request,
+      '/api/butler/collaborate/close',
+      { workorderId: workorderId, conclusion: 'x', disposition: 'y', durationMinutes: 1 },
+      butler.token,
+    );
+    expect(reclose.code, '已闭环再 close → 409').toBe(409);
+
+    // ---- 2. 反哺提交 feedback:进入待审队列,未直接入库 ----
+    const feedback = await apiPost(
+      request,
+      '/api/butler/collaborate/feedback',
+      { workorderId: workorderId, content: '可复用结论:规律作息+睡前限屏,睡眠质量提升。' },
+      butler.token,
+    );
+    expect(feedback.status).toBe(200);
+    expect(feedback.code, 'feedback code=200, 实际=' + feedback.code + ' msg=' + feedback.message).toBe(200);
+    expect(feedback.message).toBe('反哺已提交待审队列');
+    const fb = feedback.data || {};
+    expect(typeof fb.id === 'number', '反哺返回 id').toBe(true);
+    const feedbackId = fb.id;
+    expect(fb.workorderId).toBe(workorderId);
+    expect(fb.familyId, '反哺绑定本家庭').toBe(butler.familyId);
+    expect(fb.status, '入待审队列 PENDING_REVIEW,未直接入库').toBe('PENDING_REVIEW');
+    expect(fb.notified, 'notified=0 未反馈').toBe(0);
+    expect(typeof fb.dedupeKey === 'string' && fb.dedupeKey.length > 0, '幂等去重键').toBe(true);
+    expect(fb.conclusion, '继承闭环结论').toBe('睡眠调整建议有效');
+    expect(fb.disposition, '继承处置').toBe('电话随访');
+    expect(fb.durationMinutes, '继承时长').toBe(25);
+    expect(fb.reviewerId == null, '未审 reviewerId 为空').toBe(true);
+    expect(fb.reviewedAt == null, '未审 reviewedAt 为空').toBe(true);
+
+    // ---- 3. 未审不入库:PENDING_REVIEW 不可 notify,且不可直接写入已审 ----
+    const notifyBefore = await apiPost(
+      request,
+      '/api/butler/collaborate/notify',
+      { workorderId: workorderId, feedbackId: feedbackId },
+      butler.token,
+    );
+    expect(notifyBefore.status).toBe(200);
+    expect(notifyBefore.code, '未审核不得反馈家长 → 409, 实际=' + notifyBefore.code).toBe(409);
+    expect(notifyBefore.message).toBe('反哺未审核通过,不得反馈家长');
+
+    // 待审队列可见(运营)
+    const pending = await apiPost(request, '/api/admin/knowledge-base/unified/feedback/pending', {}, operator.token);
+    expect(pending.code, '运营读待审队列 code=200').toBe(200);
+    const pendingList = pending.data || [];
+    expect(Array.isArray(pendingList)).toBe(true);
+    expect(pendingList.some(function (x) { return x.id === feedbackId && x.status === 'PENDING_REVIEW'; }), '待审队列含本条 PENDING_REVIEW').toBe(true);
+
+    // ---- 4. 运营审核通过 → APPROVED + reviewer + reviewedAt;移出待审;可检索代理 ----
+    const audit = await apiPost(
+      request,
+      '/api/admin/knowledge-base/unified/feedback/audit',
+      { feedbackId: feedbackId, decision: 'APPROVED', remark: 'ok' },
+      operator.token,
+    );
+    expect(audit.status).toBe(200);
+    expect(audit.code, '审核通过 code=200, 实际=' + audit.code + ' msg=' + audit.message).toBe(200);
+    const approved = audit.data || {};
+    expect(approved.status, '审核通过 APPROVED').toBe('APPROVED');
+    expect(approved.reviewerId, '审核人留痕').toBe(operator.userId);
+    expect(approved.reviewRemark).toBe('ok');
+    expect(approved.reviewedAt != null, '审核时间留痕').toBe(true);
+    expect(approved.content != null && approved.content.trim().length > 0, '已审核通过内容非空(可检索前提)').toBe(true);
+
+    const pendingAfter = await apiPost(request, '/api/admin/knowledge-base/unified/feedback/pending', {}, operator.token);
+    const pendingAfterList = pendingAfter.data || [];
+    expect(pendingAfterList.some(function (x) { return x.id === feedbackId; }), '审核通过移出待审队列').toBe(false);
+
+    // 重复审核 → 409(已审核不可重复)
+    const reAudit = await apiPost(
+      request,
+      '/api/admin/knowledge-base/unified/feedback/audit',
+      { feedbackId: feedbackId, decision: 'REJECTED', remark: 'x' },
+      operator.token,
+    );
+    expect(reAudit.code, '已审核不可重复 → 409').toBe(409);
+
+    // ---- 5. notify:仅审核通过可反馈原家长;DTO 来源追溯;notified=1 ----
+    const notify = await apiPost(
+      request,
+      '/api/butler/collaborate/notify',
+      { workorderId: workorderId, feedbackId: feedbackId },
+      butler.token,
+    );
+    expect(notify.status).toBe(200);
+    expect(notify.code, '审核通过可反馈 code=200, 实际=' + notify.code + ' msg=' + notify.message).toBe(200);
+    expect(notify.message).toBe('已反馈原家长');
+    const dto = notify.data || {};
+    expect(dto.workorderId).toBe(workorderId);
+    expect(dto.feedbackId).toBe(feedbackId);
+    expect(dto.familyId).toBe(butler.familyId);
+    expect(dto.conclusion, '反馈仅脱敏结论').toBe('睡眠调整建议有效');
+    expect(dto.disposition).toBe('电话随访');
+    expect(dto.durationMinutes).toBe(25);
+    expect(dto.sourceWorkorderId, '来源追溯 sourceWorkorderId').toBe(workorderId);
+    expect(dto.notifiedAt != null, 'notifiedAt').toBe(true);
+
+    // notified=1 可读(审计/状态)
+    const pendingFinal = await apiPost(request, '/api/admin/knowledge-base/unified/feedback/pending', {}, operator.token);
+    expect((pendingFinal.data || []).some(function (x) { return x.id === feedbackId; }), '不在待审').toBe(false);
+
+    // ---- 6. 审计可读:HTTP 代理 + butler_ai_collaboration_audit_log 落库 ----
+    // HTTP 可读代理(本组 3 端点 + 运营端点无直接 audit 读 HTTP;见文件头登记)
+    expect(detail.data.closedAt != null).toBe(true);
+    // 直接校验审计表(auditLog 服务未暴露 HTTP;真实落库 + 可读)
+    const actions = auditActionsFor(workorderId);
+    expect(actions.indexOf(ACTION_CLOSE_ORDER) >= 0, '审计含 CLOSE_ORDER').toBe(true);
+    expect(actions.indexOf(ACTION_SUBMIT_FEEDBACK) >= 0, '审计含 SUBMIT_FEEDBACK').toBe(true);
+    expect(actions.indexOf(ACTION_AUDIT_FEEDBACK) >= 0, '审计含 AUDIT_FEEDBACK').toBe(true);
+    expect(actions.indexOf(ACTION_NOTIFY_PARENT) >= 0, '审计含 NOTIFY_PARENT').toBe(true);
+  });
+
+  // -------------------------------------------------------------------------
+  // 异常流 TC-H-06-E
+  // -------------------------------------------------------------------------
+
+  test('[异常·隐私脱敏] 反哺含家长隐私(手机号/身份证/邮箱)→ 脱敏后才入待审,原文不入库不下发;脱敏后空→400', async ({ request }) => {
+    const butler = await register(request, 'parent', 'sc-h06-privacy');
+    const workorderId = seedWorkorder(butler.familyId, butler.userId, 'QA', 'QA');
+    await apiPost(
+      request, '/api/butler/collaborate/close',
+      { workorderId: workorderId, conclusion: 'c', disposition: 'd', durationMinutes: 1 }, butler.token,
+    );
+
+    const phone = '13800001111';
+    const idCard = '110101199003070011';
+    const email = 'parent.secret@example.com';
+    const raw = '可复用结论:联系家长 张三 ' + phone + ',邮箱 ' + email + ',身份证 ' + idCard + ',建议规律作息。';
+
+    const fb = await apiPost(request, '/api/butler/collaborate/feedback', { workorderId: workorderId, content: raw }, butler.token);
+    expect(fb.code, '含隐私反哺仍 code=200(脱敏,非以明文入库)').toBe(200);
+    const stored = (fb.data && fb.data.content) || '';
+    // 原始隐私不下发/不入库
+    expect(stored.indexOf(phone), '手机号原文不出现').toBe(-1);
+    expect(stored.indexOf(idCard), '身份证原文不出现').toBe(-1);
+    expect(stored.indexOf(email), '邮箱原文不出现').toBe(-1);
+    // 脱敏标记
+    expect(stored, '手机号脱敏').toContain('1**********');
+    expect(stored, '邮箱脱敏').toContain('***@***');
+    expect(stored, '身份证脱敏').toContain('******************');
+    // 非隐私内容保留
+    expect(stored, '可复用结论保留').toContain('规律作息');
+    expect(fb.data.status).toBe('PENDING_REVIEW');
+
+    // 脱敏后为空 → 400
+    const empty = await apiPost(request, '/api/butler/collaborate/feedback', { workorderId: workorderId, content: '   ' }, butler.token);
+    expect(empty.code, '空内容 → 400').toBe(400);
+    expect(empty.message).toBe('反哺内容不能为空或不合规');
+  });
+
+  test('[异常·未审不入库] PENDING_REVIEW 不可 notify(409);重复反哺幂等去重(409);已审核不可重复(409)', async ({ request }) => {
+    const butler = await register(request, 'parent', 'sc-h06-unaudited');
+    const operator = await register(request, 'admin', 'sc-h06-unaudited-op');
+    const workorderId = seedWorkorder(butler.familyId, butler.userId, 'QA', 'QA');
+    await apiPost(request, '/api/butler/collaborate/close', { workorderId: workorderId, conclusion: 'c', disposition: 'd', durationMinutes: 1 }, butler.token);
+
+    const content = '可复用结论XYZ-去重测试';
+    const fb = await apiPost(request, '/api/butler/collaborate/feedback', { workorderId: workorderId, content: content }, butler.token);
+    expect(fb.code).toBe(200);
+    const feedbackId = fb.data.id;
+
+    // 未审核不入库/不可反馈
+    const notifyPre = await apiPost(request, '/api/butler/collaborate/notify', { workorderId: workorderId, feedbackId: feedbackId }, butler.token);
+    expect(notifyPre.code, 'PENDING_REVIEW 不可 notify → 409').toBe(409);
+
+    // 同一结论重复反哺 → 幂等去重 409
+    const dup = await apiPost(request, '/api/butler/collaborate/feedback', { workorderId: workorderId, content: content }, butler.token);
+    expect(dup.code, '重复反哺 → 409').toBe(409);
+    expect(dup.message).toBe('该结论已反哺,请勿重复提交');
+
+    // 运营待审队列仅 1 条(去重)
+    const pending = await apiPost(request, '/api/admin/knowledge-base/unified/feedback/pending', {}, operator.token);
+    const matching = (pending.data || []).filter(function (x) { return x.workorderId === workorderId && x.content === content; });
+    expect(matching.length, '同一结论仅 1 条待审').toBe(1);
+  });
+
+  test('[异常·隐私脱敏 403 越权] 非本家庭工单不可 close/feedback(403);跨家庭不可读反哺(403);家长直接写入知识库(403)', async ({ request }) => {
+    const owner = await register(request, 'parent', 'sc-h06-iso-owner');
+    const intruder = await register(request, 'parent', 'sc-h06-iso-intruder');
+    const workorderId = seedWorkorder(owner.familyId, owner.userId, 'QA', 'QA');
+
+    // 先本家庭闭环 + 反哺,造出反哺条目
+    await apiPost(request, '/api/butler/collaborate/close', { workorderId: workorderId, conclusion: 'c', disposition: 'd', durationMinutes: 1 }, owner.token);
+    const fb = await apiPost(request, '/api/butler/collaborate/feedback', { workorderId: workorderId, content: '可复用结论' }, owner.token);
+    expect(fb.code).toBe(200);
+
+    // 跨家庭 close → 403
+    const crossClose = await apiPost(request, '/api/butler/collaborate/close', { workorderId: workorderId, conclusion: 'x', disposition: 'y', durationMinutes: 1 }, intruder.token);
+    expect(crossClose.status).toBe(200);
+    expect(crossClose.code, '跨家庭 close → 403').toBe(403);
+    expect(crossClose.message).toBe('仅本家庭工单可操作');
+
+    // 跨家庭 feedback → 403
+    const crossFb = await apiPost(request, '/api/butler/collaborate/feedback', { workorderId: workorderId, content: '越权内容' }, intruder.token);
+    expect(crossFb.code, '跨家庭 feedback → 403').toBe(403);
+    expect(crossFb.message).toBe('仅本家庭工单可操作');
+
+    // 家长直接写入 AI 知识库(非运营审核)→ 403
+    const directKb = await apiPost(request, '/api/admin/knowledge-base/unified/feedback/audit', { feedbackId: fb.data.id, decision: 'APPROVED' }, owner.token);
+    expect(directKb.status).toBe(200);
+    expect(directKb.code, '家长直接写入知识库 → 403').toBe(403);
+    expect(directKb.message).toBe('仅运营角色可审核反哺');
+  });
+
+  test('[异常·不存在] 工单不存在 close/feedback→404;notify 反哺不存在/不匹配→404;参数缺失→400', async ({ request }) => {
+    const u = await register(request, 'parent', 'sc-h06-404');
+
+    const close404 = await apiPost(request, '/api/butler/collaborate/close', { workorderId: 99999999, conclusion: 'c', disposition: 'd', durationMinutes: 1 }, u.token);
+    expect(close404.code, 'close 工单不存在→404').toBe(404);
+    expect(close404.message).toBe('工单不存在');
+
+    const fb404 = await apiPost(request, '/api/butler/collaborate/feedback', { workorderId: 99999999, content: 'x' }, u.token);
+    expect(fb404.code, 'feedback 工单不存在→404').toBe(404);
+
+    const notify404 = await apiPost(request, '/api/butler/collaborate/notify', { workorderId: 99999999, feedbackId: 99999999 }, u.token);
+    expect(notify404.code, 'notify 反哺不存在→404').toBe(404);
+    expect(notify404.message).toBe('反哺条目不存在或与工单不匹配');
+
+    // 参数缺失 → 400
+    const missClose = await apiPost(request, '/api/butler/collaborate/close', { conclusion: 'c', disposition: 'd', durationMinutes: 1 }, u.token);
+    expect(missClose.code, 'close workorderId 缺失→400').toBe(400);
+    expect(missClose.message).toBe('workorderId和userId不能为空');
+
+    const missNotify = await apiPost(request, '/api/butler/collaborate/notify', { workorderId: 1 }, u.token);
+    expect(missNotify.code, 'notify feedbackId 缺失→400').toBe(400);
+    expect(missNotify.message).toBe('workorderId和feedbackId不能为空');
+  });
+
+  // -------------------------------------------------------------------------
+  // 权限流 TC-H-06-P
+  // -------------------------------------------------------------------------
+
+  test('[权限·审核权归运营] 管家自审核→403;非运营待审队列→403;运营可审核(admin/operator/knowledge_admin)', async ({ request }) => {
+    const butler = await register(request, 'parent', 'sc-h06-p-self');
+    const operator = await register(request, 'admin', 'sc-h06-p-op');
+    const workorderId = seedWorkorder(butler.familyId, butler.userId, 'QA', 'QA');
+    await apiPost(request, '/api/butler/collaborate/close', { workorderId: workorderId, conclusion: 'c', disposition: 'd', durationMinutes: 1 }, butler.token);
+    const fb = await apiPost(request, '/api/butler/collaborate/feedback', { workorderId: workorderId, content: '可复用结论' }, butler.token);
+    expect(fb.code).toBe(200);
+    const feedbackId = fb.data.id;
+
+    // 管家自行审核通过 → 403
+    const selfAudit = await apiPost(request, '/api/admin/knowledge-base/unified/feedback/audit', { feedbackId: feedbackId, decision: 'APPROVED' }, butler.token);
+    expect(selfAudit.code, '管家仅有提交权、审核权归运营 → 403').toBe(403);
+    expect(selfAudit.message).toBe('仅运营角色可审核反哺');
+
+    // 非运营读待审队列 → 403
+    const pendingNo = await apiPost(request, '/api/admin/knowledge-base/unified/feedback/pending', {}, butler.token);
+    expect(pendingNo.code, '非运营读待审→403').toBe(403);
+
+    // 管家自审失败后反哺仍 PENDING_REVIEW,未审不入库
+    const notifyPre = await apiPost(request, '/api/butler/collaborate/notify', { workorderId: workorderId, feedbackId: feedbackId }, butler.token);
+    expect(notifyPre.code, '管家自审未生效,仍未审 → notify 409').toBe(409);
+
+    // 运营可审核
+    const opAudit = await apiPost(request, '/api/admin/knowledge-base/unified/feedback/audit', { feedbackId: feedbackId, decision: 'APPROVED' }, operator.token);
+    expect(opAudit.code, '运营审核 code=200').toBe(200);
+    expect((opAudit.data || {}).status).toBe('APPROVED');
+  });
+
+  test('[权限·鉴权] 协作端点匿名/无 token → 不放行(403);admin 审核匿名→401', async ({ request }) => {
+    const u = await register(request, 'parent', 'sc-h06-anon');
+    const workorderId = seedWorkorder(u.familyId, u.userId, 'QA', 'QA');
+
+    // close 匿名:匿名 userId=-1/familyId=null → 非本家庭 → 403(协作端点不强制 401)
+    const anonClose = await request.post('/api/butler/collaborate/close', {
+      data: { workorderId: workorderId, conclusion: 'c', disposition: 'd', durationMinutes: 1 },
+      timeout: 30000,
+    });
+    expect(anonClose.status(), '匿名 close 不 500').toBe(200);
+    const anonCloseBody = await anonClose.json().catch(() => ({}));
+    expect(anonCloseBody.code, '匿名 close → 403').toBe(403);
+
+    // feedback 匿名 → 403
+    const anonFb = await request.post('/api/butler/collaborate/feedback', { data: { workorderId: workorderId, content: 'x' }, timeout: 30000 });
+    const anonFbBody = await anonFb.json().catch(() => ({}));
+    expect(anonFbBody.code, '匿名 feedback → 403').toBe(403);
+
+    // admin 审核匿名 → 401
+    const anonAdmin = await request.post('/api/admin/knowledge-base/unified/feedback/pending', { timeout: 30000 });
+    expect(anonAdmin.status(), '/api/admin 匿名→401').toBe(401);
+    const anonAdminBody = await anonAdmin.json().catch(() => ({}));
+    expect(anonAdminBody.code).toBe(401);
+    expect(anonAdminBody.message).toBe('请先登录');
+  });
+});
+
+// 安全约定:本文件不打印 token / 手机号。