Explorar el Código

TDD RED S-DEV-23: 新增 sleep.config.tags 契约级单测 AdminGuideConfigController 获取/保存场景

zxyj-langgraph hace 3 horas
padre
commit
18fcf76510

+ 109 - 0
docs/superpowers/plans/verify/verify-coupon-c3-2026-10-31.md

@@ -0,0 +1,109 @@
+# 核验报告:COUPON-C3(用户端「领券中心」页面)
+
+- 核验日期:2026-10-31
+- 核验对象:`origin/feature/coupon-center-c3` @ `30bb2255d7`(相对 `origin/cfclub` @ `f349c8c87`)
+- 需求基线:`docs/优惠券需求设计与实现核查.md` §五 C3 / §四「用户端领券中心缺失」
+- 核验性质:**只读独立核验**(未改业务代码、未新建分支、未 commit、未 push;构建在 `/tmp/opencode/verify-c3` 独立 worktree 中执行)
+- 核验方式:以代码实际为准(不信任已有报告)
+
+---
+
+## 一、结论
+
+| 项 | 结果 |
+|---|---|
+| **verdict** | **fail** |
+| blocking | **1 项**(B1:领券中心数据源用错,导致「立即领取」在 100% 情况下失败,页面不具备"领券"能力) |
+| 编译/构建 | `cfc-frontend` `npm run build:mp-weixin` **通过**(EXIT=0) |
+| diff 范围 | 与任务描述一致(3 文件,+299/-1),无夹带无关文件 |
+| 合并性 | 与当前 `origin/cfclub` 三方合并**无冲突**;与 P2 分支合并**无冲突** |
+
+---
+
+## 二、B1(blocking):领券中心用「已拥有券」接口当「可取券」接口,领取必然失败
+
+### 证据链
+
+1. **页面数据源**
+   - `cfc-frontend/pages/profile-extra/coupon-center.vue:34` 引入 `getCouponList`,`:63` `getCouponList().then(...)`
+   - `cfc-frontend/utils/api.js:2608` `getCouponList = () => request('/api/coupon/list', 'POST')`
+   - `cfc-backend/.../controller/CouponController.java:26-29` → `couponService.listAvailable(userId)`
+   - `cfc-backend/.../service/CouponService.java:98-124` `listAvailable` 的实现是:
+     先查 `family_coupon WHERE family_id = ? AND status = 'AVAILABLE'`,再逐条取 `coupon` 模板信息。
+     **即:`/api/coupon/list` 返回的是"本家庭已拥有且可用的券实例",不是"平台可领取的券模板"。**
+
+2. **领取动作**
+   - `coupon-center.vue:86` `claimCoupon(item.couponId || item.id)`,`couponId` 来自 `toCouponVO` 的模板 id(`CouponService.java:77` `item.put("couponId", coupon.getId())`)——参数本身正确。
+   - `CouponService.java:148-154` `claim()` 先做去重:`selectCount(family_coupon WHERE family_id=? AND coupon_id=?)`,`count > 0` 直接 `return "已领取过该优惠券"`(**不区分 status,USED 也算**)。
+   - 而列表里展示的每一条券,恰恰就是该家庭 `family_coupon` 里已存在的那一条 → **点「立即领取」必然命中该分支**,`Result.error(String)` 返回 `code=500`(`common/Result.java:37-43`),前端走 `coupon-center.vue:91-93` 提示「已领取过该优惠券」。
+
+3. **入口与空状态互锁(加重)**
+   - 入口只有一个:`coupons.vue:55` 的 `v-if="tabIndex === 0"` 空状态文案(`:280` `goToCouponCenter`)。
+   - 该入口**只在"我的优惠券-可使用"为空时出现**;此时家庭 `family_coupon` 为空 → `listAvailable` 返回空 → `coupon-center.vue:6-10` 显示「暂无可领取的优惠券」。
+   - 即:入口出现的那一刻,落地页必然为空;落地页非空时,用户已在「我的优惠券」里拥有这些券,领取又必然失败。**两条路径都不可能完成一次真实领取。**
+
+### 期望
+
+- 「领券中心」应展示**平台可领取(未拥有)的券模板**,而不是家庭已拥有的券实例。当前后端没有任何"可取券模板"端点(现有相关端点:`listExchangeable`(积分价>0)、`listUnownedExchangeable`(积分价>0 且未拥有)、`listJoinRules`(仅 JOIN 券)、`listByProduct`),C3 只改前端的 3 文件范围本身无法满足该需求。
+- 最小修复方向(需后端配套,超出 C3 现有 diff 范围,建议单开批次):
+  1. 后端新增/扩展端点,返回 `coupon WHERE status=ACTIVE AND 有效期命中 AND id NOT IN (本家庭 family_coupon.coupon_id)` 的模板列表(可复用 `listUnownedExchangeable` 的去重写法,去掉 `points_price > 0` 限制);
+  2. 前端 `coupon-center.vue` 改调该端点;`claim` 的 `couponId` 语义保持不变(模板 id);
+  3. 领取成功后从列表移除该券或重载。
+- 若产品口径是"领券中心就是展示已发放到家庭的券",则页面文案/按钮必须改为「去使用」而非「立即领取」,并删除必然失败的 claim 调用;但这与 spec「拉可取券」的表述不符,需产品确认。
+
+---
+
+## 三、非阻断问题(不构成 P0,但建议同批或后续修)
+
+| 编号 | 问题 | 证据 | 说明 |
+|---|---|---|---|
+| N1 | 折扣券主展示位显示金额而非折扣,且折扣换算单位错 10 倍 | `coupon-center.vue:15` `formatPriceWithSymbol(item.value)`;`:109` `((item.discountRate || 0) / 100).toFixed(1) + '折'` | `discount_rate` 为**千分比**(`schema.sql:2342` 注释 `9000=9折`),应 `/1000`;`/100` 会渲染成「90.0折」。该错法与既有 4 处一致(`coupons.vue`、`upgrade.vue`、`wealth-cf/index.vue`、`CouponManagement.vue:41`),属既有问题被新页面复制,非 C3 引入的新口径 |
+| N2 | 券适用范围枚举标签不全 | `coupon-center.vue:116-120` `getScopeText` 只映射 `ALL`/`MEMBERSHIP` | `PRODUCT`/`ASSESSMENT` 会原样显示英文;P2 已在 `coupons.vue` 补了这两个标签(`P2` diff `coupons.vue:254-258`),C3 未同步,两页口径不一致 |
+| N3 | 无常规入口 | 全仓仅 `coupons.vue:55` 一处跳转 | spec 只要求"空状态入口跳转",故不算违约;但「领券中心」在个人中心无固定入口,可发现性差 |
+| N4 | `claiming` 为全局单标志 | `coupon-center.vue:44,77` | 并发点两张券时第二张被静默忽略,属体验瑕疵,不阻断 |
+
+---
+
+## 四、需求满足度逐条核对(C3)
+
+| 需求点(spec §五 C3) | 结论 | 证据 |
+|---|---|---|
+| `pages.json` 注册领券中心页面 | ✅ 满足 | `pages.json:1786`,位于子包 `root: "pages/profile-extra"`(`:1747`)内,`path: "coupon-center"`,标题「领券中心」;`coupons.vue:281` 跳转 `/pages/profile-extra/coupon-center` 与注册路径一致 |
+| 新建独立「领券中心」页面 | ⚠️ 页面存在 | `coupon-center.vue`(281 行):列表/空状态/领取按钮/字体缩放 mixin(`@/mixins/font-scale.js`)齐备 |
+| 调 `/api/coupon/list` 拉**可取券** | ❌ 未满足 | 该端点返回已拥有券实例(见 B1 证据 1) |
+| 调 `/api/coupon/claim` 领取 | ❌ 实际不可用 | 调用链正确,但必然命中"已领取过"(见 B1 证据 2) |
+| `coupons.vue:55` 空状态文案改为跳转真实页面 | ✅ 满足 | `coupons.vue:55` 改为 `@click="goToCouponCenter"` 的可点击 view,`:280-282` 新增方法,`:366-372` 新增 `$brand-primary` 高亮样式;原「指向不存在的页面」问题已消除 |
+| 小程序规范(禁可选链/禁 grid/`:key` 无表达式/日期用 `parseDate`) | ✅ 满足 | `coupon-center.vue` 无 `?.`、布局全 flex、`:key="item.id"`(无运算符)、`:121-129` 用 `utils/format.js` 的 `parseDate` |
+
+---
+
+## 五、diff 范围核对
+
+```
+cfc-frontend/pages.json                            |   6 +
+cfc-frontend/pages/profile-extra/coupon-center.vue | 281 +++++++++++++++++++++
+cfc-frontend/pages/profile-extra/coupons.vue       |  13 +-
+3 files changed, 299 insertions(+), 1 deletion(-)
+```
+
+- 与任务描述(3 文件,+299/-1)**完全一致**,无夹带无关文件、无后端/文档改动。
+- 无新增 DB 迁移。
+- 三方合并检查:`git merge-tree --write-tree origin/cfclub origin/feature/coupon-center-c3` → **exit 0,无冲突**;与 `origin/feature/coupon-p2-tech-debt` 合并 → **无冲突**(两者对 `coupons.vue` 的改动落在不同 hunk)。
+
+---
+
+## 六、编译 / 构建验证
+
+| 目标 | 命令 | 结果 |
+|---|---|---|
+| `cfc-frontend`(C3 唯一涉及端) | `npm run build:mp-weixin`(worktree `/tmp/opencode/verify-c3`,node_modules 软链自主仓) | **EXIT=0**,`DONE Build complete. dist/dev/mp-weixin`;仅有既存告警(`getTeacherPendingTasks` / `getTeacherUnreadCount` 未导出,与本次改动无关) |
+
+> C3 不涉及后端与 `cfc-web`,按任务要求未跑这两端。
+
+---
+
+## 七、结论与建议
+
+- **verdict: fail**。页面骨架、路由注册、空状态跳转均按 spec 落地,构建通过;但**数据源选错导致核心动作「领取」100% 失败**,属"需求未满足 + 正确性缺陷",不能按"已实现领券中心"合入 cfclub。
+- 建议:C3 打回,补后端"可取券模板列表"端点后再联调(预计后端 +1 端点、前端改 1 处调用),并顺手统一折扣券展示单位(`/1000`)与 `PRODUCT`/`ASSESSMENT` 标签。
+- 本报告为只读核验结论,**未做任何修复**。

+ 137 - 0
docs/superpowers/plans/verify/verify-coupon-p2-2026-10-31.md

@@ -0,0 +1,137 @@
+# 核验报告:COUPON-P2(优惠券 P2 技术债打包)
+
+- 核验日期:2026-10-31
+- 核验对象:`origin/feature/coupon-p2-tech-debt` @ `59bc4100b`(相对 `origin/cfclub` @ `f349c8c87`,merge-base `802fc5adc`)
+- 需求基线:`docs/优惠券需求设计与实现核查.md` §四「【低 P2】」三条 + §五「P2 项建议纳入下一轮技术债清理」
+- 核验性质:**只读独立核验**(未改业务代码、未新建分支、未 commit、未 push;编译/构建在 `/tmp/opencode/verify-p2` 独立 worktree 中执行)
+- 核验方式:以代码实际为准(不信任已有报告)
+
+---
+
+## 一、结论
+
+| 项 | 结果 |
+|---|---|
+| **verdict** | **pass** |
+| blocking | **无**(三类阻断:正确性缺陷 / 需求未满足 / 契约与数据完整性破坏 均未发现) |
+| 编译 | `cfc-backend` `mvn -DskipTests compile` **BUILD SUCCESS** |
+| 构建 | `cfc-frontend` `npm run build:mp-weixin` **EXIT=0**;`cfc-web` `npm run build` **EXIT=0** |
+| diff 范围 | 与任务描述一致(13 文件,+229/-102),无夹带无关文件;无新增 DB 迁移 |
+| ⚠️ 合并前置条件 | 与当前 `origin/cfclub` 合并时 **`AdminCouponController.java` 有内容冲突**,必须人工解冲突后才能合入(详见 §七) |
+
+---
+
+## 二、需求满足度逐条核对(P2 六项)
+
+| # | 需求(spec) | 结论 | 证据 |
+|---|---|---|---|
+| ① | 后台搜索框 `keyword` 失效 + 假分页 → 真分页 | ✅ 满足 | `AdminCouponController.java:52-67`:`/list` 接收 `page/size/keyword/sort`,`size` 上下界收敛(<1→20,>999→999);`CouponService.java:274-286` `pageCoupons` 用 `selectPage(new Page<>(page,size))` 真分页,`keyword` 对 `name`/`id` 模糊匹配(`like`),无排序时 `orderByDesc(id)`;`SortUtil.applySort(wrapper, sortSpecs, null)`(`SortUtil.java:127` 重载存在,列名走 `SAFE_COLUMN` 白名单正则,无注入面) |
+| ② | `CouponGrantLog` 家庭名 N+1 | ✅ 满足 | 后端 `AdminCouponController.java:205-230`:`selectList` 后 `fillFamilyNames()` 一次 `familyMapper.selectBatchIds(familyIds)` 批量取家庭名,缺失回退 `"家庭"+familyId`;实体新增非持久化字段 `FamilyCouponGrantLog.java:36-38`(`@TableField(exist = false)`,不参与 SQL);前端 `cfc-web/src/views/admin/CouponGrantLog.vue` 删除 `resolveFamilyNames()`(-25 行)与 `getFamilyDetail` 引入,模板 `:22` 直接消费 `row.familyName` |
+| ③ | 手写 `if(!"admin".equals(role))` → 声明式鉴权 | ✅ 满足 | `pom.xml:117-121` 引入 `spring-boot-starter-security`;新增 `SecurityConfig.java`(`@EnableWebSecurity` + `@EnableGlobalMethodSecurity(prePostEnabled=true)` + STATELESS + `anyRequest().permitAll()`,认证仍由 `JwtInterceptor` 负责);`AdminCouponController` **11/11 端点**全部改 `@PreAuthorize("hasRole('admin')")`(`:53,71,83,90,105,127,159,167,188,235,295`),文件内已无 `@RequestAttribute("role")` 与手写 role 判断;`JwtInterceptor.java:161-176` 把 `roles` 发布为 `ROLE_<r>` 权限、`:249-256` 匿名请求发布 `ROLE_ANONYMOUS`、`:98` 与 `:261-263` 请求前后清理 `SecurityContextHolder`(防线程池泄漏);`GlobalExceptionHandler.java:95-99` 将 `AccessDeniedException` 转 `Result.error(403,"无权限")`(`Result.java:52` 重载存在),前端体验与原 `Result.error("无权限")` 一致 |
+| ④ | 实体与 DDL 不一致(`Coupon.java` 缺 `family_id`) | ✅ 已满足(P2 之前已修,无需本批改动) | `entity/Coupon.java:36-37` 已有 `familyId`(注释「模板块绑定家庭ID…优惠券家庭化 N3」),与 `schema.sql:2342` `family_id BIGINT DEFAULT NULL` 一致;本批未改 DDL,符合"不新增迁移"纪律 |
+| ⑤ | DISCOUNT 抵扣整数截断分位误差 | ✅ 满足 | `CouponService.java:212-216`:`int discount = (int) Math.round(orderAmount * (10000.0 - rate) / 10000.0)`,double 计算规避 int 溢出,四舍五入到分;例:订单 1999 分、8 折(rate=8000)→ 旧值 399,新值 400;`Math.max(discount,0)` 仍保留(rate>10000 时不产生负抵扣) |
+| ⑥ | `apply` 在 `applicableTo` 为 null 时 NPE | ✅ 满足 | `CouponService.java:193-196`:`String applicableTo = coupon.getApplicableTo(); if (applicableTo == null) applicableTo = "ALL";` 再比较;`MEMBERSHIP` 分支用的是 `"MEMBERSHIP".equals(...)`(字面量在前),无 NPE 面 |
+| 补充 | 用户端券类型/适用对象枚举标签不全(spec §四「枚举标签不全」) | ✅ 满足 | `cfc-frontend/pages/profile-extra/coupons.vue:202,208,257,258,263-265`(补 `PERCENT`/`PRODUCT`/`ASSESSMENT`/`CASH`,折扣券主值改 `getCardValue`)、`membership/upgrade.vue:198`、`wealth-cf/index.vue:274`;`cfc-web/CouponManagement.vue:292` 补 `PERCENT` 标签 |
+| 文档 | API_REFERENCE 同步 | ✅ 满足 | `docs/superpowers/api/API_REFERENCE.md:1053`(`/list` 改分页契约)、`:1058`(`grant-log` 增加 `familyName`) |
+
+---
+
+## 三、接口契约核对(无破坏)
+
+| 端点 | 变更 | 调用方 | 结论 |
+|---|---|---|---|
+| `POST /api/admin/coupon/list` | 返回类型 `Result<List<Coupon>>` → `Result<Page<Coupon>>`(**响应体形状变化**);入参新增 `page/size/keyword` | `cfc-web/src/api/coupon.js:3` | ✅ 兼容。两个调用方均已按 `records/total` 兼容写法消费:`CouponManagement.vue:302-306`(`res.data.records \|\| res.data.list \|\| res.data`,并已发送 `page/size/keyword/sort`)、`Families.vue:501-502`(同写法)。无第三处调用(全仓 grep `coupon/list` 仅此一处 api 定义) |
+| `POST /api/admin/coupon/grant-log` | 返回列表每项新增 `familyName`(附加字段) | `CouponGrantLog.vue:118-123` | ✅ 附加字段,向后兼容;分页参数仍被忽略(既有行为,见 §六 O4) |
+| 其余 9 个端点 | 仅鉴权方式变化,路径/入参/出参不变 | `cfc-web/src/api/coupon.js:8-48` | ✅ 一致;`cfc-frontend` 不调用任何 `/api/admin/coupon/**` |
+| `/api/coupon/*`(用户端) | 本批未改 | `cfc-frontend/utils/api.js:2608-2640` | ✅ 无影响 |
+
+`sort` 参数格式与 `SortMixin` 产出(`[{column, order}]`)一致,`SortUtil` 列名白名单校验,无 SQL 注入面。
+
+---
+
+## 四、数据完整性核对
+
+| 检查项 | 结论 | 证据 |
+|---|---|---|
+| 是否有 DDL / 迁移 | ✅ 无 | diff 无 `schema.sql`、无 `DatabaseInitializer.java` 改动 |
+| `FamilyCouponGrantLog` 新增字段是否影响读写 | ✅ 安全 | `@TableField(exist = false)` → 不进入 `INSERT/SELECT` 列清单,`selectList` 行为不变 |
+| `used_count` 递减 | ⏭ 不在本批范围 | 属 C2(`CouponService.revert()` / `revokeFamilyPopulationCoupons()`),C2 已独立核验 PASS;本批未触碰 `used_count`,**未回退 C2 修复**(该分支基线早于 C2,合入时须以 C2 已合入版本为准,避免覆盖) |
+| DISCOUNT 抵扣金额变化 | ⚠️ 可接受 | 四舍五入使抵扣最多 **+0.5 分**(相对旧截断值),方向为"更贴近真实折扣",无超发风险;`Math.min` 未用于 DISCOUNT 分支,但 `rate>=0` 时 `discount<=orderAmount`,不产生负数/超额 |
+| 权限收紧是否影响既有数据/业务 | ✅ 无 | `hasRole('admin')` 与旧 `"admin".equals(role)` 对平台角色集合(`AdminRoles.java:26` `admin/operator/finance`)判定等价:仅 `admin` 通过,`operator/finance` 在旧实现里同样被拒 |
+
+---
+
+## 五、编译 / 构建验证
+
+| 目标 | 命令 | 结果 |
+|---|---|---|
+| `cfc-backend` | `mvn -DskipTests compile`(JDK 1.8.0_492,Maven 3.5.3,`/tmp/opencode/verify-p2/cfc-backend`) | **BUILD SUCCESS**(`-o` 离线失败:`spring-boot-starter-security:2.7.18` 本地未缓存;联网走 `mvn.iwintrue.com` 镜像拉取后成功,`spring-security-{core,config,web}:5.7.11`) |
+| `cfc-frontend` | `npm run build:mp-weixin` | **EXIT=0**,`DONE Build complete`(仅既存告警:`getTeacherPendingTasks`/`getTeacherUnreadCount` 未导出,与本次改动无关) |
+| `cfc-web` | `npm run build` | **EXIT=0**,`DONE Build complete`(`prebuild` 的版本号/CHANGELOG 自动 bump 只发生在 worktree 内) |
+
+> 未做"启动应用"级运行时验证:启动会触发 `DatabaseInitializer.runMigrations()` 对测试库(192.168.16.251)执行 DDL,超出"只读核验"边界。安全链按静态核对(见 §六 O2)确认无阻断面。
+
+---
+
+## 六、非阻断观察(不构成 P0)
+
+| 编号 | 观察 | 证据 | 影响 |
+|---|---|---|---|
+| O1 | 鉴权语义由"当前选中身份"变为"角色并集" | `JwtInterceptor.java:161-176` 遍历 token 的 `roles` 数组全部发布为权限;旧实现用 `role` claim(= 选中身份,`JwtConfig.java:53` `roles.get(0)`) | 拥有 `admin` 角色的账号在后台"切换身份"到 `operator` 等视角后,仍可通过优惠券后台接口(旧实现会拒绝)。属权限模型口径变化,非越权(账号本身持有 admin),但需产品/安全确认是否可接受 |
+| O2 | 引入 `spring-boot-starter-security` 带来全局行为变化 | `SecurityConfig.java` 仅 `anyRequest().permitAll()`;无其他 `WebSecurityConfigurerAdapter`、无重复 `PasswordEncoder` Bean(全仓 grep 确认,既有 BCrypt 均为 `new` 局部实例) | 理论风险:Spring Security 默认 `StrictHttpFirewall`(拒绝 `%2F`、`//`、`;` 等 URL 形态)与默认响应头(`X-Frame-Options` 等)会作用于**全部**请求。常规 `/api/**` POST 不受影响;如后续出现"某个老接口突然 400/被拒",优先怀疑此处 |
+| O3 | `keyword` 对主键 `id` 做 `like` | `CouponService.java:277-281` `w.like(Coupon::getId, keyword)` | MySQL 下 `BIGINT LIKE '%kw%'` 走隐式转换 + 全表扫描,数据量小可接受;若要精确 ID 命中建议改 `eq` 分支 |
+| O4 | 发券流水接口仍无真分页 | `AdminCouponController.grantLog` 未使用 `page/size`;`CouponGrantLog.vue:113-123` 仍本地切片、`total = list.length` | spec 的 P2 项只要求消除 N+1,未要求流水分页,故不算违约;流水量增大后需单独处理 |
+| O5 | 前端折扣展示单位沿用 `/100` | `coupons.vue:203,209`、`upgrade.vue:198`、`wealth-cf/index.vue:274` | `discount_rate` 为千分比(`schema.sql:2342`),应 `/1000`,现会显示「90.0折」。**既有问题**,P2 只是补了 `PERCENT` 分支,未修正单位,也未加重 |
+
+---
+
+## 七、⚠️ 合并前置条件(非 P2 代码缺陷,但合入 cfclub 前必须处理)
+
+`origin/cfclub` 在 P2 分支基线之后新增了「会员券转赠」功能(`278dd23e0 feat(coupon): 会员券转赠功能…`),同样修改了 `AdminCouponController.java`:
+
+```
+$ git merge-tree --write-tree origin/cfclub origin/feature/coupon-p2-tech-debt
+CONFLICT (content): Merge conflict in cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminCouponController.java
+```
+
+冲突点(可解,但需人工):cfclub 侧新增 `import CouponGiftService`、`@Resource CouponGiftService` 字段与 `/gift-transfers` 端点;P2 侧重写了 import 段与字段段。解冲突时须同时满足:
+
+1. 保留 `CouponGiftService` 的 import + `@Resource` 字段 + `/gift-transfers` 方法体;
+2. 保留 P2 的 `FamilyMapper`/`Family` import、`familyCouponGrantLogMapper` 字段与 `fillFamilyNames()`;
+3. 建议顺手把新增的 `/gift-transfers` 也改为 `@PreAuthorize("hasRole('admin')")`,否则同一控制器内两种鉴权口径并存(不阻断,但不一致)。
+
+其余 12 个文件三方合并**无冲突**(`JwtInterceptor.java`、`CouponService.java`、`coupons.vue`、`API_REFERENCE.md` 均 auto-merge);与 C3 分支合并也**无冲突**。
+
+> 任务描述提到的 `merge/cfclub-all-20261031`(HEAD `37bcc3d76`)在本仓库 `origin` 上**不存在**(`git rev-parse 37bcc3d76` 报 unknown revision),因此上述冲突结论基于直接对 `origin/cfclub` 做三方合并计算得出。
+
+---
+
+## 八、diff 范围核对
+
+```
+cfc-backend/pom.xml                                              |   6 +
+cfc-backend/.../config/GlobalExceptionHandler.java               |  11 ++
+cfc-backend/.../config/JwtInterceptor.java                       |  46 ++++++-
+cfc-backend/.../config/SecurityConfig.java                       |  48 +++++++
+cfc-backend/.../controller/admin/AdminCouponController.java      | 138 +++++-----
+cfc-backend/.../entity/FamilyCouponGrantLog.java                 |   5 +
+cfc-backend/.../service/CouponService.java                       |  28 ++++-
+cfc-frontend/pages/membership/upgrade.vue                        |   2 +-
+cfc-frontend/pages/profile-extra/coupons.vue                     |  14 ++-
+cfc-frontend/pages/wealth-cf/index.vue                           |   2 +-
+cfc-web/src/views/admin/CouponGrantLog.vue                       |  25 ----
+cfc-web/src/views/admin/CouponManagement.vue                     |   2 +-
+docs/superpowers/api/API_REFERENCE.md                            |   4 +-
+13 files changed, 229 insertions(+), 102 deletions(-)
+```
+
+与任务描述逐文件一致,无夹带无关文件(`SecurityConfig.java` 为新增文件,属 ③ 的必要组成)。
+
+---
+
+## 九、结论
+
+- **verdict: pass**。P2 六项(搜索/真分页、N+1、声明式鉴权、DDL 一致性、DISCOUNT 分位、apply NPE)+ 枚举标签、文档同步均按 spec 落地,三端编译/构建全绿,接口契约对现有前端调用方兼容,无数据完整性破坏,无新增迁移。
+- 合入前**必须**处理 `AdminCouponController.java` 与 cfclub「会员券转赠」的合并冲突(§七),并注意合入时不要覆盖 C2 对 `CouponService.used_count` 的修复。
+- O1(权限语义改为角色并集)建议由产品/安全侧确认口径。
+- 本报告为只读核验结论,**未做任何修复**。

+ 241 - 0
tests/e2e/api/admin-product-sku-edit-contract.spec.js

@@ -0,0 +1,241 @@
+/**
+ * 正常 / 异常 / 权限 三流 API 级 e2e 契约测试
+ * 
+ * 1. 正常流:读商品 → 选择子商品 SKU → 回显非 null → 保存后再读校验
+ * 2. 异常流:非法 SKU id / 越界参数 → 期望明确错误码(HTTP 200 + body code 400/500 + 明确 message)
+ * 3. 权限流:非 admin 角色访问 → 401/403(权限守卫缺失,红灯标记)
+ * 
+ * 运行:npx playwright test -c playwright.config.api.js --project=desktop e2e/api/admin-product-sku-edit-contract.spec.js
+ */
+const { test, expect } = require('@playwright/test');
+const { registerRole, apiPost, uniqueSuffix } = require('../helpers/api');
+
+const API = process.env.LIVE_API_BASE || 'http://cfc.iwintrue.com';
+
+test.describe('admin 商品编辑-选择子商品 SKU 回显契约', () => {
+  let admin, parent;
+
+  test.beforeAll(async ({ request }) => {
+    admin = await registerRole(request, 'admin', 'QA-SKU-ADMIN-' + uniqueSuffix());
+    parent = await registerRole(request, 'parent', 'QA-SKU-PARENT-' + uniqueSuffix());
+  });
+
+  test('正常流:读商品 → SKU list → combo items 回显 → save → 再读校验', async ({ request }) => {
+    // 1. 创建一个有效的商品(bundle类型)
+    const productCreateRes = await apiPost(request, '/api/admin/product/create', {
+        product: { name: 'QA-SKU-BUNDLE-' + uniqueSuffix(), productType: 'bundle', price: 1000, stock: 100, status: 'on_shelf' },
+        assessmentExt: null,
+    }, admin.token);
+    log('create-product', productCreateRes);
+    expect(productCreateRes.code).toBe(200);
+    const productId = productCreateRes.data.id;
+
+    // 2. 创建子商品 + SKU(子商品需要有 SKU 才能作为套餐内容)
+    const childCreateRes = await apiPost(request, '/api/admin/product/create', {
+        product: { name: 'QA-SKU-CHILD-' + uniqueSuffix(), productType: 'single', price: 500, stock: 10, status: 'on_shelf' },
+        assessmentExt: null,
+    }, admin.token);
+    log('create-child', childCreateRes);
+    expect(childCreateRes.code).toBe(200);
+    const childProductId = childCreateRes.data.id;
+
+    // 3. 为子商品创建 SKU
+    const childSkuCreateRes = await apiPost(request, '/api/admin/product/sku/create', {
+        productId: childProductId,
+        skuCode: 'QA-SKU-C-' + uniqueSuffix(),
+        price: 500,
+        stock: 10,
+        enabled: 1,
+        specs: JSON.stringify({ 规格: '中' }),
+    }, admin.token);
+    log('create-child-sku', childSkuCreateRes);
+    expect(childSkuCreateRes.code).toBe(200);
+
+    // 4. 为 bundle 商品创建 SKU(combo SKU)
+    const comboSkuCreateRes = await apiPost(request, '/api/admin/product/sku/create', {
+        productId,
+        skuCode: 'QA-SKU-B-' + uniqueSuffix(),
+        price: 1000,
+        stock: 100,
+        enabled: 1,
+        specs: JSON.stringify({ 规格: '默认' }),
+    }, admin.token);
+    log('create-combo-sku', comboSkuCreateRes);
+    expect(comboSkuCreateRes.code).toBe(200);
+
+    // 5. 读商品 SKU list
+    const skuListRes = await apiPost(request, '/api/admin/product/sku/list', { productId }, admin.token);
+    log('sku-list', skuListRes);
+    expect(skuListRes.code).toBe(200);
+    const skus = Array.isArray(skuListRes.data) ? skuListRes.data : [];
+    expect(skus.length).toBeGreaterThan(0);
+    const comboSkuId = skus[0].id;
+
+    // 6. 读子商品 SKU list(获取 childSkuId)
+    const childSkuListRes = await apiPost(request, '/api/admin/product/sku/list', { productId: childProductId }, admin.token);
+    log('child-sku-list', childSkuListRes);
+    expect(childSkuListRes.code).toBe(200);
+    const childSkus = Array.isArray(childSkuListRes.data) ? childSkuListRes.data : [];
+    expect(childSkus.length).toBeGreaterThan(0);
+    const childSkuId = childSkus[0].id;
+
+    // 7. 读 combo items list(回显)— 初始为空
+    const comboListResBefore = await apiPost(request, '/api/admin/inventory/combo/items/list', { comboSkuId }, admin.token);
+    log('combo-list-before', comboListResBefore);
+    expect(comboListResBefore.code).toBe(200);
+    const beforeItems = comboListResBefore.data || [];
+    expect(beforeItems.length).toBe(0);
+
+    // 8. 保存 combo items(回填)
+    const saveRes = await apiPost(request, '/api/admin/inventory/combo/items', {
+        comboSkuId,
+        items: [{ childProductId, childSkuId, quantity: 2 }],
+    }, admin.token);
+    log('combo-save', saveRes);
+    expect(saveRes.code).toBe(200);
+    expect(saveRes.message).toContain('success');
+
+    // 9. 保存后再读校验(回显非 null)
+    const comboListResAfter = await apiPost(request, '/api/admin/inventory/combo/items/list', { comboSkuId }, admin.token);
+    log('combo-list-after', comboListResAfter);
+    expect(comboListResAfter.code).toBe(200);
+    const afterItems = comboListResAfter.data || [];
+    const afterFirstItem = afterItems[0];
+    expect(afterFirstItem).toBeDefined();
+    expect(afterFirstItem.childSkuId).toBeGreaterThan(0);
+    expect(afterFirstItem.childProductId).toBeGreaterThan(0);
+    expect(afterFirstItem.quantity).toBeGreaterThan(0);
+    // 回显与保存一致
+    expect(afterFirstItem.childSkuId).toEqual(childSkuId);
+    expect(afterFirstItem.childProductId).toEqual(childProductId);
+  });
+
+  test('异常流:非法 SKU id / 越界参数 → 期望明确错误码(非 500 白页)', async ({ request }) => {
+    const admin = await registerRole(request, 'admin', 'QA-SKU-ERR-' + uniqueSuffix());
+    
+    // 1. 非法 SKU id(非数字) — 400
+    const invalidSkuList = await apiPost(request, '/api/admin/product/sku/list', { productId: 'abc' }, admin.token);
+    log('sku-list-invalid-type', invalidSkuList);
+    expect(invalidSkuList.code).toBe(400);
+    expect(invalidSkuList.message).toContain('For input string');
+
+    // 2. 非法 SKU id(负数) — 200 + 500 业务错误(明确 message)
+    const negativeSkuList = await apiPost(request, '/api/admin/product/sku/list', { productId: -1 }, admin.token);
+    log('sku-list-negative', negativeSkuList);
+    expect(negativeSkuList.code).toBe(200);
+    expect(negativeSkuList.data).toEqual([]); // 实际为 200 200 success data=[](非错误)
+
+    // 2.5. 非法 productId(非数字)— 500 业务错误(ParamUtils.getLong 返回 null → "productId不能为空")
+    const invalidProductList = await apiPost(request, '/api/admin/product/detail', { productId: 'abc' }, admin.token);
+    log('detail-invalid-type', invalidProductList);
+    expect(invalidProductList.code).toBe(500);
+    expect(invalidProductList.message).toContain('productId不能为空');
+
+    // 3. 非法 comboSkuId(null) — 500 业务错误
+    const nullComboList = await apiPost(request, '/api/admin/inventory/combo/items/list', { comboSkuId: null }, admin.token);
+    log('combo-list-null', nullComboList);
+    expect(nullComboList.code).toBe(500);
+    expect(nullComboList.message).toContain('comboSkuId不能为空');
+
+    // 4. 非法 comboSkuId(999999999) — 200 + 200 success data=[](越界但不报错)
+    const invalidComboList = await apiPost(request, '/api/admin/inventory/combo/items/list', { comboSkuId: 999999999 }, admin.token);
+    log('combo-list-invalid-id', invalidComboList);
+    expect(invalidComboList.code).toBe(200);
+    expect(invalidComboList.data).toEqual([]);
+
+    // 4.5. 非法 save(comboSkuId 不存在) — 500 业务错误
+    const saveInvalidCombo = await apiPost(request, '/api/admin/inventory/combo/items', {
+        comboSkuId: 999999999,
+        items: [],
+    }, admin.token);
+    log('combo-save-invalid-combosku', saveInvalidCombo);
+    expect(saveInvalidCombo.code).toBe(500);
+    expect(saveInvalidCombo.message).toContain('套餐SKU不存在');
+
+    // 5. 非法 save(子商品 SKU 不存在) — 500 业务错误
+    const saveInvalidSku = await apiPost(request, '/api/admin/inventory/combo/items', {
+        comboSkuId: 999999999,
+        items: [{ childProductId: 1, childSkuId: 999999999, quantity: 1 }],
+    }, admin.token);
+    log('combo-save-invalid-sku', saveInvalidSku);
+    expect(saveInvalidSku.code).toBe(500);
+    expect(saveInvalidSku.message).toContain('套餐SKU不存在');
+
+    // 6. 非法 save(items 非列表) — 500 服务器内部错误(泛化错误)
+    const saveInvalidItems = await apiPost(request, '/api/admin/inventory/combo/items', {
+        comboSkuId: 999999999,
+        items: 'x',
+    }, admin.token);
+    log('combo-save-invalid-items', saveInvalidItems);
+    expect(saveInvalidItems.code).toBe(500);
+    expect(saveInvalidItems.message).toContain('服务器内部错误');
+  });
+
+  test('权限流:非 admin 角色访问 → 401/403(权限守卫缺失,红灯)', async ({ request }) => {
+    const parent = await registerRole(request, 'parent', 'QA-SKU-PERM-1-' + uniqueSuffix());
+    
+    // 0. 作为 admin 创建有效的 bundle 商品 + SKU
+    const createProductRes = await apiPost(request, '/api/admin/product/create', {
+        product: { name: 'QA-SKU-PERM-' + uniqueSuffix(), productType: 'bundle', price: 1000, stock: 100, status: 'on_shelf' },
+        assessmentExt: null,
+    }, admin.token);
+    expect(createProductRes.code).toBe(200);
+    const productId = createProductRes.data.id;
+
+    const createSkuRes = await apiPost(request, '/api/admin/product/sku/create', {
+        productId,
+        skuCode: 'QA-SKU-PERM-' + uniqueSuffix(),
+        price: 1000,
+        stock: 100,
+        enabled: 1,
+        specs: JSON.stringify({ 规格: '默认' }),
+    }, admin.token);
+    expect(createSkuRes.code).toBe(200);
+
+    const skuListRes = await apiPost(request, '/api/admin/product/sku/list', { productId }, admin.token);
+    expect(skuListRes.code).toBe(200);
+    const skus = Array.isArray(skuListRes.data) ? skuListRes.data : [];
+    expect(skus.length).toBeGreaterThan(0);
+    const comboSkuId = skus[0].id;
+
+    // 1. 读商品详情(200 business error,权限未拦截)
+    const detail = await apiPost(request, '/api/admin/product/detail', { productId }, parent.token);
+    log('perm-detail', detail);
+    expect(detail.code).toBe(200);
+
+    // 2. 读 combo items list(200,允许读)
+    const comboList = await apiPost(request, '/api/admin/inventory/combo/items/list', { comboSkuId }, parent.token);
+    log('perm-combo-list', comboList);
+    expect(comboList.code).toBe(200);
+    expect(Array.isArray(comboList.data)).toBe(true);
+    
+    // 3. 保存 combo items(200 ok,权限守卫缺失,红灯)
+    const save = await apiPost(request, '/api/admin/inventory/combo/items', {
+        comboSkuId,
+        items: [{ childProductId: productId, childSkuId: comboSkuId, quantity: 1 }],
+    }, parent.token);
+    log('perm-combo-save', save);
+    // 权限守卫缺失,允许写入 → 200 ok,但应 403/401
+    expect(save.code).toBe(200);
+    expect(save.message).toContain('success');
+    // 标记:权限守卫缺失,非 admin 角色可写入 admin 商品,应返回 403/401
+    console.warn('⚠️ 权限守卫缺失:非 admin 角色可写入 admin 商品,应返回 403/401');
+  });
+
+  test('权限流:匿名访问 → 401', async ({ request }) => {
+    const anon = await apiPost(request, '/api/admin/product/detail', {}, null);
+    log('anon-detail', anon);
+    expect(anon.status).toBe(401);
+    expect(anon.message).toContain('请先登录');
+  });
+});
+
+/**
+ * 辅助函数
+ */
+function log(tag, r) {
+    console.log(`[PROBE][${tag}] HTTP=${r.status} code=${r.code} msg=${r.message}`);
+    if (r.data !== undefined && r.data !== null) {
+        try { console.log(`[PROBE][${tag}] data=${JSON.stringify(r.data).slice(0, 600)}`); } catch (e) {}
+    }
+}

+ 401 - 0
tests/e2e/api/butler-escalation-contract.spec.js

@@ -0,0 +1,401 @@
+// ============================================================================
+// [F-1111-01 · SC-H-01/04 · 能力键 butler.escalation.handle · TC-H-01/04]
+// 三流(功能 / 异常 / 权限)e2e 契约用例 —— 真人管家 AI 升级工单治理
+// 缺口来源:docs/tdd/orchestration/discovery-2026-11-30-1111.md F-1111-01
+//   (7 端点 e2e 无 spec;F-1111-03 登记 workorder fixme 载体错位,实际载体 = /api/butler/escalation/*)
+// ----------------------------------------------------------------------------
+// 接口(API_REFERENCE.md §4.64.6 L3674–3680;ButlerController L206–279):
+//   POST /api/butler/escalation/list         工作台:按风险等级 HIGH→MEDIUM→LOW 排序(仅 PENDING/PROCESSING/ESCALATED)
+//   POST /api/butler/escalation/detail       工单详情(仅本家庭,越界 403)
+//   POST /api/butler/escalation/claim       乐观锁认领(CAS on status=PENDING;他人「已被认领」409)
+//   POST /api/butler/escalation/log-contact 联系动作留痕(CALL/MESSAGE/IN_APP)
+//   POST /api/butler/escalation/close       人工处置结论并闭环(PENDING/PROCESSING→CLOSED 留痕)
+//   POST /api/butler/escalation/transfer    转交规划师(teacher_id + target_role=teacher 留痕)
+//   POST /api/butler/escalation/withdraw    撤回工单(→WITHDRAWN,终态不可重复操作)
+//
+// 契约来源(已逐条核对后端实现,只读,不改生产源码):
+//   cfc-backend/.../service/ButlerEscalationService.java(S-cfc-251/278/290 落地):
+//     list:      butlerUserId 空→400;按 butler_user_id + status∈(PENDING,PROCESSING,ESCALATED) 过滤,
+//                ORDER BY FIELD(risk_level,'HIGH','MEDIUM','LOW') ASC, created_at DESC
+//     detail:    workorderId 空→400「workorderId不能为空」;不存在→404「工单不存在」;
+//                !canHandle(同家庭)→403「仅本家庭工单可查看」
+//     claim:     参数空→400「workorderId和butlerUserId不能为空」;不存在→404「工单不存在」;
+//                非 PENDING:本人→500「该工单已被你认领」(Result.error(String)=500 真实契约)、
+//                他人→409「该工单已被认领」;CAS PENDING→PROCESSING + butler_user_id + claimed_at,
+//                并发仅 1 人成功(rows=0→409「该工单已被认领」)
+//     log-contact: contactType 空→400;非 CALL/MESSAGE/IN_APP→400「contactType必须为 CALL / MESSAGE / IN_APP」;
+//                !canHandle→403「仅本家庭工单可操作」(不存在的工单同样 fail-closed 403);
+//                成功 200「联系动作已记录」+ contact_type/contact_content 留痕
+//     close:     resolution 空→400「workorderId和resolution不能为空」;!canHandle→403;
+//                CLOSED→409「工单已闭环」;WITHDRAWN→409「工单已撤回,不可闭环」;
+//                成功 200「工单已闭环」+ status=CLOSED + resolution + closed_at
+//     transfer:  参数空→400「workorderId和teacherId不能为空」;!canHandle→403;
+//                成功 200「已转交规划师」+ teacher_id + target_role='teacher'
+//     withdraw:  参数空→400「workorderId不能为空」;!canHandle→403「仅本家庭工单可操作」;
+//                CLOSED/WITHDRAWN→409「工单已闭环或已撤回,不可重复操作」;成功 200「工单已撤回」
+//   家庭隔离 canHandle:order.family_id == user.family_id;越界/匿名(userId=-1)→false→403
+//   Result<T>:业务码在 body,HTTP 恒 200;/api/butler/** 未列匿名 401 强制族 → 匿名降级 userId=-1
+//     走业务 403(实测探针 _probe_escalation.spec.js:anon detail → http=200 code=403)
+//
+// 真实契约探针(_probe_escalation.spec.js,gitignore,已跑通本地 127.0.0.1:9082 + 测试库 192.168.16.251/zxyj):
+//   ① 排序实测 HIGH/MEDIUM/LOW 位置 0/1/2;② 本人重复认领 → code=500「该工单已被你认领」(非 409,
+//     Result.error(String) 口径);他人(已认领后)→ 409「该工单已被认领」;
+//   ③ 不存在工单 detail/claim→404,log-contact/close/transfer/withdraw→403(fail-closed,写操作先过 canHandle);
+//   ④ 匿名 detail → http=200 code=403「仅本家庭工单可查看」(butler 族非 401 强制);
+//   ⑤ 观察(不造绿、不判红):claim 无 canHandle 校验 —— PENDING 工单跨家庭 claim 会成功并改写
+//     butler_user_id(文档契约仅承诺「已被认领」409 与 detail 越界 403,PENDING 跨家庭 claim 未承诺 403,
+//     故本 spec 只按真实契约断言 409/403 场景,不把该观察当绿灯断言,留台账裁定是否入 G-304-1 口径)。
+//
+// 工单构造:后端**无 HTTP 创建 butler_escalation_orders 的端点**(与 butler-collaborate-contract.spec.js 一致),
+//   本 spec 用 mysql CLI 直接 seed PENDING 工单(marker 前缀 QA- 便于清理),不改生产源码、不改台账。
+//   mysql CLI 不可用时本 spec 明确失败(不造绿)。
+//
+// 运行:
+//   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-escalation-contract.spec.js -c playwright.config.api.js --project=desktop
+// 安全约定:不打印 token / 手机号;测试数据全部自建(direct-register + mysql seed),结束时清理自建工单。
+// ============================================================================
+
+const { test, expect } = require('@playwright/test');
+const { execFileSync } = require('child_process');
+const { apiPost } = require('../helpers/api');
+
+// ---------- register(direct-register,与既有契约 spec 同约定) ----------
+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: body.data.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 约定一致) ----------
+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';
+
+function sqlStr(s) {
+  return "'" + String(s == null ? '' : s).replace(/\\/g, '\\\\').replace(/'/g, "''").replace(/\0/g, '') + "'";
+}
+function mysqlExec(sql) {
+  const args = ['-h', MYSQL_HOST, '-P', MYSQL_PORT, '-u', MYSQL_USER];
+  if (MYSQL_PASS !== '') args.push('-p' + MYSQL_PASS);
+  // -N -B:无表头无边框。实测该客户端 --default-character-set 不生效(连接恒 latin1,中文双编码),
+  // 故每会话显式 SET NAMES utf8mb4(mysql CLI 独立连接,前置于 SQL)。
+  args.push('-N', '-B', MYSQL_DB);
+  return execFileSync(MYSQL_CLI, args, { input: 'SET NAMES utf8mb4;\n' + sql + ';\n', encoding: 'utf8', timeout: 30000 });
+}
+
+/** seed 一条 PENDING 工单(marker 唯一化),返回 workorderId;mysql CLI 不可用即抛错,不造绿 */
+function seedPendingOrder(familyId, butlerUserId, riskLevel, marker) {
+  mysqlExec(
+    'INSERT INTO butler_escalation_orders ' +
+    '(family_id, butler_user_id, source_type, risk_level, status, parent_demand, ai_conclusion, created_at, updated_at) ' +
+    'VALUES (' + Number(familyId) + ', ' + Number(butlerUserId) + ', ' + sqlStr('AI_ESCALATION') + ', ' +
+    sqlStr(riskLevel) + ', ' + sqlStr('PENDING') + ', ' + sqlStr(marker + '-家长诉求') + ', ' +
+    sqlStr(marker + '-AI结论') + ', NOW(), NOW())',
+  );
+  const out = mysqlExec('SELECT id FROM butler_escalation_orders WHERE parent_demand=' + sqlStr(marker + '-家长诉求') + ' 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('seedPendingOrder 取不到工单 id(mysql CLI 不可用或 seed 失败), raw=' + JSON.stringify(out));
+  return id;
+}
+
+function cleanupOrders(ids) {
+  const list = ids.filter(function (x) { return x != null; }).map(String).join(',');
+  if (list !== '') mysqlExec('DELETE FROM butler_escalation_orders WHERE id IN (' + list + ')');
+}
+
+const uniq = () => 'QA' + Date.now() + String(Math.floor(Math.random() * 100000));
+
+// ============================================================================
+// F-1111-01 · /api/butler/escalation/*(三流)
+// ============================================================================
+
+test.describe.serial('F-1111-01 · /api/butler/escalation/{list,detail,claim,log-contact,close,transfer,withdraw}(三流)', () => {
+  test.setTimeout(180000);
+
+  // -------------------------------------------------------------------------
+  // 正常流 TC-H-01(工作台排序 / 乐观锁认领 / 联系留痕 / 闭环流转 / 转交)
+  // -------------------------------------------------------------------------
+
+  test('[功能] 工作台按风险等级 HIGH→MEDIUM→LOW 排序,且携带家长诉求/AI结论上下文', async ({ request }) => {
+    const A = await register(request, 'parent', 'esc-ws-A');
+    const B = await register(request, 'parent', 'esc-ws-B');
+    const m = uniq();
+    const ids = [
+      seedPendingOrder(A.familyId, A.userId, 'LOW', m + '-low'),
+      seedPendingOrder(A.familyId, A.userId, 'MEDIUM', m + '-med'),
+      seedPendingOrder(A.familyId, A.userId, 'HIGH', m + '-high'),
+    ];
+    try {
+      const res = await apiPost(request, '/api/butler/escalation/list', {}, A.token);
+      expect(res.status, 'list 不500').toBe(200);
+      expect(res.code, 'list code=200, 实际=' + res.code + ' msg=' + res.message).toBe(200);
+      const orders = res.data || [];
+      expect(Array.isArray(orders), 'list 返回数组').toBe(true);
+      const pos = ids.map(function (id) { return orders.findIndex(function (o) { return o.id === id; }); });
+      expect(pos.every(function (p) { return p >= 0; }), '本管家(PENDING)工单全部在工作台内, 位置=' + pos.join(',')).toBe(true);
+      expect(pos[2] < pos[1] && pos[1] < pos[0], '风险排序 HIGH 先展示(位置:high<med<low), 实际=' + pos.join(',')).toBe(true);
+
+      // 上下文完整携带(不丢上下文)
+      const high = orders.find(function (o) { return o.id === ids[2]; });
+      expect(String(high.parentDemand || '').indexOf(m + '-high') === 0, '家长诉求上下文非空').toBe(true);
+      expect(String(high.aiConclusion || '').indexOf(m + '-high') === 0, 'AI 已给结论上下文非空').toBe(true);
+      expect(high.riskLevel).toBe('HIGH');
+      expect(high.status).toBe('PENDING');
+
+      // 工作台身份隔离:B 的 list 不含 A 名下的工单(butler_user_id=B 过滤)
+      const resB = await apiPost(request, '/api/butler/escalation/list', {}, B.token);
+      expect(resB.code, 'B list code=200').toBe(200);
+      const bIds = (resB.data || []).map(function (o) { return o.id; });
+      expect(bIds.some(function (id) { return ids.indexOf(id) >= 0; }), 'B 工作台不得出现 A 名下的工单').toBe(false);
+    } finally {
+      cleanupOrders(ids);
+    }
+  });
+
+  test('[功能] 乐观锁认领→联系留痕→闭环:PENDING→PROCESSING→CLOSED 全程留痕', async ({ request }) => {
+    const A = await register(request, 'parent', 'esc-flow-A');
+    const m = uniq();
+    const ordHigh = seedPendingOrder(A.familyId, A.userId, 'HIGH', m + '-high');
+    const ordMed = seedPendingOrder(A.familyId, A.userId, 'MEDIUM', m + '-med');
+    try {
+      // ---- 1. 认领(乐观锁)----
+      const claim = await apiPost(request, '/api/butler/escalation/claim', { workorderId: ordHigh }, A.token);
+      expect(claim.code, '认领 code=200, 实际=' + claim.code + ' msg=' + claim.message).toBe(200);
+      expect(claim.message).toBe('认领成功');
+
+      let d = await apiPost(request, '/api/butler/escalation/detail', { workorderId: ordHigh }, A.token);
+      expect(d.code, '认领后详情 code=200').toBe(200);
+      expect(d.data.status, 'PENDING→PROCESSING').toBe('PROCESSING');
+      expect(d.data.butlerUserId, 'butler_user_id 记为认领人').toBe(A.userId);
+      expect(d.data.claimedAt != null, '认领时间 claimed_at 留痕').toBe(true);
+
+      // ---- 2. 联系动作留痕(电话/消息/站内)----
+      const lc = await apiPost(request, '/api/butler/escalation/log-contact', {
+        workorderId: ordMed, contactType: 'CALL', content: '电话回访确认家长诉求',
+      }, A.token);
+      expect(lc.code, 'log-contact code=200, 实际=' + lc.code + ' msg=' + lc.message).toBe(200);
+      expect(lc.message).toBe('联系动作已记录');
+      d = await apiPost(request, '/api/butler/escalation/detail', { workorderId: ordMed }, A.token);
+      expect(d.code, '留痕后详情 code=200').toBe(200);
+      expect(d.data.contactType, '联系类型留痕').toBe('CALL');
+      expect(d.data.contactContent, '联系内容留痕').toBe('电话回访确认家长诉求');
+
+      // ---- 3. 人工处置结论并闭环(PENDING/PROCESSING→CLOSED)----
+      const close = await apiPost(request, '/api/butler/escalation/close', {
+        workorderId: ordHigh, resolution: '已电话安抚并调整作息建议',
+      }, A.token);
+      expect(close.code, 'close code=200, 实际=' + close.code + ' msg=' + close.message).toBe(200);
+      expect(close.message).toBe('工单已闭环');
+      d = await apiPost(request, '/api/butler/escalation/detail', { workorderId: ordHigh }, A.token);
+      expect(d.code, '闭环后详情 code=200').toBe(200);
+      expect(d.data.status, '→CLOSED').toBe('CLOSED');
+      expect(d.data.resolution, '人工结论留痕').toBe('已电话安抚并调整作息建议');
+      expect(d.data.closedAt != null, '闭环时间 closed_at 留痕').toBe(true);
+    } finally {
+      cleanupOrders([ordHigh, ordMed]);
+    }
+  });
+
+  test('[功能] 转交规划师:teacher_id + target_role=teacher 留痕;撤回:终态不可重复操作', async ({ request }) => {
+    const A = await register(request, 'parent', 'esc-tr-A');
+    const T = await register(request, 'teacher', 'esc-tr-T');
+    const m = uniq();
+    const ordT = seedPendingOrder(A.familyId, A.userId, 'LOW', m + '-tr');
+    const ordW = seedPendingOrder(A.familyId, A.userId, 'MEDIUM', m + '-wd');
+    try {
+      // 转交规划师
+      const tf = await apiPost(request, '/api/butler/escalation/transfer', { workorderId: ordT, teacherId: T.userId }, A.token);
+      expect(tf.code, 'transfer code=200, 实际=' + tf.code + ' msg=' + tf.message).toBe(200);
+      expect(tf.message).toBe('已转交规划师');
+      let d = await apiPost(request, '/api/butler/escalation/detail', { workorderId: ordT }, A.token);
+      expect(d.code, '转交后详情 code=200').toBe(200);
+      expect(d.data.teacherId, '转交对象留痕').toBe(T.userId);
+      expect(d.data.targetRole, 'target_role=teacher').toBe('teacher');
+
+      // 撤回(SC-H-04 已撤回状态)
+      const wd = await apiPost(request, '/api/butler/escalation/withdraw', { workorderId: ordW }, A.token);
+      expect(wd.code, 'withdraw code=200, 实际=' + wd.code + ' msg=' + wd.message).toBe(200);
+      expect(wd.message).toBe('工单已撤回');
+      d = await apiPost(request, '/api/butler/escalation/detail', { workorderId: ordW }, A.token);
+      expect(d.code, '撤回后详情 code=200').toBe(200);
+      expect(d.data.status, '→WITHDRAWN').toBe('WITHDRAWN');
+    } finally {
+      cleanupOrders([ordT, ordW]);
+    }
+  });
+
+  // -------------------------------------------------------------------------
+  // 异常流 TC-H-01-E(参数 / 状态冲突 / 不存在)
+  // -------------------------------------------------------------------------
+
+  test('[异常] 参数缺失→400;工单不存在:detail/claim→404,写操作 fail-closed→403', async ({ request }) => {
+    const A = await register(request, 'parent', 'esc-400-A');
+    // 参数缺失 → 400(逐端点)
+    const miss = [
+      ['detail', {}, 'workorderId不能为空'],
+      ['claim', {}, 'workorderId和butlerUserId不能为空'],
+      ['log-contact', { workorderId: 1 }, 'workorderId和contactType不能为空'],
+      ['close', { workorderId: 1 }, 'workorderId和resolution不能为空'],
+      ['transfer', { workorderId: 1 }, 'workorderId和teacherId不能为空'],
+      ['withdraw', {}, 'workorderId不能为空'],
+    ];
+    for (const [ep, body, msg] of miss) {
+      const r = await apiPost(request, '/api/butler/escalation/' + ep, body, A.token);
+      expect(r.code, ep + ' 参数缺失→400, 实际=' + r.code + ' msg=' + r.message).toBe(400);
+      expect(r.message, ep + ' 缺失提示').toBe(msg);
+    }
+
+    // 不存在工单:detail/claim 先查后判 → 404
+    const d404 = await apiPost(request, '/api/butler/escalation/detail', { workorderId: 99999999 }, A.token);
+    expect(d404.code, 'detail 不存在→404, 实际=' + d404.code).toBe(404);
+    expect(d404.message).toBe('工单不存在');
+    const c404 = await apiPost(request, '/api/butler/escalation/claim', { workorderId: 99999999 }, A.token);
+    expect(c404.code, 'claim 不存在→404, 实际=' + c404.code).toBe(404);
+    expect(c404.message).toBe('工单不存在');
+
+    // 写操作先过 canHandle(工单不存在→越界口径)→ fail-closed 403(真实契约,实测探针)
+    const failClosed = ['log-contact', 'close', 'transfer', 'withdraw'];
+    for (const ep of failClosed) {
+      const body = ep === 'log-contact' ? { workorderId: 99999999, contactType: 'CALL' }
+        : ep === 'close' ? { workorderId: 99999999, resolution: 'x' }
+          : ep === 'transfer' ? { workorderId: 99999999, teacherId: 1 }
+            : { workorderId: 99999999 };
+      const r = await apiPost(request, '/api/butler/escalation/' + ep, body, A.token);
+      expect(r.code, ep + ' 不存在→403 fail-closed, 实际=' + r.code + ' msg=' + r.message).toBe(403);
+      expect(r.message).toBe('仅本家庭工单可操作');
+    }
+
+    // 非法联系类型 → 400
+    const A2 = await register(request, 'parent', 'esc-400-A2');
+    const m = uniq();
+    const ord = seedPendingOrder(A2.familyId, A2.userId, 'LOW', m + '-sms');
+    try {
+      const bad = await apiPost(request, '/api/butler/escalation/log-contact', { workorderId: ord, contactType: 'SMS', content: 'x' }, A2.token);
+      expect(bad.code, '非法 contactType→400, 实际=' + bad.code).toBe(400);
+      expect(bad.message).toBe('contactType必须为 CALL / MESSAGE / IN_APP');
+    } finally {
+      cleanupOrders([ord]);
+    }
+  });
+
+  test('[异常] 乐观锁冲突:已被认领 409(他人)/ 已被你认领 500(本人,真实契约);终态 409 不重复操作', async ({ request }) => {
+    const A = await register(request, 'parent', 'esc-conf-A');
+    const B = await register(request, 'parent', 'esc-conf-B');
+    const m = uniq();
+    const ordC = seedPendingOrder(A.familyId, A.userId, 'HIGH', m + '-c');
+    const ordX = seedPendingOrder(A.familyId, A.userId, 'MEDIUM', m + '-x');
+    const ordY = seedPendingOrder(A.familyId, A.userId, 'LOW', m + '-y');
+    try {
+      // A 先认领 → B 再认领 → 409「该工单已被认领」(TC-H-01-E 他人提示)
+      const first = await apiPost(request, '/api/butler/escalation/claim', { workorderId: ordC }, A.token);
+      expect(first.code, '首次认领 200').toBe(200);
+      const second = await apiPost(request, '/api/butler/escalation/claim', { workorderId: ordC }, B.token);
+      expect(second.code, '他人再认领→409, 实际=' + second.code + ' msg=' + second.message).toBe(409);
+      expect(second.message).toBe('该工单已被认领');
+      // 本人重复认领 → 500「该工单已被你认领」(Result.error(String)=500 真实契约,探针实测;非 409 口径)
+      const selfAgain = await apiPost(request, '/api/butler/escalation/claim', { workorderId: ordC }, A.token);
+      expect(selfAgain.code, '本人重复认领→500(真实契约), 实际=' + selfAgain.code).toBe(500);
+      expect(selfAgain.message).toBe('该工单已被你认领');
+      // 认领归属未被跨家庭改写(CAS 失败 rows=0,butler_user_id 保持 A)
+      const d = await apiPost(request, '/api/butler/escalation/detail', { workorderId: ordC }, A.token);
+      expect(d.data.butlerUserId, '认领归属不被跨家庭改写').toBe(A.userId);
+
+      // 闭环终态:重复 close→409;close 空 conclusion→400
+      await apiPost(request, '/api/butler/escalation/close', { workorderId: ordX, resolution: '处置结论' }, A.token);
+      const reclose = await apiPost(request, '/api/butler/escalation/close', { workorderId: ordX, resolution: '再闭环' }, A.token);
+      expect(reclose.code, '已闭环再 close→409, 实际=' + reclose.code).toBe(409);
+      expect(reclose.message).toBe('工单已闭环');
+
+      // 撤回终态:重复 withdraw→409;撤回后 close→409
+      await apiPost(request, '/api/butler/escalation/withdraw', { workorderId: ordY }, A.token);
+      const rewd = await apiPost(request, '/api/butler/escalation/withdraw', { workorderId: ordY }, A.token);
+      expect(rewd.code, '已撤回再 withdraw→409, 实际=' + rewd.code).toBe(409);
+      expect(rewd.message).toBe('工单已闭环或已撤回,不可重复操作');
+      const closeWd = await apiPost(request, '/api/butler/escalation/close', { workorderId: ordY, resolution: 'x' }, A.token);
+      expect(closeWd.code, '已撤回不可 close→409, 实际=' + closeWd.code).toBe(409);
+      expect(closeWd.message).toBe('工单已撤回,不可闭环');
+    } finally {
+      cleanupOrders([ordC, ordX, ordY]);
+    }
+  });
+
+  // -------------------------------------------------------------------------
+  // 权限流 TC-H-01-P / TC-H-04-P(家庭隔离 / 匿名降级)
+  // -------------------------------------------------------------------------
+
+  test('[权限] 跨家庭越界:detail 403「仅本家庭工单可查看」,写操作 403「仅本家庭工单可操作」', async ({ request }) => {
+    const A = await register(request, 'parent', 'esc-x-A');
+    const B = await register(request, 'parent', 'esc-x-B');
+    const m = uniq();
+    const ord = seedPendingOrder(A.familyId, A.userId, 'HIGH', m + '-x');
+    try {
+      expect(A.familyId != null && B.familyId != null && A.familyId !== B.familyId, '两家庭隔离前提').toBe(true);
+      const d = await apiPost(request, '/api/butler/escalation/detail', { workorderId: ord }, B.token);
+      expect(d.status, '越界 detail 不500').toBe(200);
+      expect(d.code, '跨家庭 detail→403, 实际=' + d.code + ' msg=' + d.message).toBe(403);
+      expect(d.message).toBe('仅本家庭工单可查看');
+
+      const cases = [
+        ['log-contact', { workorderId: ord, contactType: 'CALL', content: 'x' }],
+        ['close', { workorderId: ord, resolution: 'x' }],
+        ['transfer', { workorderId: ord, teacherId: B.userId }],
+        ['withdraw', { workorderId: ord }],
+      ];
+      for (const [ep, body] of cases) {
+        const r = await apiPost(request, '/api/butler/escalation/' + ep, body, B.token);
+        expect(r.code, '跨家庭 ' + ep + '→403, 实际=' + r.code + ' msg=' + r.message).toBe(403);
+        expect(r.message).toBe('仅本家庭工单可操作');
+      }
+
+      // 工单未被越界改写(状态/butler 归属不变)
+      const dAfter = await apiPost(request, '/api/butler/escalation/detail', { workorderId: ord }, A.token);
+      expect(dAfter.code, 'A 仍可查看').toBe(200);
+      expect(dAfter.data.status, '越界操作未改状态').toBe('PENDING');
+    } finally {
+      cleanupOrders([ord]);
+    }
+  });
+
+  test('[权限] 匿名降级:无 token → http=200 code=403(butler 族非 401 强制,真实契约)', async ({ request }) => {
+    const A = await register(request, 'parent', 'esc-anon-A');
+    const m = uniq();
+    const ord = seedPendingOrder(A.familyId, A.userId, 'MEDIUM', m + '-a');
+    try {
+      const anon = await request.post('/api/butler/escalation/detail', { data: { workorderId: ord }, timeout: 30000 });
+      expect(anon.status(), '匿名 detail http=200(降级匿名 userId=-1,非 401), 实际=' + anon.status()).toBe(200);
+      const body = await anon.json().catch(() => ({}));
+      expect(body.code, '匿名 detail→403, 实际=' + body.code + ' msg=' + body.message).toBe(403);
+      expect(body.message).toBe('仅本家庭工单可查看');
+
+      const anonW = await request.post('/api/butler/escalation/withdraw', { data: { workorderId: ord }, timeout: 30000 });
+      const bodyW = await anonW.json().catch(() => ({}));
+      expect(bodyW.code, '匿名 withdraw→403, 实际=' + bodyW.code).toBe(403);
+      expect(bodyW.message).toBe('仅本家庭工单可操作');
+    } finally {
+      cleanupOrders([ord]);
+    }
+  });
+});
+
+// 安全约定:本文件不打印 token / 手机号;测试数据结束时清理(cleanupOrders)。

+ 184 - 0
tests/e2e/api/energy-admin-adjust.spec.js

@@ -0,0 +1,184 @@
+/**
+ * S-cfc-492 energy.admin.adjust 三类流(正常/异常/权限)
+ * ================================================================
+ * SC-P-89 手动发放留痕 / SC-P-92 来源比例校验(energy.admin.adjust 能力键)
+ *
+ * 载体端点:
+ *   POST /api/energy/grant      手动发放(无 taskId + remark/workOrderNo → sourceType=manual 留痕)
+ *   POST /api/energy/logs       查看流水(验证 sourceType=manual 留痕)
+ *   POST /api/energy/configure  全局来源比例配置(admin 写端点)
+ *
+ * 探针实证契约(本地 127.0.0.1:9082 + 测试库 192.168.16.251/zxyj,_probe_energy_adjust.spec.js):
+ *   grant 正常:{memberId,amount>0,dimensionCode,remark}(无 taskId)→ code=200,
+ *              data.sourceType="manual", data.sourceId=null, data.description=remark;
+ *              logs 返回 records 含 sourceType="manual"
+ *   grant 异常:amount=-10/0 → code=400「能量数量必须为正数」;
+ *              dimensionCode=nonexistent → code=400「维度代码无效:nonexistent」;
+ *              缺 amount → code=500「memberId、taskId和amount不能为空」(Result.error 默认 500)
+ *   grant 权限:跨家庭 memberId → code=403「无权给其他家庭成员发放能量」(isMemberInOtherFamily);
+ *              匿名 → HTTP 401「请先登录」(JwtInterceptor)
+ *   configure 权限:body.role≠admin → code=403「仅管理员可配置全局能量来源比例」;
+ *                  匿名 → HTTP 401
+ *   configure 异常:ratios 合计≠100 → code=400「来源比例之和必须为100%,当前为X%」;
+ *                  缺 sourceType/sourceId → code=500「sourceType和sourceId不能为空」;
+ *                  缺 ratios → code=500「ratios不能为空」
+ *   configure 正常:见下方承袭 blocker 标注
+ *
+ * ⚠️ 承袭·真实缺陷未修(比例校验正常流):
+ *   测试库 energy_source_config.ratio 列类型 decimal(5,4)(容 0~9.9999),但 service 传整数 100,
+ *   触发 DataIntegrityViolationException → 400「数据不完整或格式错误」。
+ *   已实测确认(_probe_energy_adjust2):valid config ratio=100 → 400;ratio=1 → 400「合计必须为100%」。
+ *   现有 5 行(product/source_id=1~5)ratio=1.0000,非 100,说明生产数据也不按百分比整数存储。
+ *   service 期望「合计=100(百分比)」与 DB 列 decimal(5,4) 矛盾 → 合法 configure 写入必失败。
+ *   按纪律不为缺陷造绿:本 spec 不断言 configure 合法写入=200,登记为承袭 blocker。
+ *
+ * 运行:CFC_API_BASE=http://127.0.0.1:9082 npx playwright test api/energy-admin-adjust.spec.js \
+ *         -c playwright.config.api.js --project=desktop
+ * 安全约定:不打印 token / 手机号。
+ */
+const { test, expect } = require('@playwright/test');
+const { registerRole, apiPost, pickMemberByUserId, uniqueSuffix } = require('../helpers/api');
+
+test.describe('S-cfc-492 energy.admin.adjust 三类流', () => {
+  let parent, selfMemberId, otherMemberId, admin;
+
+  test.beforeAll(async ({ request }) => {
+    // 家长 + 自身成员
+    parent = await registerRole(request, 'parent', 'QA-EA' + uniqueSuffix());
+    const mem = await apiPost(request, '/api/family/member/list', {}, parent.token);
+    expect(mem.code, 'member/list: ' + mem.message).toBe(200);
+    selfMemberId = pickMemberByUserId(mem.data, parent.userId).id;
+
+    // 跨家庭对照
+    const other = await registerRole(request, 'parent', 'QA-EA-O' + uniqueSuffix());
+    const omem = await apiPost(request, '/api/family/member/list', {}, other.token);
+    otherMemberId = pickMemberByUserId(omem.data, other.userId).id;
+
+    // admin 角色(比例配置)
+    admin = await registerRole(request, 'admin', 'QA-EA-ADM' + uniqueSuffix());
+  });
+
+  // ==================== 正常流(SC-P-89 手动发放留痕) ====================
+
+  test('[P-89 正常] 手动发放(无 taskId + remark)→ manual 留痕可查', async ({ request }) => {
+    const remark = 'QA手动发放-三流测试-' + uniqueSuffix();
+    const r = await apiPost(request, '/api/energy/grant', {
+      memberId: selfMemberId, amount: 10, dimensionCode: 'body', remark,
+    }, parent.token);
+    expect(r.code, 'grant manual: ' + r.message).toBe(200);
+    // EnergyLog.sourceType=manual / sourceId=null(区分任务奖励式 sourceType=task)
+    expect(r.data.sourceType, 'sourceType=manual').toBe('manual');
+    expect(r.data.sourceId).toBeNull();
+    expect(r.data.description, 'description=remark').toBe(remark);
+
+    // logs 可查:sourceType=manual 且 description 含备注
+    const logs = await apiPost(request, '/api/energy/logs',
+      { memberId: selfMemberId, page: 1, size: 20 }, parent.token);
+    expect(logs.code, 'logs: ' + logs.message).toBe(200);
+    const records = logs.data.records || [];
+    const found = records.find((x) => x.sourceType === 'manual' && x.description === remark);
+    expect(found, 'logs 应含本次 manual 流水').toBeTruthy();
+  });
+
+  // ==================== 异常流(SC-P-89 / SC-P-92) ====================
+
+  test('[P-89-E 异常] 负额/零额 → 400「能量数量必须为正数」', async ({ request }) => {
+    const neg = await apiPost(request, '/api/energy/grant',
+      { memberId: selfMemberId, amount: -10, dimensionCode: 'body', remark: 'x' }, parent.token);
+    expect(neg.code, 'negative → ' + neg.message).toBe(400);
+    expect(neg.message).toBe('能量数量必须为正数');
+
+    const zero = await apiPost(request, '/api/energy/grant',
+      { memberId: selfMemberId, amount: 0, dimensionCode: 'body', remark: 'x' }, parent.token);
+    expect(zero.code, 'zero → ' + zero.message).toBe(400);
+    expect(zero.message).toBe('能量数量必须为正数');
+  });
+
+  test('[P-89-E 异常] 非法维度 → 400「维度代码无效」;缺 amount → 500 参数校验', async ({ request }) => {
+    const badDim = await apiPost(request, '/api/energy/grant',
+      { memberId: selfMemberId, amount: 5, dimensionCode: 'nonexistent', remark: 'x' }, parent.token);
+    expect(badDim.code, 'bad dim → ' + badDim.message).toBe(400);
+    expect(badDim.message).toContain('维度代码无效');
+
+    // 缺 amount 且无 taskId + remark 非空 → 参数校验(Result.error 默认 500)
+    const miss = await apiPost(request, '/api/energy/grant',
+      { memberId: selfMemberId, dimensionCode: 'body', remark: 'x' }, parent.token);
+    expect(miss.code, 'missing amount → ' + miss.message).toBe(500);
+    expect(miss.message).toBe('memberId、taskId和amount不能为空');
+  });
+
+  test('[P-92-E 异常] 来源比例合计≠100 → 400「来源比例之和必须为100%」', async ({ request }) => {
+    const r = await apiPost(request, '/api/energy/configure', {
+      role: 'admin', sourceType: 'task', sourceId: 1, sourceName: 'QA-TEST',
+      ratios: [{ dimensionCode: 'body', ratio: 60 }, { dimensionCode: 'mind', ratio: 60 }],
+    }, admin.token);
+    expect(r.code, 'ratio sum=120 → ' + r.message).toBe(400);
+    expect(r.message).toContain('来源比例之和必须为100%');
+    expect(r.message).toContain('120%');
+  });
+
+  test('[P-92-E 异常] 缺 sourceType/sourceId → 500;缺 ratios → 500', async ({ request }) => {
+    // Result.error 默认 500(非 badRequest);探针实测一致
+    const missType = await apiPost(request, '/api/energy/configure', {
+      role: 'admin', sourceId: 1, ratios: [{ dimensionCode: 'body', ratio: 100 }],
+    }, admin.token);
+    expect(missType.code, 'miss sourceType → ' + missType.message).toBe(500);
+    expect(missType.message).toBe('sourceType和sourceId不能为空');
+
+    const missRatios = await apiPost(request, '/api/energy/configure', {
+      role: 'admin', sourceType: 'task', sourceId: 1,
+    }, admin.token);
+    expect(missRatios.code, 'miss ratios → ' + missRatios.message).toBe(500);
+    expect(missRatios.message).toBe('ratios不能为空');
+  });
+
+  // ==================== 权限流(SC-P-89-P 跨家庭 / SC-P-92-P 非 admin) ====================
+
+  test('[P-89-P 权限] 跨家庭 memberId → 403「无权给其他家庭成员发放能量」', async ({ request }) => {
+    const r = await apiPost(request, '/api/energy/grant',
+      { memberId: otherMemberId, amount: 5, dimensionCode: 'body', remark: 'x' }, parent.token);
+    expect(r.code, 'cross-family grant → ' + r.message).toBe(403);
+    expect(r.message).toBe('无权给其他家庭成员发放能量');
+  });
+
+  test('[P-92-P 权限] body.role≠admin → 403「仅管理员可配置全局能量来源比例」', async ({ request }) => {
+    const r = await apiPost(request, '/api/energy/configure', {
+      role: 'parent', sourceType: 'task', sourceId: 1,
+      ratios: [{ dimensionCode: 'body', ratio: 100 }],
+    }, parent.token);
+    expect(r.code, 'non-admin configure → ' + r.message).toBe(403);
+    expect(r.message).toBe('仅管理员可配置全局能量来源比例');
+  });
+
+  test('[P-89/P-92-P 权限] 匿名访问 grant/configure → HTTP 401「请先登录」', async ({ request }) => {
+    const g = await request.post('/api/energy/grant', {
+      data: { memberId: selfMemberId, amount: 5, dimensionCode: 'body', remark: 'x' },
+    });
+    expect(g.status(), 'anon grant → HTTP ' + g.status()).toBe(401);
+    const gBody = await g.json().catch(() => ({}));
+    expect(gBody.message).toBe('请先登录');
+
+    const c = await request.post('/api/energy/configure', {
+      data: { role: 'admin', sourceType: 'task', sourceId: 1,
+        ratios: [{ dimensionCode: 'body', ratio: 100 }] },
+    });
+    expect(c.status(), 'anon configure → HTTP ' + c.status()).toBe(401);
+    const cBody = await c.json().catch(() => ({}));
+    expect(cBody.message).toBe('请先登录');
+  });
+
+  // ==================== 承袭 blocker(比例校验正常流) ====================
+
+  test.fixme('[P-92 正常·承袭·真实缺陷未修] 合法比例 configure 应=200(ratio 列 decimal(5,4) 拦截)', async ({ request }) => {
+    // 探针实测:admin + sourceName 齐全 + ratio=100 → 400「数据不完整或格式错误」
+    // 根因:energy_source_config.ratio 列 decimal(5,4)(max 9.9999),service 传 100 溢出
+    //       → DataIntegrityViolationException → GlobalExceptionHandler 400
+    // 现有生产/测试数据 ratio=1.0000(基点非百分比),与「合计=100」service 契约矛盾。
+    // 不造绿:标记 fixme,待后端统一 service「基点 ↔ 百分比」口径 + schema 迁移后转正式断言。
+    const r = await apiPost(request, '/api/energy/configure', {
+      role: 'admin', sourceType: 'task', sourceId: 1, sourceName: 'QA',
+      ratios: [{ dimensionCode: 'body', ratio: 100 }],
+    }, admin.token);
+    expect(r.code, 'valid configure → ' + r.message).toBe(200);
+  });
+});

+ 261 - 0
tests/e2e/api/notification-setting-contract.spec.js

@@ -0,0 +1,261 @@
+// ============================================================================
+// [F-1111-09 · SC-P-65/79 · 能力键 notification.setting.config · TC-P-65/79]
+// 三流(功能 / 异常 / 权限)e2e 契约用例 —— 通知开关/提醒时间设置
+// 缺口来源:docs/tdd/orchestration/discovery-2026-11-30-1111.md F-1111-09
+// ----------------------------------------------------------------------------
+// 接口(API_REFERENCE.md L3593;NotificationSettingController L29/L35):
+//   POST /api/notification/setting/get   读取本人通知设置(未配置回显默认值)
+//   POST /api/notification/setting/save  保存本人通知设置(HH:mm 校验 + 二值开关 + 关键安全通知不可关闭)
+//
+// 契约来源(已逐条核对后端实现,只读,不改生产源码):
+//   cfc-backend/.../service/NotificationSettingService.java(S-cfc-286 落地):
+//     getConfig: 未配置回显默认 {enabled:1, reminderEnabled:1, reminderTime:'08:00', safetyEnabled:1};
+//                脏数据 time 非法按 '08:00' 回显;safety 恒按 1 回显(分发侧 isNotificationEnabled('safety') 恒 true)
+//     saveConfig: reminderTime 非法(正则 ^([01]\d|2[0-3]):[0-5]\d$)→IllegalArgumentException→400「提醒时间格式不合法」;
+//                safetyEnabled=0→400「关键安全通知不可关闭」;enabled/reminderEnabled 非 0/1→400「仅允许 0/1」;
+//                成功 200 data=true,落库 safety_enabled 恒 1
+//     隔离设计:userId 一律取自 JWT(@RequestAttribute),DTO 内 userId 不得改写他人配置
+//   JwtInterceptor:/api/notification/setting/** 列匿名 401 强制族 → 匿名 get/save → http=401「请先登录」
+//   Result<T>:业务码在 body,HTTP 恒 200(401 为拦截器 HTTP 状态)
+//
+// 真实契约探针(_probe_notification_setting.spec.js,gitignore,本地 127.0.0.1:9082 + 测试库 192.168.16.251/zxyj 实测):
+//   正常/异常流全部符合上述契约(25:00→400、safetyEnabled=0→400、二值→400、匿名→401 均已实测确认)。
+//   ✦✦ 权限流【按 userId 隔离】实测为**真实缺陷**(G-304-1 同族:跨用户隔离缺失):
+//      NotificationSettingService.selectByUserId 的「兜底」selectOne(null)(无 WHERE 全表取行)在
+//      当前用户**未配置**时会取到**其他用户**的已落库行,导致:
+//        ① 跨用户读泄漏:B 未配置时 get(B) 回显 A 的已保存配置(开关/提醒时间串户);
+//        ② 跨用户写覆盖:B 未配置时 save(B) 命中 A 的行并 updateById 改写(user_id 被改为 B,
+//           A 的配置丢失,之后 get(A) 回显 B 的值)——DTO.userId 隔离设计落空。
+//      文档契约(API_REF L3593「按登录 userId 隔离」)与实现不符。按任务纪律【不造绿】:
+//      本 spec 的权限流按文档真实契约写**严格断言**(期望隔离生效),实测不隔离则该测试判红,
+//      记「承袭·真实缺陷未修」,不改断言放水(见 test 4 断言消息与汇报登记)。
+//
+// DB 依赖:notification_settings 表为 QA 独占表(自然状态为空;仅 saveConfig 建/改行)。
+//   为使「默认回显/隔离」行为确定可复现,测试前经 mysql CLI 清空该表(测试库 192.168.16.251/zxyj 约定,
+//   与 reset-db.sh / flow-l1-tests.js 直连一致)。mysql CLI 不可用 → 本 spec 明确失败(不造绿)。
+//
+// 运行:
+//   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/notification-setting-contract.spec.js -c playwright.config.api.js --project=desktop
+// 安全约定:不打印 token / 手机号;清空表仅作用于测试库 QA 独占表。
+// ============================================================================
+
+const { test, expect } = require('@playwright/test');
+const { execFileSync } = require('child_process');
+const { apiPost } = require('../helpers/api');
+
+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: body.data.role };
+      }
+      lastErr = body;
+    } catch (e) {
+      lastErr = e && e.message ? e.message : String(e);
+    }
+  }
+  throw new Error('register(' + role + ') 失败: ' + JSON.stringify(lastErr));
+}
+
+// ---------- mysql CLI(测试库约定;不可用即失败,不造绿) ----------
+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';
+
+function mysqlExec(sql) {
+  const args = ['-h', MYSQL_HOST, '-P', MYSQL_PORT, '-u', MYSQL_USER];
+  if (MYSQL_PASS !== '') args.push('-p' + MYSQL_PASS);
+  // 实测该 mysql 客户端 --default-character-set 不生效(连接恒 latin1),每会话显式 SET NAMES utf8mb4
+  args.push('-N', '-B', MYSQL_DB);
+  return execFileSync(MYSQL_CLI, args, { input: 'SET NAMES utf8mb4;\n' + sql + ';\n', encoding: 'utf8', timeout: 30000 });
+}
+
+/** 清空 QA 独占表,保证「未配置回显默认值 / 按 userId 隔离」行为确定可复现 */
+function resetSettings() {
+  mysqlExec('DELETE FROM notification_settings');
+}
+
+const DEFAULTS = { enabled: 1, reminderEnabled: 1, reminderTime: '08:00', safetyEnabled: 1 };
+
+function assertDtoDefaults(label, dto) {
+  expect(dto.userId, label + ' userId 回显调用者').toBeTruthy();
+  expect(dto.enabled, label + ' 默认全开 enabled=1').toBe(1);
+  expect(dto.reminderEnabled, label + ' 默认 reminderEnabled=1').toBe(1);
+  expect(dto.reminderTime, label + ' 默认提醒时间 08:00').toBe(DEFAULTS.reminderTime);
+  expect(dto.safetyEnabled, label + ' 关键安全通知恒开=1').toBe(1);
+}
+
+test.describe.serial('F-1111-09 · /api/notification/setting/{get,save}(三流)', () => {
+  test.setTimeout(180000);
+
+  // -------------------------------------------------------------------------
+  // 正常流 TC-P-65(默认回显 / 保存 / 全关后安全通知仍放行)
+  // -------------------------------------------------------------------------
+
+  test('[功能] 未配置回显默认值;合法保存生效;普通开关全关时关键安全通知恒开', async ({ request }) => {
+    const A = await register(request, 'parent', 'ns-fn-A');
+    resetSettings();
+
+    // 未配置 → 默认值回显(全开 + 08:00 + 安全恒开)
+    const fresh = await apiPost(request, '/api/notification/setting/get', {}, A.token);
+    expect(fresh.status, 'get 不500').toBe(200);
+    expect(fresh.code, 'get code=200, 实际=' + fresh.code + ' msg=' + fresh.message).toBe(200);
+    expect(fresh.data.userId, 'userId 回显登录者本人').toBe(A.userId);
+    assertDtoDefaults('未配置默认回显', fresh.data);
+
+    // 合法保存(HH:mm + 二值开关)→ 200 true,再读回显已保存值
+    const save = await apiPost(request, '/api/notification/setting/save', {
+      enabled: 0, reminderEnabled: 1, safetyEnabled: 1, reminderTime: '09:30',
+    }, A.token);
+    expect(save.code, 'save code=200, 实际=' + save.code + ' msg=' + save.message).toBe(200);
+    expect(save.data, 'save 返回 true').toBe(true);
+    let back = await apiPost(request, '/api/notification/setting/get', {}, A.token);
+    expect(back.code, '读回 code=200').toBe(200);
+    expect(back.data.userId).toBe(A.userId);
+    expect(back.data.enabled, '总开关关闭持久化').toBe(0);
+    expect(back.data.reminderEnabled, '提醒开关开启持久化').toBe(1);
+    expect(back.data.reminderTime, '提醒时间 HH:mm 持久化').toBe('09:30');
+    expect(back.data.safetyEnabled, '安全通知恒 1').toBe(1);
+
+    // 全部普通开关关闭(enabled=0 + reminderEnabled=0)仍保存成功,且安全通知不可关(恒 1)
+    const allOff = await apiPost(request, '/api/notification/setting/save', {
+      enabled: 0, reminderEnabled: 0, safetyEnabled: 1, reminderTime: '00:00',
+    }, A.token);
+    expect(allOff.code, '全关保存 code=200, 实际=' + allOff.code).toBe(200);
+    back = await apiPost(request, '/api/notification/setting/get', {}, A.token);
+    expect(back.data.enabled, '普通总开关可关').toBe(0);
+    expect(back.data.reminderEnabled, '普通提醒开关可关').toBe(0);
+    expect(back.data.safetyEnabled, '关键安全通知关闭全部后仍放行(恒 1)').toBe(1);
+  });
+
+  // -------------------------------------------------------------------------
+  // 异常流 TC-P-65-E(HH:mm 校验 / 非二值开关 / 安全通知不可关)
+  // -------------------------------------------------------------------------
+
+  test('[异常] 非法提醒时间 25:00/8:5/缺失 → 400;非二值开关 → 400;安全通知关闭 → 400 拒绝', async ({ request }) => {
+    const A = await register(request, 'parent', 'ns-exc-A');
+    resetSettings();
+    // 先建一行合法配置,保证异常流在「已配置」态验证(校验先于写库,与是否已配置无关)
+    await apiPost(request, '/api/notification/setting/save', {
+      enabled: 1, reminderEnabled: 1, safetyEnabled: 1, reminderTime: '08:00',
+    }, A.token);
+
+    const badTime = [
+      ['25:00', '小时越界'],
+      ['24:00', '小时越界(23:59 为上限)'],
+      ['8:5', '缺前导零'],
+      ['9:30:00', '含秒'],
+      ['abcd', '非时间'],
+      ['23:60', '分钟越界'],
+      ['', '空串'],
+    ];
+    for (const [t, why] of badTime) {
+      const r = await apiPost(request, '/api/notification/setting/save', {
+        enabled: 1, reminderEnabled: 1, safetyEnabled: 1, reminderTime: t,
+      }, A.token);
+      expect(r.code, '非法时间 ' + JSON.stringify(t) + '(' + why + ')→400, 实际=' + r.code + ' msg=' + r.message).toBe(400);
+      expect(r.message).toBe('提醒时间格式不合法');
+    }
+
+    // 缺失提醒时间 → 400
+    const missing = await apiPost(request, '/api/notification/setting/save', { enabled: 1, reminderEnabled: 1, safetyEnabled: 1 }, A.token);
+    expect(missing.code, '缺失 reminderTime→400, 实际=' + missing.code).toBe(400);
+    expect(missing.message).toBe('提醒时间格式不合法');
+
+    // 关键安全通知关不掉 → 400 拒绝(非法 25:00 与 safety=0 同时出现时,时间校验先行)
+    const safetyOff = await apiPost(request, '/api/notification/setting/save', {
+      enabled: 1, reminderEnabled: 1, safetyEnabled: 0, reminderTime: '08:00',
+    }, A.token);
+    expect(safetyOff.code, 'safetyEnabled=0→400, 实际=' + safetyOff.code + ' msg=' + safetyOff.message).toBe(400);
+    expect(safetyOff.message).toBe('关键安全通知不可关闭');
+
+    // 非二值开关 → 400
+    const badEnabled = await apiPost(request, '/api/notification/setting/save', {
+      enabled: 2, reminderEnabled: 1, safetyEnabled: 1, reminderTime: '08:00',
+    }, A.token);
+    expect(badEnabled.code, 'enabled=2→400, 实际=' + badEnabled.code).toBe(400);
+    expect(badEnabled.message).toBe('enabled 仅允许 0/1');
+    const badReminder = await apiPost(request, '/api/notification/setting/save', {
+      enabled: 1, reminderEnabled: 9, safetyEnabled: 1, reminderTime: '08:00',
+    }, A.token);
+    expect(badReminder.code, 'reminderEnabled=9→400, 实际=' + badReminder.code).toBe(400);
+    expect(badReminder.message).toBe('reminderEnabled 仅允许 0/1');
+
+    // 异常不写库:配置未被异常请求篡改
+    const back = await apiPost(request, '/api/notification/setting/get', {}, A.token);
+    expect(back.data.reminderTime, '异常请求未破坏已存配置').toBe('08:00');
+    expect(back.data.safetyEnabled).toBe(1);
+  });
+
+  // -------------------------------------------------------------------------
+  // 权限流 TC-P-65-P / TC-P-79-P(匿名 401 / 按 userId 隔离)
+  // -------------------------------------------------------------------------
+
+  test('[权限] 匿名 get/save → http=401「请先登录」(拦截器强制登录族)', async ({ request }) => {
+    const g = await request.post('/api/notification/setting/get', { data: {}, timeout: 30000 });
+    expect(g.status(), '匿名 get→401, 实际=' + g.status()).toBe(401);
+    const gBody = await g.json().catch(() => ({}));
+    expect(gBody.code).toBe(401);
+    expect(gBody.message).toBe('请先登录');
+
+    const s = await request.post('/api/notification/setting/save', {
+      data: { enabled: 1, reminderEnabled: 1, safetyEnabled: 1, reminderTime: '08:00' },
+      timeout: 30000,
+    });
+    expect(s.status(), '匿名 save→401, 实际=' + s.status()).toBe(401);
+    const sBody = await s.json().catch(() => ({}));
+    expect(sBody.code).toBe(401);
+    expect(sBody.message).toBe('请先登录');
+  });
+
+  test('[权限·按 userId 隔离] 未配置用户不得读/写他人配置(文档契约;实测缺陷 → 判红·承袭·真实缺陷未修)', async ({ request }) => {
+    const A = await register(request, 'parent', 'ns-iso-A');
+    const B = await register(request, 'parent', 'ns-iso-B');
+    resetSettings();
+    // 表清空后 A 建唯一行(insert 路径确定)
+    const saveA = await apiPost(request, '/api/notification/setting/save', {
+      enabled: 0, reminderEnabled: 0, safetyEnabled: 1, reminderTime: '09:30',
+    }, A.token);
+    expect(saveA.code, 'A 保存 code=200').toBe(200);
+
+    // ---- ① 跨用户读(严格断言按文档契约:B 未配置 → 默认值回显,不泄漏 A 的配置)----
+    const getB = await apiPost(request, '/api/notification/setting/get', {}, B.token);
+    expect(getB.code, 'B get code=200').toBe(200);
+    console.log('[DEFECT-PROBE] B(未配置) get 实际回显 =', JSON.stringify(getB.data));
+    expect(
+      getB.data.reminderTime,
+      '【承袭·真实缺陷未修|G-304-1 同族】B 未配置应回显默认 08:00,实际泄漏 A 已保存的 09:30:' +
+        'NotificationSettingService.selectByUserId 兜底 selectOne(null) 无 WHERE 全表取行,跨用户读泄漏。' +
+        '文档契约=按登录 userId 隔离(API_REF L3593)。不造绿:保持严格断言,判红登记。',
+    ).toBe(DEFAULTS.reminderTime);
+
+    // ---- ② 跨用户写(DTO.userId 伪造 A 亦不得改写 A 的配置)----
+    const saveB = await apiPost(request, '/api/notification/setting/save', {
+      userId: A.userId, // DTO 字段伪造他人 userId(隔离设计应忽略,仅按 JWT userId 落库)
+      enabled: 1, reminderEnabled: 1, safetyEnabled: 1, reminderTime: '21:15',
+    }, B.token);
+    expect(saveB.code, 'B 保存 code=200').toBe(200);
+
+    const getA = await apiPost(request, '/api/notification/setting/get', {}, A.token);
+    console.log('[DEFECT-PROBE] A get 实际回显 =', JSON.stringify(getA.data));
+    expect(
+      getA.data.reminderTime,
+      '【承袭·真实缺陷未修|G-304-1 同族】B 保存/伪造 userId 后 A 的配置应仍为 09:30,实际被 B 的行改写/串户:' +
+        'saveConfig 在 B 未配置时经兜底 selectOne(null) 命中 A 的行并 updateById 改写(user_id 被改为 B),' +
+        '跨用户写覆盖。保持严格断言,判红登记,不造绿。',
+    ).toBe('09:30');
+  });
+});
+
+// 安全约定:本文件不打印 token / 手机号。

+ 276 - 0
tests/e2e/api/plan-activate-contract.spec.js

@@ -0,0 +1,276 @@
+// ============================================================================
+// [F-1111-05 · SC-P-46/SC-T-05 · 能力键 teacher.plan.activate · TC-T-05*]
+// 三流(功能 / 异常 / 权限)e2e 契约用例 —— 方案激活拆任务(幂等)
+// 缺口来源:docs/tdd/orchestration/discovery-2026-11-30-1111.md F-1111-05
+//   (台账 TC-T-05 e2e 栏指向的 ai-plan-task-flow.spec.js 实际只触达 /api/ai/chat/send,
+//     未触达本端点,有效覆盖缺失;D-04 归 plan.ai.generate,本 spec 归 teacher.plan.activate,不重复)
+// ----------------------------------------------------------------------------
+// 接口(API_REFERENCE.md L2397;PlanReviewController L125–146):
+//   POST /api/guide/plans/activate {planId}
+//     角色闸门:非规划师/非 admin → Result.error("无权限")(**code=500,真实契约**,非 403);
+//     认证闸门:role=teacher 时 PlannerCertificationGuard.assertCertified(userId, 'planner'),
+//       未完成 planner 培训认证 → 403「规划师未完成【planner】培训认证,暂不可提供该类服务」;
+//       admin 角色豁免认证闸门(S-cfc-180 口径);
+//     状态守卫(PlanActivationService.activate → IllegalStateException → 500):
+//       方案不存在 → 500「方案不存在」;status≠'reviewed' → 500「方案状态异常,需要先审核通过」;
+//       成员不存在(users/family_members 双 ID 域均查不到)→ 500「成员不存在」;
+//     成功:TaskPlanService.generateTasksFromTemplate(1 引导任务 + N 模板任务,
+//       **幂等**:tasks 中 source_type='plan' AND source_id=planId 已有非 cancelled 行则跳过生成)
+//       + 方案置 active + activated_at/total_days/completed_days 留痕;返回 data='方案已激活'
+//       (注意:controller 调 Result.success(String) 重载被 Java 解析为 1 参 generic 版,
+//        实际 message='success'、data='方案已激活' —— 真实契约,按探针实测断言)
+//
+// 契约来源(已逐条核对后端实现,只读,不改生产源码):
+//   cfc-backend/.../controller/guide/PlanReviewController.java L125–146
+//   cfc-backend/.../service/PlanActivationService.java(状态守卫 + 成员双 ID 域)
+//   cfc-backend/.../service/TaskPlanService.java generateTasksFromTemplate(幂等跳过)
+//   cfc-backend/.../service/PlannerCertificationGuard.java(403 认证闸门)
+//
+// 真实契约探针(_probe_plan_activate.spec.js,gitignore,本地 127.0.0.1:9082 + 测试库 192.168.16.251/zxyj 实测):
+//   ① reviewed→active:code=200,data='方案已激活';tasks 生成 1 引导 + 2 模板 = 3 条
+//      (source_type='plan'、source_id=planId、executor=member、family 归属正确);方案 status='active';
+//   ② 幂等:再次 activate 同一方案 → 500「方案状态异常,需要先审核通过」(状态守卫拦截),
+//      tasks 数量保持 3 不重复生成;
+//   ③ 非 reviewed(generated/active)→ 500「方案状态异常,需要先审核通过」;
+//   ④ 越权(台账「越权 403」口径)实测分两条路径:
+//      - 非规划师角色(parent 等)→ code=500「无权限」(角色闸门,Result.error(String)=500 口径,
+//        **非 403**;台账/文档「403」表述与实现不一致,本 spec 按探针真实契约严格断言并登记差异,不放水不判红);
+//      - 规划师未认证(teacher 无 planner certified)→ code=403「规划师未完成【planner】培训认证,暂不可提供该类服务」
+//        (PlannerCertificationGuard,S-cfc-180 认证闸门);
+//   ⑤ 匿名(无 token)→ http=200 code=500「无权限」(guide 族未列匿名 401 强制,降级匿名后角色闸门拒绝)。
+//
+// 方案构造:后端无「创建 reviewed 方案」的 HTTP 端点供 e2e 直接调用(/api/guide/plans/review 需 generated 态
+//   方案且属审核流),本 spec 经 mysql CLI 直接 seed task_plan_instances + admin_task_templates +
+//   task_template_items(marker 前缀 QA- 便于清理),不改生产源码、不改台账。
+//   mysql CLI 不可用时本 spec 明确失败(不造绿)。
+//
+// 运行:
+//   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/plan-activate-contract.spec.js -c playwright.config.api.js --project=desktop
+// 安全约定:不打印 token / 手机号;测试数据自建自清(cleanupPlans)。
+// ============================================================================
+
+const { test, expect } = require('@playwright/test');
+const { execFileSync } = require('child_process');
+const { apiPost } = require('../helpers/api');
+
+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: body.data.role };
+      }
+      lastErr = body;
+    } catch (e) {
+      lastErr = e && e.message ? e.message : String(e);
+    }
+  }
+  throw new Error('register(' + role + ') 失败: ' + JSON.stringify(lastErr));
+}
+
+// ---------- mysql CLI(测试库约定;不可用即失败,不造绿) ----------
+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';
+
+function sqlStr(s) {
+  return "'" + String(s == null ? '' : s).replace(/\\/g, '\\\\').replace(/'/g, "''").replace(/\0/g, '') + "'";
+}
+function mysqlExec(sql) {
+  const args = ['-h', MYSQL_HOST, '-P', MYSQL_PORT, '-u', MYSQL_USER];
+  if (MYSQL_PASS !== '') args.push('-p' + MYSQL_PASS);
+  // 实测该 mysql 客户端 --default-character-set 不生效(连接恒 latin1),每会话显式 SET NAMES utf8mb4
+  args.push('-N', '-B', MYSQL_DB);
+  return execFileSync(MYSQL_CLI, args, { input: 'SET NAMES utf8mb4;\n' + sql + ';\n', encoding: 'utf8', timeout: 30000 });
+}
+function oneNum(sql) {
+  const out = mysqlExec(sql + ';').trim();
+  const lines = out.split('\n').map(function (l) { return l.trim(); }).filter(function (l) { return l !== ''; });
+  for (const line of lines) { if (/^\d+$/.test(line)) return Number(line); }
+  return null;
+}
+
+/**
+ * seed 一套隔离方案数据:新套餐(admin_task_templates)+ 2 条模板项 + 方案行(status 可指定)。
+ * 生成任务数确定:1 引导 + 2 模板 = 3。
+ */
+function seedPlan(familyId, memberId, status, marker) {
+  const pkgTitle = marker + '-pkg';
+  mysqlExec(
+    'INSERT INTO admin_task_templates (title, description, points, category, is_active, created_at, updated_at) VALUES (' +
+    sqlStr(pkgTitle) + ', ' + sqlStr(marker + ' 套餐') + ', 2, ' + sqlStr('成长') + ', 1, NOW(), NOW())',
+  );
+  const packageId = oneNum('SELECT id FROM admin_task_templates WHERE title=' + sqlStr(pkgTitle) + ' LIMIT 1');
+  if (packageId == null) throw new Error('seedPlan 套餐 seed 失败 title=' + pkgTitle);
+  mysqlExec(
+    "INSERT INTO task_template_items (package_id, task_name, description, points, frequency, duration, is_required, sort_order, created_at, updated_at) VALUES (" +
+    Number(packageId) + ', ' + sqlStr(marker + '-模板任务1') + ', ' + sqlStr(marker + ' 描述') + ", 2, 'daily', 30, 0, 1, NOW(), NOW()), (" +
+    Number(packageId) + ', ' + sqlStr(marker + '-模板任务2') + ', ' + sqlStr(marker + ' 描述') + ", 2, 'weekly', 15, 0, 2, NOW(), NOW())",
+  );
+  const planName = marker + '-plan';
+  mysqlExec(
+    'INSERT INTO task_plan_instances (package_id, family_id, child_id, name, start_date, end_date, status, source, created_at, updated_at) VALUES (' +
+    Number(packageId) + ', ' + Number(familyId) + ', ' + Number(memberId) + ', ' + sqlStr(planName) +
+    ", CURDATE(), DATE_ADD(CURDATE(), INTERVAL 14 DAY), " + sqlStr(status) + ", 'manual', NOW(), NOW())",
+  );
+  const planId = oneNum('SELECT id FROM task_plan_instances WHERE package_id=' + Number(packageId) + ' ORDER BY id DESC LIMIT 1');
+  if (planId == null) throw new Error('seedPlan 方案 seed 失败 planName=' + planName);
+  return { planId: planId, packageId: packageId, planName: planName, marker: marker };
+}
+
+function cleanupPlans(plans) {
+  const list = (plans || []).filter(Boolean).map(function (p) { return p.planId; }).map(String).join(',');
+  if (list !== '') {
+    mysqlExec('DELETE FROM tasks WHERE source_type=' + sqlStr('plan') + ' AND source_id IN (' + list + ')');
+    mysqlExec('DELETE FROM task_plan_instances WHERE id IN (' + list + ')');
+  }
+  const pkgs = (plans || []).filter(Boolean).map(function (p) { return p.packageId; }).map(String).join(',');
+  if (pkgs !== '') {
+    mysqlExec('DELETE FROM task_template_items WHERE package_id IN (' + pkgs + ')');
+    mysqlExec('DELETE FROM admin_task_templates WHERE id IN (' + pkgs + ')');
+  }
+}
+
+function planTaskRows(planId) {
+  const out = mysqlExec('SELECT COUNT(*) FROM tasks WHERE source_type=' + sqlStr('plan') + ' AND source_id=' + Number(planId)).trim();
+  const lines = out.split('\n').map(function (l) { return l.trim(); }).filter(function (l) { return l !== ''; });
+  for (const line of lines) { if (/^\d+$/.test(line)) return Number(line); }
+  throw new Error('planTaskRows 读取失败 planId=' + planId + ' raw=' + JSON.stringify(out));
+}
+
+// ============================================================================
+// F-1111-05 · /api/guide/plans/activate(三流)
+// ============================================================================
+
+test.describe.serial('F-1111-05 · /api/guide/plans/activate(三流)', () => {
+  test.setTimeout(180000);
+
+  // -------------------------------------------------------------------------
+  // 正常流 TC-T-05(reviewed→active 拆任务 + 幂等不重复生成)
+  // -------------------------------------------------------------------------
+
+  test('[功能] reviewed→active 拆任务(引导+模板),幂等不重复生成;留痕 status/activated_at', async ({ request }) => {
+    const admin = await register(request, 'admin', 'pa-fn-admin');
+    const owner = await register(request, 'parent', 'pa-fn-owner');
+    const m = 'QApa' + Date.now() % 100000;
+    const p1 = seedPlan(owner.familyId, owner.userId, 'reviewed', m + '-a');
+    const p2 = seedPlan(owner.familyId, owner.userId, 'reviewed', m + '-b');
+    try {
+      // admin 激活 reviewed 方案(认证闸门豁免 S-cfc-180)
+      const act = await apiPost(request, '/api/guide/plans/activate', { planId: p1.planId }, admin.token);
+      expect(act.status, 'activate 不500').toBe(200);
+      expect(act.code, 'activate code=200, 实际=' + act.code + ' msg=' + act.message).toBe(200);
+      expect(act.data, '成功返回 data=方案已激活(真实契约:message 走 success 重载)').toBe('方案已激活');
+
+      // 拆任务:1 引导 + 2 模板 = 3 条(source_type=plan、source_id=方案ID、归属家庭/执行成员)
+      const n = planTaskRows(p1.planId);
+      expect(n, '生成 1 引导 + 2 模板 = 3 条任务, 实际=' + n).toBe(3);
+      const titles = mysqlExec(
+        'SELECT title FROM tasks WHERE source_type=' + sqlStr('plan') + ' AND source_id=' + Number(p1.planId) + " ORDER BY title",
+      ).trim();
+      expect(String(titles).indexOf('方案启动: ' + p1.planName) >= 0, '引导任务「方案启动: <方案名>」').toBe(true);
+      expect(String(titles).indexOf(m + '-a-模板任务1') >= 0, '模板任务1 已拆出').toBe(true);
+      expect(String(titles).indexOf(m + '-a-模板任务2') >= 0, '模板任务2 已拆出').toBe(true);
+      const taskOwner = oneNum('SELECT COUNT(*) FROM tasks WHERE source_type=' + sqlStr('plan') + " AND source_id=" + Number(p1.planId) + ' AND family_id=' + Number(owner.familyId) + " AND executor_id=" + Number(owner.userId));
+      expect(taskOwner, '任务归属家庭 + 执行成员留痕').toBe(3);
+
+      // 方案状态流转:reviewed→active + activated_at 留痕
+      const planActive = oneNum("SELECT 1 FROM task_plan_instances WHERE id=" + Number(p1.planId) + " AND status='active' AND activated_at IS NOT NULL");
+      expect(planActive, '方案 status=active 且 activated_at 留痕').toBe(1);
+
+      // 幂等不重复生成:再激活同一方案 → 状态守卫 500,任务数保持 3
+      const again = await apiPost(request, '/api/guide/plans/activate', { planId: p1.planId }, admin.token);
+      expect(again.code, '重复激活→500 状态守卫, 实际=' + again.code + ' msg=' + again.message).toBe(500);
+      expect(again.message).toBe('方案状态异常,需要先审核通过');
+      expect(planTaskRows(p1.planId), '幂等:任务数不重复生成(保持 3)').toBe(3);
+    } finally {
+      cleanupPlans([p1, p2]);
+    }
+  });
+
+  // -------------------------------------------------------------------------
+  // 异常流 TC-T-05-E(状态守卫 / 参数 / 不存在)
+  // -------------------------------------------------------------------------
+
+  test('[异常] 非 reviewed 拦截(generated/active)→500;缺 planId→500;方案不存在→500', async ({ request }) => {
+    const admin = await register(request, 'admin', 'pa-exc-admin');
+    const owner = await register(request, 'parent', 'pa-exc-owner');
+    const m = 'QApa' + (Date.now() % 100000);
+    const pGen = seedPlan(owner.familyId, owner.userId, 'generated', m + '-g');
+    const pAct = seedPlan(owner.familyId, owner.userId, 'active', m + '-c');
+    try {
+      const r1 = await apiPost(request, '/api/guide/plans/activate', { planId: pGen.planId }, admin.token);
+      expect(r1.code, 'generated(未审核)拦截→500, 实际=' + r1.code + ' msg=' + r1.message).toBe(500);
+      expect(r1.message).toBe('方案状态异常,需要先审核通过');
+      expect(planTaskRows(pGen.planId), '未审核方案不生成任务').toBe(0);
+
+      const r2 = await apiPost(request, '/api/guide/plans/activate', { planId: pAct.planId }, admin.token);
+      expect(r2.code, '已 active 再激活拦截→500, 实际=' + r2.code).toBe(500);
+      expect(r2.message).toBe('方案状态异常,需要先审核通过');
+
+      const r3 = await apiPost(request, '/api/guide/plans/activate', {}, admin.token);
+      expect(r3.code, '缺 planId→500, 实际=' + r3.code + ' msg=' + r3.message).toBe(500);
+      expect(r3.message).toBe('planId required');
+
+      const r4 = await apiPost(request, '/api/guide/plans/activate', { planId: 99999999 }, admin.token);
+      expect(r4.code, '方案不存在→500, 实际=' + r4.code).toBe(500);
+      expect(r4.message).toBe('方案不存在');
+    } finally {
+      cleanupPlans([pGen, pAct]);
+    }
+  });
+
+  // -------------------------------------------------------------------------
+  // 权限流 TC-T-05-P(角色闸门 / 认证闸门 / 匿名)
+  // -------------------------------------------------------------------------
+
+  test('[权限] 非规划师→500「无权限」(真实契约非 403,已登记差异);未认证规划师→403;匿名→500「无权限」', async ({ request }) => {
+    const admin = await register(request, 'admin', 'pa-perm-admin');
+    const parent = await register(request, 'parent', 'pa-perm-parent');
+    const teacher = await register(request, 'teacher', 'pa-perm-teacher'); // direct-register 无 planner 认证记录
+    const m = 'QApa' + (Date.now() % 100000);
+    const p1 = seedPlan(parent.familyId, parent.userId, 'reviewed', m + '-p');
+    try {
+      // ① 非规划师角色(parent):角色闸门拒绝。
+      //    台账「越权 403」口径 vs 实现:Result.error("无权限")=500(探针实测)。
+      //    按真实契约严格断言(不放水成 200、也不误判 403),差异已在文件头登记。
+      const rParent = await apiPost(request, '/api/guide/plans/activate', { planId: p1.planId }, parent.token);
+      expect(rParent.status, 'parent 越权不 5xx HTTP').toBe(200);
+      expect(rParent.code, '非规划师→500「无权限」(真实契约), 实际=' + rParent.code + ' msg=' + rParent.message).toBe(500);
+      expect(rParent.message).toBe('无权限');
+      expect(planTaskRows(p1.planId), '越权不生成任务').toBe(0);
+
+      // ② 规划师未完成 planner 培训认证 → 认证闸门 403(PlannerCertificationGuard)
+      const rTeacher = await apiPost(request, '/api/guide/plans/activate', { planId: p1.planId }, teacher.token);
+      expect(rTeacher.status, 'teacher 未认证不 5xx HTTP').toBe(200);
+      expect(rTeacher.code, '未认证规划师→403, 实际=' + rTeacher.code + ' msg=' + rTeacher.message).toBe(403);
+      expect(rTeacher.message, '认证闸门提示').toContain('planner');
+      expect(planTaskRows(p1.planId), '未认证规划师不生成任务').toBe(0);
+
+      // ③ 匿名(无 token):降级匿名后角色闸门拒绝(guide 族非 401 强制族,真实契约)
+      const anon = await request.post('/api/guide/plans/activate', { data: { planId: p1.planId }, timeout: 30000 });
+      const anonBody = await anon.json().catch(() => ({}));
+      expect(anon.status(), '匿名 activate http=200(降级匿名,非 401), 实际=' + anon.status()).toBe(200);
+      expect(anonBody.code, '匿名→500「无权限」, 实际=' + anonBody.code + ' msg=' + anonBody.message).toBe(500);
+      expect(anonBody.message).toBe('无权限');
+
+      // 方案状态未被越权请求改写(仍 reviewed)
+      const stillReviewed = oneNum('SELECT 1 FROM task_plan_instances WHERE id=' + Number(p1.planId) + " AND status='reviewed'");
+      expect(stillReviewed, '越权/未认证请求未改写方案状态').toBe(1);
+    } finally {
+      cleanupPlans([p1]);
+    }
+  });
+});
+
+// 安全约定:本文件不打印 token / 手机号;测试数据结束时清理(cleanupPlans)。