Sfoglia il codice sorgente

merge(cfclub): 同步 origin/cfclub 至任务分支,消解迁移编号冲突 S-cfc-387

origin/cfclub 已占迁移494(coupon_share)/495/496,本任务关系类型字典迁移
顺延为迁移497(family_relation_types,admin.familyRelation.manage)。
契约测试 AdminFamilyRelationManageContractTest 保持 8/8 绿;mvn compile 通过。
Sisyphus 2 giorni fa
parent
commit
061f3d14cf
59 ha cambiato i file con 7130 aggiunte e 1960 eliminazioni
  1. 77 6
      cfc-backend/src/main/java/com/etotem/cfc/config/DatabaseInitializer.java
  2. 10 1
      cfc-backend/src/main/java/com/etotem/cfc/config/JwtInterceptor.java
  3. 66 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/CouponGiftController.java
  4. 43 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/growth/GrowthPlanController.java
  5. 13 1
      cfc-backend/src/main/java/com/etotem/cfc/controller/product/ProductReviewController.java
  6. 20 0
      cfc-backend/src/main/java/com/etotem/cfc/dto/ProductReviewResponse.java
  7. 40 0
      cfc-backend/src/main/java/com/etotem/cfc/entity/CfPlatformRevenueLog.java
  8. 6 0
      cfc-backend/src/main/java/com/etotem/cfc/entity/CouponGiftTransfer.java
  9. 67 0
      cfc-backend/src/main/java/com/etotem/cfc/entity/CouponShare.java
  10. 4 0
      cfc-backend/src/main/java/com/etotem/cfc/entity/GrowthPlan.java
  11. 14 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/CfPlatformRevenueLogMapper.java
  12. 16 0
      cfc-backend/src/main/java/com/etotem/cfc/mapper/CouponShareMapper.java
  13. 78 0
      cfc-backend/src/main/java/com/etotem/cfc/service/CfCommissionService.java
  14. 54 7
      cfc-backend/src/main/java/com/etotem/cfc/service/CouponGiftService.java
  15. 448 0
      cfc-backend/src/main/java/com/etotem/cfc/service/CouponShareService.java
  16. 31 0
      cfc-backend/src/main/java/com/etotem/cfc/service/FamilyMemberService.java
  17. 98 0
      cfc-backend/src/main/java/com/etotem/cfc/service/GrowthPlanService.java
  18. 2 0
      cfc-backend/src/main/java/com/etotem/cfc/service/ProductOrderService.java
  19. 13 1
      cfc-backend/src/main/java/com/etotem/cfc/service/ProductReviewService.java
  20. 62 7
      cfc-backend/src/main/java/com/etotem/cfc/service/ProductReviewServiceImpl.java
  21. 17 1
      cfc-backend/src/main/java/com/etotem/cfc/service/UserService.java
  22. 224 0
      cfc-backend/src/main/java/com/etotem/cfc/task/OrderReceiptTimeoutTask.java
  23. 12 0
      cfc-backend/src/main/java/com/etotem/cfc/util/ParamUtils.java
  24. 27 3
      cfc-backend/src/main/resources/schema.sql
  25. 592 0
      cfc-backend/src/test/java/com/etotem/cfc/unit/CouponShareClaimContractTest.java
  26. 396 0
      cfc-backend/src/test/java/com/etotem/cfc/unit/RewardV2E2EExampleContractTest.java
  27. 349 0
      cfc-backend/src/test/java/com/etotem/cfc/unit/TeamShareWeightedContractTest.java
  28. 11 0
      cfc-frontend/pages.json
  29. 375 0
      cfc-frontend/pages/coupon/share-claim.vue
  30. 75 5
      cfc-frontend/pages/membership/gift-coupon.vue
  31. 74 2
      cfc-frontend/pages/profile-extra/coupons.vue
  32. 17 0
      cfc-frontend/utils/api.js
  33. 1 1
      cfc-web/.last_build_commit
  34. 2 2
      cfc-web/package-lock.json
  35. 1 1
      cfc-web/package.json
  36. 120 0
      cfc-web/public/CHANGELOG-v1.0.md
  37. 121 1
      cfc-web/public/CHANGELOG.md
  38. 148 0
      cfc-web/src/styles/admin-tokens.css
  39. 65 0
      docs/2026-11-15-用户115-高尿酸-食材指数调整与健康方案-执行报告.md
  40. 318 0
      docs/scripts/2026-11-15-user115-uric-plan.py
  41. 75 0
      docs/scripts/2026-11-16-user115-followup.py
  42. 15 2
      docs/superpowers/api/API_REFERENCE.md
  43. 32 0
      docs/tdd/orchestration/notice-2026-11-15-R222-研发通知.md
  44. 69 0
      docs/tdd/orchestration/notice-2026-11-16-R224-研发通知.md
  45. 51 0
      docs/tdd/orchestration/report-deploy-2026-11-16-597f5d873.md
  46. 154 0
      docs/tdd/orchestration/report-dev-2026-11-15-2109.md
  47. 147 0
      docs/tdd/orchestration/report-dev-2026-11-16-0055.md
  48. 165 0
      docs/tdd/orchestration/report-dev-2026-11-16-0226.md
  49. 353 0
      docs/tdd/orchestration/report-test-2026-11-15-R222.md
  50. 258 0
      docs/tdd/orchestration/report-test-2026-11-16-R224.md
  51. 30 0
      docs/tdd/test/_r224_agg.cjs
  52. 38 0
      docs/tdd/test/automation-run-2026-11-15-R222.md
  53. 45 0
      docs/tdd/test/automation-run-2026-11-16-R224.md
  54. 731 952
      docs/tdd/test/automation-status.md
  55. 37 0
      docs/tdd/test/blockers.md
  56. 13 10
      docs/tdd/test/discovery.md
  57. 730 951
      docs/tdd/test/inventory.md
  58. 11 6
      tests/e2e/api/dimension-energy-contract.spec.js
  59. 69 0
      tests/test-cases/2026-11-16-review-detail-my-receipt-timeout.md

+ 77 - 6
cfc-backend/src/main/java/com/etotem/cfc/config/DatabaseInitializer.java

@@ -3637,7 +3637,17 @@ insertSysConfigSeed("gift_membership_pay_price", "198000", "送会员商品达
         // + ensureServiceConfig 播种 6 键 + F03c 种子(seedCfEarnRules / seedCfServiceConfig 内已含)
         migrateCfRewardV2TeamPool();
 
-        // 迁移494: 家庭关系类型字典表 family_relation_types(SC-A-04 关系类型 CRUD 管理,
+        // 迁移494: 会员券分享转赠——创建 coupon_share 表(ARCH-CFC-COUPON-SHARE-GIFT-001 §4.1):
+        // 承载分享生命周期(PENDING/CLAIMED/REVOKED/EXPIRED,EXPIRED 懒判定),share_token 全局唯一
+        migrateCouponShareTable();
+
+        // 迁移495: coupon_gift_transfer 增列 share_token / claim_method(记录分享领取方式,§4.2)
+        addCouponGiftTransferShareColumns();
+
+        // 迁移496: growth_plans 增列 draft_expires_at / draft_version(SC-P-81 方案草稿保存与恢复,能力键 plan.draft.save)
+        addGrowthPlanDraftColumns();
+
+        // 迁移497: 家庭关系类型字典表 family_relation_types(SC-A-04 关系类型 CRUD 管理,
         // admin.familyRelation.manage)。v2 辈分重构后 relationship_types 已废弃 DROP(迁移169),
         // 此处重建字典作为管理端关系类型列表/新增/编辑/停用的数据载体;表名避开历史
         // relationship_types(迁移169 历史 DROP 会在每次启动清表,勿复用该名)。
@@ -3646,7 +3656,7 @@ insertSysConfigSeed("gift_membership_pay_price", "198000", "送会员商品达
 
 
     /**
-     * 迁移494: 创建家庭关系类型字典表 family_relation_types + 默认字典种子
+     * 迁移497: 创建家庭关系类型字典表 family_relation_types + 默认字典种子
      * (SC-A-04 关系类型 CRUD,能力键 admin.familyRelation.manage)。
      *
      * <p>幂等:CREATE TABLE IF NOT EXISTS + 空表才播种默认 6 类(spouse/parent/child/
@@ -3665,9 +3675,9 @@ insertSysConfigSeed("gift_membership_pay_price", "198000", "送会员商品达
                     + "created_at DATETIME DEFAULT CURRENT_TIMESTAMP, "
                     + "updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
                     + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='家庭关系类型字典表(关系类型 CRUD 管理)'");
-            log.info("迁移494: family_relation_types 表已就绪");
+            log.info("迁移497: family_relation_types 表已就绪");
         } catch (Exception e) {
-            log.warn("迁移494: family_relation_types 表创建失败(忽略): {}", e.getMessage());
+            log.warn("迁移497: family_relation_types 表创建失败(忽略): {}", e.getMessage());
         }
         try {
             Integer cnt = jdbcTemplate.queryForObject("SELECT COUNT(*) FROM family_relation_types", Integer.class);
@@ -3682,9 +3692,9 @@ insertSysConfigSeed("gift_membership_pay_price", "198000", "送会员商品达
                     + "('sibling', '兄弟姐妹', 0, 4, 1), "
                     + "('grandparent', '祖父母', 2, 5, 1), "
                     + "('grandchild', '孙辈', -2, 6, 1)");
-            log.info("迁移494: family_relation_types 默认字典种子已写入 6 行");
+            log.info("迁移497: family_relation_types 默认字典种子已写入 6 行");
         } catch (Exception e) {
-            log.warn("迁移494: family_relation_types 种子写入失败(忽略): {}", e.getMessage());
+            log.warn("迁移497: family_relation_types 种子写入失败(忽略): {}", e.getMessage());
         }
     }
 
@@ -16804,4 +16814,65 @@ log.info("迁移298: 已为无 openid 的 child 账号补齐 family_members 记
             log.warn("迁移491: data_export_request 表创建失败(忽略): {}", e.getMessage());
         }
     }
+
+    /**
+     * 迁移494: 创建会员券分享转赠记录表 coupon_share(ARCH-CFC-COUPON-SHARE-GIFT-001 §4.1)。
+     *
+     * <p>承载分享生命周期(PENDING/CLAIMED/REVOKED/EXPIRED,EXPIRED 懒判定不跑定时任务);
+     * {@code share_token} 全局唯一(uk_share_token 防碰撞);幂等(CREATE TABLE IF NOT EXISTS)。</p>
+     */
+    private void migrateCouponShareTable() {
+        try {
+            jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS coupon_share ("
+                    + "id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID', "
+                    + "share_token VARCHAR(64) NOT NULL COMMENT '全局唯一分享令牌(path/query传递)', "
+                    + "giver_user_id BIGINT NOT NULL COMMENT '赠送人用户ID(users.id)', "
+                    + "giver_family_id BIGINT NOT NULL COMMENT '赠送人家庭ID', "
+                    + "family_coupon_id BIGINT NOT NULL COMMENT '被分享的 family_coupon 实例ID', "
+                    + "coupon_id BIGINT NOT NULL COMMENT '券模板ID(coupon.id)', "
+                    + "status VARCHAR(16) NOT NULL DEFAULT 'PENDING' COMMENT 'PENDING/CLAIMED/REVOKED/EXPIRED(懒判定)', "
+                    + "claim_user_id BIGINT NULL COMMENT '领取人用户ID(users.id,领取前为NULL)', "
+                    + "claim_family_id BIGINT NULL COMMENT '领取人家庭ID(领取前为NULL)', "
+                    + "claim_time DATETIME NULL COMMENT '领取时间', "
+                    + "expire_at DATETIME NOT NULL COMMENT '分享有效期截止(创建时now+配置天数,默认7)', "
+                    + "created_at DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', "
+                    + "updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', "
+                    + "UNIQUE KEY uk_share_token (share_token), "
+                    + "INDEX idx_giver_status (giver_user_id, status), "
+                    + "INDEX idx_family_coupon (family_coupon_id), "
+                    + "INDEX idx_status (status)"
+                    + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='会员券分享转赠记录(分享生命周期)'");
+            log.info("迁移494: coupon_share 表已就绪(coupon.share.gift / ARCH-CFC-COUPON-SHARE-GIFT-001)");
+        } catch (Exception e) {
+            log.warn("迁移494: coupon_share 表创建失败(忽略): {}", e.getMessage());
+        }
+    }
+
+    /**
+     * 迁移495: coupon_gift_transfer 增列 share_token / claim_method(ARCH-CFC-COUPON-SHARE-GIFT-001 §4.2)。
+     *
+     * <p>记录领取方式:DIRECT=定向转赠 / SHARE=分享转赠;share_token 仅分享领取时回写(DIRECT 为 NULL)。
+     * ensureColumn 幂等,重复执行自动跳过。</p>
+     */
+    private void addCouponGiftTransferShareColumns() {
+        ensureColumn("coupon_gift_transfer", "share_token",
+                "VARCHAR(64) NULL COMMENT '分享令牌(分享转赠领取时回写 coupon_share.share_token, 定向转赠为NULL)'");
+        ensureColumn("coupon_gift_transfer", "claim_method",
+                "VARCHAR(16) NOT NULL DEFAULT 'DIRECT' COMMENT '领取方式: DIRECT=定向转赠 SHARE=分享转赠(存量行默认DIRECT)'");
+        log.info("迁移495: coupon_gift_transfer.share_token / claim_method 列已就绪");
+    }
+
+    /**
+     * 迁移496: growth_plans 增列 draft_expires_at / draft_version(SC-P-81 方案草稿保存与恢复,能力键 plan.draft.save)。
+     *
+     * <p>draft_expires_at:草稿有效期(存草稿时 now+7 天),恢复时超期判定『草稿已失效』的持久化基础(TC-P-81-E);
+     * draft_version:草稿版本号(并发存两版草稿:后者覆盖且提示冲突,TC-P-81-E)。ensureColumn 幂等。</p>
+     */
+    private void addGrowthPlanDraftColumns() {
+        ensureColumn("growth_plans", "draft_expires_at",
+                "DATETIME NULL COMMENT '草稿有效期(SC-P-81 草稿保存/恢复,plan.draft.save)'");
+        ensureColumn("growth_plans", "draft_version",
+                "INT NULL COMMENT '草稿版本号(并发存两版草稿:后者覆盖且提示冲突)'");
+        log.info("迁移496: growth_plans.draft_expires_at / draft_version 列已就绪(plan.draft.save / SC-P-81)");
+    }
 }

+ 10 - 1
cfc-backend/src/main/java/com/etotem/cfc/config/JwtInterceptor.java

@@ -87,6 +87,8 @@ private static final String[] PUBLIC_PATHS = {
          "/api/activity/detail",
          "/api/activity/order/notify",
          "/api/content-sections/visible",
+         // 会员券分享转赠:落地领取页匿名可浏览(share/detail 公开;其余 4 接口见 LOGIN_REQUIRED_PATHS)
+         "/api/coupon/gift/share/detail",
          "/api/mcp/**"
      };
 
@@ -154,7 +156,14 @@ private static final String[] PUBLIC_PATHS = {
         // 登录,无 token 直接 401,controller 层再按 @RequestAttribute("role") 守卫拒绝非 admin,
         // 构成双层防线(契约:admin.article.create / S-cfc-153、admin.article.audit / S-cfc-154)。
         // 注意 /api/admin-auth/* 不匹配此前缀(admin-auth ≠ admin/),仍走 PUBLIC_PATHS,不受影响。
-        "/api/admin/"
+        "/api/admin/",
+        // 会员券分享转赠(ARCH-CFC-COUPON-SHARE-GIFT-001 §5):create/claim/revoke/list 为写数据/
+        // 私有数据操作,匿名(userId=-1)不得放行(否则业务 500 口径漂移),无 token 直接 401;
+        // detail 已在 PUBLIC_PATHS 公开(匿名可浏览)。
+        "/api/coupon/gift/share/create",
+        "/api/coupon/gift/share/claim",
+        "/api/coupon/gift/share/revoke",
+        "/api/coupon/gift/share/list"
     };
 
     /**

+ 66 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/CouponGiftController.java

@@ -2,6 +2,7 @@ package com.etotem.cfc.controller;
 
 import com.etotem.cfc.common.Result;
 import com.etotem.cfc.service.CouponGiftService;
+import com.etotem.cfc.service.CouponShareService;
 import com.etotem.cfc.util.ParamUtils;
 import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestAttribute;
@@ -24,6 +25,9 @@ public class CouponGiftController {
     @Resource
     private CouponGiftService couponGiftService;
 
+    @Resource
+    private CouponShareService couponShareService;
+
     /** 可接收转赠的推荐下级列表(直推 + 隔级) */
     @PostMapping("/recipients")
     public Result<List<Map<String, Object>>> recipients(@RequestAttribute("userId") Long userId) {
@@ -78,4 +82,66 @@ public class CouponGiftController {
     public Result<List<Map<String, Object>>> received(@RequestAttribute("userId") Long userId) {
         return Result.success(couponGiftService.listReceived(userId));
     }
+
+    // ==================== 分享转赠(/api/coupon/gift/share/*,ARCH-CFC-COUPON-SHARE-GIFT-001 §5) ====================
+
+    /** 创建分享:生成 shareToken(幂等:同 giver+familyCouponId 已有 PENDING 返回既有 token) */
+    @PostMapping("/share/create")
+    public Result<Map<String, Object>> shareCreate(@RequestAttribute("userId") Long userId,
+                                                   @RequestBody Map<String, Object> params) {
+        Long familyCouponId = ParamUtils.getLong(params.get("familyCouponId"));
+        try {
+            return Result.success(couponShareService.create(userId, familyCouponId));
+        } catch (IllegalArgumentException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /** 分享详情(公开接口,匿名可浏览;JwtInterceptor 已放行 detail,不注入 userId) */
+    @PostMapping("/share/detail")
+    public Result<Map<String, Object>> shareDetail(@RequestBody Map<String, Object> params) {
+        String shareToken = ParamUtils.getString(params.get("shareToken"));
+        try {
+            return Result.success(couponShareService.detail(shareToken, null));
+        } catch (IllegalArgumentException e) {
+            if (CouponShareService.MSG_SHARE_NOT_FOUND.equals(e.getMessage())) {
+                return Result.notFound(e.getMessage());
+            }
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /** 领取分享:条件更新防重领,成功返回 transferId */
+    @PostMapping("/share/claim")
+    public Result<Map<String, Object>> shareClaim(@RequestAttribute("userId") Long userId,
+                                                  @RequestBody Map<String, Object> params) {
+        String shareToken = ParamUtils.getString(params.get("shareToken"));
+        try {
+            Long transferId = couponShareService.claim(userId, shareToken);
+            Map<String, Object> data = new java.util.HashMap<>();
+            data.put("transferId", transferId);
+            return Result.success(data);
+        } catch (IllegalArgumentException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /** 撤回一笔 PENDING 分享(不动券实例) */
+    @PostMapping("/share/revoke")
+    public Result<Map<String, Object>> shareRevoke(@RequestAttribute("userId") Long userId,
+                                                   @RequestBody Map<String, Object> params) {
+        String shareToken = ParamUtils.getString(params.get("shareToken"));
+        try {
+            couponShareService.revoke(userId, shareToken);
+            return Result.success(java.util.Collections.singletonMap("message", "已撤回"));
+        } catch (IllegalArgumentException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /** 我的分享记录(created_at DESC) */
+    @PostMapping("/share/list")
+    public Result<List<Map<String, Object>>> shareList(@RequestAttribute("userId") Long userId) {
+        return Result.success(couponShareService.list(userId));
+    }
 }

+ 43 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/growth/GrowthPlanController.java

@@ -238,4 +238,47 @@ public class GrowthPlanController {
 
         return Result.success(resultMap);
     }
+
+    /**
+     * 存草稿(SC-P-81 正常流:计划创建前暂存未完,能力键 plan.draft.save)。
+     * 持久化 status=draft + 有效期 draftExpiresAt(now+7 天)+ 版本号递增。
+     */
+    @Operation(summary = "保存成长方案草稿(SC-P-81 存草稿,status=draft + 有效期)")
+    @PostMapping("/draft-save")
+    public Result<GrowthPlan> saveDraft(@RequestBody GrowthPlan plan,
+                                         @RequestAttribute("userId") Long userId) {
+        if (plan.getMemberId() == null) {
+            return Result.error("请选择家庭成员");
+        }
+        plan.setTeacherId(userId);
+        try {
+            GrowthPlan saved = growthPlanService.saveDraft(plan);
+            return Result.success(saved);
+        } catch (IllegalStateException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /**
+     * 恢复草稿继续编辑(SC-P-81 正常流/异常流/权限流,能力键 plan.draft.save)。
+     * 过期 → 提示『草稿已失效』;越权(非归属)→ 403 拒绝,不泄露他人草稿。
+     */
+    @Operation(summary = "恢复成长方案草稿(SC-P-81 恢复继续编辑;过期提示草稿已失效;越权 403)")
+    @PostMapping("/draft-restore")
+    public Result<GrowthPlan> restoreDraft(@RequestBody Map<String, Object> body,
+                                            @RequestAttribute("userId") Long userId) {
+        Long draftId = ParamUtils.getLong(body.get("draftId"));
+        if (draftId == null) {
+            return Result.error("draftId不能为空");
+        }
+        try {
+            GrowthPlan restored = growthPlanService.restoreDraft(draftId, userId);
+            if (restored == null) {
+                return Result.error("草稿不存在");
+            }
+            return Result.success(restored);
+        } catch (IllegalStateException e) {
+            return Result.error(e.getMessage());
+        }
+    }
 }

+ 13 - 1
cfc-backend/src/main/java/com/etotem/cfc/controller/product/ProductReviewController.java

@@ -2,6 +2,7 @@ package com.etotem.cfc.controller.product;
 
 import com.etotem.cfc.common.Result;
 import com.etotem.cfc.dto.ProductReviewRequest;
+import com.etotem.cfc.dto.ProductReviewResponse;
 import com.etotem.cfc.service.ProductReviewService;
 import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestAttribute;
@@ -13,10 +14,13 @@ import javax.annotation.Resource;
 import java.util.Map;
 
 /**
- * 普通商品评价控制器(能力键 {@code shop.review.create} / {@code shop.review.my})。
+ * 普通商品评价控制器(能力键 {@code shop.review.create},R1;{@code shop.review.detail},R2;
+ * {@code shop.review.my},R5)。
  *
  * <p>设计 {@code docs/superpowers/specs/2026-11-14-product-order-gap-arch-design.md} §3.1:
  * R1 {@code POST /api/product/review/create}(鉴权=登录买家本人)、
+ * R2 {@code POST /api/product/review/detail}(鉴权=登录下单人/商家,出参
+ * {@code Result<ProductReviewResponse>})、
  * R5 {@code POST /api/product/review/my}(鉴权=登录买家)。
  * 对齐 {@code ProductOrderController} 同点位 {@code @RequestAttribute("userId")} 写法。</p>
  */
@@ -34,6 +38,14 @@ public class ProductReviewController {
         return Result.success(result);
     }
 
+    @PostMapping("/detail")
+    public Result<ProductReviewResponse> detail(@RequestBody Map<String, Object> params,
+                                                @RequestAttribute("userId") Long userId) {
+        Long orderId = params != null && params.get("orderId") != null
+                ? Long.valueOf(params.get("orderId").toString()) : null;
+        return Result.success(reviewService.detail(orderId, userId));
+    }
+
     @PostMapping("/my")
     public Result<Map<String, Object>> my(@RequestBody Map<String, Object> params,
                                           @RequestAttribute("userId") Long userId) {

+ 20 - 0
cfc-backend/src/main/java/com/etotem/cfc/dto/ProductReviewResponse.java

@@ -0,0 +1,20 @@
+package com.etotem.cfc.dto;
+
+import com.etotem.cfc.entity.ProductReview;
+import lombok.Data;
+
+import java.io.Serializable;
+
+/**
+ * R2 响应 DTO:商品评价详情/去评价按钮态载体(能力键 {@code shop.review.detail},任务 S-be-2)。
+ * 包含已评记录、可评态和提示文案。
+ */
+@Data
+public class ProductReviewResponse implements Serializable {
+
+    private ProductReview review;      // 已评记录,未评为 null
+
+    private Boolean canReview;         // 可评价态:completed 且 90 天窗口内且未评时 true
+
+    private String reviewHint;         // 提示文案:不可评/已评提示文案,供前端按钮态兜底
+}

+ 40 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/CfPlatformRevenueLog.java

@@ -0,0 +1,40 @@
+package com.etotem.cfc.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.Date;
+
+/**
+ * 平台抽成 R0 流水(独立入平台账,设计 §2.4)。
+ *
+ * <p>口径见 docs/superpowers/plans/2026-11-14-cf-reward-model-v2-design.md §2.4:
+ * 平台抽成 = floor(实付 × TAKE_BPS / 10000)(TAKE_BPS=1000 → 10%),
+ * 唯一键 {@code uk_order(order_type, order_id)} 幂等;实付为 null 时回退 orderAmountCent。</p>
+ */
+@Data
+@TableName("cf_platform_revenue_log")
+public class CfPlatformRevenueLog implements Serializable {
+
+    @TableId(type = IdType.AUTO)
+    private Long id;
+
+    /** 订单ID */
+    private Long orderId;
+
+    /** 订单类型(product/package/assessment/membership/subscription) */
+    private String orderType;
+
+    /** 平台抽成金额(分)= 实付 × TAKE_BPS / 10000 */
+    private Integer amountCent;
+
+    /** 实际采用的抽成费率(bps) */
+    private Integer takeBps;
+
+    private String remark;
+
+    private Date createdAt;
+}

+ 6 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/CouponGiftTransfer.java

@@ -47,6 +47,12 @@ public class CouponGiftTransfer implements Serializable {
     /** GIFTED=已赠送(可撤回) / USED=已被接收方使用 / REVOKED=已撤回 */
     private String status;
 
+    /** 分享令牌:分享转赠(claimMethod=SHARE)领取时回写的 coupon_share.share_token;定向转赠为 NULL */
+    private String shareToken;
+
+    /** 领取方式:DIRECT=定向转赠 / SHARE=分享转赠(存量行默认 DIRECT,兼容历史数据) */
+    private String claimMethod;
+
     /** 赠送留言 */
     private String remark;
 

+ 67 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/CouponShare.java

@@ -0,0 +1,67 @@
+package com.etotem.cfc.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.Date;
+
+/**
+ * 会员券「分享转赠」记录(分享生命周期表)。
+ *
+ * <p>承载分享链路的完整状态机:{@code PENDING(待领取) → CLAIMED(已领取,终态) /
+ * REVOKED(已撤回) / EXPIRED(已过期,懒判定不跑定时任务)}。分享采用「两段式」:
+ * 先异步 {@code POST /api/coupon/gift/share/create} 生成全局唯一 {@code shareToken},
+ * 再同步 {@code onShareAppMessage} 携带 token 转发;接收人打开落地页后凭 token
+ * 浏览/领取。领取时 {@code shareToken} 会回写到 {@code coupon_gift_transfer.share_token},
+ * 与定向转赠(DIRECT)在 {@code coupon_gift_transfer.claim_method} 上区分。</p>
+ *
+ * <p>幂等与并发:同一 {@code giverUserId + familyCouponId} 已存在 PENDING 分享时,
+ * create 直接返回既有 token(不新建);claim 用「条件更新影响 1 行」原子防重领;
+ * {@code shareToken} 有全局唯一索引 {@code uk_share_token} 防碰撞。</p>
+ */
+@Data
+@TableName("coupon_share")
+public class CouponShare implements Serializable {
+
+    @TableId(type = IdType.AUTO)
+    private Long id;
+
+    /** 全局唯一分享令牌(path/query 传递,生成规则 CS + 时间戳/随机串,长度 ≤64) */
+    private String shareToken;
+
+    /** 赠送人用户ID (users.id) */
+    private Long giverUserId;
+
+    /** 赠送人家庭ID */
+    private Long giverFamilyId;
+
+    /** 被分享的 family_coupon 实例ID */
+    private Long familyCouponId;
+
+    /** 券模板ID (coupon.id) */
+    private Long couponId;
+
+    /** PENDING=待领取 / CLAIMED=已领取(终态) / REVOKED=已撤回 / EXPIRED=已过期(懒判定) */
+    private String status;
+
+    /** 领取人用户ID (users.id),领取前为 NULL */
+    private Long claimUserId;
+
+    /** 领取人家庭ID,领取前为 NULL */
+    private Long claimFamilyId;
+
+    /** 领取时间,领取前为 NULL */
+    private Date claimTime;
+
+    /** 分享有效期截止(创建时 now + 配置天数,默认 7) */
+    private Date expireAt;
+
+    /** 创建时间 */
+    private Date createdAt;
+
+    /** 更新时间 */
+    private Date updatedAt;
+}

+ 4 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/GrowthPlan.java

@@ -42,6 +42,10 @@ public class GrowthPlan implements Serializable {
 
     private Integer reviewCount;  // 已复盘次数
 
+    private Date draftExpiresAt;  // 草稿有效期(SC-P-81 草稿保存/恢复,能力键 plan.draft.save;超期判定『草稿已失效』)
+
+    private Integer draftVersion;  // 草稿版本号(并发存两版草稿:后者覆盖且提示冲突)
+
     private Date createdAt;
 
     private Date updatedAt;

+ 14 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/CfPlatformRevenueLogMapper.java

@@ -0,0 +1,14 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.CfPlatformRevenueLog;
+import org.apache.ibatis.annotations.Mapper;
+
+/**
+ * 平台抽成 R0 流水 Mapper(唯一键 uk_order(order_type, order_id) 幂等)。
+ *
+ * @see com.etotem.cfc.entity.CfPlatformRevenueLog
+ */
+@Mapper
+public interface CfPlatformRevenueLogMapper extends BaseMapper<CfPlatformRevenueLog> {
+}

+ 16 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/CouponShareMapper.java

@@ -0,0 +1,16 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.CouponShare;
+import org.apache.ibatis.annotations.Mapper;
+
+/**
+ * 会员券分享转赠记录 Mapper。
+ *
+ * <p>继承 {@link BaseMapper},提供常规 CRUD;claim 并发防重领走
+ * MyBatis-Plus {@code LambdaUpdateWrapper} 条件更新 + 影响行数判定,
+ * 无需自定义 XML。</p>
+ */
+@Mapper
+public interface CouponShareMapper extends BaseMapper<CouponShare> {
+}

+ 78 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/CfCommissionService.java

@@ -7,6 +7,7 @@ import com.etotem.cfc.dto.CfEarnResult;
 import com.etotem.cfc.entity.CfDirectSalesTier;
 import com.etotem.cfc.entity.CfEarnRule;
 import com.etotem.cfc.entity.CfIndirectSalesTier;
+import com.etotem.cfc.entity.CfPlatformRevenueLog;
 import com.etotem.cfc.entity.FamilyMember;
 import com.etotem.cfc.entity.OctopusEffectKeyPerson;
 import com.etotem.cfc.entity.OctopusEffectRecord;
@@ -19,6 +20,7 @@ import com.etotem.cfc.entity.ProductGiftRule;
 import com.etotem.cfc.entity.ProductOrder;
 import com.etotem.cfc.entity.ReferralTree;
 import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.CfPlatformRevenueLogMapper;
 import com.etotem.cfc.mapper.FamilyMemberMapper;
 import com.etotem.cfc.mapper.MembershipLevelMapper;
 import com.etotem.cfc.mapper.ProductGiftRuleMapper;
@@ -87,6 +89,9 @@ public class CfCommissionService {
     /** 销售奖发放的参与层级数量(直接奖 L1 + 间接奖 L2) */
     private static final int SALES_AWARD_LEVELS = 2;
 
+    /** R0 平台抽成默认费率(bps,1000 = 10%,设计 §1.1) */
+    public static final int TAKE_BPS = 1000;
+
     @Resource
     private ReferralTreeMapper referralTreeMapper;
     @Resource
@@ -125,6 +130,8 @@ public class CfCommissionService {
     private ConfigService configService;
     @Resource
     private ObjectMapper objectMapper;
+    @Resource
+    private CfPlatformRevenueLogMapper cfPlatformRevenueLogMapper;
 
     /**
      * 通用分佣(双返):当前人 + 推荐人。
@@ -189,6 +196,77 @@ public class CfCommissionService {
         }
     }
 
+    /**
+     * R0 平台抽成记账(设计 §3.1 / §6-T03,新增)。
+     *
+     * <p>按 {@code floor(实付 × TAKE_BPS / 10000)} 写入 {@code cf_platform_revenue_log},
+     * 唯一键 {@code uk_order(order_type, order_id)} 幂等;实付为 null 时回退 orderAmountCent。
+     * 费率优先读 {@code cf.platform.take_rate_bps} 配置({@link CfConfigKeys#PLATFORM_TAKE_RATE_BPS}),
+     * 配置缺失时用常量 {@link #TAKE_BPS} 兜底。</p>
+     *
+     * @param orderId        订单ID
+     * @param orderType      订单类型
+     * @param paidAmountCent 实付金额(分),null 时回退 orderAmountCent
+     * @param orderAmountCent 订单金额(分),实付为 null 时的回退值
+     * @return 实际抽成金额(分);入参全 null 或 ≤0 时返回 0
+     */
+    public int settlePlatformTake(Long orderId, String orderType,
+                                  Integer paidAmountCent, Integer orderAmountCent) {
+        int amount = paidAmountCent != null ? paidAmountCent
+                : (orderAmountCent != null ? orderAmountCent : 0);
+        if (amount <= 0) return 0;
+
+        int takeBps;
+        try {
+            takeBps = configService.getIntConfig(CfConfigKeys.PLATFORM_TAKE_RATE_BPS, TAKE_BPS);
+        } catch (Exception e) {
+            takeBps = TAKE_BPS;
+        }
+        int r0 = amount * takeBps / 10000;
+
+        CfPlatformRevenueLog entity = new CfPlatformRevenueLog();
+        entity.setOrderId(orderId);
+        entity.setOrderType(orderType);
+        entity.setAmountCent(r0);
+        entity.setTakeBps(takeBps);
+        entity.setRemark("R0平台抽成:" + orderType);
+        entity.setCreatedAt(new Date());
+        try {
+            cfPlatformRevenueLogMapper.insert(entity);
+            log.info("R0平台抽成记账: orderType={}, orderId={}, amount={}, takeBps={}, r0={}",
+                    orderType, orderId, amount, takeBps, r0);
+        } catch (DuplicateKeyException e) {
+            log.info("R0平台抽成已存在,跳过重复写入: orderType={}, orderId={}", orderType, orderId);
+        } catch (Exception e) {
+            log.warn("R0平台抽成写入失败: orderType={}, orderId={}, err={}", orderType, orderId, e.getMessage());
+        }
+        return r0;
+    }
+
+    /**
+     * 可分配额 base 计算(设计 §3.1 / §6-T03,T03 交付)。
+     *
+     * <p>{@code base = A − R0 − R1_等值 − costCent},其中:</p>
+     * <ul>
+     *   <li>{@code R0 = floor(A × TAKE_BPS / 10000)}(平台抽成,先扣);</li>
+     *   <li>{@code R1_等值 = floor(A / 100)}(消费返 CF 等值成本,1 分 = 1 CF 参照,先扣);</li>
+     *   <li>{@code base < 0} 时返回 0(不得为负,设计 §1.1 / §1.4)。</li>
+     * </ul>
+     *
+     * <p>账目示例(设计 §1.1 / §8 #1):A=20000 分(200 元),costCent=10000 分(100 元)→
+     * R0=2000、R1_等值=200、base=7800(78 元)≠ 原始毛利 10000(100 元)。</p>
+     *
+     * @param amountCent 实付金额(分)
+     * @param costCent   商品成本(分)
+     * @return 可分配额 base(分),亏损仓(base &lt; 0)返回 0
+     */
+    public int calcDistributableBase(int amountCent, int costCent) {
+        int r0 = amountCent * TAKE_BPS / 10000;
+        int r1Equiv = amountCent / 100;
+        int base = amountCent - r0 - r1Equiv - costCent;
+        return base > 0 ? base : 0;
+    }
+
     /**
      * 推荐人分润:两级销售奖(F03a 直接销售奖 + F03b 间接销售奖)。
      *

+ 54 - 7
cfc-backend/src/main/java/com/etotem/cfc/service/CouponGiftService.java

@@ -251,20 +251,67 @@ public class CouponGiftService {
             throw new IllegalArgumentException("只能转赠给自己的直推或隔级推荐人");
         }
 
+        // 券实例转移 + transfer 记录 + 通知 + 审计:统一下沉到 commitTransfer(分享转赠复用,行为不变)
+        return commitTransfer(giverUserId, giverFamilyId, receiverUserId, receiver.getFamilyId(),
+                coupon.getId(), fc.getId(), referral.getLevel(), "DIRECT", null, remark);
+    }
+
+    /**
+     * 提交券实例转移 + transfer 记录 + 通知 + 审计流水(定向转赠与分享转赠共有的尾段)。
+     *
+     * <p>调用方必须在事务中({@code @Transactional} 传播 REQUIRED 合并):定向转赠
+     * {@link #transfer} 与分享转赠 {@code CouponShareService.claim} 均在本方法内完成
+     * 「券实例归属转移(family_coupon.family_id + is_gift=1)→ coupon_gift_transfer 记录 →
+     * 通知(模板 coupon_gift)→ grant log(GIFT_TRANSFER, source=transfer:id)」,任一失败整体回滚。</p>
+     *
+     * @param giverUserId     赠送人 users.id
+     * @param giverFamilyId   赠送人家庭
+     * @param receiverUserId  接收人 users.id(券最终归属人)
+     * @param receiverFamilyId 接收人家庭(券实例最终归属)
+     * @param couponId        券模板 id
+     * @param familyCouponId  family_coupon 实例 id
+     * @param giftLevel       推荐层级(定向:1=直推/2=隔级;分享:0=无推荐层级,见 SHARE_GIFT_LEVEL)
+     * @param claimMethod     领取方式:"DIRECT"=定向转赠 / "SHARE"=分享转赠(null 兜底 DIRECT)
+     * @param shareToken      分享领取时回写 coupon_gift_transfer.share_token(定向为 null)
+     * @param remark          留言(可空)
+     * @return transferId
+     */
+    @Transactional
+    public Long commitTransfer(Long giverUserId, Long giverFamilyId,
+                               Long receiverUserId, Long receiverFamilyId,
+                               Long couponId, Long familyCouponId,
+                               Integer giftLevel, String claimMethod,
+                               String shareToken, String remark) {
+        if (giverUserId == null || receiverUserId == null || familyCouponId == null
+                || couponId == null || receiverFamilyId == null) {
+            throw new IllegalArgumentException("参数不完整");
+        }
+        Coupon coupon = couponMapper.selectById(couponId);
+        if (coupon == null) {
+            throw new IllegalArgumentException("优惠券已失效");
+        }
+
         // 转移券实例到接收方家庭,并打 is_gift 标记(接收方非会员也可用其购买会员)
-        fc.setFamilyId(receiver.getFamilyId());
+        FamilyCoupon fc = familyCouponMapper.selectById(familyCouponId);
+        if (fc == null) {
+            throw new IllegalArgumentException("该优惠券不可用或不属于你");
+        }
+        fc.setFamilyId(receiverFamilyId);
         fc.setIsGift(1);
         familyCouponMapper.updateById(fc);
 
+        Date now = new Date();
         CouponGiftTransfer transfer = new CouponGiftTransfer();
         transfer.setGiverUserId(giverUserId);
         transfer.setGiverFamilyId(giverFamilyId);
         transfer.setReceiverUserId(receiverUserId);
-        transfer.setReceiverFamilyId(receiver.getFamilyId());
+        transfer.setReceiverFamilyId(receiverFamilyId);
         transfer.setCouponId(coupon.getId());
         transfer.setFamilyCouponId(fc.getId());
-        transfer.setGiftLevel(referral.getLevel());
+        transfer.setGiftLevel(giftLevel);
         transfer.setStatus("GIFTED");
+        transfer.setClaimMethod(claimMethod != null ? claimMethod : "DIRECT");
+        transfer.setShareToken(shareToken);
         transfer.setRemark(remark);
         transfer.setCreatedAt(now);
         couponGiftTransferMapper.insert(transfer);
@@ -289,9 +336,9 @@ public class CouponGiftService {
                     transfer.getId(), e.getMessage());
         }
 
-        // 发放流水(审计)
+        // 发放流水(审计)——分享与定向统一 GIFT_TRANSFER,source 均记 transferId(对账口径一致)
         FamilyCouponGrantLog log = new FamilyCouponGrantLog();
-        log.setFamilyId(receiver.getFamilyId());
+        log.setFamilyId(receiverFamilyId);
         log.setCouponId(coupon.getId());
         log.setGrantType("GIFT_TRANSFER");
         log.setPeriod(null);
@@ -300,8 +347,8 @@ public class CouponGiftService {
         log.setCreatedAt(now);
         familyCouponGrantLogMapper.insert(log);
 
-        logger.info("会员券转赠成功: giver={}, receiver={}, familyCouponId={}, level={}, transferId={}",
-                giverUserId, receiverUserId, familyCouponId, referral.getLevel(), transfer.getId());
+        logger.info("会员券转赠提交: giver={}, receiver={}, familyCouponId={}, level={}, method={}, transferId={}",
+                giverUserId, receiverUserId, familyCouponId, giftLevel, transfer.getClaimMethod(), transfer.getId());
         return transfer.getId();
     }
 

+ 448 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/CouponShareService.java

@@ -0,0 +1,448 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
+import com.etotem.cfc.entity.Coupon;
+import com.etotem.cfc.entity.CouponShare;
+import com.etotem.cfc.entity.FamilyCoupon;
+import com.etotem.cfc.entity.FamilyCouponGrantLog;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.CouponMapper;
+import com.etotem.cfc.mapper.CouponShareMapper;
+import com.etotem.cfc.mapper.FamilyCouponGrantLogMapper;
+import com.etotem.cfc.mapper.FamilyCouponMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.util.StringUtils;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.UUID;
+
+/**
+ * 会员券「分享转赠」服务(ARCH-CFC-COUPON-SHARE-GIFT-001 §6.2 + §5)。
+ *
+ * <p>在既有「定向转赠」({@link CouponGiftService})之上新增分享通道:
+ * <ul>
+ *   <li><b>create</b>:生成全局唯一 {@code shareToken}(两段式分享第一步),幂等——同
+ *       {@code giverUserId + familyCouponId} 已有 PENDING 分享直接返回既有 token,不新建;
+ *       事务内 {@code SELECT ... FOR UPDATE} 锁行防并发双 PENDING。</li>
+ *   <li><b>detail</b>:公开接口(JwtInterceptor 已放行),匿名可浏览,懒判定 EXPIRED。</li>
+ *   <li><b>claim</b>:单事务,核心「条件更新 PENDING→CLAIMED 影响 1 行」原子防重领,
+ *       成功后复用 {@link CouponGiftService#commitTransfer} 完成券实例转移 + transfer 记录 +
+ *       通知 + 审计流水(claimMethod=SHARE、shareToken 回写、giftLevel=0)。</li>
+ *   <li><b>revoke</b>:PENDING→REVOKED(券实例仍在赠送人名下,不动券);CLAIMED 终态不可撤回。</li>
+ *   <li><b>list</b>:我的分享记录,created_at DESC。</li>
+ * </ul></p>
+ *
+ * <p>错误文案统一使用本类 {@code MSG_*} 常量(§11 约定:集中定义,Controller 与测试复用)。</p>
+ */
+@Service
+public class CouponShareService {
+
+    private static final Logger logger = LoggerFactory.getLogger(CouponShareService.class);
+
+    // ---------------- 错误文案常量(§11:集中定义,Controller/测试复用) ----------------
+    public static final String MSG_PARAM_INCOMPLETE = "参数不完整";
+    public static final String MSG_NO_FAMILY = "请先加入家庭";
+    public static final String MSG_COUPON_UNAVAILABLE = "该优惠券不可用或不属于你";
+    public static final String MSG_COUPON_INVALID = "优惠券已失效";
+    public static final String MSG_COUPON_EXPIRED = "优惠券已过期";
+    public static final String MSG_ONLY_MEMBERSHIP = "仅会员专属券可分享";
+    public static final String MSG_SHARE_NOT_FOUND = "分享不存在或已失效";
+    public static final String MSG_SHARE_NOT_EXIST = "分享不存在";
+    public static final String MSG_ALREADY_CLAIMED = "该分享已被领取";
+    public static final String MSG_ALREADY_REVOKED = "该分享已撤回";
+    public static final String MSG_SHARE_EXPIRED = "该分享已过期";
+    public static final String MSG_SELF_CLAIM = "不能领取自己分享的券";
+    public static final String MSG_SAME_FAMILY = "不能领取同家庭成员的券";
+    public static final String MSG_CLAIM_FAILED = "领取失败,请联系客服";
+    public static final String MSG_NO_PERMISSION = "无权操作该分享";
+    public static final String MSG_CLAIMED_CANNOT_REVOKE = "该分享已被领取,无法撤回";
+
+    /** 分享链路无推荐层级:coupon_gift_transfer.gift_level 写 0(§4.2) */
+    public static final int SHARE_GIFT_LEVEL = 0;
+
+    /** 分享有效期天数,可配置 coupon.share.expire-days(本期落常量 + application.yml/db config 占位) */
+    public static final int DEFAULT_EXPIRE_DAYS = 7;
+
+    private static final long DAY_MILLIS = 24L * 3600 * 1000;
+
+    private static final String STATUS_PENDING = "PENDING";
+    private static final String STATUS_CLAIMED = "CLAIMED";
+    private static final String STATUS_REVOKED = "REVOKED";
+    private static final String STATUS_EXPIRED = "EXPIRED";
+    private static final String CLAIM_METHOD_SHARE = "SHARE";
+    private static final String GIFTABLE_APPLICABLE_TO = "MEMBERSHIP";
+    private static final String AVAILABLE = "AVAILABLE";
+    private static final String ACTIVE = "ACTIVE";
+    private static final String SHARE_PATH_PREFIX = "/pages/coupon/share-claim?shareToken=";
+
+    @Resource
+    private CouponShareMapper couponShareMapper;
+    @Resource
+    private FamilyCouponMapper familyCouponMapper;
+    @Resource
+    private CouponMapper couponMapper;
+    @Resource
+    private UserMapper userMapper;
+    @Resource
+    private CouponGiftService couponGiftService;   // 复用 commitTransfer(定向转赠尾段)
+    @Resource
+    private NotificationDispatchService notificationDispatchService;
+    @Resource
+    private FamilyCouponGrantLogMapper familyCouponGrantLogMapper;
+
+    // ----------------------------------------------------------------
+    // create(幂等 + 防并发双 PENDING)
+    // ----------------------------------------------------------------
+
+    /**
+     * 创建一笔分享,返回 {@code {shareToken, sharePath, expireAt}}。
+     *
+     * <p>幂等:同一 {@code giverUserId + familyCouponId} 已存在 PENDING 分享时直接返回既有
+     * token(不新建、不报错,§2.4)。并发双 PENDING 靠事务内 {@code SELECT ... FOR UPDATE}
+     * 锁行 serialize;token 另有 {@code uk_share_token} 全局唯一索引兜底。</p>
+     *
+     * @param giverUserId    赠送人 users.id(已登录)
+     * @param familyCouponId 被分享的 family_coupon 实例 ID
+     * @return {shareToken, sharePath, expireAt}
+     */
+    @Transactional
+    public Map<String, Object> create(Long giverUserId, Long familyCouponId) {
+        if (giverUserId == null || familyCouponId == null) {
+            throw new IllegalArgumentException(MSG_PARAM_INCOMPLETE);
+        }
+        Long giverFamilyId = getFamilyId(giverUserId);
+        if (giverFamilyId == null) {
+            throw new IllegalArgumentException(MSG_NO_FAMILY);
+        }
+        Date now = new Date();
+
+        // 幂等查询(锁行防并发双 PENDING):同 giver+familyCouponId 已有 PENDING → 复用既有分享
+        CouponShare existing = couponShareMapper.selectOne(
+                new LambdaQueryWrapper<CouponShare>()
+                        .eq(CouponShare::getGiverUserId, giverUserId)
+                        .eq(CouponShare::getFamilyCouponId, familyCouponId)
+                        .eq(CouponShare::getStatus, STATUS_PENDING)
+                        .last("LIMIT 1 FOR UPDATE"));
+        if (existing != null) {
+            logger.info("会员券分享创建幂等命中: giver={}, familyCouponId={}, token={}",
+                    giverUserId, familyCouponId, existing.getShareToken());
+            return buildCreateResult(existing);
+        }
+
+        // 券校验(属于赠送人家庭 && AVAILABLE && applicableTo=MEMBERSHIP && ACTIVE && 未过期)
+        FamilyCoupon fc = familyCouponMapper.selectById(familyCouponId);
+        if (fc == null || !Objects.equals(fc.getFamilyId(), giverFamilyId)
+                || !AVAILABLE.equals(fc.getStatus())) {
+            throw new IllegalArgumentException(MSG_COUPON_UNAVAILABLE);
+        }
+        Coupon coupon = couponMapper.selectById(fc.getCouponId());
+        if (coupon == null || !ACTIVE.equals(coupon.getStatus())) {
+            throw new IllegalArgumentException(MSG_COUPON_INVALID);
+        }
+        if (!GIFTABLE_APPLICABLE_TO.equals(coupon.getApplicableTo())) {
+            throw new IllegalArgumentException(MSG_ONLY_MEMBERSHIP);
+        }
+        if (coupon.getValidFrom() != null && now.before(coupon.getValidFrom())
+                || coupon.getValidUntil() != null && now.after(coupon.getValidUntil())) {
+            throw new IllegalArgumentException(MSG_COUPON_EXPIRED);
+        }
+
+        CouponShare share = new CouponShare();
+        share.setShareToken(generateShareToken());
+        share.setGiverUserId(giverUserId);
+        share.setGiverFamilyId(giverFamilyId);
+        share.setFamilyCouponId(familyCouponId);
+        share.setCouponId(coupon.getId());
+        share.setStatus(STATUS_PENDING);
+        share.setExpireAt(new Date(now.getTime() + DEFAULT_EXPIRE_DAYS * DAY_MILLIS));
+        share.setCreatedAt(now);
+        couponShareMapper.insert(share);
+
+        logger.info("会员券分享创建成功: giver={}, familyCouponId={}, token={}, expireAt={}",
+                giverUserId, familyCouponId, share.getShareToken(), share.getExpireAt());
+        return buildCreateResult(share);
+    }
+
+    // ----------------------------------------------------------------
+    // detail(公开——匿名可浏览,懒判定 EXPIRED)
+    // ----------------------------------------------------------------
+
+    /**
+     * 分享详情(ShareDetailVO,公开接口,匿名可调)。
+     *
+     * @param shareToken    分享令牌
+     * @param viewerUserId  浏览用户(可空;本期仅返回 claimable,不区分 viewerCanClaim)
+     * @return {shareToken, status, couponName, couponValue, couponType, minSpend,
+     *          validUntil, giverNickname, giverAvatar, expireAt, claimable}
+     */
+    public Map<String, Object> detail(String shareToken, Long viewerUserId) {
+        if (!StringUtils.hasText(shareToken)) {
+            throw new IllegalArgumentException(MSG_PARAM_INCOMPLETE);
+        }
+        CouponShare share = findShare(shareToken);
+        if (share == null) {
+            throw new IllegalArgumentException(MSG_SHARE_NOT_FOUND);
+        }
+        Date now = new Date();
+        Coupon coupon = couponMapper.selectById(share.getCouponId());
+        User giver = userMapper.selectById(share.getGiverUserId());
+
+        boolean couponActive = coupon != null
+                && ACTIVE.equals(coupon.getStatus())
+                && (coupon.getValidFrom() == null || !now.before(coupon.getValidFrom()))
+                && (coupon.getValidUntil() == null || !now.after(coupon.getValidUntil()));
+        boolean claimable = STATUS_PENDING.equals(share.getStatus())
+                && share.getExpireAt() != null && !now.after(share.getExpireAt())
+                && couponActive;
+
+        Map<String, Object> data = new HashMap<>();
+        data.put("shareToken", share.getShareToken());
+        data.put("status", resolveDisplayStatus(share, now));
+        data.put("couponName", coupon != null ? coupon.getName() : "优惠券");
+        data.put("couponValue", coupon != null ? coupon.getValue() : null);
+        data.put("couponType", coupon != null ? coupon.getType() : null);
+        data.put("minSpend", coupon != null ? coupon.getMinSpend() : null);
+        data.put("validUntil", coupon != null ? coupon.getValidUntil() : null);
+        data.put("giverNickname", giver != null && StringUtils.hasText(giver.getNickname())
+                ? giver.getNickname() : "微信用户");
+        data.put("giverAvatar", giver != null ? giver.getAvatar() : null);
+        data.put("expireAt", share.getExpireAt());
+        data.put("claimable", claimable);
+        return data;
+    }
+
+    // ----------------------------------------------------------------
+    // claim(并发防重领 = 核心,单事务)
+    // ----------------------------------------------------------------
+
+    /**
+     * 领取一笔分享,返回 transferId。
+     *
+     * <p>单事务(§5.3):① 校验(分享存在/非本人/非同家庭/状态/券可用)→
+     * ② 条件更新 PENDING→CLAIMED(影响 1 行才继续,原子防重领)→
+     * ③ 复用 {@link CouponGiftService#commitTransfer} 完成券实例转移 + transfer 记录 +
+     *    通知接收人 + 审计流水(claimMethod=SHARE、shareToken 回写、giftLevel=0)→
+     * ④ 通知赠送人 → ⑤ 分享链路审计流水(source=share:id)。②~⑤ 任一失败整体回滚。</p>
+     */
+    @Transactional
+    public Long claim(Long claimUserId, String shareToken) {
+        if (claimUserId == null || !StringUtils.hasText(shareToken)) {
+            throw new IllegalArgumentException(MSG_PARAM_INCOMPLETE);
+        }
+        CouponShare share = findShare(shareToken);
+        if (share == null) {
+            throw new IllegalArgumentException(MSG_SHARE_NOT_FOUND);
+        }
+        if (Objects.equals(share.getGiverUserId(), claimUserId)) {
+            throw new IllegalArgumentException(MSG_SELF_CLAIM);
+        }
+        User claimUser = userMapper.selectById(claimUserId);
+        if (claimUser == null || claimUser.getFamilyId() == null) {
+            throw new IllegalArgumentException(MSG_CLAIM_FAILED);
+        }
+        Long claimFamilyId = claimUser.getFamilyId();
+        if (Objects.equals(claimFamilyId, share.getGiverFamilyId())) {
+            throw new IllegalArgumentException(MSG_SAME_FAMILY);
+        }
+
+        Date now = new Date();
+        if (STATUS_REVOKED.equals(share.getStatus())) {
+            throw new IllegalArgumentException(MSG_ALREADY_REVOKED);
+        }
+        if (STATUS_CLAIMED.equals(share.getStatus())) {
+            throw new IllegalArgumentException(MSG_ALREADY_CLAIMED);
+        }
+        if (STATUS_EXPIRED.equals(share.getStatus())
+                || (share.getExpireAt() != null && now.after(share.getExpireAt()))) {
+            throw new IllegalArgumentException(MSG_SHARE_EXPIRED);
+        }
+        Coupon coupon = couponMapper.selectById(share.getCouponId());
+        if (coupon == null || !ACTIVE.equals(coupon.getStatus())) {
+            throw new IllegalArgumentException(MSG_COUPON_INVALID);
+        }
+        if (coupon.getValidFrom() != null && now.before(coupon.getValidFrom())
+                || coupon.getValidUntil() != null && now.after(coupon.getValidUntil())) {
+            throw new IllegalArgumentException(MSG_COUPON_EXPIRED);
+        }
+        // 券实例仍应在赠送人名下且可用(与 transfer 前置校验同口径)
+        FamilyCoupon fc = familyCouponMapper.selectById(share.getFamilyCouponId());
+        if (fc == null || !Objects.equals(fc.getFamilyId(), share.getGiverFamilyId())
+                || !AVAILABLE.equals(fc.getStatus())) {
+            throw new IllegalArgumentException(MSG_COUPON_INVALID);
+        }
+
+        // ② 条件更新 PENDING→CLAIMED:影响行数=1 才继续(并发第二个请求 / 已被领走 / 已撤回均 0 行)
+        int updated = couponShareMapper.update(null, new LambdaUpdateWrapper<CouponShare>()
+                .eq(CouponShare::getShareToken, shareToken)
+                .eq(CouponShare::getStatus, STATUS_PENDING)
+                .set(CouponShare::getStatus, STATUS_CLAIMED)
+                .set(CouponShare::getClaimUserId, claimUserId)
+                .set(CouponShare::getClaimFamilyId, claimFamilyId)
+                .set(CouponShare::getClaimTime, now));
+        if (updated != 1) {
+            throw new IllegalArgumentException(MSG_ALREADY_CLAIMED);
+        }
+
+        // ③+(commitTransfer 内部):券实例转移 + transfer 记录 + 通知接收人 + 审计流水
+        Long transferId = couponGiftService.commitTransfer(
+                share.getGiverUserId(), share.getGiverFamilyId(),
+                claimUserId, claimFamilyId,
+                share.getCouponId(), share.getFamilyCouponId(),
+                SHARE_GIFT_LEVEL, CLAIM_METHOD_SHARE, shareToken, null);
+
+        // ④ 通知赠送人(失败不影响领取主流程)
+        try {
+            String claimNickname = StringUtils.hasText(claimUser.getNickname())
+                    ? claimUser.getNickname() : "微信用户";
+            Map<String, Object> vars = NotificationDispatchService.vars("claimNickname", claimNickname);
+            vars.put("couponName", coupon.getName());
+            notificationDispatchService.sendByTemplate(
+                    "coupon_gift",
+                    share.getGiverUserId(),
+                    vars,
+                    "coupon_gift",
+                    share.getId(),
+                    "你的分享券已被领取",
+                    "{claimNickname} 领取了你分享的「{couponName}」会员券。");
+        } catch (Exception e) {
+            logger.warn("分享领取通知发送失败(不影响领取): shareId={}, error={}", share.getId(), e.getMessage());
+        }
+
+        // ⑤ 分享链路审计流水(source=share:id,与定向 transfer:id 并行可对账,均 GIFT_TRANSFER)
+        FamilyCouponGrantLog log = new FamilyCouponGrantLog();
+        log.setFamilyId(claimFamilyId);
+        log.setCouponId(share.getCouponId());
+        log.setGrantType("GIFT_TRANSFER");
+        log.setPeriod(null);
+        log.setQuantity(1);
+        log.setSource("share:" + share.getId());
+        log.setCreatedAt(now);
+        familyCouponGrantLogMapper.insert(log);
+
+        logger.info("会员券分享领取成功: shareId={}, token={}, claimUser={}, transferId={}",
+                share.getId(), shareToken, claimUserId, transferId);
+        return transferId;
+    }
+
+    // ----------------------------------------------------------------
+    // revoke(PENDING 阶段可撤回,不动券实例)
+    // ----------------------------------------------------------------
+
+    /**
+     * 撤回一笔分享(仅 PENDING 可撤回;CLAIMED 终态不可撤回)。
+     * PENDING 阶段券仍在赠送人名下,仅置 status=REVOKED,不动券实例。
+     */
+    public void revoke(Long giverUserId, String shareToken) {
+        if (giverUserId == null || !StringUtils.hasText(shareToken)) {
+            throw new IllegalArgumentException(MSG_PARAM_INCOMPLETE);
+        }
+        CouponShare share = findShare(shareToken);
+        if (share == null) {
+            throw new IllegalArgumentException(MSG_SHARE_NOT_EXIST);
+        }
+        if (!Objects.equals(share.getGiverUserId(), giverUserId)) {
+            throw new IllegalArgumentException(MSG_NO_PERMISSION);
+        }
+        if (STATUS_CLAIMED.equals(share.getStatus())) {
+            throw new IllegalArgumentException(MSG_CLAIMED_CANNOT_REVOKE);
+        }
+        if (STATUS_REVOKED.equals(share.getStatus())) {
+            throw new IllegalArgumentException(MSG_ALREADY_REVOKED);
+        }
+        // PENDING(含已过期未领)→ REVOKED;条件更新兜底并发领取竞态(0 行=已被领走/状态已变)
+        CouponShare update = new CouponShare();
+        update.setStatus(STATUS_REVOKED);
+        int updated = couponShareMapper.update(update, new LambdaUpdateWrapper<CouponShare>()
+                .eq(CouponShare::getShareToken, shareToken)
+                .eq(CouponShare::getStatus, STATUS_PENDING));
+        if (updated != 1) {
+            throw new IllegalArgumentException(MSG_ALREADY_REVOKED);
+        }
+        logger.info("会员券分享撤回成功: token={}, giver={}", shareToken, giverUserId);
+    }
+
+    // ----------------------------------------------------------------
+    // list(我的分享记录,created_at DESC)
+    // ----------------------------------------------------------------
+
+    /**
+     * 我的分享记录列表(created_at DESC)。
+     *
+     * @return [{shareToken, couponName, couponValue, status, expireAt, claimTime, createdAt, claimNickname}]
+     */
+    public List<Map<String, Object>> list(Long giverUserId) {
+        if (giverUserId == null) return new ArrayList<>();
+        List<CouponShare> shares = couponShareMapper.selectList(
+                new LambdaQueryWrapper<CouponShare>()
+                        .eq(CouponShare::getGiverUserId, giverUserId)
+                        .orderByDesc(CouponShare::getCreatedAt));
+        if (shares.isEmpty()) return new ArrayList<>();
+        Date now = new Date();
+        List<Map<String, Object>> result = new ArrayList<>();
+        for (CouponShare s : shares) {
+            Coupon coupon = couponMapper.selectById(s.getCouponId());
+            User claimUser = s.getClaimUserId() != null ? userMapper.selectById(s.getClaimUserId()) : null;
+            Map<String, Object> m = new HashMap<>();
+            m.put("shareToken", s.getShareToken());
+            m.put("couponName", coupon != null ? coupon.getName() : "优惠券");
+            m.put("couponValue", coupon != null ? coupon.getValue() : null);
+            m.put("status", resolveDisplayStatus(s, now));
+            m.put("expireAt", s.getExpireAt());
+            m.put("claimTime", s.getClaimTime());
+            m.put("createdAt", s.getCreatedAt());
+            m.put("claimNickname", claimUser != null && StringUtils.hasText(claimUser.getNickname())
+                    ? claimUser.getNickname() : null);
+            result.add(m);
+        }
+        return result;
+    }
+
+    // ----------------------------------------------------------------
+    // 内部辅助
+    // ----------------------------------------------------------------
+
+    private Long getFamilyId(Long userId) {
+        User user = userMapper.selectById(userId);
+        if (user == null || user.getFamilyId() == null) return null;
+        return user.getFamilyId();
+    }
+
+    private CouponShare findShare(String shareToken) {
+        return couponShareMapper.selectOne(new LambdaQueryWrapper<CouponShare>()
+                .eq(CouponShare::getShareToken, shareToken)
+                .last("LIMIT 1"));
+    }
+
+    /** 生成全局唯一分享令牌:CS- + UUID 片段(≤64 字符,uk_share_token 全局唯一兜底) */
+    private String generateShareToken() {
+        return "CS-" + UUID.randomUUID().toString().replace("-", "").substring(0, 12).toUpperCase();
+    }
+
+    private Map<String, Object> buildCreateResult(CouponShare share) {
+        Map<String, Object> data = new HashMap<>();
+        data.put("shareToken", share.getShareToken());
+        data.put("sharePath", SHARE_PATH_PREFIX + share.getShareToken());
+        data.put("expireAt", share.getExpireAt());
+        return data;
+    }
+
+    /** 懒判定 EXPIRED:PENDING 但已过 expireAt 时对外展示 EXPIRED(DB 行保持 PENDING,detail/claim 判定) */
+    private String resolveDisplayStatus(CouponShare share, Date now) {
+        if (STATUS_PENDING.equals(share.getStatus())
+                && (share.getExpireAt() == null || now.after(share.getExpireAt()))) {
+            return STATUS_EXPIRED;
+        }
+        return share.getStatus();
+    }
+}

+ 31 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/FamilyMemberService.java

@@ -12,6 +12,7 @@ import com.etotem.cfc.entity.FamilyMemberAttributes;
 import com.etotem.cfc.entity.FamilyMemberLog;
 import com.etotem.cfc.entity.FiveDimensionScore;
 import com.etotem.cfc.entity.HealthReport;
+import com.etotem.cfc.entity.Task;
 import com.etotem.cfc.entity.User;
 import com.etotem.cfc.enums.GenerationLevel;
 import com.etotem.cfc.mapper.FamilyMapper;
@@ -20,6 +21,7 @@ import com.etotem.cfc.mapper.FamilyMemberLogMapper;
 import com.etotem.cfc.mapper.FamilyMemberMapper;
 import com.etotem.cfc.mapper.FiveDimensionScoreMapper;
 import com.etotem.cfc.mapper.HealthReportMapper;
+import com.etotem.cfc.mapper.TaskMapper;
 import com.etotem.cfc.mapper.UserMapper;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -76,6 +78,9 @@ public class FamilyMemberService {
     @Resource
     private FiveDimensionScoreMapper fiveDimensionScoreMapper;
 
+    @Resource
+    private TaskMapper taskMapper;
+
     @Resource
     private HealthReportMapper healthReportMapper;
 
@@ -972,6 +977,10 @@ vo.setIsSelf(viewerMember != null && viewerMember.getId().equals(fm.getId()));
         // 方案B补充:剥离切换成员本人从原家庭继承的会员身份(reconcileFamilyMembership 只处理仍留在原家庭的成员)
         membershipService.reconcileLeavingMemberMembership(userId, oldFamilyId, targetFamilyId);
 
+        // T28补充:切换家庭后刷新新旧家庭食材总览(该成员指数计入目标家庭、不再计入原家庭)
+        refreshFoodOverviewQuietly(oldFamilyId);
+        refreshFoodOverviewQuietly(targetFamilyId);
+
         logMemberAction(oldFamilyId, member.getId(), "switch", member.getNickname(), null, userId);
     }
 
@@ -982,6 +991,7 @@ vo.setIsSelf(viewerMember != null && viewerMember.getId().equals(fm.getId()));
      * - dan_assessment_results(测评):以 familyMemberId 关联,改 family_members.family_id 后自动跟随,无需迁移
      * - family_member_attributes(属性):以 memberId 关联,自动跟随
      * - family_relationships(关系):删旧建新(新家庭关系需重新计算)
+     * - tasks(任务):按 family_member_id / executor_id 迁移到目标家庭
      */
     private void migrateMemberAssets(FamilyMember member, Long oldFamilyId, Long targetFamilyId) {
         if (oldFamilyId.equals(targetFamilyId)) {
@@ -1017,6 +1027,27 @@ vo.setIsSelf(viewerMember != null && viewerMember.getId().equals(fm.getId()));
         } catch (Exception e) {
             log.warn("迁移健康报告异常: memberId={}", memberId, e);
         }
+        // 任务(育儿/健康任务):随成员切换到目标家庭(按 family_member_id 或 executor_id 匹配,
+        // 兼容 child 任务(executor=成员卡id)与 parent 任务(executor=用户id)两种口径)
+        try {
+            List<Task> memberTasks = taskMapper.selectList(
+                    new LambdaQueryWrapper<Task>()
+                            .eq(Task::getFamilyId, oldFamilyId)
+                            .and(w -> w.eq(Task::getFamilyMemberId, memberId)
+                                    .or().eq(Task::getExecutorId, memberId)
+                                    .or().eq(Task::getExecutorId, member.getUserId())));
+            int moved = 0;
+            for (Task t : memberTasks) {
+                t.setFamilyId(targetFamilyId);
+                moved += taskMapper.updateById(t);
+            }
+            if (moved > 0) {
+                log.info("切换家庭任务迁移: memberId={}, oldFamilyId={}, targetFamilyId={}, tasks={}",
+                        memberId, oldFamilyId, targetFamilyId, moved);
+            }
+        } catch (Exception e) {
+            log.warn("迁移任务异常: memberId={}", memberId, e);
+        }
     }
 
     /**

+ 98 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/GrowthPlanService.java

@@ -254,4 +254,102 @@ public class GrowthPlanService {
         plan.setUpdatedAt(new Date());
         return growthPlanMapper.updateById(plan) > 0;
     }
+
+    /** 草稿默认有效期 7 天(SC-P-81 边界:草稿有效期) */
+    private static final long DRAFT_VALIDITY_MS = 7L * 24L * 3600_000L;
+
+    /**
+     * 存草稿(SC-P-81 正常流:计划创建前暂存未完,能力键 plan.draft.save)。
+     *
+     * <p>持久化 {@code status="draft"};设置 {@code draftExpiresAt = now + 7 天}(有效期边界);
+     * 并发存两版草稿:{@code draftVersion} 递增,后存覆盖前存(TC-P-81-E 冲突检测依据)。
+     * 已有 id 为更新(版本号+1,后存覆盖),无 id 为新建。</p>
+     */
+    public GrowthPlan saveDraft(GrowthPlan plan) {
+        if (plan.getStatus() == null || !"draft".equals(plan.getStatus())) {
+            plan.setStatus("draft");
+        }
+        plan.setDraftExpiresAt(new Date(System.currentTimeMillis() + DRAFT_VALIDITY_MS));
+        if (plan.getId() != null) {
+            GrowthPlan existing = growthPlanMapper.selectById(plan.getId());
+            if (existing != null) {
+                plan.setDraftVersion((existing.getDraftVersion() != null ? existing.getDraftVersion() : 0) + 1);
+            } else {
+                plan.setDraftVersion(1);
+            }
+            plan.setCreatedAt(existing != null ? existing.getCreatedAt() : new Date());
+            plan.setUpdatedAt(new Date());
+            growthPlanMapper.updateById(plan);
+        } else {
+            plan.setDraftVersion(1);
+            plan.setCreatedAt(new Date());
+            plan.setUpdatedAt(new Date());
+            growthPlanMapper.insert(plan);
+        }
+        return plan;
+    }
+
+    /**
+     * 恢复草稿继续编辑(SC-P-81 正常流,能力键 plan.draft.save)。
+     *
+     * <p>草稿不存在返回 null;已超有效期抛 {@link IllegalStateException}『草稿已失效』
+     * (TC-P-81-E 异常流提示);有效期内返回可继续编辑的草稿(status 保持 draft)。</p>
+     */
+    public GrowthPlan restoreDraft(Long draftId) {
+        GrowthPlan plan = growthPlanMapper.selectById(draftId);
+        if (plan == null) {
+            return null;
+        }
+        if (isDraftExpired(plan)) {
+            throw new IllegalStateException("草稿已失效");
+        }
+        return plan;
+    }
+
+    /**
+     * 权限恢复(SC-P-81-P 越权拒绝,不泄露他人草稿,能力键 plan.draft.save)。
+     *
+     * <p>归属判定:{@code userId} 须等于草稿创建人 {@code teacherId}(方案由
+     * 规划师/家长创建,创建人即归属方)。非归属 → 抛 {@link IllegalStateException}
+     *『无权限』(403 拒绝,不返回他人草稿);归属 → 恢复,过期则抛『草稿已失效』。</p>
+     */
+    public GrowthPlan restoreDraft(Long draftId, Long userId) {
+        GrowthPlan plan = growthPlanMapper.selectById(draftId);
+        if (plan == null) {
+            // 方案不存在:统一 403 口径拒绝,不泄露任何草稿信息
+            throw new IllegalStateException("无权限:草稿不存在");
+        }
+        if (userId == null || !userId.equals(plan.getTeacherId())) {
+            throw new IllegalStateException("无权限");
+        }
+        if (isDraftExpired(plan)) {
+            throw new IllegalStateException("草稿已失效");
+        }
+        return plan;
+    }
+
+    /**
+     * 草稿是否已超有效期({@code draftExpiresAt < now},TC-P-81-E『草稿已失效』判定)。
+     * 无有效期记录的存量草稿视为未过期(安全默认,不阻断历史数据恢复)。
+     */
+    public boolean isDraftExpired(GrowthPlan draft) {
+        if (draft == null || draft.getDraftExpiresAt() == null) {
+            return false;
+        }
+        return draft.getDraftExpiresAt().getTime() < System.currentTimeMillis();
+    }
+
+    /**
+     * 并发检测(TC-P-81-E:后存覆盖前存且提示冲突)。
+     *
+     * <p>服务端已存版本 &gt; 本地版本 → 冲突(true,提示用户重新拉取);
+     * 本地版本 ≥ 服务端版本 → 无冲突(false)。草稿不存在时返回 false(无版本可比对)。</p>
+     */
+    public boolean isDraftVersionConflict(Long draftId, long localVersion) {
+        GrowthPlan plan = growthPlanMapper.selectById(draftId);
+        if (plan == null || plan.getDraftVersion() == null) {
+            return false;
+        }
+        return plan.getDraftVersion() > localVersion;
+    }
 }

+ 2 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ProductOrderService.java

@@ -1474,6 +1474,8 @@ public class ProductOrderService {
             order.setShippingCost(shippingCost);
         }
         order.setStatus("pending_receipt");
+        // P0-B 待收货超时兜底:发货成功即写 shipped_at=now,作为超时自动完成/收货提醒的基准时间
+        order.setShippedAt(new Date());
         if (st == ShipType.SELF_PICKUP) {
             // 履约扩展:自取/线上订单必须供应商先确认(confirmReceive 有校验),此处统一置为已确认
             order.setFulfillStatus("confirmed_by_vendor");

+ 13 - 1
cfc-backend/src/main/java/com/etotem/cfc/service/ProductReviewService.java

@@ -1,11 +1,13 @@
 package com.etotem.cfc.service;
 
 import com.etotem.cfc.dto.ProductReviewRequest;
+import com.etotem.cfc.dto.ProductReviewResponse;
 
 import java.util.Map;
 
 /**
- * 普通商品评价服务(能力键 {@code shop.review.create} / {@code shop.review.my})。
+ * 普通商品评价服务(能力键 {@code shop.review.create} / {@code shop.review.detail} /
+ * {@code shop.review.my})。
  *
  * <p>独立于活动评价 {@link ReviewOrderService}(PRD P0-A:活动链路零改动,不走复用)。
  * 设计 {@code docs/superpowers/specs/2026-11-14-product-order-gap-arch-design.md} §5.3 类图。</p>
@@ -21,6 +23,16 @@ public interface ProductReviewService {
      */
     String createReview(ProductReviewRequest request, Long reviewerId);
 
+    /**
+     * 评价详情/去评价按钮态(设计 §3.1 R2:订单详情页「去评价」按钮 + 已评展示)。
+     *
+     * @param orderId 订单主键
+     * @param userId  登录用户ID(下单人/商家)
+     * @return {@link ProductReviewResponse}:review 已评记录(未评为 null)、
+     *         canReview 可评态(review==null 且可评时 true)、reviewHint 提示文案
+     */
+    ProductReviewResponse detail(Long orderId, Long userId);
+
     /**
      * 我的评价 + 待评价入口(R5,能力键 {@code shop.review.my})。
      *

+ 62 - 7
cfc-backend/src/main/java/com/etotem/cfc/service/ProductReviewServiceImpl.java

@@ -3,6 +3,7 @@ package com.etotem.cfc.service;
 import com.alibaba.fastjson.JSON;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
 import com.etotem.cfc.dto.ProductReviewRequest;
+import com.etotem.cfc.dto.ProductReviewResponse;
 import com.etotem.cfc.entity.ProductOrder;
 import com.etotem.cfc.entity.ProductReview;
 import com.etotem.cfc.mapper.ProductOrderMapper;
@@ -20,12 +21,14 @@ import java.util.List;
 import java.util.Map;
 
 /**
- * 普通商品评价服务实现(能力键 {@code shop.review.create} / {@code shop.review.my})。
+ * 普通商品评价服务实现(能力键 {@code shop.review.create} / {@code shop.review.detail} /
+ * {@code shop.review.my},R1 + R2 + R5)。
  *
  * <p>设计 {@code docs/superpowers/specs/2026-11-14-product-order-gap-arch-design.md} §3.1 R1 校验链:
  * 订单存在 / {@code productType != 'activity'}(活动评价零污染)/ {@code status=completed} /
  * {@code buyerId==userId}(评价人为下单人本人)/ {@code confirmTime >= now-90d}(Q4 窗口)/
- * {@link ProductReviewMapper#findByOrderId} 幂等(一单一评,表唯一键 {@code uk_order_id})。</p>
+ * {@link ProductReviewMapper#findByOrderId} 幂等(一单一评,表唯一键 {@code uk_order_id})。
+ * §3.1 R2:{@link #detail} 判定「去评价」按钮态(completed + 90 天窗口 + 未评)。</p>
  */
 @Service
 public class ProductReviewServiceImpl extends ServiceImpl<ProductReviewMapper, ProductReview>
@@ -38,7 +41,7 @@ public class ProductReviewServiceImpl extends ServiceImpl<ProductReviewMapper, P
     private ProductReviewMapper reviewMapper;
 
     @Resource
-    private ProductOrderMapper productOrderMapper;
+    private ProductOrderMapper orderMapper;
 
     @Override
     @Transactional
@@ -61,7 +64,7 @@ public class ProductReviewServiceImpl extends ServiceImpl<ProductReviewMapper, P
         Long orderId = request.getOrderId();
 
         // 1) 订单存在
-        ProductOrder order = productOrderMapper.selectById(orderId);
+        ProductOrder order = orderMapper.selectById(orderId);
         if (order == null) {
             throw new RuntimeException("订单不存在");
         }
@@ -109,6 +112,47 @@ public class ProductReviewServiceImpl extends ServiceImpl<ProductReviewMapper, P
         return "评价提交成功";
     }
 
+    @Override
+    public ProductReviewResponse detail(Long orderId, Long userId) {
+        // 入参守卫
+        if (orderId == null) {
+            throw new RuntimeException("订单ID不能为空");
+        }
+        // 订单存在
+        ProductOrder order = orderMapper.selectById(orderId);
+        if (order == null) {
+            throw new RuntimeException("订单不存在");
+        }
+        // 已评记录(未评为 null)
+        ProductReview review = reviewMapper.findByOrderId(orderId);
+
+        ProductReviewResponse resp = new ProductReviewResponse();
+        resp.setReview(review);
+        if (review != null) {
+            resp.setCanReview(false);
+            resp.setReviewHint("该订单已评价");
+            return resp;
+        }
+        if (!"completed".equals(order.getStatus())) {
+            resp.setCanReview(false);
+            resp.setReviewHint("订单完成后可评价");
+            return resp;
+        }
+        if ("activity".equals(order.getProductType())) {
+            resp.setCanReview(false);
+            resp.setReviewHint("活动订单暂不支持评价");
+            return resp;
+        }
+        if (!inReviewWindow(order.getConfirmTime())) {
+            resp.setCanReview(false);
+            resp.setReviewHint("确认收货后90天内可评价");
+            return resp;
+        }
+        resp.setCanReview(true);
+        resp.setReviewHint("");
+        return resp;
+    }
+
     @Override
     public Map<String, Object> my(Long userId, int page, int size) {
         int pageNum = Math.max(page, 1);
@@ -116,8 +160,7 @@ public class ProductReviewServiceImpl extends ServiceImpl<ProductReviewMapper, P
 
         Map<String, Object> result = new HashMap<>();
 
-        // 1) 我的评价列表:按 reviewer_id 查,review_at 倒序分页(只取首屏页规模,不做总数统计——
-        //    小程序「我的评价」为简单列表,翻页按 offset 拉取即可)
+        // 1) 我的评价列表:按 reviewer_id 查,review_at 倒序分页
         List<ProductReview> reviews = lambdaQuery()
                 .eq(ProductReview::getReviewerId, userId)
                 .orderByDesc(ProductReview::getReviewAt)
@@ -136,7 +179,7 @@ public class ProductReviewServiceImpl extends ServiceImpl<ProductReviewMapper, P
         }
 
         // selectBatchIds 不保序,按 findReviewableOrderIds 返回的 confirm_time 倒序顺序重组
-        List<ProductOrder> fetched = productOrderMapper.selectBatchIds(reviewableOrderIds);
+        List<ProductOrder> fetched = orderMapper.selectBatchIds(reviewableOrderIds);
         Map<Long, ProductOrder> byId = new HashMap<>();
         if (fetched != null) {
             for (ProductOrder o : fetched) {
@@ -154,4 +197,16 @@ public class ProductReviewServiceImpl extends ServiceImpl<ProductReviewMapper, P
         result.put("reviewableCount", reviewableOrders.size());
         return result;
     }
+
+    /**
+     * 90 天评价窗口判定:confirmTime 存在且 >= now - 90d。
+     */
+    private boolean inReviewWindow(Date confirmTime) {
+        if (confirmTime == null) {
+            return false;
+        }
+        Calendar cal = Calendar.getInstance();
+        cal.add(Calendar.DAY_OF_MONTH, -REVIEW_WINDOW_DAYS);
+        return !confirmTime.before(cal.getTime());
+    }
 }

+ 17 - 1
cfc-backend/src/main/java/com/etotem/cfc/service/UserService.java

@@ -936,11 +936,27 @@ private FamilyInvitationService familyInvitationService;
                 break;
             }
         }
+        // userId -> 本家庭 family_members.id 映射:用户绑定的家长在 family_members 表也有记录,
+        // 成员的统一身份键应为 family_members.id(任务/打卡/健康等均按成员键存取)
+        Map<Long, Long> linkedMemberIds = new HashMap<>();
+        for (FamilyMember fm : familyMembersForVisible) {
+            if (fm.getUserId() != null && !linkedMemberIds.containsKey(fm.getUserId())) {
+                linkedMemberIds.put(fm.getUserId(), fm.getId());
+            }
+        }
         for (User p : parents) {
             if (p.getId().equals(userId) || (p.getShowToFamily() != null && p.getShowToFamily() == 1)) {
                 FamilyMemberVO vo = new FamilyMemberVO();
                 vo.setId(p.getId());
-                vo.setMemberId(p.getId());
+                // 关键修复:familyMemberId / memberId 必须指向本家庭的 family_members.id(而非 users.id)。
+                // 前端统一成员选择器以 familyMemberId 作为 memberId 调用任务/打卡等接口,
+                // 旧实现用 users.id(如姥姥 76)会在 tasks.family_member_id 查不到任务,导致
+                // 「用户12 在成员选择器里看不到姥姥(76) 的任务,但能看到娜娜(无用户,family_member) 的任务」。
+                Long linkedMemberId = linkedMemberIds.get(p.getId());
+                if (linkedMemberId != null) {
+                    vo.setMemberId(linkedMemberId);
+                    vo.setFamilyMemberId(linkedMemberId);
+                }
                 vo.setSource("parent");
                 vo.setUserId(p.getId());
                 vo.setNickname(p.getNickname());

+ 224 - 0
cfc-backend/src/main/java/com/etotem/cfc/task/OrderReceiptTimeoutTask.java

@@ -0,0 +1,224 @@
+package com.etotem.cfc.task;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.config.DatabaseInitializer;
+import com.etotem.cfc.entity.ProductOrder;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.ProductOrderMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.UserOperationLogService;
+import com.etotem.cfc.service.WechatService;
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Component;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 待收货超时自动完成 / 第N天收货提醒定时任务(能力键 {@code shop.order.receiptTimeout})。
+ *
+ * <p>契约来源:{@code docs/superpowers/specs/2026-11-14-product-order-gap-prd.md} §3 P0-B +
+ * {@code docs/superpowers/specs/2026-11-14-product-order-gap-arch-design.md} §3.3 / §6 T03,
+ * 仿 {@code OrderTimeoutCancelTask} 模式({@code @Scheduled} + {@code isMigrationsComplete} 守卫 + {@code @Transactional})。</p>
+ *
+ * <p>行为:
+ * <ol>
+ *   <li><b>自动完成</b>:{@code status=pending_receipt AND COALESCE(shipped_at, updated_at) &lt; now - receipt-timeout-days}
+ *       → {@code status=completed}、{@code confirmTime=now}、{@code updatedAt=now}、写 {@code user_operation_logs}
+ *       (type=product_order_auto_complete,备注含 orderNo/原因)留痕;completed 不再被扫中,重复执行幂等;</li>
+ *   <li><b>第N天提醒</b>:{@code status=pending_receipt AND shipped_at IS NOT NULL AND shipped_at &lt; now - receipt-remind-days
+ *       AND receipt_remind_at IS NULL} → 经 {@code WechatService.sendTemplateMessage} 推送,推送后写
+ *       {@code receipt_remind_at=now}(幂等防重复;模板ID空=跳过,fail-open);</li>
+ *   <li><b>总开关</b>:{@code receipt-auto-complete-enabled=false} 时仅提醒不自动完成(灰度开关)。</li>
+ * </ol>
+ * 阈值 / 提醒天数 / 开关 / 模板ID 全部走 {@code application.yml}({@code shop.order.*})配置,不硬编码。</p>
+ */
+@Component
+public class OrderReceiptTimeoutTask {
+
+    private static final Logger log = LoggerFactory.getLogger(OrderReceiptTimeoutTask.class);
+
+    /** 待收货状态:自动完成/提醒仅作用于该状态,completed 不再被扫中(幂等) */
+    static final String STATUS_PENDING_RECEIPT = "pending_receipt";
+
+    /** 自动完成可追溯日志类型(user_operation_logs.operation_type) */
+    static final String AUTO_COMPLETE_LOG_TYPE = "product_order_auto_complete";
+
+    @Resource
+    private ProductOrderMapper orderMapper;
+
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private WechatService wechatService;
+
+    @Resource
+    private UserOperationLogService operationLogService;
+
+    /** 发货后未确认收货自动完成天数(默认10,配置键 shop.order.receipt-timeout-days) */
+    @Value("${shop.order.receipt-timeout-days:10}")
+    private int receiptTimeoutDays;
+
+    /** 发货后第N天推送收货提醒(默认9,配置键 shop.order.receipt-remind-days) */
+    @Value("${shop.order.receipt-remind-days:9}")
+    private int receiptRemindDays;
+
+    /** 自动完成总开关(灰度/回滚用,false 时仅提醒不自动完成) */
+    @Value("${shop.order.receipt-auto-complete-enabled:true}")
+    private boolean receiptAutoCompleteEnabled;
+
+    /** 收货提醒订阅消息模板ID(空=跳过推送,fail-open,运营配置) */
+    @Value("${shop.order.receipt-remind-template-id:}")
+    private String receiptRemindTemplateId;
+
+    /**
+     * 定时入口:每分钟扫描待收货超时订单。先提醒(第N天)后自动完成(超时),
+     * 避免同一轮先完成再提醒的错序;自动完成受总开关控制。
+     */
+    @Scheduled(fixedRate = 60000)
+    @Transactional(rollbackFor = Exception.class)
+    public void processTimeoutOrders() {
+        if (!DatabaseInitializer.isMigrationsComplete()) {
+            log.info("数据库迁移尚未完成,跳过本轮待收货超时检查");
+            return;
+        }
+        sendRemind();
+        if (receiptAutoCompleteEnabled) {
+            autoComplete();
+        } else {
+            log.info("自动完成总开关关闭(receipt-auto-complete-enabled=false),本轮仅提醒不自动完成");
+        }
+    }
+
+    /**
+     * 自动完成:扫描 pending_receipt 且 COALESCE(shipped_at, updated_at) 早于超时阈值的订单,
+     * 置 completed + confirmTime=now + updatedAt=now,写 user_operation_logs 可追溯留痕 + SLF4J 日志。
+     * 幂等:completed 订单不在扫描范围内,重复执行不重复完成。
+     */
+    void autoComplete() {
+        Calendar cal = Calendar.getInstance();
+        cal.add(Calendar.DAY_OF_MONTH, -receiptTimeoutDays);
+        Date deadline = cal.getTime();
+
+        // COALESCE(shipped_at, updated_at) < deadline ⇔ (shipped_at 非空且 < deadline) OR (shipped_at 空且 updated_at < deadline)
+        List<ProductOrder> timeoutOrders = orderMapper.selectList(
+                new LambdaQueryWrapper<ProductOrder>()
+                        .eq(ProductOrder::getStatus, STATUS_PENDING_RECEIPT)
+                        .and(w -> w.isNotNull(ProductOrder::getShippedAt)
+                                        .lt(ProductOrder::getShippedAt, deadline)
+                                .or()
+                                .isNull(ProductOrder::getShippedAt)
+                                        .lt(ProductOrder::getUpdatedAt, deadline)));
+
+        if (timeoutOrders.isEmpty()) {
+            return;
+        }
+
+        Date now = new Date();
+        for (ProductOrder order : timeoutOrders) {
+            try {
+                order.setStatus("completed");
+                order.setConfirmTime(now);
+                order.setUpdatedAt(now);
+                orderMapper.updateById(order);
+                writeAutoCompleteLog(order);
+                log.info("订单 {} 发货后 {} 天未确认收货,系统自动完成", order.getOrderNo(), receiptTimeoutDays);
+            } catch (Exception e) {
+                // 单条失败不阻塞批次;状态幂等,下一轮可自动补齐
+                log.error("订单 {} 自动完成失败: {}", order.getOrderNo(), e.getMessage());
+            }
+        }
+        log.info("本次自动完成 {} 个超时待收货订单", timeoutOrders.size());
+    }
+
+    /**
+     * 第N天提醒:扫描 pending_receipt 且 shipped_at 存在、早于提醒阈值且未推送过(receipt_remind_at IS NULL)的订单,
+     * 经 WechatService.sendTemplateMessage 向买家推送收货提醒,推送后写 receipt_remind_at=now(幂等防重复);
+     * 模板ID未配置时跳过(fail-open)。
+     */
+    void sendRemind() {
+        if (StringUtils.isBlank(receiptRemindTemplateId)) {
+            log.info("收货提醒模板ID未配置(receipt-remind-template-id 为空),跳过第{}天收货提醒", receiptRemindDays);
+            return;
+        }
+        Calendar cal = Calendar.getInstance();
+        cal.add(Calendar.DAY_OF_MONTH, -receiptRemindDays);
+        Date remindTime = cal.getTime();
+
+        List<ProductOrder> remindOrders = orderMapper.selectList(
+                new LambdaQueryWrapper<ProductOrder>()
+                        .eq(ProductOrder::getStatus, STATUS_PENDING_RECEIPT)
+                        .isNotNull(ProductOrder::getShippedAt)
+                        .lt(ProductOrder::getShippedAt, remindTime)
+                        .isNull(ProductOrder::getReceiptRemindAt));
+
+        if (remindOrders.isEmpty()) {
+            return;
+        }
+
+        for (ProductOrder order : remindOrders) {
+            try {
+                if (order.getBuyerId() == null) {
+                    continue;
+                }
+                User buyer = userMapper.selectById(order.getBuyerId());
+                if (buyer == null || StringUtils.isBlank(buyer.getOpenid())) {
+                    log.info("订单 {} 买家无 openid,跳过收货提醒", order.getOrderNo());
+                    continue;
+                }
+                Map<String, Object> keywordMap = new HashMap<>();
+                keywordMap.put("keyword1", order.getProductName() != null ? order.getProductName() : "商品订单");
+                keywordMap.put("keyword2", order.getOrderNo());
+                keywordMap.put("keyword3", "您的订单已发货 " + receiptRemindDays + " 天,请及时确认收货");
+                wechatService.sendTemplateMessage(buyer.getOpenid(), receiptRemindTemplateId, keywordMap);
+                order.setReceiptRemindAt(new Date());
+                order.setUpdatedAt(new Date());
+                orderMapper.updateById(order);
+                log.info("订单 {} 第{}天收货提醒已推送", order.getOrderNo(), receiptRemindDays);
+            } catch (Exception e) {
+                // 失败仅日志,不重试风暴:receipt_remind_at 未写则下一轮自然再试
+                log.error("订单 {} 第{}天收货提醒推送失败: {}", order.getOrderNo(), receiptRemindDays, e.getMessage());
+            }
+        }
+        log.info("本次共推送 {} 个收货提醒", remindOrders.size());
+    }
+
+    /**
+     * 发货时间基准:COALESCE(shipped_at, updated_at)。
+     * 存量订单 shipped_at 为空时以 updated_at 兜底,避免历史待收货订单永久卡单(架构设计 §2.2)。
+     */
+    Date resolveShipTimeBase(ProductOrder order) {
+        if (order == null) {
+            return null;
+        }
+        return order.getShippedAt() != null ? order.getShippedAt() : order.getUpdatedAt();
+    }
+
+    /**
+     * 自动完成可追溯留痕:写 user_operation_logs(type=product_order_auto_complete,备注含 orderNo/原因)。
+     */
+    private void writeAutoCompleteLog(ProductOrder order) {
+        if (order.getBuyerId() == null) {
+            return;
+        }
+        try {
+            operationLogService.logOperation(order.getBuyerId(), AUTO_COMPLETE_LOG_TYPE,
+                    "订单 " + order.getOrderNo() + " 发货后超过 " + receiptTimeoutDays
+                            + " 天未确认收货,系统自动完成",
+                    null, null, null, null, null, null);
+        } catch (Exception e) {
+            // 留痕失败不阻塞自动完成主流程(日志服务内部已兜底)
+            log.warn("订单 {} 自动完成操作日志写入失败: {}", order.getOrderNo(), e.getMessage());
+        }
+    }
+}

+ 12 - 0
cfc-backend/src/main/java/com/etotem/cfc/util/ParamUtils.java

@@ -49,6 +49,18 @@ public final class ParamUtils {
         return parsed != null ? parsed : defaultVal;
     }
 
+    /**
+     * 安全解析 String:null / 空字符串 / 空白 => null(视为"未传")。
+     * 其余情况返回 {@code value.toString().trim()}(去除首尾空白,统一为 null 或干净字符串)。
+     */
+    public static String getString(Object value) {
+        if (value == null) {
+            return null;
+        }
+        String s = value.toString().trim();
+        return s.isEmpty() ? null : s;
+    }
+
     /**
      * 安全解析 Boolean:null / 空字符串 / 空白 => null(视为"未传")。
      * 支持 true/false、1/0、yes/no、on/off(忽略大小写);其余值 => null。

+ 27 - 3
cfc-backend/src/main/resources/schema.sql

@@ -522,6 +522,8 @@ CREATE TABLE IF NOT EXISTS growth_plans (
     start_date DATE,
     end_date DATE,
     review_count INT DEFAULT 0 COMMENT '已复盘次数',
+    draft_expires_at DATETIME DEFAULT NULL COMMENT '草稿有效期(SC-P-81 草稿保存/恢复,plan.draft.save)',
+    draft_version INT DEFAULT NULL COMMENT '草稿版本号(并发存两版草稿:后者覆盖且提示冲突)',
     created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
     updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
     INDEX idx_child_id (child_id),
@@ -2341,7 +2343,7 @@ CREATE TABLE IF NOT EXISTS family_relationships (
     INDEX idx_to (to_member_id)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='家庭成员双向关系表';
 
--- 家庭关系类型字典表(SC-A-04 关系类型 CRUD 管理,admin.familyRelation.manage;迁移494)
+-- 家庭关系类型字典表(SC-A-04 关系类型 CRUD 管理,admin.familyRelation.manage;迁移497)
 -- v2 辈分重构后 relationship_types 已废弃 DROP(迁移169),本表重建字典作为管理端
 -- 关系类型列表/新增/编辑/停用的数据载体(表名避开历史 relationship_types 防启动清表)
 CREATE TABLE IF NOT EXISTS family_relation_types (
@@ -2356,7 +2358,7 @@ CREATE TABLE IF NOT EXISTS family_relation_types (
     updated_at        DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='家庭关系类型字典表(关系类型 CRUD 管理)';
 
--- 默认关系类型字典种子(迁移494 空表播种,运营可编辑/停用)
+-- 默认关系类型字典种子(迁移497 空表播种,运营可编辑/停用)
 INSERT IGNORE INTO family_relation_types (type_key, type_name, generation_value, sort_order, enabled) VALUES
 ('spouse', '配偶', 0, 1, 1),
 ('parent', '父母', 1, 2, 1),
@@ -4982,8 +4984,10 @@ CREATE TABLE IF NOT EXISTS coupon_gift_transfer (
     receiver_family_id BIGINT NOT NULL COMMENT '接收人家庭ID',
     coupon_id BIGINT NOT NULL COMMENT '券模板ID(coupon.id)',
     family_coupon_id BIGINT NOT NULL COMMENT '被转移的 family_coupon 实例ID',
-    gift_level INT NOT NULL COMMENT '推荐层级 1=直推 2=隔级',
+    gift_level INT NOT NULL COMMENT '推荐层级 0=分享转赠 1=直推 2=隔级',
     status VARCHAR(16) NOT NULL DEFAULT 'GIFTED' COMMENT 'GIFTED/USED/REVOKED',
+    share_token VARCHAR(64) NULL COMMENT '分享令牌(分享转赠领取时回写 coupon_share.share_token, 定向转赠为NULL)',
+    claim_method VARCHAR(16) NOT NULL DEFAULT 'DIRECT' COMMENT '领取方式: DIRECT=定向转赠 SHARE=分享转赠(存量行默认DIRECT)',
     remark VARCHAR(255) NULL COMMENT '赠送留言',
     created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
     used_at DATETIME NULL,
@@ -4993,6 +4997,26 @@ CREATE TABLE IF NOT EXISTS coupon_gift_transfer (
     INDEX idx_family_coupon (family_coupon_id)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='会员优惠券转赠记录';
 
+CREATE TABLE IF NOT EXISTS coupon_share (
+    id BIGINT AUTO_INCREMENT PRIMARY KEY,
+    share_token VARCHAR(64) NOT NULL COMMENT '全局唯一分享令牌(path/query传递)',
+    giver_user_id BIGINT NOT NULL COMMENT '赠送人用户ID(users.id)',
+    giver_family_id BIGINT NOT NULL COMMENT '赠送人家庭ID',
+    family_coupon_id BIGINT NOT NULL COMMENT '被分享的 family_coupon 实例ID',
+    coupon_id BIGINT NOT NULL COMMENT '券模板ID(coupon.id)',
+    status VARCHAR(16) NOT NULL DEFAULT 'PENDING' COMMENT 'PENDING/CLAIMED/REVOKED/EXPIRED(懒判定)',
+    claim_user_id BIGINT NULL COMMENT '领取人用户ID(users.id,领取前为NULL)',
+    claim_family_id BIGINT NULL COMMENT '领取人家庭ID(领取前为NULL)',
+    claim_time DATETIME NULL COMMENT '领取时间',
+    expire_at DATETIME NOT NULL COMMENT '分享有效期截止(创建时now+配置天数,默认7)',
+    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+    UNIQUE KEY uk_share_token (share_token),
+    INDEX idx_giver_status (giver_user_id, status),
+    INDEX idx_family_coupon (family_coupon_id),
+    INDEX idx_status (status)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='会员券分享转赠记录(分享生命周期)';
+
 CREATE TABLE IF NOT EXISTS family_coupon_grant_log (
     id BIGINT AUTO_INCREMENT PRIMARY KEY,
     family_id BIGINT NOT NULL COMMENT '受赠家庭ID',

+ 592 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/CouponShareClaimContractTest.java

@@ -0,0 +1,592 @@
+package com.etotem.cfc.unit;
+
+import com.baomidou.mybatisplus.core.MybatisConfiguration;
+import com.baomidou.mybatisplus.core.conditions.Wrapper;
+import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
+import com.etotem.cfc.entity.Coupon;
+import com.etotem.cfc.entity.CouponGiftTransfer;
+import com.etotem.cfc.entity.CouponShare;
+import com.etotem.cfc.entity.FamilyCoupon;
+import com.etotem.cfc.entity.FamilyCouponGrantLog;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.CouponMapper;
+import com.etotem.cfc.mapper.CouponShareMapper;
+import com.etotem.cfc.mapper.FamilyCouponGrantLogMapper;
+import com.etotem.cfc.mapper.FamilyCouponMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.CouponGiftService;
+import com.etotem.cfc.service.CouponShareService;
+import com.etotem.cfc.service.NotificationDispatchService;
+import org.apache.ibatis.builder.MapperBuilderAssistant;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+import java.lang.reflect.Field;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * 契约级单测:会员券「分享转赠」后端(ARCH-CFC-COUPON-SHARE-GIFT-001 §10.1 十场景)。
+ *
+ * <p>契约溯源:{@code docs/superpowers/api/API_REFERENCE.md} 会员券分享转赠
+ * {@code /api/coupon/gift/share/*}(§5 create/detail/claim/revoke/list);
+ * 实现承载:{@link CouponShareService}(create 幂等 + claim 条件更新防重领 + 复用
+ * {@link CouponGiftService#commitTransfer})。纯 Mockito 无 Spring 上下文 / 无 DB /
+ * 无外部服务,风格参考 {@code ShopCouponClaimContractTest}。</p>
+ *
+ * <p><b>覆盖流</b>:</p>
+ * <ul>
+ *   <li><b>create</b>:正常(token/path/expireAt,insert 1 行 PENDING,expireAt=now+7 天);
+ *       幂等(已有 PENDING → 返回既有 token 不新增);校验(券不属我 / 非 MEMBERSHIP /
+ *       非 ACTIVE / 已过期 → 对应文案);</li>
+ *   <li><b>detail</b>:正常(PENDING → 券信息 + claimable=true,匿名可调);失效态
+ *       (CLAIMED/REVOKED/EXPIRED 懒判定 / token 不存在 → claimable=false + 对应状态);</li>
+ *   <li><b>claim</b>:成功(条件更新 1 行 → commitTransfer 委托参数 giftLevel=0/claimMethod=SHARE/
+ *       shareToken 回写,通知赠送人与 grant log 各 1 次);并发防重领(条件更新 0 行 →
+ *       「该分享已被领取」,transfer 不重复写);校验(自己分享/同家庭/已撤回/已过期/
+ *       券失效/领取人无家庭 → 各自文案);</li>
+ *   <li><b>revoke</b>:PENDING→REVOKED(不动券实例);CLAIMED 终态不可撤回;非赠送人无权;</li>
+ *   <li><b>list</b>:仅本人记录,created_at 倒序。</li>
+ * </ul>
+ */
+class CouponShareClaimContractTest {
+
+    private static final String TOKEN = "CS-CONTRACT001";
+    private static final String AVATAR = "http://avatar/";
+
+    /** 纯 Mockito 无 Spring:为 Lambda 包装器预注册 TableInfo(否则 set()/getSqlSegment() 报 lambda cache 异常) */
+    @BeforeAll
+    static void initMpTableInfo() {
+        MapperBuilderAssistant assistant = new MapperBuilderAssistant(new MybatisConfiguration(), "");
+        TableInfoHelper.initTableInfo(assistant, CouponShare.class);
+        TableInfoHelper.initTableInfo(assistant, Coupon.class);
+        TableInfoHelper.initTableInfo(assistant, CouponGiftTransfer.class);
+        TableInfoHelper.initTableInfo(assistant, FamilyCoupon.class);
+        TableInfoHelper.initTableInfo(assistant, FamilyCouponGrantLog.class);
+        TableInfoHelper.initTableInfo(assistant, User.class);
+    }
+
+    private CouponShareService service;
+    private CouponShareMapper couponShareMapper;
+    private FamilyCouponMapper familyCouponMapper;
+    private CouponMapper couponMapper;
+    private UserMapper userMapper;
+    private CouponGiftService couponGiftService;
+    private NotificationDispatchService notificationDispatchService;
+    private FamilyCouponGrantLogMapper familyCouponGrantLogMapper;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        service = new CouponShareService();
+        couponShareMapper = mock(CouponShareMapper.class);
+        familyCouponMapper = mock(FamilyCouponMapper.class);
+        couponMapper = mock(CouponMapper.class);
+        userMapper = mock(UserMapper.class);
+        couponGiftService = mock(CouponGiftService.class);
+        notificationDispatchService = mock(NotificationDispatchService.class);
+        familyCouponGrantLogMapper = mock(FamilyCouponGrantLogMapper.class);
+
+        inject(service, "couponShareMapper", couponShareMapper);
+        inject(service, "familyCouponMapper", familyCouponMapper);
+        inject(service, "couponMapper", couponMapper);
+        inject(service, "userMapper", userMapper);
+        inject(service, "couponGiftService", couponGiftService);
+        inject(service, "notificationDispatchService", notificationDispatchService);
+        inject(service, "familyCouponGrantLogMapper", familyCouponGrantLogMapper);
+    }
+
+    private static void inject(Object target, String field, Object value) throws Exception {
+        Field f = target.getClass().getDeclaredField(field);
+        f.setAccessible(true);
+        f.set(target, value);
+    }
+
+    // ==================== 桩数据 ====================
+
+    /** 用户:id=1 赠送人(家庭5)/ 其他 id 领取人(familyId 可指定) */
+    private User user(Long id, Long familyId) {
+        User u = new User();
+        u.setId(id);
+        u.setFamilyId(familyId);
+        u.setNickname(id == 1L ? "赠送人" : "领取人" + id);
+        u.setAvatar(AVATAR + id);
+        return u;
+    }
+
+    /** 有效期内、ACTIVE、MEMBERSHIP 的会员券模板 */
+    private Coupon membershipCoupon() {
+        Coupon c = new Coupon();
+        c.setId(100L);
+        c.setName("会员升级券");
+        c.setType("CASH");
+        c.setStatus("ACTIVE");
+        c.setApplicableTo("MEMBERSHIP");
+        c.setValue(2000);
+        c.setMinSpend(0);
+        c.setValidFrom(new Date(System.currentTimeMillis() - 86400000L * 7));
+        c.setValidUntil(new Date(System.currentTimeMillis() + 86400000L * 30));
+        return c;
+    }
+
+    private FamilyCoupon familyCoupon(Long id, Long familyId, Long couponId) {
+        FamilyCoupon fc = new FamilyCoupon();
+        fc.setId(id);
+        fc.setFamilyId(familyId);
+        fc.setCouponId(couponId);
+        fc.setStatus("AVAILABLE");
+        fc.setIsGift(0);
+        return fc;
+    }
+
+    /** 分享行:赠送人=1(家庭5),familyCoupon=500,coupon=100,expireAt=7 天后 */
+    private CouponShare pendingShare(String token) {
+        CouponShare s = new CouponShare();
+        s.setId(10L);
+        s.setShareToken(token);
+        s.setGiverUserId(1L);
+        s.setGiverFamilyId(5L);
+        s.setFamilyCouponId(500L);
+        s.setCouponId(100L);
+        s.setStatus("PENDING");
+        s.setExpireAt(new Date(System.currentTimeMillis() + 86400000L * 7));
+        s.setCreatedAt(new Date());
+        return s;
+    }
+
+    private String createError(Long giverUserId, Long familyCouponId) {
+        try {
+            service.create(giverUserId, familyCouponId);
+            return null;
+        } catch (IllegalArgumentException e) {
+            return e.getMessage();
+        }
+    }
+
+    private String detailError(String token) {
+        try {
+            service.detail(token, null);
+            return null;
+        } catch (IllegalArgumentException e) {
+            return e.getMessage();
+        }
+    }
+
+    private String claimError(Long userId, String token) {
+        try {
+            service.claim(userId, token);
+            return null;
+        } catch (IllegalArgumentException e) {
+            return e.getMessage();
+        }
+    }
+
+    private String revokeError(Long userId, String token) {
+        try {
+            service.revoke(userId, token);
+            return null;
+        } catch (IllegalArgumentException e) {
+            return e.getMessage();
+        }
+    }
+
+    // ==================== 场景1-3:create ====================
+
+    @Test
+    @DisplayName("create正常:返回 token/sharePath/expireAt,insert 1 行 PENDING,expireAt=now+7天")
+    void create_正常() {
+        when(userMapper.selectById(1L)).thenReturn(user(1L, 5L));
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(null);
+        when(familyCouponMapper.selectById(500L)).thenReturn(familyCoupon(500L, 5L, 100L));
+        when(couponMapper.selectById(100L)).thenReturn(membershipCoupon());
+        when(couponShareMapper.insert(any(CouponShare.class))).thenAnswer(inv -> {
+            CouponShare s = inv.getArgument(0);
+            s.setId(10L);
+            return 1;
+        });
+
+        Map<String, Object> data = service.create(1L, 500L);
+
+        String token = (String) data.get("shareToken");
+        assertNotNull(token, "应生成 shareToken");
+        assertTrue(((String) data.get("sharePath")).startsWith("/pages/coupon/share-claim?shareToken="),
+                "sharePath 应指向落地领取页并携带 token");
+        assertNotNull(data.get("expireAt"), "应返回失效时间");
+
+        ArgumentCaptor<CouponShare> captor = ArgumentCaptor.forClass(CouponShare.class);
+        verify(couponShareMapper).insert(captor.capture());
+        CouponShare inserted = captor.getValue();
+        assertEquals("PENDING", inserted.getStatus(), "新分享行状态应为 PENDING");
+        assertEquals(Long.valueOf(1L), inserted.getGiverUserId());
+        assertEquals(Long.valueOf(5L), inserted.getGiverFamilyId());
+        assertEquals(Long.valueOf(500L), inserted.getFamilyCouponId());
+        assertEquals(Long.valueOf(100L), inserted.getCouponId());
+        long diff = inserted.getExpireAt().getTime() - System.currentTimeMillis();
+        long expected = CouponShareService.DEFAULT_EXPIRE_DAYS * 86400000L;
+        assertTrue(diff > expected - 60000L && diff < expected + 60000L, "expireAt 应为 now + 7 天");
+    }
+
+    @Test
+    @DisplayName("create幂等:同 giver+familyCouponId 已有 PENDING → 返回既有 token,不新增行")
+    void create_幂等() {
+        when(userMapper.selectById(1L)).thenReturn(user(1L, 5L));
+        CouponShare existing = pendingShare("CS-EXISTING001");
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(existing);
+
+        Map<String, Object> data = service.create(1L, 500L);
+
+        assertEquals("CS-EXISTING001", data.get("shareToken"), "幂等命中应返回既有 token");
+        verify(couponShareMapper, never()).insert(any(CouponShare.class));
+        verify(familyCouponMapper, never()).selectById(anyLong());
+    }
+
+    @Test
+    @DisplayName("create校验-1:券不属于我(familyId 不符)→ 该优惠券不可用或不属于你")
+    void create_校验_券不属于我() {
+        when(userMapper.selectById(1L)).thenReturn(user(1L, 5L));
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(null);
+        when(familyCouponMapper.selectById(500L)).thenReturn(familyCoupon(500L, 99L, 100L));
+
+        assertEquals(CouponShareService.MSG_COUPON_UNAVAILABLE, createError(1L, 500L));
+        verify(couponShareMapper, never()).insert(any(CouponShare.class));
+    }
+
+    @Test
+    @DisplayName("create校验-2:非 MEMBERSHIP → 仅会员专属券可分享")
+    void create_校验_非会员券() {
+        when(userMapper.selectById(1L)).thenReturn(user(1L, 5L));
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(null);
+        when(familyCouponMapper.selectById(500L)).thenReturn(familyCoupon(500L, 5L, 100L));
+        Coupon coupon = membershipCoupon();
+        coupon.setApplicableTo("ALL");
+        when(couponMapper.selectById(100L)).thenReturn(coupon);
+
+        assertEquals(CouponShareService.MSG_ONLY_MEMBERSHIP, createError(1L, 500L));
+        verify(couponShareMapper, never()).insert(any(CouponShare.class));
+    }
+
+    @Test
+    @DisplayName("create校验-3:非 ACTIVE → 优惠券已失效")
+    void create_校验_券已失效() {
+        when(userMapper.selectById(1L)).thenReturn(user(1L, 5L));
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(null);
+        when(familyCouponMapper.selectById(500L)).thenReturn(familyCoupon(500L, 5L, 100L));
+        Coupon coupon = membershipCoupon();
+        coupon.setStatus("DISABLED");
+        when(couponMapper.selectById(100L)).thenReturn(coupon);
+
+        assertEquals(CouponShareService.MSG_COUPON_INVALID, createError(1L, 500L));
+        verify(couponShareMapper, never()).insert(any(CouponShare.class));
+    }
+
+    @Test
+    @DisplayName("create校验-4:已过券有效期 → 优惠券已过期")
+    void create_校验_券已过期() {
+        when(userMapper.selectById(1L)).thenReturn(user(1L, 5L));
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(null);
+        when(familyCouponMapper.selectById(500L)).thenReturn(familyCoupon(500L, 5L, 100L));
+        Coupon coupon = membershipCoupon();
+        coupon.setValidUntil(new Date(System.currentTimeMillis() - 86400000L));
+        when(couponMapper.selectById(100L)).thenReturn(coupon);
+
+        assertEquals(CouponShareService.MSG_COUPON_EXPIRED, createError(1L, 500L));
+        verify(couponShareMapper, never()).insert(any(CouponShare.class));
+    }
+
+    // ==================== 场景4-5:detail ====================
+
+    @Test
+    @DisplayName("detail正常:PENDING → 返回券信息 + claimable=true(匿名可调 viewerUserId=null)")
+    void detail_正常() {
+        CouponShare s = pendingShare(TOKEN);
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(s);
+        when(couponMapper.selectById(100L)).thenReturn(membershipCoupon());
+        when(userMapper.selectById(1L)).thenReturn(user(1L, 5L));
+
+        Map<String, Object> d = service.detail(TOKEN, null);
+
+        assertEquals(TOKEN, d.get("shareToken"));
+        assertEquals("PENDING", d.get("status"));
+        assertEquals(Boolean.TRUE, d.get("claimable"), "PENDING 且未过期且券可用 → 可领取");
+        assertEquals("会员升级券", d.get("couponName"));
+        assertEquals(Integer.valueOf(2000), d.get("couponValue"));
+        assertEquals("CASH", d.get("couponType"));
+        assertEquals(Integer.valueOf(0), d.get("minSpend"));
+        assertEquals("赠送人", d.get("giverNickname"));
+        assertEquals(AVATAR + "1", d.get("giverAvatar"));
+        assertNotNull(d.get("validUntil"));
+        assertNotNull(d.get("expireAt"));
+    }
+
+    @Test
+    @DisplayName("detail失效态-1:CLAIMED → claimable=false,status=CLAIMED")
+    void detail_失效态_已领取() {
+        CouponShare s = pendingShare(TOKEN);
+        s.setStatus("CLAIMED");
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(s);
+        when(couponMapper.selectById(100L)).thenReturn(membershipCoupon());
+        when(userMapper.selectById(1L)).thenReturn(user(1L, 5L));
+
+        Map<String, Object> d = service.detail(TOKEN, null);
+        assertEquals("CLAIMED", d.get("status"));
+        assertEquals(Boolean.FALSE, d.get("claimable"));
+    }
+
+    @Test
+    @DisplayName("detail失效态-2:REVOKED → claimable=false,status=REVOKED")
+    void detail_失效态_已撤回() {
+        CouponShare s = pendingShare(TOKEN);
+        s.setStatus("REVOKED");
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(s);
+        when(couponMapper.selectById(100L)).thenReturn(membershipCoupon());
+        when(userMapper.selectById(1L)).thenReturn(user(1L, 5L));
+
+        Map<String, Object> d = service.detail(TOKEN, null);
+        assertEquals("REVOKED", d.get("status"));
+        assertEquals(Boolean.FALSE, d.get("claimable"));
+    }
+
+    @Test
+    @DisplayName("detail失效态-3:PENDING 但已过 expireAt → 懒判定 EXPIRED,claimable=false")
+    void detail_失效态_过期懒判定() {
+        CouponShare s = pendingShare(TOKEN);
+        s.setExpireAt(new Date(System.currentTimeMillis() - 60000L)); // 1 分钟前过期
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(s);
+        when(couponMapper.selectById(100L)).thenReturn(membershipCoupon());
+        when(userMapper.selectById(1L)).thenReturn(user(1L, 5L));
+
+        Map<String, Object> d = service.detail(TOKEN, null);
+        assertEquals("EXPIRED", d.get("status"), "PENDING 且过期 → 展示 EXPIRED(懒判定)");
+        assertEquals(Boolean.FALSE, d.get("claimable"));
+    }
+
+    @Test
+    @DisplayName("detail失效态-4:token 无记录 → 分享不存在或已失效")
+    void detail_失效态_不存在() {
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(null);
+        assertEquals(CouponShareService.MSG_SHARE_NOT_FOUND, detailError("CS-NOT-FOUND"));
+    }
+
+    // ==================== 场景6-8:claim ====================
+
+    /** claim 成功前置:分享可领取(赠送人1/家庭5,领取人2/家庭6,券在赠送人名下且可用) */
+    private void stubClaimable() {
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(pendingShare(TOKEN));
+        when(userMapper.selectById(2L)).thenReturn(user(2L, 6L));
+        when(couponMapper.selectById(100L)).thenReturn(membershipCoupon());
+        when(familyCouponMapper.selectById(500L)).thenReturn(familyCoupon(500L, 5L, 100L));
+    }
+
+    @Test
+    @DisplayName("claim成功:条件更新 1 行 → 委托 commitTransfer(giftLevel=0,SHARE,token) + 通知赠送人 + grant log 各 1 次")
+    void claim_成功() {
+        stubClaimable();
+        when(couponShareMapper.update(isNull(), any(Wrapper.class))).thenReturn(1);
+        when(couponGiftService.commitTransfer(1L, 5L, 2L, 6L, 100L, 500L,
+                CouponShareService.SHARE_GIFT_LEVEL, "SHARE", TOKEN, null)).thenReturn(300L);
+
+        Long transferId = service.claim(2L, TOKEN);
+
+        assertEquals(Long.valueOf(300L), transferId, "应返回 commitTransfer 生成的 transferId");
+        // 条件更新恰好执行 1 次(防重领原子门)
+        verify(couponShareMapper).update(isNull(), any(Wrapper.class));
+        // 委托参数:giftLevel=0、claimMethod=SHARE、shareToken 回写、receiver=领取人家庭
+        verify(couponGiftService).commitTransfer(1L, 5L, 2L, 6L, 100L, 500L,
+                CouponShareService.SHARE_GIFT_LEVEL, "SHARE", TOKEN, null);
+        // 通知赠送人 1 次(模板 coupon_gift,目标 share.giverUserId=1)
+        verify(notificationDispatchService, times(1)).sendByTemplate(anyString(), eq(1L),
+                anyMap(), anyString(), anyLong(), anyString(), anyString());
+        // grant log 1 次(GIFT_TRANSFER, source=share:shareId)
+        ArgumentCaptor<FamilyCouponGrantLog> logCaptor = ArgumentCaptor.forClass(FamilyCouponGrantLog.class);
+        verify(familyCouponGrantLogMapper).insert(logCaptor.capture());
+        assertEquals("GIFT_TRANSFER", logCaptor.getValue().getGrantType());
+        assertEquals("share:10", logCaptor.getValue().getSource(), "分享链路审计 source=share:shareId");
+        assertEquals(Long.valueOf(6L), logCaptor.getValue().getFamilyId(), "流水落接收方家庭");
+        assertEquals(Long.valueOf(100L), logCaptor.getValue().getCouponId());
+    }
+
+    @Test
+    @DisplayName("claim并发防重领:条件更新影响 0 行(第二次/已被领走)→ 该分享已被领取,不重复写 transfer")
+    void claim_并发防重领() {
+        stubClaimable();
+        when(couponShareMapper.update(isNull(), any(Wrapper.class))).thenReturn(0); // 并发第二个请求
+
+        assertEquals(CouponShareService.MSG_ALREADY_CLAIMED, claimError(2L, TOKEN));
+        verify(couponGiftService, never()).commitTransfer(any(), any(), any(), any(),
+                any(), any(), any(), any(), any(), any());
+        verify(familyCouponGrantLogMapper, never()).insert(any(FamilyCouponGrantLog.class));
+        verify(notificationDispatchService, never()).sendByTemplate(anyString(), anyLong(),
+                anyMap(), anyString(), anyLong(), anyString(), anyString());
+    }
+
+    @Test
+    @DisplayName("claim校验-1:领取人=赠送人 → 不能领取自己分享的券")
+    void claim_校验_自己分享() {
+        CouponShare s = pendingShare(TOKEN);
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(s);
+        when(userMapper.selectById(1L)).thenReturn(user(1L, 5L));
+
+        assertEquals(CouponShareService.MSG_SELF_CLAIM, claimError(1L, TOKEN));
+        verify(couponShareMapper, never()).update(isNull(), any(Wrapper.class));
+    }
+
+    @Test
+    @DisplayName("claim校验-2:同家庭(领取人家庭=赠送人家庭)→ 不能领取同家庭成员的券")
+    void claim_校验_同家庭() {
+        CouponShare s = pendingShare(TOKEN);
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(s);
+        when(userMapper.selectById(2L)).thenReturn(user(2L, 5L)); // 与赠送人同家庭
+
+        assertEquals(CouponShareService.MSG_SAME_FAMILY, claimError(2L, TOKEN));
+        verify(couponShareMapper, never()).update(isNull(), any(Wrapper.class));
+    }
+
+    @Test
+    @DisplayName("claim校验-3:已撤回 → 该分享已撤回")
+    void claim_校验_已撤回() {
+        CouponShare s = pendingShare(TOKEN);
+        s.setStatus("REVOKED");
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(s);
+        when(userMapper.selectById(2L)).thenReturn(user(2L, 6L));
+
+        assertEquals(CouponShareService.MSG_ALREADY_REVOKED, claimError(2L, TOKEN));
+        verify(couponShareMapper, never()).update(isNull(), any(Wrapper.class));
+    }
+
+    @Test
+    @DisplayName("claim校验-4:已过期(PENDING 且过 expireAt)→ 该分享已过期")
+    void claim_校验_已过期() {
+        CouponShare s = pendingShare(TOKEN);
+        s.setExpireAt(new Date(System.currentTimeMillis() - 60000L));
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(s);
+        when(userMapper.selectById(2L)).thenReturn(user(2L, 6L));
+
+        assertEquals(CouponShareService.MSG_SHARE_EXPIRED, claimError(2L, TOKEN));
+        verify(couponShareMapper, never()).update(isNull(), any(Wrapper.class));
+    }
+
+    @Test
+    @DisplayName("claim校验-5:券模板失效 → 优惠券已失效")
+    void claim_校验_券失效() {
+        stubClaimable();
+        Coupon coupon = membershipCoupon();
+        coupon.setStatus("DISABLED");
+        when(couponMapper.selectById(100L)).thenReturn(coupon);
+
+        assertEquals(CouponShareService.MSG_COUPON_INVALID, claimError(2L, TOKEN));
+        verify(couponShareMapper, never()).update(isNull(), any(Wrapper.class));
+    }
+
+    @Test
+    @DisplayName("claim校验-6:领取人无家庭(familyId 空)→ 领取失败,请联系客服")
+    void claim_校验_无家庭() {
+        CouponShare s = pendingShare(TOKEN);
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(s);
+        when(userMapper.selectById(2L)).thenReturn(user(2L, null)); // 理论兜底:登录用户必有家庭
+
+        assertEquals(CouponShareService.MSG_CLAIM_FAILED, claimError(2L, TOKEN));
+        verify(couponShareMapper, never()).update(isNull(), any(Wrapper.class));
+    }
+
+    // ==================== 场景9:revoke ====================
+
+    @Test
+    @DisplayName("revoke:PENDING → REVOKED(条件更新 1 行),不动券实例")
+    void revoke_正常() {
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(pendingShare(TOKEN));
+        when(couponShareMapper.update(any(CouponShare.class), any(Wrapper.class))).thenReturn(1);
+
+        service.revoke(1L, TOKEN);
+
+        ArgumentCaptor<CouponShare> captor = ArgumentCaptor.forClass(CouponShare.class);
+        verify(couponShareMapper).update(captor.capture(), any(Wrapper.class));
+        assertEquals("REVOKED", captor.getValue().getStatus(), "仅置 status=REVOKED");
+        verify(familyCouponMapper, never()).updateById(any(FamilyCoupon.class));
+    }
+
+    @Test
+    @DisplayName("revoke:CLAIMED 终态 → 该分享已被领取,无法撤回")
+    void revoke_已领取不可撤回() {
+        CouponShare s = pendingShare(TOKEN);
+        s.setStatus("CLAIMED");
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(s);
+
+        assertEquals(CouponShareService.MSG_CLAIMED_CANNOT_REVOKE, revokeError(1L, TOKEN));
+        verify(couponShareMapper, never()).update(any(CouponShare.class), any(Wrapper.class));
+    }
+
+    @Test
+    @DisplayName("revoke:非赠送人 → 无权操作该分享")
+    void revoke_非赠送人() {
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(pendingShare(TOKEN));
+
+        assertEquals(CouponShareService.MSG_NO_PERMISSION, revokeError(2L, TOKEN));
+        verify(couponShareMapper, never()).update(any(CouponShare.class), any(Wrapper.class));
+    }
+
+    @Test
+    @DisplayName("revoke:已 REVOKED → 该分享已撤回(幂等兜底)")
+    void revoke_已撤回() {
+        CouponShare s = pendingShare(TOKEN);
+        s.setStatus("REVOKED");
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(s);
+
+        assertEquals(CouponShareService.MSG_ALREADY_REVOKED, revokeError(1L, TOKEN));
+        verify(couponShareMapper, never()).update(any(CouponShare.class), any(Wrapper.class));
+    }
+
+    // ==================== 场景10:list ====================
+
+    @Test
+    @DisplayName("list:仅返回本人分享记录,created_at 倒序,含领取人昵称")
+    void list_倒序() {
+        CouponShare newer = pendingShare("CS-LIST-A"); // 10s 前
+        newer.setCreatedAt(new Date(System.currentTimeMillis() - 10000L));
+        CouponShare older = pendingShare("CS-LIST-B"); // 60s 前
+        older.setCreatedAt(new Date(System.currentTimeMillis() - 60000L));
+        older.setClaimUserId(2L);
+        when(couponShareMapper.selectList(any(Wrapper.class))).thenReturn(Arrays.asList(newer, older));
+        when(couponMapper.selectById(100L)).thenReturn(membershipCoupon());
+        when(userMapper.selectById(2L)).thenReturn(user(2L, 6L));
+
+        List<Map<String, Object>> list = service.list(1L);
+
+        assertEquals(2, list.size());
+        assertEquals("CS-LIST-A", list.get(0).get("shareToken"), "列表应按 created_at 倒序");
+        assertEquals("CS-LIST-B", list.get(1).get("shareToken"));
+        assertEquals("会员升级券", list.get(0).get("couponName"));
+        assertEquals(Integer.valueOf(2000), list.get(0).get("couponValue"));
+        assertNotNull(list.get(0).get("expireAt"));
+        assertNotNull(list.get(0).get("createdAt"));
+        assertNull(list.get(0).get("claimNickname"), "未领取行 claimNickname 为 null");
+        assertEquals("领取人2", list.get(1).get("claimNickname"));
+
+        // 查询条件:giver_user_id=本人 + orderByDesc(createdAt)
+        ArgumentCaptor<Wrapper<CouponShare>> wrapperCaptor = ArgumentCaptor.forClass(Wrapper.class);
+        verify(couponShareMapper).selectList(wrapperCaptor.capture());
+        String sql = wrapperCaptor.getValue().getSqlSegment().toLowerCase();
+        assertTrue(sql.contains("giver_user_id"), "list 应按赠送人过滤");
+        assertTrue(sql.contains("desc"), "list 应按 created_at 倒序(ORDER BY ... DESC)");
+    }
+}

+ 396 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/RewardV2E2EExampleContractTest.java

@@ -0,0 +1,396 @@
+package com.etotem.cfc.unit;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import java.io.InputStream;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.nio.charset.StandardCharsets;
+import java.util.Scanner;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * 能力键 {@code cf.rewardv2.e2eExample}(任务号 S-cfc-400,TDD-RED 阶段)契约级单测。
+ *
+ * <p>契约溯源:
+ * <ul>
+ *   <li>需求:{@code docs/superpowers/plans/2026-11-14-cf-reward-model-v2.md}
+ *       §3.1 账目示例 + §5-5 测试(200/100 例)+ D4/D5/D8 裁决(base=78、销售奖在 base 上分、
+ *       F02 改比例返利 1%);</li>
+ *   <li>设计:{@code docs/superpowers/plans/2026-11-14-cf-reward-model-v2-design.md}
+ *       §1.1 账目公式 + §5 层级树瓜分 + §6 T08(端到端测试矩阵)+ §8 测试用例 #1(本例)。</li>
+ * </ul>
+ *
+ * <p><b>契约范围</b>:分润 v2 端到端账目验证的 <b>200/100 账目示例</b>(T08 首个矩阵用例)——
+ * 商品售价 200 元({@code A=20000} 分)/ 成本 100 元({@code C=10000} 分)/ 体系
+ * {@code T=30%}(3000bps)/ 直推 70% 档 / 间推 20% 档:</p>
+ * <pre>
+ *   R0  平台抽成   = floor(20000 × 1000 / 10000) = 2000 分 = 20 元
+ *   R1  消费返 CF  = floor(20000 × 100 / 10000)  = 200 CF(等值 200 分 = 2 元,设计 §1.1/§1.6 裁决 A)
+ *   base 可分配额  = 20000 − 2000 − 200 − 10000  = 7800 分 = 78 元   (≠ v1 原始毛利 100 元)
+ *   直推销售奖     = 7800 × 70%  = 5460 分 = 54.6 元
+ *   间推销售奖     = 7800 × 20%  = 1560 分 = 15.6 元
+ *   团队分润池     = floor(10000 × 3000 / 10000) = 3000 分 = 30 元(成本侧切出,不占 base)
+ *   平台留存       = 20000 − 200 − 5460 − 1560 − (10000 − 3000) = 5780 分 = 57.8 元(含 R0)
+ *   校验:R1(200) + 直推(5460) + 间推(1560) + 留存(5780) + 商家自担(7000) = 20000 ✓
+ * </pre>
+ *
+ * <p><b>实现现状</b>:本分支 {@code src/main} 中分润 v2 全部未落地(已核实)——无
+ * {@code calcDistributableBase / settlePlatformTake / settleTeamPool / distributeTeamPool / RULE_TEAM_POOL("F03c")}、
+ * 无 {@code TeamShareConfigService / CfTeamShareConfig / CfTeamPoolOrder / CfTeamPoolShare / CfPlatformRevenueLog}、
+ * {@code schema.sql} 无 4 张 v2 新表、{@code CfConfigKeys} 无 6 个 v2 配置键。因此本测试以
+ * 「反射结构契约」探测实现缺失:能编译、能运行、断言失败(红),且失败断言原文清晰可贴。</p>
+ *
+ * <p><b>GREEN 升级指引</b>:实现者按设计 §6 T01-T07 落地后(T03 交付
+ * {@code calcDistributableBase}、T04 交付 {@code settleTeamPool}、T05 交付
+ * {@code distributeTeamPool}、T01 建表/播种配置键),本测试自动转绿;届时可将
+ * 结构探测升级为行为级 mock 验证(校验账目登账金额)。</p>
+ *
+ * <p><b>权限流说明</b>:本能力为后端内部结算链路(订单支付 → 分润服务),无用户权限维度,
+ * 权限流不适用,以说明性用例标注。</p>
+ */
+class RewardV2E2EExampleContractTest {
+
+    // ---------- 契约目标类 FQCN ----------
+    private static final String CF_COMMISSION_SERVICE = "com.etotem.cfc.service.CfCommissionService";
+    private static final String CF_CONFIG_KEYS = "com.etotem.cfc.constant.CfConfigKeys";
+    private static final String TEAM_SHARE_CONFIG_SERVICE = "com.etotem.cfc.service.TeamShareConfigService";
+    private static final String CF_TEAM_SHARE_CONFIG = "com.etotem.cfc.entity.CfTeamShareConfig";
+    private static final String CF_TEAM_POOL_ORDER = "com.etotem.cfc.entity.CfTeamPoolOrder";
+    private static final String CF_TEAM_POOL_SHARE = "com.etotem.cfc.entity.CfTeamPoolShare";
+    private static final String CF_PLATFORM_REVENUE_LOG = "com.etotem.cfc.entity.CfPlatformRevenueLog";
+
+    // ---------- 200/100 账目示例数学锚点(金额单位:分;CF 单位:CF) ----------
+    /** 实付 200 元(paidAmountCent) */
+    private static final int A = 20000;
+    /** 商品成本 100 元 */
+    private static final int C = 10000;
+    /** R0 平台抽成 = floor(A × 1000 / 10000) = 20 元 */
+    private static final int R0 = 2000;
+    /** R1 消费返 CF = floor(A × 100 / 10000) = 200 CF */
+    private static final int R1_CF = 200;
+    /** R1 等值成本(分) = floor(A / 100) = 2 元 */
+    private static final int R1_CENT = 200;
+    /** base 可分配额 = A − R0 − R1_等值 − C = 78 元(≠ v1 原始毛利 100 元) */
+    private static final int BASE = 7800;
+    /** v1 原始毛利 = A − C = 100 元(base 口径必须与其区分) */
+    private static final int V1_GROSS_MARGIN = 10000;
+    /** 直推销售奖 = base × 70% = 54.6 元 */
+    private static final int DIRECT_CENT = 5460;
+    /** 间推销售奖 = base × 20% = 15.6 元 */
+    private static final int INDIRECT_CENT = 1560;
+    /** 团队分润池 = floor(C × 3000 / 10000) = 30 元 */
+    private static final int POOL_CENT = 3000;
+    /** 平台留存 = A − R1 − 直推 − 间推 − (C − 团队池) = 57.8 元(含 R0) */
+    private static final int RETAIN_CENT = 5780;
+
+    /** 设计 §2/§4 四张 v2 新表 */
+    private static final String[] V2_TABLES = {
+            "cf_team_share_config", "cf_team_pool_order", "cf_team_pool_share", "cf_platform_revenue_log"
+    };
+
+    /** 设计 §4 六个新增配置键(默认值) */
+    private static final String[] V2_CONFIG_KEYS = {
+            "cf.platform.take_rate_bps",      // 1000 = 10%
+            "cf.team_pool.enabled",           // true
+            "cf.team_pool.default_t_bps",     // 3000 = 30%
+            "cf.team_pool.on_loss",           // payout
+            "cf.team_pool.max_depth",         // 8
+            "cf.team_pool.non_goods_cost_rate" // 5000 = 50%
+    };
+
+    // ==================== 正常流:结算入口与结算顺序方法契约(§3.1) ====================
+
+    @Test
+    @DisplayName("正常流-1:CfCommissionService 应提供 v2 结算四入口方法")
+    void cfCommissionService_hasV2SettleMethods() {
+        Class<?> svc = loadClass(CF_COMMISSION_SERVICE);
+        assertTrue(svc != null, "[cf.rewardv2.e2eExample] CfCommissionService 类应存在。");
+
+        // §3.1 T03:base 计算入口(本测试的核心契约锚点)
+        assertTrue(methodExists(svc, "calcDistributableBase", int.class, int.class),
+                "[cf.rewardv2.e2eExample]CfCommissionService 缺少 calcDistributableBase(int A, int costCent):"
+                        + "设计 §3.1 T03 要求 base = A − R0 − R1_等值 − costCent,base<0 按 0。实现未落地。");
+        // §3.1 T03:平台抽成记账入口
+        assertTrue(methodExists(svc, "settlePlatformTake"),
+                "[cf.rewardv2.e2eExample] CfCommissionService 缺少 settlePlatformTake:"
+                        + "设计 §3.1 T03 要求 R0 = floor(A × take_rate_bps / 10000) 写 cf_platform_revenue_log。实现未落地。");
+        // §3.1 T04:团队池建池入口
+        assertTrue(methodExists(svc, "settleTeamPool"),
+                "[cf.rewardv2.e2eExample] CfCommissionService 缺少 settleTeamPool:"
+                        + "设计 §3.1 T04 要求解析 T → 建 cf_team_pool_order(uk_order 幂等)。实现未落地。");
+        // §3.1/§5 T05:层级树瓜分入口
+        assertTrue(methodExists(svc, "distributeTeamPool"),
+                "[cf.rewardv2.e2eExample] CfCommissionService 缺少 distributeTeamPool:"
+                        + "设计 §5 T05 要求层级树+档位权重瓜分(尾差守恒/同家庭跳过)。实现未落地。");
+    }
+
+    @Test
+    @DisplayName("正常流-2:calcDistributableBase(20000, 10000) 应为 78 元(7800 分),≠ v1 毛利 100 元")
+    void calcDistributableBase_200yuan_shouldReturn78yuan() {
+        int base = invokeStatelessInt(CF_COMMISSION_SERVICE, "calcDistributableBase", A, C);
+        assertEquals(BASE, base,
+                "[cf.rewardv2.e2eExample] 200 元实付 / 100 元成本:base 应为 78 元(7800 分)"
+                        + "= A − R0(20元) − R1_等值(2元) − C(100元)(设计 §1.1 公式)。");
+        assertNotEquals(V1_GROSS_MARGIN, base,
+                "[cf.rewardv2.e2eExample] base 不得等于 v1 原始毛利 100 元(10000 分):"
+                        + "分润基数是扣减平台抽成与消费返 CF 后的可分配额,不是毛利(需求 §3.2/设计 §8 用例#10)。");
+    }
+
+    @Test
+    @DisplayName("正常流-3:base 恒等于 A − R0 − R1_等值 − C(R0/R1 先扣口径)")
+    void base_equalsAminusR0minusR1minusC() {
+        assertEquals(A - R0 - R1_CENT - C, BASE,
+                "[cf.rewardv2.e2eExample] 测试锚点自洽性:base 数学锚点须等于 A − R0 − R1_等值 − C。");
+        int base = invokeStatelessInt(CF_COMMISSION_SERVICE, "calcDistributableBase", A, C);
+        assertEquals(A - R0 - R1_CENT - C, base,
+                "[cf.rewardv2.e2eExample] calcDistributableBase 必须按「R0/R1 先扣」口径计算:"
+                        + "R1_等值 = floor(A/100) 分(200 CF ≈ 2 元),平台抽成与消费返 CF 都是先扣成本"
+                        + "(需求 D4/设计 §1.1)。");
+    }
+
+    // ==================== 正常流:团队池通道契约(§3.1/§5) ====================
+
+    @Test
+    @DisplayName("正常流-4:RULE_TEAM_POOL 常量应为 F03c")
+    void ruleTeamPoolConstant_isF03c() {
+        assertTrue(constantValueEquals(CF_COMMISSION_SERVICE, "F03c"),
+                "[cf.rewardv2.e2eExample] CfCommissionService 缺少 RULE_TEAM_POOL = \"F03c\" 常量:"
+                        + "设计 §3.1 要求团队池发放走 earnByRule(memberId, \"F03c\", poolId, {amount})"
+                        + "(cf_earn_rule 新种子,§3.3)。实现未落地。");
+    }
+
+    @Test
+    @DisplayName("正常流-5:团队池两实体应存在并承载 poolCent(金额锚点 30 元)")
+    void teamPoolEntities_carryPoolCent() {
+        Class<?> orderEntity = loadClass(CF_TEAM_POOL_ORDER);
+        assertTrue(orderEntity != null,
+                "[cf.rewardv2.e2eExample] CfTeamPoolOrder 实体不存在:"
+                        + "设计 §2.2 要求 cf_team_pool_order 记录团队池金额(成本×T%,如 30 元)。实现未落地。");
+        assertTrue(fieldExists(orderEntity, "poolCent"),
+                "[cf.rewardv2.e2eExample] CfTeamPoolOrder 应含 poolCent 字段(对应 pool_cent),"
+                        + "承载团队池金额 = floor(C × T_bps / 10000) = 3000 分(30 元)。");
+
+        Class<?> shareEntity = loadClass(CF_TEAM_POOL_SHARE);
+        assertTrue(shareEntity != null,
+                "[cf.rewardv2.e2eExample] CfTeamPoolShare 实体不存在:"
+                        + "设计 §2.3 要求 cf_team_pool_share 记录池内成员瓜分明细(uk_pool_member 幂等)。实现未落地。");
+        assertTrue(fieldExists(shareEntity, "shareCent"),
+                "[cf.rewardv2.e2eExample] CfTeamPoolShare 应含 shareCent 字段(对应 share_cent)。");
+    }
+
+    // ==================== 正常流:平台抽成与新增服务契约(§3.1/§2.4) ====================
+
+    @Test
+    @DisplayName("正常流-6:CfPlatformRevenueLog 应存在并承载 amountCent(R0=20 元)")
+    void platformRevenueLog_carriesAmountCent() {
+        Class<?> entity = loadClass(CF_PLATFORM_REVENUE_LOG);
+        assertTrue(entity != null,
+                "[cf.rewardv2.e2eExample] CfPlatformRevenueLog 实体不存在:"
+                        + "设计 §2.4 要求 cf_platform_revenue_log 单列 R0 平台抽成(uk_order 幂等)。实现未落地。");
+        assertTrue(fieldExists(entity, "amountCent"),
+                "[cf.rewardv2.e2eExample] CfPlatformRevenueLog 应含 amountCent 字段"
+                        + "(对应 amount_cent,200 元实付 → 20 元抽成)。");
+    }
+
+    @Test
+    @DisplayName("正常流-7:TeamShareConfigService 应存在并提供 resolveTbps 解析入口")
+    void teamShareConfigService_resolvesTbps() {
+        Class<?> svc = loadClass(TEAM_SHARE_CONFIG_SERVICE);
+        assertTrue(svc != null,
+                "[cf.rewardv2.e2eExample] TeamShareConfigService 不存在:"
+                        + "设计 §3.2 T02 要求解析 T%(优先级 MINIAPP>SYSTEM>GLOBAL>3000 兜底)。实现未落地。");
+        assertTrue(methodExists(svc, "resolveTbps"),
+                "[cf.rewardv2.e2eExample] TeamShareConfigService 应提供 resolveTbps(...) 解析入口(设计 §3.2)。");
+    }
+
+    @Test
+    @DisplayName("正常流-8:cf_team_share_config 实体类应存在(T 作用域配置承载)")
+    void teamShareConfigEntity_exists() {
+        assertTrue(loadClass(CF_TEAM_SHARE_CONFIG) != null,
+                "[cf.rewardv2.e2eExample] CfTeamShareConfig 实体不存在:"
+                        + "设计 §2.1 T01 要求 cf_team_share_config 承载 GLOBAL/SYSTEM/MINIAPP 三作用域 T 配置。实现未落地。");
+    }
+
+    // ==================== 边界流(§1.4) ====================
+
+    @Test
+    @DisplayName("边界流-1:亏损仓 base 不得为负,按 0 返回")
+    void calcDistributableBase_lossMaking_returnsZero() {
+        // 售价 100 元(10000 分)/ 成本 120 元(12000 分):base = 10000 − 1000 − 100 − 12000 < 0 ⇒ 0
+        int base = invokeStatelessInt(CF_COMMISSION_SERVICE, "calcDistributableBase", 10000, 12000);
+        assertEquals(0, base,
+                "[cf.rewardv2.e2eExample] 亏损仓(A < C)base 必须为 0(不得为负):"
+                        + "直推/间推 = 0,R0/R1 照旧,团队池照发(设计 §1.4/§8 用例#3)。");
+    }
+
+    @Test
+    @DisplayName("边界流-2:实付为 0 时 base 为 0")
+    void calcDistributableBase_zeroPaid_returnsZero() {
+        assertEquals(0, invokeStatelessInt(CF_COMMISSION_SERVICE, "calcDistributableBase", 0, C),
+                "[cf.rewardv2.e2eExample] 实付 = 0:R0=0、R1=0、base=0(设计 §1.4)。");
+    }
+
+    @Test
+    @DisplayName("边界流-3:亏损仓团队池照发配置键 cf.team_pool.on_loss 应播种(默认 payout)")
+    void onLossConfigKey_shouldBeDeclared() {
+        assertTrue(configKeyDeclared(CF_CONFIG_KEYS, "cf.team_pool.on_loss"),
+                "[cf.rewardv2.e2eExample] CfConfigKeys 缺少 cf.team_pool.on_loss 键:"
+                        + "亏损仓团队池按成本×T% 照发(2026-11-14 裁决 payout,设计 §1.4)。实现未落地。");
+    }
+
+    // ==================== 配置流(§2/§4) ====================
+
+    @Test
+    @DisplayName("配置流-1:schema.sql 应包含四张 v2 新表")
+    void schemaSql_containsFourV2Tables() {
+        String schema = readSchemaSql();
+        for (String table : V2_TABLES) {
+            assertTrue(schema.contains(table),
+                    "[cf.rewardv2.e2eExample] schema.sql 缺少 " + table + " 建表"
+                            + "(设计 §2,迁移462-465)。实现未落地。");
+        }
+    }
+
+    @Test
+    @DisplayName("配置流-2:CfConfigKeys 应声明六个 v2 配置键")
+    void configKeys_sixV2KeysDeclared() {
+        for (String key : V2_CONFIG_KEYS) {
+            assertTrue(configKeyDeclared(CF_CONFIG_KEYS, key),
+                    "[cf.rewardv2.e2eExample] CfConfigKeys 缺少配置键 " + key
+                            + "(设计 §4,种子进 seedCfServiceConfig)。实现未落地。");
+        }
+    }
+
+    // ==================== 权限流(不适用) ====================
+
+    @Test
+    @DisplayName("权限流:本能力为后端内部结算链路,无用户权限维度,权限流不适用")
+    void permissionFlow_notApplicable() {
+        // 说明性用例:cf.rewardv2.e2eExample 契约 AC 为「订单支付 → 分润结算」内部链路,
+        // 无请求级权限校验维度。不产生断言失败,仅为三流覆盖标注「不适用」。
+        assertTrue(true, "权限流不适用:cf.rewardv2.e2eExample 为后端内部结算链路,无用户权限维度。");
+    }
+
+    // ==================== 反射辅助 ====================
+
+    private Class<?> loadClass(String name) {
+        try {
+            return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
+        } catch (ClassNotFoundException e) {
+            return null;
+        }
+    }
+
+    private boolean methodExists(Class<?> clazz, String name, Class<?>... params) {
+        try {
+            clazz.getDeclaredMethod(name, params);
+            return true;
+        } catch (NoSuchMethodException e) {
+            return false;
+        }
+    }
+
+    private boolean fieldExists(Class<?> clazz, String name) {
+        try {
+            clazz.getDeclaredField(name);
+            return true;
+        } catch (NoSuchFieldException e) {
+            return false;
+        }
+    }
+
+    /**
+     * 无参构造实例化 + 反射调用静态无副作用契约方法(如 {@code calcDistributableBase(int, int)}),
+     * 返回 int。方法缺失时以契约失败断言结束(RED),GREEN 实现落地后转绿。
+     */
+    private int invokeStatelessInt(String targetClass, String methodName, int arg1, int arg2) {
+        Class<?> clazz = loadClass(targetClass);
+        if (clazz == null) {
+            fail("[cf.rewardv2.e2eExample] 目标类不存在:" + targetClass);
+        }
+        Object instance;
+        try {
+            instance = clazz.getDeclaredConstructor().newInstance();
+        } catch (Exception e) {
+            fail("[cf.rewardv2.e2eExample] 无法实例化 " + targetClass + ":" + e.getClass().getSimpleName()
+                    + "(GREEN 时 calcDistributableBase 应为纯函数,无依赖也可实例化)。");
+            return 0;
+        }
+        try {
+            Method m = clazz.getDeclaredMethod(methodName, int.class, int.class);
+            m.setAccessible(true);
+            Object result = m.invoke(instance, arg1, arg2);
+            return ((Number) result).intValue();
+        } catch (NoSuchMethodException e) {
+            fail("[cf.rewardv2.e2eExample] " + targetClass + " 缺少 " + methodName + "(int, int)"
+                    + "(设计 §3.1 T03 要求交付,实现未落地)。");
+        } catch (Exception e) {
+            fail("[cf.rewardv2.e2eExample] 调用 " + targetClass + "." + methodName + " 失败:"
+                    + e.getCause() == null ? e.toString() : e.getCause().toString());
+        }
+        return 0;
+    }
+
+    /** CfConfigKeys 是否已声明值为 keyValue 的静态 String 常量(不绑定 Java 常量名,防命名漂移) */
+    private boolean configKeyDeclared(String configKeysClass, String keyValue) {
+        Class<?> clazz = loadClass(configKeysClass);
+        if (clazz == null) {
+            return false;
+        }
+        try {
+            for (Field f : clazz.getDeclaredFields()) {
+                if (Modifier.isStatic(f.getModifiers()) && f.getType() == String.class) {
+                    f.setAccessible(true);
+                    if (keyValue.equals(f.get(null))) {
+                        return true;
+                    }
+                }
+            }
+        } catch (Exception e) {
+            return false;
+        }
+        return false;
+    }
+
+    /** 目标类是否存在值为 expected 的静态 String 常量 */
+    private boolean constantValueEquals(String targetClass, String expected) {
+        Class<?> clazz = loadClass(targetClass);
+        if (clazz == null) {
+            return false;
+        }
+        try {
+            for (Field f : clazz.getDeclaredFields()) {
+                if (Modifier.isStatic(f.getModifiers()) && f.getType() == String.class) {
+                    f.setAccessible(true);
+                    if (expected.equals(f.get(null))) {
+                        return true;
+                    }
+                }
+            }
+        } catch (Exception e) {
+            return false;
+        }
+        return false;
+    }
+
+    private String readSchemaSql() {
+        try (InputStream is = getClass().getClassLoader().getResourceAsStream("schema.sql")) {
+            if (is == null) {
+                return "";
+            }
+            try (Scanner scanner = new Scanner(is, StandardCharsets.UTF_8.name())) {
+                scanner.useDelimiter("\\A");
+                return scanner.hasNext() ? scanner.next() : "";
+            }
+        } catch (Exception e) {
+            return "";
+        }
+    }
+}

+ 349 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/TeamShareWeightedContractTest.java

@@ -0,0 +1,349 @@
+package com.etotem.cfc.unit;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.InputStream;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Scanner;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * 契约级单测:团队分润池层级瓜分——档位权重加权分配(能力键 {@code cf.teamshare.weightedShare},
+ * 单元 team.share;TDD-RED 阶段,任务 S-cfc-397)。
+ *
+ * <p><b>契约溯源</b>:
+ * <ul>
+ *   <li>需求:{@code docs/superpowers/plans/2026-11-14-cf-reward-model-v2.md} §3 —— 团队分润池
+ *       = 成本 × T%(新通道,用户口径 R2);池内按决策 <b>D2</b>「沿用 referral_tree 层级树 +
+ *       销售档位」瓜分(与直推档位体系一致的瓜分规则);</li>
+ *   <li>设计:{@code docs/superpowers/plans/2026-11-14-cf-reward-model-v2-design.md}
+ *       §5(层级树瓜分算法 {@code distributeTeamPool} 伪代码)、§6 T05(能力键
+ *       {@code cf.teamshare.share.weighted} / remainder / family-skip)、§2.3(cf_team_pool_share 表)、
+ *       §8 用例 #1(数学锚点)/ #9(尾差守恒)。</li>
+ * </ul>
+ *
+ * <p><b>契约范围</b>:「加权瓜分」——池金额按成员档位权重({@code weight = rate_percent},与 F03a
+ * 直推档位同一口径,权重数据源 = {@link com.etotem.cfc.service.CfReferralService#getTeamAnnualPpoints}
+ * + {@code matchDirectSalesTier})比例分配;尾差守恒(最后一人补齐,Σ share_cent == pool_cent,
+ * 金额不蒸发);无档位(totalW ≤ 0)无人可分(池置 unclaimed,不私发)。</p>
+ *
+ * <p><b>数学校验锚点</b>(设计 §8#1,单位:分):池 3000 分(30 元),成员权重 {70, 50},totalW=120:</p>
+ * <pre>
+ *   raw₁ = floor(3000 × 70 / 120) = 1750
+ *   raw₂ = 3000 − 1750 = 1250        // 最后一人补齐(尾差守恒)
+ *   Σ = 3000 == pool_cent ✓(§8#9)
+ * </pre>
+ *
+ * <p><b>宿主契约(TDD-RED 锚点)</b>:{@code com.etotem.cfc.service.CfCommissionService} ——
+ * 设计 §3.1(T04/T05)新增 {@code distributeTeamPool(...)} 入口与常量 {@code RULE_TEAM_POOL = "F03c"};
+ * 以及新实体 {@code CfTeamPoolOrder} / {@code CfTeamPoolShare}(§2.2/§2.3)与 schema.sql 建表
+ * (迁移 463/464)。当前 src/main <b>均未落地</b>(全库 0 引用、schema.sql 无对应建表)——
+ * 本测试通过反射锚定宿主契约,运行时探测缺失即断言失败(红);GREEN 阶段实现方按
+ * 「契约方法签名」落地后转绿。</p>
+ *
+ * <p><b>契约方法签名(实现方按此落地)</b>:
+ * <ul>
+ *   <li>{@code void distributeTeamPool(Long orderId, String orderType, Long buyerUserId,
+ *       Long buyerFamilyId, Integer paidCent, Long productId)}
+ *       —— 层级树瓜分流水入口(§3.1 T05 / §5),内部完成取层级树 → 档位权重 → 加权瓜分 →
+ *       {@code earnByRule(memberId, "F03c", poolId, {amount: raw})} + cf_team_pool_share 幂等落库;
+ *       与 {@code allocateTeamPoolShareByWeight} 分治,使加权算法可独立单测;</li>
+ *   <li>{@code List<Integer> allocateTeamPoolShareByWeight(int[] weights, int poolCent)}
+ *       —— 纯加权瓜分(§5 step 5 算法抽离):返回每人分得(分),长度 = 成员数;
+ *       末位成员吸收尾差保证 Σ = poolCent;权重全 0(totalW ≤ 0,无档位)返回空列表
+ *       (不私发,调用方将池置 unclaimed);</li>
+ *   <li>常量 {@code RULE_TEAM_POOL = "F03c"}(§3.1 cf_earn_rule 新规则码)。</li>
+ * </ul>
+ *
+ * <p><b>权限流</b>:本能力为后端内部结算链路(订单结算 → 团队池瓜分 → CF 发放),无用户权限维度,
+ * 权限流不适用(以说明性用例标注)。</p>
+ *
+ * <p><b>RED 预期</b>:宿主 {@code CfCommissionService} 缺 {@code distributeTeamPool} /
+ * {@code allocateTeamPoolShareByWeight} / {@code RULE_TEAM_POOL},新实体与 schema 建表全部缺失,
+ * 对应用例在反射探测处失败(红)。</p>
+ */
+class TeamShareWeightedContractTest {
+
+    /** 规格设计宿主服务(类已存在,契约方法未落地)。 */
+    private static final String HOST_CLASS = "com.etotem.cfc.service.CfCommissionService";
+
+    /** 规格设计宿主实体(§2.3,T05 新增,未实现)。 */
+    private static final String ENTITY_SHARE = "com.etotem.cfc.entity.CfTeamPoolShare";
+
+    /** 规格设计宿主实体(§2.2,T04 新增,T05 依赖,未实现)。 */
+    private static final String ENTITY_ORDER = "com.etotem.cfc.entity.CfTeamPoolOrder";
+
+    /** 数学校验锚点(§8#1):池 = 30 元 = 3000 分。 */
+    private static final int POOL_CENT = 3000;
+
+    /** 数学校验锚点(§8#1):2 名团队成员档位权重(rate_percent 同 F03a 直推档位)。 */
+    private static final int[] WEIGHTS_70_50 = {70, 50};
+
+    /** 期望份额:3000×70/120 = 1750 分。 */
+    private static final int EXPECT_FIRST_CENT = 1750;
+
+    /** 期望份额(尾差守恒补最后一人):3000 − 1750 = 1250 分。 */
+    private static final int EXPECT_LAST_CENT = 1250;
+
+    // ==================== 正常流:加权瓜分数学校验(§8#1 / §8#9) ====================
+
+    @Test
+    void 正常流_加权瓜分_规格数学锚点_3000分与70和50权重() {
+        Object host = contractHost();
+        // 数学锚点:池 3000 分、权重 {70,50}、totalW=120 → 1750 / 1250(末位补齐尾差)
+        List<Integer> shares = callListInteger(host, "allocateTeamPoolShareByWeight",
+                WEIGHTS_70_50, POOL_CENT);
+        assertNotNullOrEmpty(shares, "应返回 2 名成员各自分得份额");
+        assertEquals(2, shares.size(), "2 名成员");
+        assertEquals(Integer.valueOf(EXPECT_FIRST_CENT), shares.get(0),
+                "成员1 应得 3000×70/120 = 1750 分(§8#1)");
+        assertEquals(Integer.valueOf(EXPECT_LAST_CENT), shares.get(1),
+                "成员2(末位)应得 3000−1750 = 1250 分,补齐尾差(§8#1/#9)");
+    }
+
+    @Test
+    void 正常流_加权瓜分_尾差守恒_任意权重组合份额之和恒等于池() {
+        Object host = contractHost();
+        assertConserved(host, new int[]{70, 50});
+        assertConserved(host, new int[]{33, 33, 34});
+        assertConserved(host, new int[]{80, 15, 5});
+        assertConserved(host, new int[]{100});
+        assertConserved(host, new int[]{12, 30, 58});
+        assertConserved(host, new int[]{25, 25, 25, 25});
+    }
+
+    @Test
+    void 正常流_加权瓜分_单人持有_全池归一人() {
+        Object host = contractHost();
+        List<Integer> shares = callListInteger(host, "allocateTeamPoolShareByWeight",
+                new int[]{100}, POOL_CENT);
+        assertNotNullOrEmpty(shares, "单人成员应返回 1 条份额");
+        assertEquals(Integer.valueOf(POOL_CENT), shares.get(0),
+                "唯一成员权重 100 → 全池 3000 分归其一人");
+    }
+
+    // ==================== 边界流:无档位(totalW ≤ 0)→ 无人可分 ====================
+
+    @Test
+    void 边界流_无档位零权重_无人可分不私发() {
+        Object host = contractHost();
+        // §5 step 4/5:totalW ≤ 0 → 无成员可分 → 池置 unclaimed(不私发);纯函数返回空列表
+        List<Integer> shares = callListInteger(host, "allocateTeamPoolShareByWeight",
+                new int[]{0, 0}, POOL_CENT);
+        assertTrue(shares.isEmpty(),
+                "权重全 0(无档位)→ 返回空列表,调用方将池置 unclaimed(不私发,§5)");
+    }
+
+    // ==================== 正常流(结构契约):宿主方法 / 常量应存在 ====================
+
+    @Test
+    void 宿主入口_distributeTeamPool_应存在() {
+        Object host = contractHost();
+        boolean hasMethod = false;
+        for (Method m : host.getClass().getDeclaredMethods()) {
+            if ("distributeTeamPool".equals(m.getName())) {
+                hasMethod = true;
+                break;
+            }
+        }
+        assertTrue(hasMethod,
+                "RED[cf.teamshare.weightedShare] CfCommissionService 应提供 distributeTeamPool(...) "
+                        + "层级树瓜分入口(设计 §3.1 T05 / §5)。实现未落地。");
+    }
+
+    @Test
+    void 宿主入口_allocateTeamPoolShareByWeight_应存在() {
+        Object host = contractHost();
+        // 直接调用:方法缺失即 fail(RED 信号更清晰)
+        callListInteger(host, "allocateTeamPoolShareByWeight", new int[]{1}, 1);
+    }
+
+    @Test
+    void 宿主常量_RULE_TEAM_POOL_应为F03c() {
+        Object value = staticFieldValue(HOST_CLASS, "RULE_TEAM_POOL");
+        assertEquals("F03c", String.valueOf(value),
+                "RED[cf.teamshare.weightedShare] RULE_TEAM_POOL 应为 \"F03c\"(cf_earn_rule 团队分润池"
+                        + " 规则码,§3.1)。实现未落地。");
+    }
+
+    // ==================== 正常流(结构契约):新实体应存在(§2.2 / §2.3) ====================
+
+    @Test
+    void 实体_CfTeamPoolShare_字段契约() {
+        String[] fields = {"poolId", "memberId", "userId", "layer", "ratePercent",
+                "weight", "shareCent", "status"};
+        assertEntityFields(ENTITY_SHARE, fields,
+                "cf_team_pool_share 成员瓜分明细(§2.3):weight 为档位权重(=rate_percent,0=无档位跳过),"
+                        + "shareCent 为分得金额(分)。实现未落地。");
+    }
+
+    @Test
+    void 实体_CfTeamPoolOrder_状态承载() {
+        String[] fields = {"orderId", "orderType", "poolCent", "tBps", "configScope", "status"};
+        assertEntityFields(ENTITY_ORDER, fields,
+                "cf_team_pool_order 团队池整单(§2.2):status 承载 pooled/share_issued/unclaimed 生命周期"
+                        + "(§5:建池 pooled → 瓜分 share_issued / 无成员可瓜分 unclaimed)。实现未落地。");
+    }
+
+    // ==================== 正常流(结构契约):schema.sql 应落地建表 + 唯一键 ====================
+
+    @Test
+    void schema_cf_team_pool_share_建表与uk_pool_member唯一键() {
+        String schema = readSchemaSql();
+        assertTrue(schema.contains("cf_team_pool_share"),
+                "RED[cf.teamshare.weightedShare] schema.sql 缺少 cf_team_pool_share 建表(§2.3,"
+                        + "迁移464)。实现未落地。");
+        assertTrue(schema.contains("uk_pool_member"),
+                "RED[cf.teamshare.weightedShare] cf_team_pool_share 应含 uk_pool_member 唯一键"
+                        + " `(pool_id, member_id)`,保证重复结算不重复瓜分(§2.3 / §1.5 三层兜底)。实现未落地。");
+    }
+
+    @Test
+    void schema_cf_team_pool_order_建表与uk_order唯一键() {
+        String schema = readSchemaSql();
+        assertTrue(schema.contains("cf_team_pool_order"),
+                "RED[cf.teamshare.weightedShare] schema.sql 缺少 cf_team_pool_order 建表(§2.2,"
+                        + "迁移463)。实现未落地。");
+        assertTrue(schema.contains("uk_order"),
+                "RED[cf.teamshare.weightedShare] cf_team_pool_order 应含 uk_order 唯一键"
+                        + " `(order_type, order_id)`(建池幂等,§2.2)。实现未落地。");
+    }
+
+    // ==================== 权限流(不适用):后端内部结算链路 ====================
+
+    @Test
+    void 权限流_不适用() {
+        // 契约 AC(§8#1/#9)为「订单结算 → 团队池加权瓜分 → F03c CF 发放」内部链路,无用户权限断言维度。
+        assertTrue(true, "权限流不适用:cf.teamshare.weightedShare 为后端内部结算链路,无用户权限维度。");
+    }
+
+    // ==================== 断言辅助 ====================
+
+    private void assertConserved(Object host, int[] weights) {
+        List<Integer> shares = callListInteger(host, "allocateTeamPoolShareByWeight", weights, POOL_CENT);
+        assertNotNullOrEmpty(shares, "每次瓜分都应返回份额数组");
+        long sum = 0;
+        for (Integer s : shares) {
+            if (s != null) sum += s;
+        }
+        assertEquals(POOL_CENT, sum,
+                "尾差守恒(§8#9):Σ 份额必须恒 = 池金额 " + POOL_CENT
+                        + " 分,最后一人补齐,无金额蒸发");
+        assertEquals(weights.length, shares.size(), "份额数量 = 成员数");
+    }
+
+    private static void assertNotNullOrEmpty(List<Integer> list, String msg) {
+        if (list == null) {
+            fail(msg);
+        }
+    }
+
+    // ==================== 反射辅助(锚定宿主契约,避免编译期依赖不存在类) ====================
+
+    /** 加载宿主服务;宿主类不可实例化即断言失败(红,暴露实现未落地)。 */
+    private Object contractHost() {
+        try {
+            Class<?> clazz = Class.forName(HOST_CLASS);
+            return clazz.getDeclaredConstructor().newInstance();
+        } catch (ClassNotFoundException e) {
+            fail("RED[cf.teamshare.weightedShare] 契约宿主 CfCommissionService 未实现:" + e.getMessage());
+            throw new IllegalStateException("unreachable");
+        } catch (Exception e) {
+            fail("契约宿主 CfCommissionService 实例化失败:" + e.getMessage());
+            throw new IllegalStateException("unreachable");
+        }
+    }
+
+    /** 按方法名 + 参数个数匹配并调用(宽松适配基本/包装类型),契约方法缺失即断言失败(红)。 */
+    private Object call(Object host, String method, Object... args) {
+        for (Method m : host.getClass().getMethods()) {
+            if (m.getName().equals(method) && m.getParameterCount() == args.length) {
+                try {
+                    return m.invoke(host, args);
+                } catch (Exception e) {
+                    fail("契约方法 " + HOST_CLASS + "#" + method + " 调用失败:" + e.getMessage());
+                    throw new IllegalStateException("unreachable");
+                }
+            }
+        }
+        fail("RED[cf.teamshare.weightedShare] 契约方法 " + HOST_CLASS + "#" + method + " 未实现"
+                + "(设计 §5 加权瓜分 / §3.1 T05)。实现未落地。");
+        throw new IllegalStateException("unreachable");
+    }
+
+    @SuppressWarnings("unchecked")
+    private List<Integer> callListInteger(Object host, String method, Object... args) {
+        Object r = call(host, method, args);
+        if (r instanceof List) {
+            return (List<Integer>) r;
+        }
+        fail("契约方法 " + method + " 应返回 List,实际 " + r);
+        throw new IllegalStateException("unreachable");
+    }
+
+    private void assertEntityFields(String className, String[] fields, String reason) {
+        Class<?> clazz = loadClass(className);
+        if (clazz == null) {
+            fail("RED[cf.teamshare.weightedShare] 契约实体 " + className + " 不存在:" + reason);
+        }
+        for (String field : fields) {
+            boolean found = false;
+            for (Field f : clazz.getDeclaredFields()) {
+                if (field.equals(f.getName())) {
+                    found = true;
+                    break;
+                }
+            }
+            assertTrue(found,
+                    "RED[cf.teamshare.weightedShare] 契约实体 " + className + " 应含字段 " + field + ":" + reason);
+        }
+    }
+
+    /** 读取宿主静态常量字段;类或字段缺失即断言失败(红)。 */
+    private Object staticFieldValue(String className, String fieldName) {
+        Class<?> clazz = loadClass(className);
+        if (clazz == null) {
+            fail("RED[cf.teamshare.weightedShare] 宿主类 " + className + " 未实现:" + fieldName);
+        }
+        try {
+            Field f = clazz.getDeclaredField(fieldName);
+            f.setAccessible(true);
+            return f.get(null);
+        } catch (NoSuchFieldException e) {
+            fail("RED[cf.teamshare.weightedShare] 契约常量 " + className + "#" + fieldName + " 未实现"
+                    + "(§3.1 RULE_TEAM_POOL)。实现未落地。");
+            throw new IllegalStateException("unreachable");
+        } catch (Exception e) {
+            fail("读取常量 " + className + "#" + fieldName + " 失败:" + e.getMessage());
+            throw new IllegalStateException("unreachable");
+        }
+    }
+
+    private Class<?> loadClass(String name) {
+        try {
+            return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
+        } catch (ClassNotFoundException e) {
+            return null;
+        }
+    }
+
+    private String readSchemaSql() {
+        try (InputStream is = getClass().getClassLoader().getResourceAsStream("schema.sql")) {
+            if (is == null) {
+                return "";
+            }
+            try (Scanner scanner = new Scanner(is, StandardCharsets.UTF_8.name())) {
+                scanner.useDelimiter("\\A");
+                return scanner.hasNext() ? scanner.next() : "";
+            }
+        } catch (Exception e) {
+            return "";
+        }
+    }
+}

+ 11 - 0
cfc-frontend/pages.json

@@ -2045,6 +2045,17 @@
           }
         }
       ]
+    },
+    {
+      "root": "pages/coupon",
+      "pages": [
+        {
+          "path": "share-claim",
+          "style": {
+            "navigationBarTitleText": "好友送你一张会员券"
+          }
+        }
+      ]
     }
   ],
   "globalStyle": {

+ 375 - 0
cfc-frontend/pages/coupon/share-claim.vue

@@ -0,0 +1,375 @@
+<template>
+  <view class="page" :style="{ '--font-scale': fontScale }">
+    <!-- 登录浮层(全局 login-sheet 组件,mixin 提供 openLoginSheet) -->
+    <login-sheet ref="loginSheet" @success="onSheetLoginSuccess" />
+
+    <view v-if="loading" class="state-box">
+      <text class="state-text">加载中...</text>
+    </view>
+
+    <block v-else>
+      <!-- 标题:正常态 / 失效态 -->
+      <view class="hero">
+        <text class="hero-emoji">🎁</text>
+        <text class="hero-text">{{ isInvalid ? '分享已失效' : '好友送你一张会员券' }}</text>
+      </view>
+
+      <!-- 券卡片(token 无效无 detail,不渲染卡片) -->
+      <view v-if="detail" class="coupon-card" :class="isInvalid ? 'coupon-card-disabled' : ''">
+        <view class="card-left">
+          <text class="card-value">{{ formatValue(detail) }}</text>
+          <text class="card-type-label">{{ typeLabel(detail.couponType) }}</text>
+        </view>
+        <view class="card-right">
+          <text class="card-name">{{ detail.couponName }}</text>
+          <text class="card-condition">{{ conditionText(detail.minSpend) }}</text>
+          <text class="card-scope">会员专享</text>
+          <text class="card-expiry">有效期至 {{ formatDate(detail.validUntil) }}</text>
+        </view>
+      </view>
+
+      <!-- 赠送人信息(正常态展示) -->
+      <view v-if="!isInvalid && detail && detail.giverNickname" class="giver-row">
+        <image v-if="detail.giverAvatar" class="giver-avatar" :src="detail.giverAvatar" mode="aspectFill"></image>
+        <view v-else class="giver-avatar giver-avatar-default">{{ giverInitial }}</view>
+        <text class="giver-name">赠送人:{{ detail.giverNickname }}</text>
+      </view>
+
+      <!-- 正常态:确认领取 -->
+      <view v-if="!isInvalid" class="action-area">
+        <button class="claim-btn" :disabled="claiming" @click="onConfirmClaim">{{ claiming ? '领取中...' : '确认领取' }}</button>
+        <text class="claim-tip">领取后可用于购买会员</text>
+      </view>
+
+      <!-- 失效态:提示 + 知道了 -->
+      <view v-else class="action-area">
+        <text class="invalid-tip">⚠ {{ invalidText }}</text>
+        <button class="know-btn" @click="onKnow">知道了</button>
+      </view>
+    </block>
+  </view>
+</template>
+
+<script>
+import { getCouponShareDetail, claimCouponShare } from '../../utils/api.js'
+import { parseDate } from '../../utils/format.js'
+import fontScaleMixin from '@/mixins/font-scale.js'
+
+export default {
+  mixins: [fontScaleMixin],
+  data() {
+    return {
+      shareToken: '',
+      loading: true,
+      detail: null,
+      loadError: '',
+      claimError: '',
+      claiming: false
+    }
+  },
+  computed: {
+    isInvalid: function() {
+      if (this.loading) return false
+      if (this.loadError || this.claimError) return true
+      if (!this.detail) return true
+      if (this.detail.status !== 'PENDING') return true
+      if (this.detail.claimable !== true) return true
+      return false
+    },
+    invalidText: function() {
+      if (this.loadError) return this.loadError
+      if (this.claimError) return this.claimError
+      if (!this.detail) return '分享不存在或已失效'
+      var status = this.detail.status || ''
+      if (status === 'CLAIMED') return '该分享已被领取'
+      if (status === 'REVOKED') return '该分享已撤回'
+      if (status === 'EXPIRED') return '该分享已过期'
+      if (this.detail.claimable !== true) return '优惠券已失效'
+      return '分享不存在或已失效'
+    },
+    giverInitial: function() {
+      var name = this.detail && this.detail.giverNickname
+      if (!name) return '友'
+      return name.substring(0, 1)
+    }
+  },
+  onLoad(options) {
+    this.shareToken = (options && options.shareToken) || ''
+    this.loadDetail()
+  },
+  methods: {
+    loadDetail() {
+      var self = this
+      if (!this.shareToken) {
+        this.loadError = '分享不存在或已失效'
+        this.loading = false
+        return
+      }
+      this.loading = true
+      this.loadError = ''
+      this.claimError = ''
+      getCouponShareDetail(this.shareToken).then(function(res) {
+        self.detail = (res && res.data) || null
+      }).catch(function(e) {
+        self.loadError = (e && e.message) || '分享不存在或已失效'
+      }).then(function() {
+        self.loading = false
+      })
+    },
+    onConfirmClaim() {
+      if (this.claiming || this.isInvalid) return
+      // 未登录先弹登录浮层,登录成功后经 onLoginSuccess 自动继续领取
+      if (!uni.getStorageSync('token')) {
+        var self = this
+        this.openLoginSheet({ onSuccess: function() { self.doClaim() } })
+        return
+      }
+      this.doClaim()
+    },
+    // 登录浮层登录成功回调(login-sheet mixin onSheetLoginSuccess 调用)
+    onLoginSuccess() {
+      this.doClaim()
+    },
+    doClaim() {
+      var self = this
+      if (this.claiming || !this.shareToken) return
+      this.claiming = true
+      claimCouponShare(this.shareToken).then(function(res) {
+        if (res && res.code === 200) {
+          uni.showToast({ title: '领取成功', icon: 'success' })
+          setTimeout(function() {
+            uni.redirectTo({ url: '/pages/profile-extra/coupons' })
+          }, 1200)
+        } else {
+          self.claimError = (res && res.message) || '领取失败'
+        }
+      }).catch(function(e) {
+        self.claimError = (e && e.message) || '领取失败'
+      }).then(function() {
+        self.claiming = false
+      })
+    },
+    onKnow() {
+      var pages = getCurrentPages()
+      if (pages.length > 1) {
+        uni.navigateBack({ delta: 1 })
+      } else {
+        uni.switchTab({ url: '/pages/index-home/index' })
+      }
+    },
+    formatValue(detail) {
+      var type = detail.couponType
+      var value = detail.couponValue
+      if (type === 'DISCOUNT' || type === 'PERCENT') {
+        return (value ? (value / 100).toFixed(1) : '9.0') + '折'
+      }
+      return '¥' + (value ? (value / 100).toFixed(2) : '0.00')
+    },
+    typeLabel(type) {
+      if (type === 'FIXED') return '满减券'
+      if (type === 'DISCOUNT' || type === 'PERCENT') return '折扣券'
+      if (type === 'CASH') return '无门槛券'
+      return '会员券'
+    },
+    conditionText(minSpend) {
+      if (!minSpend || minSpend <= 0) return '无门槛'
+      return '满' + (minSpend / 100).toFixed(2) + '元可用'
+    },
+    formatDate(date) {
+      if (!date) return '长期有效'
+      var d = parseDate(date)
+      if (!d) return String(date)
+      var y = d.getFullYear()
+      var m = String(d.getMonth() + 1).padStart(2, '0')
+      var day = String(d.getDate()).padStart(2, '0')
+      return y + '.' + m + '.' + day
+    }
+  }
+}
+</script>
+
+<style scoped lang="scss">
+.page {
+  min-height: 100vh;
+  background: $facade-fill-2;
+  padding: 40rpx $uni-space-page;
+  box-sizing: border-box;
+}
+
+/* ===== 加载态 ===== */
+.state-box {
+  display: flex;
+  justify-content: center;
+  padding-top: 240rpx;
+}
+.state-text {
+  font-size: calc(28rpx * var(--font-scale, 1));
+  color: $facade-text-muted;
+}
+
+/* ===== 标题 ===== */
+.hero {
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  margin: 24rpx 0 40rpx;
+}
+.hero-emoji {
+  font-size: calc(40rpx * var(--font-scale, 1));
+  margin-right: 12rpx;
+}
+.hero-text {
+  font-size: calc(40rpx * var(--font-scale, 1));
+  font-weight: bold;
+  color: $facade-text-strong;
+}
+
+/* ===== 券卡片 ===== */
+.coupon-card {
+  display: flex;
+  background: $app-surface;
+  border-radius: 16rpx;
+  margin-bottom: 24rpx;
+  overflow: hidden;
+  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
+}
+.coupon-card-disabled {
+  opacity: 0.55;
+}
+.card-left {
+  width: 220rpx;
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  justify-content: center;
+  background: linear-gradient(135deg, $brand-primary, $brand-primary-light);
+  padding: $uni-space-lg 12rpx;
+  flex-shrink: 0;
+}
+.coupon-card-disabled .card-left {
+  background: #c0c0c0;
+}
+.card-value {
+  font-size: calc(44rpx * var(--font-scale, 1));
+  font-weight: bold;
+  color: $app-surface;
+}
+.card-type-label {
+  font-size: calc(20rpx * var(--font-scale, 1));
+  color: rgba(255, 255, 255, 0.85);
+  margin-top: 8rpx;
+}
+.card-right {
+  flex: 1;
+  padding: 28rpx 24rpx;
+  display: flex;
+  flex-direction: column;
+}
+.card-name {
+  font-size: calc(30rpx * var(--font-scale, 1));
+  font-weight: 600;
+  color: $facade-text-strong;
+  display: block;
+  margin-bottom: 10rpx;
+  overflow: hidden;
+  text-overflow: ellipsis;
+  white-space: nowrap;
+}
+.card-condition {
+  font-size: calc(24rpx * var(--font-scale, 1));
+  color: $brand-primary;
+  display: block;
+  margin-bottom: 8rpx;
+}
+.card-scope {
+  font-size: calc(22rpx * var(--font-scale, 1));
+  color: $uni-info;
+  background: $tint-sky-ghost;
+  display: inline-block;
+  padding: 2rpx 12rpx;
+  border-radius: 8rpx;
+  margin-bottom: 8rpx;
+  align-self: flex-start;
+}
+.card-expiry {
+  font-size: calc(22rpx * var(--font-scale, 1));
+  color: $facade-text-ghost-light;
+  display: block;
+}
+
+/* ===== 赠送人 ===== */
+.giver-row {
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  margin: 8rpx 0 32rpx;
+}
+.giver-avatar {
+  width: 64rpx;
+  height: 64rpx;
+  border-radius: 50%;
+  margin-right: 16rpx;
+  background: $brand-primary-light-2;
+}
+.giver-avatar-default {
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  color: $app-surface;
+  font-size: calc(30rpx * var(--font-scale, 1));
+}
+.giver-name {
+  font-size: calc(28rpx * var(--font-scale, 1));
+  color: $facade-text-strong;
+}
+
+/* ===== 操作区 ===== */
+.action-area {
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  margin-top: 32rpx;
+}
+.claim-btn {
+  width: 100%;
+  height: 88rpx;
+  line-height: 88rpx;
+  border-radius: 44rpx;
+  background: linear-gradient(135deg, $brand-primary, $brand-primary-light);
+  color: $app-surface;
+  font-size: calc(32rpx * var(--font-scale, 1));
+  font-weight: 600;
+  border: none;
+}
+.claim-btn::after {
+  border: none;
+}
+.claim-btn[disabled] {
+  opacity: 0.7;
+}
+.claim-tip {
+  font-size: calc(22rpx * var(--font-scale, 1));
+  color: $facade-text-muted;
+  margin-top: 20rpx;
+}
+.invalid-tip {
+  font-size: calc(26rpx * var(--font-scale, 1));
+  color: $status-danger-2;
+  display: block;
+  margin-bottom: 32rpx;
+  text-align: center;
+}
+.know-btn {
+  width: 100%;
+  height: 88rpx;
+  line-height: 88rpx;
+  border-radius: 44rpx;
+  background: $facade-fill;
+  color: $facade-text-strong;
+  font-size: calc(32rpx * var(--font-scale, 1));
+  border: none;
+}
+.know-btn::after {
+  border: none;
+}
+</style>

+ 75 - 5
cfc-frontend/pages/membership/gift-coupon.vue

@@ -65,7 +65,7 @@
     </scroll-view>
 
     <!-- 赠送记录 -->
-    <scroll-view v-else scroll-y class="content" refresher-enabled
+    <scroll-view v-else-if="activeTab === 1" scroll-y class="content" refresher-enabled
       :refresher-triggered="refreshing" @refresherrefresh="onRefresh">
       <view v-if="sentList.length === 0" class="empty-state">
         <text class="empty-icon">🎁</text>
@@ -84,6 +84,26 @@
         <button v-if="item.status === 'GIFTED'" class="revoke-btn" @click="doRevoke(item)">撤回</button>
       </view>
     </scroll-view>
+
+    <!-- 分享记录(P1-2,分享转赠通道) -->
+    <scroll-view v-else scroll-y class="content" refresher-enabled
+      :refresher-triggered="refreshing" @refresherrefresh="onRefresh">
+      <view v-if="shareList.length === 0" class="empty-state">
+        <text class="empty-icon">🎁</text>
+        <text class="empty-text">还没有分享记录</text>
+      </view>
+      <view v-for="item in shareList" :key="item.shareToken" class="sent-item">
+        <view class="sent-row">
+          <text class="sent-name">{{ item.couponName }}</text>
+          <text class="sent-status" :class="'sh-' + item.status">{{ shareStatusLabel(item.status) }}</text>
+        </view>
+        <view class="sent-row sub">
+          <text>有效期至 {{ formatDate(item.expireAt) }}</text>
+          <text v-if="item.status === 'CLAIMED' && item.claimNickname">由 {{ item.claimNickname }} 领取</text>
+        </view>
+        <button v-if="item.status === 'PENDING'" class="revoke-btn" @click="doRevokeShare(item)">撤回</button>
+      </view>
+    </scroll-view>
   </view>
 </template>
 
@@ -93,13 +113,16 @@ import {
   getGiftableCoupons,
   giftCoupon,
   revokeGiftCoupon,
-  getSentGifts
+  getSentGifts,
+  getCouponShareList,
+  revokeCouponShare
 } from '../../utils/api.js'
+import { parseDate } from '../../utils/format.js'
 
 export default {
   data() {
     return {
-      tabs: [{ name: '赠送会员券' }, { name: '赠送记录' }],
+      tabs: [{ name: '赠送会员券' }, { name: '赠送记录' }, { name: '分享记录' }],
       activeTab: 0,
       recipients: [],
       coupons: [],
@@ -108,6 +131,7 @@ export default {
       remark: '',
       sending: false,
       sentList: [],
+      shareList: [],
       refreshing: false
     }
   },
@@ -138,6 +162,7 @@ export default {
         self.refreshing = false
       })
       self.loadSent()
+      self.loadShares()
     },
     loadSent: function() {
       var self = this
@@ -147,11 +172,22 @@ export default {
         console.error('加载赠送记录失败', e)
       })
     },
+    loadShares: function() {
+      var self = this
+      getCouponShareList().then(function(res) {
+        self.shareList = (res && res.data) || []
+      }).catch(function(e) {
+        console.error('加载分享记录失败', e)
+      })
+    },
     onRefresh: function() {
       this.loadAll()
     },
     switchTab: function(idx) {
       this.activeTab = idx
+      if (idx === 2) {
+        this.loadShares()
+      }
     },
     pickRecipient: function(r) {
       this.selectedRecipient = r
@@ -201,6 +237,36 @@ export default {
         }
       })
     },
+    // 撤回分享(仅 PENDING 态):分享记录 tab
+    doRevokeShare: function(item) {
+      var self = this
+      uni.showModal({
+        title: '撤回分享',
+        content: '确定撤回「' + item.couponName + '」的分享吗?撤回后好友将无法领取。',
+        success: function(m) {
+          if (!m.confirm) return
+          revokeCouponShare(item.shareToken).then(function(res) {
+            if (res && res.code === 200) {
+              uni.showToast({ title: '已撤回', icon: 'success' })
+              self.loadShares()
+            } else {
+              uni.showToast({ title: (res && res.message) || '撤回失败', icon: 'none' })
+            }
+          }).catch(function(e) {
+            uni.showToast({ title: (e && e.message) || '撤回失败', icon: 'none' })
+            console.error(e)
+          })
+        }
+      })
+    },
+    // 分享记录状态文案(PENDING/CLAIMED/REVOKED/EXPIRED)
+    shareStatusLabel: function(status) {
+      if (status === 'PENDING') return '待领取'
+      if (status === 'CLAIMED') return '已领取'
+      if (status === 'REVOKED') return '已撤回'
+      if (status === 'EXPIRED') return '已过期'
+      return status || ''
+    },
     formatValue: function(c) {
       if (c.type === 'DISCOUNT') {
         return (c.discountRate ? (c.discountRate / 100).toFixed(1) : '9.0') + '折'
@@ -218,8 +284,8 @@ export default {
     },
     formatDate: function(d) {
       if (!d) return '长期有效'
-      var dt = new Date(d)
-      if (isNaN(dt.getTime())) return String(d)
+      var dt = parseDate(d)
+      if (!dt) return String(d)
       var m = dt.getMonth() + 1
       var day = dt.getDate()
       return dt.getFullYear() + '-' + (m < 10 ? '0' + m : m) + '-' + (day < 10 ? '0' + day : day)
@@ -433,6 +499,10 @@ export default {
 .st-GIFTED { color: #ff6b35; }
 .st-USED { color: #999; }
 .st-REVOKED { color: #bbb; }
+.sh-PENDING { color: #ff6b35; }
+.sh-CLAIMED { color: #52c41a; }
+.sh-REVOKED { color: #bbb; }
+.sh-EXPIRED { color: #bbb; }
 .sent-remark {
   font-size: 24rpx;
   color: #888;

+ 74 - 2
cfc-frontend/pages/profile-extra/coupons.vue

@@ -81,6 +81,8 @@
             <view v-if="tabIndex === 0 && (!coupon.status || coupon.status === 'AVAILABLE')" class="coupon-actions">
               <button class="use-btn" @click="useCoupon(coupon)">使用</button>
               <button class="gift-btn" @click="giftCoupon(coupon)">转赠</button>
+              <button v-if="shareTokenMap[coupon.id]" class="share-btn" open-type="share" @tap="setShareTarget(coupon)">发送给好友</button>
+              <button v-else class="share-btn" @click="prepareShare(coupon)">分享</button>
             </view>
           </view>
         </view>
@@ -90,7 +92,7 @@
 </template>
 
 <script>
-import { getMyCoupons, getExchangeableCoupons, exchangeCouponByCf, getMyMembership, productDetail } from '../../utils/api.js'
+import { getMyCoupons, getExchangeableCoupons, exchangeCouponByCf, getMyMembership, productDetail, createCouponShare } from '../../utils/api.js'
 import { parseDate } from '../../utils/format.js'
 import fontScaleMixin from '@/mixins/font-scale.js'
 
@@ -109,7 +111,9 @@ export default {
       exchangeableList: [],
       loading: false,
       refreshing: false,
-      isMember: false
+      isMember: false,
+      shareTokenMap: {},
+      shareTarget: null
     }
   },
   computed: {
@@ -151,6 +155,26 @@ export default {
     this.loadCoupons()
     this.loadExchangeable()
   },
+  // 分享转赠(两段式):shareToken 预备在 shareTokenMap 后,onShareAppMessage 同步返回带 token 的 path
+  onShareAppMessage() {
+    var target = this.shareTarget
+    var token = ''
+    if (target && target.id) {
+      token = this.shareTokenMap[target.id] || ''
+    }
+    if (token) {
+      return {
+        title: '送你一张「' + target.name + '」会员券,快来领取',
+        path: '/pages/coupon/share-claim?shareToken=' + token,
+        imageUrl: ''
+      }
+    }
+    return {
+      title: '我有一张会员券想送给你,快来领取!',
+      path: '/pages/profile-extra/coupons',
+      imageUrl: ''
+    }
+  },
   methods: {
     async loadCoupons() {
       this.loading = true
@@ -277,6 +301,34 @@ export default {
     giftCoupon(coupon) {
       uni.navigateTo({ url: '/pages/membership/gift-coupon' })
     },
+    // 分享转赠第一步:点「分享」→ 异步 create 拿 token(幂等:已有 PENDING 返回同一 token)→ 切换为「发送给好友」
+    prepareShare(coupon) {
+      var self = this
+      if (this.shareTokenMap[coupon.id]) {
+        this.shareTarget = coupon
+        return
+      }
+      uni.showLoading({ title: '生成中...' })
+      createCouponShare(coupon.id).then(function(res) {
+        if (res && res.code === 200 && res.data && res.data.shareToken) {
+          var map = Object.assign({}, self.shareTokenMap)
+          map[coupon.id] = res.data.shareToken
+          self.shareTokenMap = map
+          self.shareTarget = coupon
+        } else {
+          uni.showToast({ title: (res && res.message) || '分享失败', icon: 'none' })
+        }
+      }).catch(function(e) {
+        uni.showToast({ title: (e && e.message) || '分享失败,请重试', icon: 'none' })
+        console.error('创建分享失败', e)
+      }).then(function() {
+        uni.hideLoading()
+      })
+    },
+    // 分享转赠第二步:点击「发送给好友」(open-type=share)时记录当前分享目标,供 onShareAppMessage 取 token
+    setShareTarget(coupon) {
+      this.shareTarget = coupon
+    },
     getConditionText(minSpend) {
       if (!minSpend || minSpend <= 0) return '无门槛'
       return '满' + (minSpend / 100).toFixed(2) + '元可用'
@@ -618,6 +670,26 @@ export default {
   opacity: 0.85;
 }
 
+.share-btn {
+  background: $app-surface;
+  color: $brand-primary;
+  font-size: calc(24rpx * var(--font-scale, 1));
+  padding: 10rpx 24rpx;
+  border-radius: 24rpx;
+  border: 2rpx solid $brand-primary-light-2;
+  line-height: 1.4;
+  height: auto;
+  margin: 0;
+}
+
+.share-btn::after {
+  border: none;
+}
+
+.share-btn:active {
+  opacity: 0.85;
+}
+
 .gift-entry {
   display: flex;
   align-items: center;

+ 17 - 0
cfc-frontend/utils/api.js

@@ -2730,6 +2730,23 @@ export const getSentGifts = () => {
   return request('/api/coupon/gift/sent', 'POST', {})
 }
 
+// ===== 会员券分享转赠(ARCH-CFC-COUPON-SHARE-GIFT-001 §5,契约登记见 API_REFERENCE §4.32) =====
+export const createCouponShare = (familyCouponId) => {
+  return request('/api/coupon/gift/share/create', 'POST', { familyCouponId })
+}
+export const getCouponShareDetail = (shareToken) => {
+  return request('/api/coupon/gift/share/detail', 'POST', { shareToken })
+}
+export const claimCouponShare = (shareToken) => {
+  return request('/api/coupon/gift/share/claim', 'POST', { shareToken })
+}
+export const revokeCouponShare = (shareToken) => {
+  return request('/api/coupon/gift/share/revoke', 'POST', { shareToken })
+}
+export const getCouponShareList = () => {
+  return request('/api/coupon/gift/share/list', 'POST', {})
+}
+
 // ===== 新手任务(Onboarding Rewards) =====
 export const getOnboardingProgress = () => {
   return request('/api/onboarding/progress', 'POST')

+ 1 - 1
cfc-web/.last_build_commit

@@ -1 +1 @@
-16a11928e7f9e04a57b05779614ce84abc918e0a
+67249758744dfe6fbf302387bd1c5a860b5b159c

+ 2 - 2
cfc-web/package-lock.json

@@ -1,12 +1,12 @@
 {
   "name": "cfc-web",
-  "version": "1.0.2538",
+  "version": "1.0.2547",
   "lockfileVersion": 3,
   "requires": true,
   "packages": {
     "": {
       "name": "cfc-web",
-      "version": "1.0.2538",
+      "version": "1.0.2547",
       "dependencies": {
         "@wangeditor/editor": "^5.1.23",
         "@wangeditor/editor-for-vue": "^1.0.2",

+ 1 - 1
cfc-web/package.json

@@ -1,6 +1,6 @@
 {
   "name": "cfc-web",
-  "version": "1.0.2539",
+  "version": "1.0.2548",
   "private": true,
   "scripts": {
     "dev": "vue-cli-service serve",

+ 120 - 0
cfc-web/public/CHANGELOG-v1.0.md

@@ -4,6 +4,126 @@
 
 ---
 
+## v1.0.2548 (2026-11-15)
+
+### 文档
+- 研发负责人第188轮闭环汇报 2026-11-16 02:26(自动化142轮)
+
+### 新功能
+- 优惠券分享转赠 T02 后端接口+契约单测(commitTransfer 抽取 + CouponShareService + Controller 5 端点 + JwtInterceptor 放行)
+
+
+## v1.0.2547 (2026-11-15)
+
+### 新功能
+- 优惠券分享转赠 T03 前端——share-claim 落地页+券列表分享入口+分享记录tab
+
+
+## v1.0.2546 (2026-11-15)
+
+### 测试
+- 增量复验 a1aa51d19 优惠券T01数据层 77例68过(仅AdminDataMigration 8F与主窗一致,非新增回归)
+- 后端全量首次实跑 510类/4469例92.12%(真实红17=存量16+P0守卫1) + 越权pin转断言(SC-X-19 403/14-14绿) + 三节点浏览器33过2跳 + R223台账24TC回收
+
+
+## v1.0.2545 (2026-11-15)
+
+### 新功能
+- 优惠券分享转赠 T01 数据层——coupon_share 表(迁移494)+coupon_gift_transfer 扩展列(迁移495)
+
+
+## v1.0.2544 (2026-11-15)
+
+### 文档
+- 研发负责人第187轮闭环汇报 2026-11-16 0055
+- 用户115高尿酸 食材推荐指数-50 + 健康方案/任务(含后续修正)执行记录
+
+
+## v1.0.2543 (2026-11-15)
+
+### Bug 修复
+- 切换家庭时迁移成员任务并刷新新旧家庭食材总览
+- 家庭成员可见列表的成员身份键改为 family_members.id
+
+### 其他
+- 也未刷新新旧家庭食材总览(T28 退出/踢人路径有、切换路径无)。
+- 本次补充:
+- - migrateMemberAssets 增加 tasks 迁移(按 family_member_id / executor_id 匹配,
+-   兼容 child 任务 executor=成员卡id 与 parent 任务 executor=用户id 两种口径)
+- - switchMemberToFamily 末尾调用 refreshFoodOverviewQuietly 重算新旧家庭总览
+- 
+- 对绑定账号的家长成员下发 id/memberId/familyMemberId = users.id(如姥姥 76),
+- 而任务/打卡/健康等数据按 family_members.id(如姥姥 38)存取。
+- 前端以 familyMemberId 作为 memberId 查询今日任务时按 users.id 匹配不到任务,
+- 表现为成员选择器里能看到娜娜(无用户,id=family_members.id)的任务、却看不到姥姥的任务。
+- 修复:存在本家庭 family_members 记录时,familyMemberId/memberId 指向 family_members.id(id 保持 users.id 兼容旧消费方)
+- 
+
+
+## v1.0.2542 (2026-11-15)
+
+### Bug 修复
+- 密度四期 §8.F.6 焦点环边界补修(textarea/is-active提权/small日期子元素)
+- 密度四期无障碍补修 §8.F(P0 文字按钮24x24目标/P1 焦点环/mini圆形图标/最小宽度)
+
+
+## v1.0.2541 (2026-11-15)
+
+### 新功能
+- S-cfc-403 商品评价详情/去评价按钮态契约使绿
+- 后台密度四期——控件32px档+标题/查询区紧凑化(含8.E三处修复)
+- S-cfc-402 待收货超时自动完成+第N天收货提醒定时任务落地
+
+### 其他
+- - ProductReviewService 接口新增 detail(Long orderId, Long userId)
+- - ProductReviewServiceImpl 实现 detail:未评=null、已评→canReview=false;completed+90天窗口+非activity+未评→canReview=true 并附 reviewHint
+- - 字段 productOrderMapper 重命名为 orderMapper(对齐设计 §5.3 类图)
+- - ProductReviewController 新增 POST /api/product/review/detail(@RequestAttribute userId)
+- - API_REFERENCE.md 登记 R2 接口
+- 验证:ProductReviewDetailContractTest 9 跑 0 失败(红 9 → 绿 9);ProductReviewCreateContractTest 10 跑 0 失败(回归零漂移)
+- 
+- - autoComplete:COALESCE(shipped_at,updated_at)<now-超时天数 → completed+confirmTime=now+updatedAt=now+user_operation_logs(type=product_order_auto_complete) 留痕,幂等(completed 不再被扫中)
+- - sendRemind:shipped_at<now-提醒天数且 receipt_remind_at IS NULL → WechatService.sendTemplateMessage 推送后写 receipt_remind_at=now(幂等防重复;模板ID空=跳过 fail-open)
+- - 总开关 receipt-auto-complete-enabled=false 时仅提醒不自动完成(灰度);阈值/提醒天数/开关/模板ID全走 application.yml,不硬编码
+- - ProductOrderService.ship 发货成功写 shipped_at=now(超时/提醒基准时间数据源)
+- 契约测试:OrderReceiptTimeoutContractTest 8红->13/13绿,OrderReceiptTimeoutTaskContractTest 7红->14/14绿
+- 
+
+
+## v1.0.2540 (2026-11-15)
+
+### 测试
+- S-cfc-397 cf.teamshare.weightedShare 团队池档位权重加权瓜分契约级单测(RED,11红1过)
+- 闭环汇报 R222 工件提交 + 台账刷新 + blockers 更新
+- RED 契约测试 cf.rewardv2.dispatchF03c F03c 规则+发放接入(S-cfc-398,T06 earnByRule per_item + 三道闸)
+- S-cfc-400 cf.rewardv2.e2eExample 分润v2 200/100账目示例契约级单测(RED,13红1过)
+- S-cfc-399 契约测试 cf.rewardv2.removeLegacy 旧体系废弃清理(TDD RED)
+- S-cfc-396 契约测试 cf.teamshare.createPool 团队池建池(TDD RED)
+
+### 文档
+- 研发负责人第186轮闭环汇报 2026-11-15 2109
+
+### 新功能
+- S-cfc-404 我的评价/待评价入口 R5 实现使绿
+
+### 其他
+-   (reviews[] 按 review_at 倒序分页 + reviewableOrders[] + reviewableCount,
+-    待评价口径复用 findReviewableOrderIds:completed 且 90 天内且未评且非 activity)
+- - ProductReviewController 新增 POST /api/product/review/my,@RequestAttribute("userId") 登录买家
+- - API_REFERENCE.md 同步登记 R5 接口
+- - ProductReviewMyContractTest 10/10 全绿(此前红 3:controller my 路由/鉴权参数、service 契约)
+- 
+- - CfCommissionService#settleTeamPool / RULE_TEAM_POOL=F03c / calcDistributableBase 结构探测
+- - TeamShareConfigService#resolveTbps(T02 依赖,MINIAPP>SYSTEM>GLOBAL>3000)
+- - CfTeamPoolOrder 实体(orderId/orderType/buyerUserId/poolCent/tBps/configScope/status/settledAt)+ Mapper
+- - schema.sql 三表:cf_team_pool_order(uk_order 幂等)/ cf_team_share_config / cf_platform_revenue_log
+- - 权限流不适用(后端结算内部建池,无用户权限维度)
+- RED 实测:13 用例中 8 断言失败(settleTeamPool/RULE_TEAM_POOL/calcDistributableBase/TeamShareConfigService/
+- CfTeamPoolOrder 实体与 Mapper 未落地),5 通过(schema.sql 三表已由前置 T01 迁移落地 + 权限流说明性);
+- 溯源 2026-11-14-cf-reward-model-v2-design.md §6 T04
+- 
+
+
 ## v1.0.2539 (2026-11-15)
 
 ### Bug 修复

+ 121 - 1
cfc-web/public/CHANGELOG.md

@@ -1,6 +1,6 @@
 # 更新日志
 
-> 当前版本: v1.0.2539
+> 当前版本: v1.0.2548
 
 ## 历史版本
 
@@ -8,6 +8,126 @@
 
 ---
 
+## v1.0.2548 (2026-11-15)
+
+### 文档
+- 研发负责人第188轮闭环汇报 2026-11-16 02:26(自动化142轮)
+
+### 新功能
+- 优惠券分享转赠 T02 后端接口+契约单测(commitTransfer 抽取 + CouponShareService + Controller 5 端点 + JwtInterceptor 放行)
+
+
+## v1.0.2547 (2026-11-15)
+
+### 新功能
+- 优惠券分享转赠 T03 前端——share-claim 落地页+券列表分享入口+分享记录tab
+
+
+## v1.0.2546 (2026-11-15)
+
+### 测试
+- 增量复验 a1aa51d19 优惠券T01数据层 77例68过(仅AdminDataMigration 8F与主窗一致,非新增回归)
+- 后端全量首次实跑 510类/4469例92.12%(真实红17=存量16+P0守卫1) + 越权pin转断言(SC-X-19 403/14-14绿) + 三节点浏览器33过2跳 + R223台账24TC回收
+
+
+## v1.0.2545 (2026-11-15)
+
+### 新功能
+- 优惠券分享转赠 T01 数据层——coupon_share 表(迁移494)+coupon_gift_transfer 扩展列(迁移495)
+
+
+## v1.0.2544 (2026-11-15)
+
+### 文档
+- 研发负责人第187轮闭环汇报 2026-11-16 0055
+- 用户115高尿酸 食材推荐指数-50 + 健康方案/任务(含后续修正)执行记录
+
+
+## v1.0.2543 (2026-11-15)
+
+### Bug 修复
+- 切换家庭时迁移成员任务并刷新新旧家庭食材总览
+- 家庭成员可见列表的成员身份键改为 family_members.id
+
+### 其他
+- 也未刷新新旧家庭食材总览(T28 退出/踢人路径有、切换路径无)。
+- 本次补充:
+- - migrateMemberAssets 增加 tasks 迁移(按 family_member_id / executor_id 匹配,
+-   兼容 child 任务 executor=成员卡id 与 parent 任务 executor=用户id 两种口径)
+- - switchMemberToFamily 末尾调用 refreshFoodOverviewQuietly 重算新旧家庭总览
+- 
+- 对绑定账号的家长成员下发 id/memberId/familyMemberId = users.id(如姥姥 76),
+- 而任务/打卡/健康等数据按 family_members.id(如姥姥 38)存取。
+- 前端以 familyMemberId 作为 memberId 查询今日任务时按 users.id 匹配不到任务,
+- 表现为成员选择器里能看到娜娜(无用户,id=family_members.id)的任务、却看不到姥姥的任务。
+- 修复:存在本家庭 family_members 记录时,familyMemberId/memberId 指向 family_members.id(id 保持 users.id 兼容旧消费方)
+- 
+
+
+## v1.0.2542 (2026-11-15)
+
+### Bug 修复
+- 密度四期 §8.F.6 焦点环边界补修(textarea/is-active提权/small日期子元素)
+- 密度四期无障碍补修 §8.F(P0 文字按钮24x24目标/P1 焦点环/mini圆形图标/最小宽度)
+
+
+## v1.0.2541 (2026-11-15)
+
+### 新功能
+- S-cfc-403 商品评价详情/去评价按钮态契约使绿
+- 后台密度四期——控件32px档+标题/查询区紧凑化(含8.E三处修复)
+- S-cfc-402 待收货超时自动完成+第N天收货提醒定时任务落地
+
+### 其他
+- - ProductReviewService 接口新增 detail(Long orderId, Long userId)
+- - ProductReviewServiceImpl 实现 detail:未评=null、已评→canReview=false;completed+90天窗口+非activity+未评→canReview=true 并附 reviewHint
+- - 字段 productOrderMapper 重命名为 orderMapper(对齐设计 §5.3 类图)
+- - ProductReviewController 新增 POST /api/product/review/detail(@RequestAttribute userId)
+- - API_REFERENCE.md 登记 R2 接口
+- 验证:ProductReviewDetailContractTest 9 跑 0 失败(红 9 → 绿 9);ProductReviewCreateContractTest 10 跑 0 失败(回归零漂移)
+- 
+- - autoComplete:COALESCE(shipped_at,updated_at)<now-超时天数 → completed+confirmTime=now+updatedAt=now+user_operation_logs(type=product_order_auto_complete) 留痕,幂等(completed 不再被扫中)
+- - sendRemind:shipped_at<now-提醒天数且 receipt_remind_at IS NULL → WechatService.sendTemplateMessage 推送后写 receipt_remind_at=now(幂等防重复;模板ID空=跳过 fail-open)
+- - 总开关 receipt-auto-complete-enabled=false 时仅提醒不自动完成(灰度);阈值/提醒天数/开关/模板ID全走 application.yml,不硬编码
+- - ProductOrderService.ship 发货成功写 shipped_at=now(超时/提醒基准时间数据源)
+- 契约测试:OrderReceiptTimeoutContractTest 8红->13/13绿,OrderReceiptTimeoutTaskContractTest 7红->14/14绿
+- 
+
+
+## v1.0.2540 (2026-11-15)
+
+### 测试
+- S-cfc-397 cf.teamshare.weightedShare 团队池档位权重加权瓜分契约级单测(RED,11红1过)
+- 闭环汇报 R222 工件提交 + 台账刷新 + blockers 更新
+- RED 契约测试 cf.rewardv2.dispatchF03c F03c 规则+发放接入(S-cfc-398,T06 earnByRule per_item + 三道闸)
+- S-cfc-400 cf.rewardv2.e2eExample 分润v2 200/100账目示例契约级单测(RED,13红1过)
+- S-cfc-399 契约测试 cf.rewardv2.removeLegacy 旧体系废弃清理(TDD RED)
+- S-cfc-396 契约测试 cf.teamshare.createPool 团队池建池(TDD RED)
+
+### 文档
+- 研发负责人第186轮闭环汇报 2026-11-15 2109
+
+### 新功能
+- S-cfc-404 我的评价/待评价入口 R5 实现使绿
+
+### 其他
+-   (reviews[] 按 review_at 倒序分页 + reviewableOrders[] + reviewableCount,
+-    待评价口径复用 findReviewableOrderIds:completed 且 90 天内且未评且非 activity)
+- - ProductReviewController 新增 POST /api/product/review/my,@RequestAttribute("userId") 登录买家
+- - API_REFERENCE.md 同步登记 R5 接口
+- - ProductReviewMyContractTest 10/10 全绿(此前红 3:controller my 路由/鉴权参数、service 契约)
+- 
+- - CfCommissionService#settleTeamPool / RULE_TEAM_POOL=F03c / calcDistributableBase 结构探测
+- - TeamShareConfigService#resolveTbps(T02 依赖,MINIAPP>SYSTEM>GLOBAL>3000)
+- - CfTeamPoolOrder 实体(orderId/orderType/buyerUserId/poolCent/tBps/configScope/status/settledAt)+ Mapper
+- - schema.sql 三表:cf_team_pool_order(uk_order 幂等)/ cf_team_share_config / cf_platform_revenue_log
+- - 权限流不适用(后端结算内部建池,无用户权限维度)
+- RED 实测:13 用例中 8 断言失败(settleTeamPool/RULE_TEAM_POOL/calcDistributableBase/TeamShareConfigService/
+- CfTeamPoolOrder 实体与 Mapper 未落地),5 通过(schema.sql 三表已由前置 T01 迁移落地 + 权限流说明性);
+- 溯源 2026-11-14-cf-reward-model-v2-design.md §6 T04
+- 
+
+
 ## v1.0.2539 (2026-11-15)
 
 ### Bug 修复

+ 148 - 0
cfc-web/src/styles/admin-tokens.css

@@ -569,3 +569,151 @@
   display: block;
   min-height: 0;
 }
+
+/* ============================================================
+   8. 密度四期:控件本体 32px 档 + 标题区 / 查询区紧凑化
+   说明:全局无作用域,覆盖 portal 到 body 的弹窗按钮 / 下拉 / 日期面板;
+        纯尺寸与间距收口,颜色 / 字体族 / 圆角一律沿用 --adm-* 令牌,
+        第 6 节弹性填充链与第 7 节非表格页滚动修复逐字保留,未在此改写。
+   ============================================================ */
+
+/* ---- 8.A 控件本体:32 / 28 / 24 三档 ---- */
+.el-button { height: 32px; padding: 0 15px; font-size: 13px; line-height: 1; }
+.el-button--small { height: 28px; padding: 0 12px; font-size: 12px; }
+.el-button--mini { height: 24px; padding: 0 10px; font-size: 12px; }
+
+.el-input__inner { height: 32px; line-height: 32px; font-size: 13px; }
+.el-input--small .el-input__inner { height: 28px; line-height: 28px; font-size: 12px; }
+.el-input--mini .el-input__inner { height: 24px; line-height: 24px; font-size: 12px; }
+.el-textarea__inner { font-size: 13px; }
+.el-select .el-input__inner { height: 32px; line-height: 32px; font-size: 13px; }
+
+/* 图标垂直居中:line-height 随输入档位同步 */
+.el-input__icon,
+.el-select__caret,
+.el-input__prefix,
+.el-input__suffix { line-height: 32px; }
+.el-input--small .el-input__icon,
+.el-input--small .el-select__caret,
+.el-input--small .el-input__prefix,
+.el-input--small .el-input__suffix { line-height: 28px; }
+.el-input--mini .el-input__icon,
+.el-input--mini .el-select__caret,
+.el-input--mini .el-input__prefix,
+.el-input--mini .el-input__suffix { line-height: 24px; }
+
+/* 联动控件压到 32px 档(日期 / 区间 / 级联 / 数字 / 自动补全) */
+.el-date-editor .el-input__inner,
+.el-date-editor--daterange.el-input__inner,
+.el-cascader .el-input__inner,
+.el-input-number .el-input__inner,
+.el-autocomplete .el-input__inner { height: 32px; line-height: 32px; font-size: 13px; }
+.el-date-editor--daterange,
+.el-cascader,
+.el-input-number,
+.el-autocomplete { line-height: 32px; }
+
+/* 分页:按钮与页码 28px(is-background active 主色沿用第 2 节,不改写) */
+.el-pagination button { height: 28px; line-height: 28px; padding: 0 6px; }
+.el-pagination .el-pager li { height: 28px; line-height: 28px; }
+
+/* ---- 8.B 页面标题区紧凑化(font-weight:600 沿用第 3 节,不改写) ---- */
+.admin-page-header { margin-bottom: 12px; }
+.admin-page-title { font-size: 16px; line-height: 1.3; }
+.admin-page-subtitle { margin-left: 8px; }
+.admin-page-actions { gap: 6px; }
+
+/* ---- 8.C 查询筛选区紧凑化 ----
+   review/* 等页 scoped 规则编译为 .filter-bar[data-v-*] (0,2,0),
+   重复类名 .main-wrapper .filter-bar.filter-bar (0,3,0) 稳胜之;
+   flex / flex-wrap / align-items 由既有规则承担,本节不改写布局语义,
+   也不触碰 .filter-bar 内 .el-select / .el-input 的宽度 token。 */
+.main-wrapper .filter-bar.filter-bar {
+  gap: 8px;
+  padding: 8px 0;
+  margin-bottom: 8px;
+  background: transparent;
+  box-shadow: none;
+  border-radius: 0;
+  border-bottom: 1px solid var(--adm-border-split);
+}
+.main-wrapper .filter-bar .el-form-item { margin-bottom: 0; }
+
+/* ---- 8.D 卡片头内距收口 ----
+   第 2 节全局与第 3 节 .main-wrapper 作用域的 20px 24px 统一由本节覆盖;
+   卡片 body 内距保持 20px 不动(第 7 节功能逻辑,禁止触碰)。 */
+.el-card__header { padding: 12px 16px; }
+
+
+/* ============================================================
+   8.E 合入前修复补充(三处硬缺陷;纯追加,§1-§7 与 §8.A-D 逐字未动)
+   背景:design-critic 审查链路三次 RPC 超时未产出结论,由主理人本机按实证接管。
+   ============================================================ */
+
+/* 8.E.1 文字按钮回归修复(P0)
+   theme-chalk: .el-button--text{padding-left:0;padding-right:0} (0,1,0);
+   §8.A .el-button{height:32px;padding:0 15px} (0,1,0) 后加载胜,101 处 type="text"
+   (48 文件) 会被撑成 32px 高 + 30px 内距透明盒。本条 (0,2,0) 稳胜并置于末尾。 */
+.el-button.el-button--text { height: auto; padding: 0; line-height: inherit; font-size: 13px; }
+
+/* 8.E.2 标题区 / 卡片头提权(P0)
+   Families.vue L801-803 / FamilyWorkbench.vue L372-374 / AssessmentProducts.vue L208
+   的 scoped 规则 (0,2,0) 压过 §8.B (0,1,0);TeacherDashboard.vue L293 /deep/ 编译后 (0,3,0)。
+   重复类名提到 (0,3,0) / (0,4,0) 稳胜,禁 !important、禁改 .vue。 */
+.main-wrapper .admin-page-header.admin-page-header { margin-bottom: 12px; }
+.main-wrapper .admin-page-title.admin-page-title { font-size: 16px; line-height: 1.3; }
+.main-wrapper .admin-page-subtitle.admin-page-subtitle { margin-left: 8px; }
+.main-wrapper .admin-page-actions.admin-page-actions { gap: 6px; }
+.main-wrapper .el-card__header.el-card__header.el-card__header { padding: 12px 16px; }
+
+/* 8.E.3 mini 档日期区间保持 28px(P1)
+   §8.A .el-date-editor--daterange.el-input__inner (0,2,0) 会压过 Element mini (0,2,0);
+   本条同权重且后加载,令 mini 档维持 28px。 */
+.el-range-editor--mini.el-input__inner,
+.el-range-editor--mini .el-input__inner { height: 28px; line-height: 28px; }
+
+/* ============================================================
+   8.F 合入后无障碍修复(design-critic 审查裁决 P0-1 / P1-1 / P1-2 / P1-3)
+   纯追加、零删除;沿用既有 --adm-* 令牌,无 !important、无裸色值、无新增 --var。
+   勘误(以本段实测为准):type="text" 实为 108 处/51 文件(§8.E.1 注释写 101/48 偏低);
+   含 filter-bar 的是 admin/* 等 43 个 vue 文件,views/review/ 下为 0(§8.C 注释所指页面集合有误)。
+   ============================================================ */
+
+/* F.1 修 8.E.1:文字按钮 ~20px 目标补足 24x24,且不重新撑宽操作列 */
+.el-button.el-button--text {
+  min-height: 24px;
+  min-width: 24px;
+  display: inline-flex;
+  align-items: center;
+  justify-content: center;
+  padding: 0 2px;
+  line-height: 20px;
+}
+
+/* F.2 相邻文字按钮间距:圆心距 12+8+12=32px >=24,spacing 豁免成立 */
+.el-button.el-button--text + .el-button.el-button--text { margin-left: 8px; }
+
+/* F.3 8.A 新增三档控件的键盘焦点环(沿用 §1-§7 L144 既有令牌) */
+.el-button:focus-visible,
+.el-input__inner:focus-visible,
+.el-pagination button:focus-visible,
+.el-pager li:focus-visible {
+  outline: 2px solid var(--adm-primary-active);
+  outline-offset: 2px;
+}
+
+/* F.4 theme-chalk (0,2,0) 压过 8.A (0,1,0):mini 圆形按钮图标防裁切、round 档收口 */
+.el-button--mini.is-circle { padding: 0; width: 24px; }
+.el-button.is-round { padding: 0 15px; }
+
+/* F.5 P1-3:mini 档与分页图标按钮补足 24px 最小宽度 */
+.el-button--mini { min-width: 24px; }
+.el-pagination button { min-width: 24px; }
+.el-range-editor--small.el-input__inner { height: 28px; line-height: 28px; }
+
+/* 8.F.6 补 F.3 焦点环边界(design-critic 复审建议项,非阻断):
+   textarea 纳入、(0,3,0) 提权覆盖 theme-chalk .el-input.is-active、
+   补齐 small 日期区间子元素形态;沿用既有 --adm-primary-active。 */
+.el-textarea__inner:focus-visible { outline: 2px solid var(--adm-primary-active); outline-offset: 2px; }
+.el-input.is-active .el-input__inner:focus-visible { outline: 2px solid var(--adm-primary-active); outline-offset: 2px; }
+.el-range-editor--small .el-input__inner { height: 28px; line-height: 28px; }

+ 65 - 0
docs/2026-11-15-用户115-高尿酸-食材指数调整与健康方案-执行报告.md

@@ -0,0 +1,65 @@
+# 用户115(李志清)高尿酸健康管理 — 生产库执行报告
+
+| 项 | 内容 |
+|---|---|
+| 执行日期 | 2026-11-15(2026-11-16 后续修正) |
+| 操作人 | AI 助手(经用户确认方案后执行) |
+| 对象 | 用户115(李志清,family_members.id=75,family_id=119) |
+| 依据报告 | health_reports.id=64(gut_flora,2026-11-13,报告编号 555711538) |
+| 数据库 | 生产库 zxyj(JD Cloud RDS) |
+
+## 一、食材推荐指数调整(-50)
+
+**口径**:沿用系统 disease_intake_limits 痛风禁令口径 —— 动物内脏 + 部分海鲜 + 浓肉汤 + 含糖饮料(果汁)。
+
+**操作**:food_recommend_idx(user_id=115)中 25 种高尿酸食材 index_score = index_score - 50,逐条写 food_recommend_idx_log(change_reason=高尿酸健康管理调整:痛风禁令口径高尿酸食材(动物内脏/部分海鲜/浓肉汤/含糖饮料),推荐指数-50)。
+
+| 类别 | 食材(减50后) |
+|---|---|
+| 动物内脏(5) | 猪脑-80、猪肝-36、鹅肝-41、鸡心-42、鸡肝-44 |
+| 部分海鲜(15) | 鱼子酱-85、虾-58、蛤蜊-57、扇贝-52、贻贝-47、鲍鱼-48、蟹-40、龙虾-50、小龙虾-33、牡蛎-33、章鱼-38、鱿鱼-39、墨鱼-46、沙丁鱼-19、凤尾鱼-37 |
+| 浓肉汤(2) | 牛肉汤-50、鸡汤-61 |
+| 含糖饮料(3) | 苹果汁-72、橙汁7、橙菠萝汁-25 |
+
+> **后续修正(2026-11-16)**:猪头肉(原-50 后 -84)按用户要求撤销调整 —— 猪头肉为面肉、非动物内脏,已还原为 -34,并写"口径修正:猪头肉非动物内脏(面肉),撤销高尿酸-50调整"逆转日志(-84 → -34)。
+
+**验证**:剩余 25 条日志 previous - new = 50 精确;food_recommend_idx 总数 224 不变。
+
+> 说明:属一次性数据调整,未改 foods.score;报告重算时将按最新报告重建(用户确认的语义)。
+
+## 二、健康方案 + 任务创建
+
+**方案**:health_plans.id=30(family 119 / member 75 / status=published / plan_type=health_plan / total_days=14)
+- plan_content:报告解读(菌群 整体51、平衡35、多样性37、有益菌22、有害菌65、核心菌属87、慢性病风险46、营养73)+ 初步方案
+- plan_json:结构化 sections(12 条任务意图;服药任务 action_type=use)
+
+**任务**:tasks 12 条(source_type=health_plan,source_id=30)
+
+| id | 任务 | 类型 | 前置 |
+|---|---|---|---|
+| 5361 | 牙科洗牙 + 牙周检查 | 打卡/一次性 | — |
+| 5362 | 空腹血糖 + HbA1c | 打卡/一次性 | — |
+| 5363 | 血尿酸 + 肾功能(肌酐/eGFR) | 打卡/一次性 | — |
+| 5364 | 购买:PHGG瓜尔豆益生元 | 购买(cart 商品55) | — |
+| 5365 | 购买:AKK + 乳杆菌 | 购买(无平台商品) | — |
+| 5366 | 购买:Enagic 姜黄 | 购买(cart 商品15) | — |
+| 5367 | 购买:EPA + DHA | 购买(cart 商品79) | — |
+| 5368 | 每天饮用2.5-3升还原水 | 饮食/每日 | — |
+| 5369 | 服用:PHGG瓜尔豆益生元(每日) | **使用**/每日 | 5364 |
+| 5370 | 服用:AKK + 乳杆菌(每日) | **使用**/每日 | 5365 |
+| 5371 | 服用:Enagic 姜黄(每日) | **使用**/每日 | 5366 |
+| 5372 | 服用:EPA + DHA(每日) | **使用**/每日 | 5367 |
+
+> **后续修正(2026-11-16)**:4 条服药任务由"打卡任务/checkin"调整为"使用任务/use"(系统 D6 购买→使用依赖链语义),plan_json 同步。
+
+**"每个购买任务完成后,开始服药任务"**:服药任务各自 prerequisite_task_id 绑定对应购买任务(5369→5364、5370→5365、5371→5366、5372→5367)。
+
+## 三、回滚
+
+执行前已建快照备份表(可一键恢复):food_recommend_idx_bak_20261115、food_recommend_idx_log_bak_20261115、health_plans_bak_20261115、tasks_bak_20261115。
+
+## 四、脚本与文档
+
+- docs/scripts/2026-11-15-user115-uric-plan.py(dry-run / verify / apply,幂等防重复)
+- docs/scripts/2026-11-16-user115-followup.py(后续修正:撤销猪头肉 + 服药任务转使用任务)
+- 本报告

+ 318 - 0
docs/scripts/2026-11-15-user115-uric-plan.py

@@ -0,0 +1,318 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+用户115(李志清 / family_members.id=75 / family_id=119 / user_id=115)高尿酸健康管理数据操作
+
+Part A: food_recommend_idx 高尿酸食材推荐指数 -50(痛风禁令口径 26 种)+ 变更日志
+Part B: health_plans 健康方案(报告解读 + 初步方案)+ 12 条 tasks(购买任务为服药任务前置)
+
+操作对象:生产库 zxyj(JD Cloud RDS)。执行前已建立快照备份表(可回滚)。
+"""
+import pymysql, json, datetime, sys
+
+DB = dict(host='mysql-internet-cn-north-1-23feae22680e4dfa.rds.jdcloud.com',
+          port=3306, user='cfc', password='cfc@1314', database='zxyj', charset='utf8mb4')
+
+USER_ID, MEMBER_ID, FAMILY_ID, REPORT_ID = 115, 75, 119, 64
+TODAY = '2026-11-15'
+STAMP = TODAY.replace('-', '')
+
+# 痛风禁令口径(disease_intake_limits 痛风规则):动物内脏 + 部分海鲜 + 浓肉汤 + 含糖饮料(果汁)
+HIGH_UA_FOOD_IDS = [
+    7526, 7522, 7525, 7536, 7532, 7535,                                        # 动物内脏
+    7449, 7444, 7445, 7437, 7447, 7452, 7446, 7465, 7436, 7440, 7443, 7450,
+    7433, 7463, 7432,                                                          # 部分海鲜
+    7517, 7533,                                                                # 浓肉汤
+    7491, 7480, 7482,                                                          # 含糖饮料(果汁)
+]
+CHANGE_REASON = ('高尿酸健康管理调整:痛风禁令口径高尿酸食材'
+                 '(动物内脏/部分海鲜/浓肉汤/含糖饮料),推荐指数-50')
+
+APPLY = '--apply' in sys.argv
+VERIFY = '--verify' in sys.argv
+
+conn = pymysql.connect(**DB)
+cur = conn.cursor()
+
+def q(sql, args=None):
+    cur.execute(sql, args)
+    return cur.fetchall()
+
+def run(sql, args=None):
+    cur.execute(sql, args)
+    return cur.rowcount
+
+# ---------------------------------------------------------------- 快照备份
+def backup():
+    for tbl, where in [
+        ('food_recommend_idx', 'user_id=%d' % USER_ID),
+        ('food_recommend_idx_log', 'user_id=%d' % USER_ID),
+        ('health_plans', 'family_id=%d' % FAMILY_ID),
+        ('tasks', 'family_id=%d' % FAMILY_ID),
+    ]:
+        bak = '%s_bak_%s' % (tbl, STAMP)
+        run('DROP TABLE IF EXISTS %s' % bak)
+        run('CREATE TABLE %s AS SELECT * FROM %s WHERE %s' % (bak, tbl, where))
+        n = q('SELECT COUNT(*) FROM %s' % bak)[0][0]
+        print('[backup] %s -> %s (%d rows)' % (tbl, bak, n))
+
+# ---------------------------------------------------------------- Part A
+def part_a():
+    in_clause = ','.join(str(int(x)) for x in HIGH_UA_FOOD_IDS)  # 仅整数,安全内联
+    rows = q('SELECT id, food_id, food_name, index_score FROM food_recommend_idx '
+             'WHERE user_id=%s AND food_id IN (' + in_clause + ')',
+             (USER_ID,))
+    got = {r[1]: r for r in rows}
+    missing = [x for x in HIGH_UA_FOOD_IDS if x not in got]
+    print('[A] 命中 %d/%d 种;缺失: %s' % (len(rows), len(HIGH_UA_FOOD_IDS), missing or '无'))
+    if missing:
+        # 缺失说明 ID 漂移,安全起见中止
+        print('[A] ABORT: 存在未命中的食材ID,请核对后重跑')
+        return False
+
+    changed = []
+    for r in rows:
+        idx_id, food_id, food_name, old = r
+        new = old - 50
+        changed.append((idx_id, food_id, food_name, old, new))
+        print('[A] %s: %d -> %d' % (food_name, old, new))
+
+    if APPLY or VERIFY:
+        for idx_id, food_id, food_name, old, new in changed:
+            run('UPDATE food_recommend_idx SET index_score=%s WHERE id=%s', (new, idx_id))
+            run('INSERT INTO food_recommend_idx_log '
+                '(user_id, food_id, food_name, previous_index, new_index, health_report_id, change_reason, changed_at) '
+                'VALUES (%s,%s,%s,%s,%s,%s,%s,%s)',
+                (USER_ID, food_id, food_name, old, new, REPORT_ID, CHANGE_REASON, datetime.datetime.now()))
+        print('[A] 已更新 %d 条 index_score 并写 %d 条变更日志' % (len(changed), len(changed)))
+    else:
+        print('[A] DRY-RUN 未落库')
+    return True
+
+# ---------------------------------------------------------------- Part B
+def plan_content_md():
+    return """# 李志清|肠道菌群报告解读与高尿酸初步干预方案
+
+> 依据:肠道菌群检测报告(报告编号 555711538 / 报告ID 64 / 2026-11-13)
+> 成员:李志清(家庭成员ID 75)|已知血液学情况:**血尿酸偏高**(血检结果,非本报告内容)
+
+## 一、报告解读
+
+### 1.1 报告评分总览
+
+| 维度 | 得分 | 判读 |
+|---|---|---|
+| 整体评分 | 51 | 中等偏低 |
+| 肠健康 | 51 | 需干预 |
+| 慢性病风险 | 46 | 偏高 |
+| 营养 | 73 | 相对良好 |
+| 菌群平衡 | 35 | 偏低 |
+| 菌群多样性 | 37 | 偏低 |
+| 有益菌 | 22 | 明显不足 |
+| 有害菌 | 65 | 偏高 |
+| 核心菌属 | 87 | 良好 |
+
+### 1.2 解读要点
+
+1. **菌群失衡**:有益菌 22 分(明显不足)、有害菌 65 分(偏高),平衡分仅 35 → 肠道定植能力弱,有害代谢产物(炎症、代谢负担)易累积。
+2. **多样性不足**:多样性 37 分,菌株类型偏单一,饮食结构单一进一步限制菌群可塑性 → 需要"喂菌 + 补菌"两条腿同时走。
+3. **核心菌属基础尚可**:核心菌属 87 分 → 干预重点不是重建菌群,而是补上"养料(益生元)+ 菌株(益生菌)",把多样性与有益菌占比拉起来。
+4. **慢性病风险偏高**:慢性病风险 46 分,与有害菌偏高、营养代谢负担相关 → 炎症与代谢管理需同步进行。
+5. **尿酸偏高(外部已知)**:血尿酸偏高压缩了"低嘌呤"饮食空间,且与肠道菌群代谢相互影响 → 本方案饮食端已按痛风禁令口径下调高尿酸食材推荐指数(-50),并安排血尿酸 + 肾功能复查以确认安全边界。
+
+### 1.3 干预主线
+
+**喂菌(PHGG 瓜尔豆益生元)→ 补菌(AKK + 乳杆菌)→ 抗炎(Enagic 姜黄)→ 优杆菌(EPA + DHA)→ 生活方式(还原水 2.5–3 L/日 + 体检排查)**
+
+## 二、初步方案
+
+### 2.1 马上要做(第 1 周内完成)
+
+| # | 事项 | 类型 | 说明 |
+|---|---|---|---|
+| 1 | 牙科洗牙 + 牙周检查 | 体检 | 排查口腔慢性炎症源(全身炎症与代谢负担的常见来源) |
+| 2 | 空腹血糖 + HbA1c | 体检 | 建立血糖基线(菌群失衡与胰岛素敏感性相关) |
+| 3 | 血尿酸 + 肾功能(肌酐/eGFR) | 体检 | 量化尿酸水平并评估肾功能,作为饮食与补充剂的安全边界 |
+| 4 | 购买 PHGG 瓜尔豆益生元 | 购买 | 喂菌:为肠道菌群提供可利用的益生元底物 |
+| 5 | 购买 AKK + 乳杆菌 | 购买 | 补菌:补充有益菌株(平台暂无含 AKK 菌株商品,先按补菌方向备货) |
+| 6 | 购买 Enagic 姜黄 | 购买 | 抗炎:针对有害菌偏高带来的炎症负担 |
+| 7 | 购买 EPA + DHA | 购买 | 优杆菌:支持核心菌属与肠膜完整性 |
+| 8 | 每天 2.5–3 升还原水 | 每日 | 分次饮用,增加饮水与排泄,帮助冲刷嘌呤代谢产物 |
+
+### 2.2 购买完成后的服药任务
+
+每个购买任务完成后,自动开始对应的每日服药任务(PHGG 益生元 / AKK + 乳杆菌 / Enagic 姜黄 / EPA + DHA),具体用法按产品说明执行。
+"""
+
+def plan_json_obj():
+    tasks = [
+        dict(action_type='checkin', title='牙科洗牙 + 牙周检查', dimension='body', frequency='once',
+             notes='排查口腔慢性炎症源'),
+        dict(action_type='checkin', title='空腹血糖 + HbA1c', dimension='body', frequency='once',
+             notes='建立血糖基线'),
+        dict(action_type='checkin', title='血尿酸 + 肾功能(肌酐/eGFR)', dimension='body', frequency='once',
+             notes='量化尿酸水平并评估肾功能'),
+        dict(action_type='buy', title='购买:PHGG瓜尔豆益生元', dimension='wealth', frequency='once',
+             notes='喂菌:为肠道菌群提供可利用益生元底物'),
+        dict(action_type='buy', title='购买:AKK + 乳杆菌', dimension='wealth', frequency='once',
+             notes='补菌:补充有益菌株'),
+        dict(action_type='buy', title='购买:Enagic 姜黄', dimension='wealth', frequency='once',
+             notes='抗炎:针对有害菌偏高带来的炎症负担'),
+        dict(action_type='buy', title='购买:EPA + DHA', dimension='wealth', frequency='once',
+             notes='优杆菌:支持核心菌属与肠膜完整性'),
+        dict(action_type='diet', title='每天饮用2.5-3升还原水', dimension='body', frequency='daily',
+             notes='分次饮用,帮助冲刷嘌呤代谢产物'),
+        dict(action_type='checkin', title='服用:PHGG瓜尔豆益生元(每日)', dimension='body', frequency='daily',
+             notes='按产品说明每日服用'),
+        dict(action_type='checkin', title='服用:AKK + 乳杆菌(每日)', dimension='body', frequency='daily',
+             notes='按产品说明每日服用'),
+        dict(action_type='checkin', title='服用:Enagic 姜黄(每日)', dimension='body', frequency='daily',
+             notes='按产品说明每日服用'),
+        dict(action_type='checkin', title='服用:EPA + DHA(每日)', dimension='body', frequency='daily',
+             notes='按产品说明每日服用'),
+    ]
+    return {
+        'overview': ('依据 2026-11-13 肠道菌群检测报告(报告ID 64):整体 51 / 有益菌 22(不足)/ '
+                     '有害菌 65(偏高)/ 多样性 37 / 核心菌属 87;已知血尿酸偏高。'
+                     '干预主线:喂菌 + 补菌 + 抗炎 + 优杆菌 + 还原水生活方式。'),
+        'sections': [
+            {'key': 'diet', 'title': '报告解读与初步干预方案',
+             'content': '有益菌不足、有害菌偏高、多样性不足,需喂菌/补菌;已知尿酸偏高,饮食端已下调高尿酸食材推荐指数。',
+             'items': [], 'tasks': tasks},
+        ],
+        'abnormal_indicators': [
+            {'member': '李志清', 'indicator': '有益菌', 'value': '22', 'unit': '分'},
+            {'member': '李志清', 'indicator': '有害菌', 'value': '65', 'unit': '分'},
+            {'member': '李志清', 'indicator': '菌群多样性', 'value': '37', 'unit': '分'},
+            {'member': '李志清', 'indicator': '血尿酸', 'value': '偏高', 'unit': ''},
+        ],
+        'knowledge_sources': [],
+    }
+
+def part_b():
+    # 幂等:family 119 已有同名方案则中止
+    dup = q('SELECT id FROM health_plans WHERE family_id=%s AND goal LIKE %s',
+            (FAMILY_ID, '%李志清%肠道菌群%'))
+    if dup:
+        print('[B] ABORT: 已存在方案 id=%s,中止以防重复' % dup[0][0])
+        return
+
+    now = datetime.datetime.now()
+    today_end = now.replace(hour=23, minute=59, second=59, microsecond=0)
+    plan_end = (now + datetime.timedelta(days=14)).replace(hour=23, minute=59, second=59, microsecond=0)
+
+    content = plan_content_md()
+    pj = json.dumps(plan_json_obj(), ensure_ascii=False)
+
+    # 1) health_plans
+    run('INSERT INTO health_plans '
+        '(family_id, member_ids, dimensions, goal, plan_content, member_name, created_at, updated_at, plan_json, status, total_days, plan_type) '
+        'VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)',
+        (FAMILY_ID, str(MEMBER_ID), 'body,action',
+         '基于2026-11-13肠道菌群检测报告的解读与高尿酸初步干预方案',
+         content, '李志清', now, now, pj, 'published', 14, 'health_plan'))
+    plan_id = q('SELECT LAST_INSERT_ID()')[0][0]
+    print('[B] health_plans id=%s' % plan_id)
+
+    # 2) 任务行字段
+    def base_row(**kw):
+        row = dict(family_id=FAMILY_ID, family_member_id=MEMBER_ID, child_id=MEMBER_ID,
+                   creator_id=USER_ID, executor_type='child', executor_id=MEMBER_ID,
+                   source_type='health_plan', source_id=plan_id,
+                   need_review=0, review_by_category=0, status='pending',
+                   member_only=0, is_flow_task=1, dimension_code='body',
+                   is_daily_progress=0, duration=0, is_template=0,
+                   task_type=None, repeat_type='none', frequency=None,
+                   deadline=None, prerequisite_task_id=None,
+                   action_type=None, action_config=None, complete_types=None,
+                   created_at=now, updated_at=now, points=10)
+        row.update(kw)
+        return row
+
+    def insert_task(row):
+        cols = list(row.keys())
+        ph = ','.join(['%s'] * len(cols))
+        run('INSERT INTO tasks (%s) VALUES (%s)' % (','.join(cols), ph),
+            tuple(row[c] for c in cols))
+        return q('SELECT LAST_INSERT_ID()')[0][0]
+
+    # 2a) 体检 3(一次性)
+    exam_titles = [
+        ('牙科洗牙 + 牙周检查', '排查口腔慢性炎症源(全身炎症与代谢负担常见来源)'),
+        ('空腹血糖 + HbA1c', '建立血糖基线(菌群失衡与胰岛素敏感性相关)'),
+        ('血尿酸 + 肾功能(肌酐/eGFR)', '量化尿酸水平并评估肾功能,作为饮食与补充剂安全边界'),
+    ]
+    for title, desc in exam_titles:
+        tid = insert_task(base_row(title=title, description=desc, points=10,
+                                   category='打卡任务', task_type='onetime', repeat_type='none',
+                                   frequency=None, is_template=0, deadline=today_end, action_type='checkin'))
+        print('[B] 体检任务 id=%s: %s' % (tid, title))
+
+    # 2b) 购买 4(一次性,category=购买任务)
+    purchases = [
+        ('购买:PHGG瓜尔豆益生元', 55, '瓜尔纤维', '喂菌:为肠道菌群提供可利用益生元底物'),
+        ('购买:AKK + 乳杆菌', None, '益生菌', '补菌:补充有益菌株(平台暂无含AKK菌株商品)'),
+        ('购买:Enagic 姜黄', 15, '姜黄', '抗炎:针对有害菌偏高带来的炎症负担'),
+        ('购买:EPA + DHA', 79, '鱼油', '优杆菌:支持核心菌属与肠膜完整性'),
+    ]
+    purchase_ids = []
+    for title, product_id, cat, desc in purchases:
+        row = base_row(title=title, description=desc + '(方案ID ' + str(plan_id) + ',品类:' + cat + ')',
+                       points=10, category='购买任务', task_type='onetime', repeat_type='none',
+                       frequency=None, is_template=0, deadline=today_end)
+        if product_id is not None:
+            row['action_type'] = 'cart'
+            row['action_config'] = json.dumps({'productId': product_id, 'quantity': 1,
+                                               'planId': plan_id, 'category': cat}, ensure_ascii=False)
+        tid = insert_task(row)
+        purchase_ids.append(tid)
+        print('[B] 购买任务 id=%s: %s (product=%s)' % (tid, title, product_id or '无'))
+
+    # 2c) 饮水 1(每日)
+    wtid = insert_task(base_row(title='每天饮用2.5-3升还原水',
+                                description='分次饮用,增加饮水与排泄,帮助冲刷嘌呤代谢产物',
+                                points=5, category='饮食任务', task_type='recurring',
+                                repeat_type='daily', frequency='daily', is_template=1,
+                                deadline=plan_end, action_type='diet'))
+    print('[B] 饮水任务 id=%s: 每天2.5-3升还原水' % wtid)
+
+    # 2d) 服药 4(每日,前置=对应购买任务)
+    meds = [
+        ('服用:PHGG瓜尔豆益生元(每日)', '按产品说明每日服用,餐后为佳', 0),
+        ('服用:AKK + 乳杆菌(每日)', '按产品说明每日服用', 1),
+        ('服用:Enagic 姜黄(每日)', '按产品说明每日服用,抗炎方向', 2),
+        ('服用:EPA + DHA(每日)', '按产品说明每日服用,优杆菌方向', 3),
+    ]
+    for title, desc, pi in meds:
+        tid = insert_task(base_row(title=title, description=desc, points=5,
+                                   category='打卡任务', task_type='recurring',
+                                   repeat_type='daily', frequency='daily', is_template=1,
+                                   deadline=plan_end, action_type='checkin',
+                                   prerequisite_task_id=purchase_ids[pi]))
+        print('[B] 服药任务 id=%s: %s (prereq=%s)' % (tid, title, purchase_ids[pi]))
+
+    print('[B] 方案ID=%s,共生成 12 条任务' % plan_id)
+
+# ---------------------------------------------------------------- main
+print('=== 用户115 高尿酸健康管理 ===')
+if APPLY:
+    print('模式: APPLY')
+    backup()
+    ok = part_a()
+    if ok:
+        part_b()
+        conn.commit()
+        print('[main] 已提交')
+elif VERIFY:
+    print('模式: VERIFY(事务内执行+回滚,不落库)')
+    ok = part_a()
+    if ok:
+        part_b()
+    conn.rollback()
+    print('[main] VERIFY 已回滚,未持久化任何数据')
+else:
+    print('模式: DRY-RUN')
+    part_a()
+    print('[B] DRY-RUN 未执行方案/任务创建')
+print('=== 完成 ===')
+conn.close()

+ 75 - 0
docs/scripts/2026-11-16-user115-followup.py

@@ -0,0 +1,75 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""用户115 高尿酸 后续修正
+① 撤销 猪头肉(7522) 的 -50(口径:猪头肉为面肉,非动物内脏)→ 还原 -34 + 写逆转日志
+② 服药任务 5369-5372:category 打卡任务→使用任务,action_type checkin→use;同步 plan_json
+"""
+import pymysql, json, datetime
+
+DB = dict(host='mysql-internet-cn-north-1-23feae22680e4dfa.rds.jdcloud.com',
+          port=3306, user='cfc', password='cfc@1314', database='zxyj', charset='utf8mb4')
+USER_ID, MEMBER_ID, FAMILY_ID, REPORT_ID = 115, 75, 119, 64
+PLAN_ID = 30
+MED_TASK_IDS = [5369, 5370, 5371, 5372]
+
+conn = pymysql.connect(**DB)
+cur = conn.cursor()
+
+def q(sql, args=None):
+    cur.execute(sql, args)
+    return cur.fetchall()
+
+def run(sql, args=None):
+    cur.execute(sql, args)
+    return cur.rowcount
+
+now = datetime.datetime.now()
+
+# ---------- ① 撤销猪头肉 -50 ----------
+rows = q('SELECT id, food_id, food_name, index_score FROM food_recommend_idx WHERE user_id=%s AND food_id=7522', (USER_ID,))
+for r in rows:
+    idx_id, food_id, food_name, cur_score = r
+    if cur_score == -84:
+        run('UPDATE food_recommend_idx SET index_score=%s WHERE id=%s', (-34, idx_id))
+        run('INSERT INTO food_recommend_idx_log '
+            '(user_id, food_id, food_name, previous_index, new_index, health_report_id, change_reason, changed_at) '
+            'VALUES (%s,%s,%s,%s,%s,%s,%s,%s)',
+            (USER_ID, food_id, food_name, cur_score, -34, REPORT_ID,
+             '口径修正:猪头肉非动物内脏(面肉),撤销高尿酸-50调整', now))
+        print('[1] 猪头肉 %s -> -34(已撤销)' % food_name)
+    elif cur_score == -34:
+        print('[1] 猪头肉已是 -34,无需撤销')
+    else:
+        print('[1] 猪头肉当前指数异常: %s,跳过' % cur_score)
+
+# ---------- ② 服药任务 → 使用任务 ----------
+if not MED_TASK_IDS:
+    print('[2] 无服药任务ID,跳过')
+else:
+    ph = ','.join(str(x) for x in MED_TASK_IDS)
+    b = q('SELECT id, title, category, action_type FROM tasks WHERE id IN (%s)' % ph)
+    if len(b) != 4:
+        print('[2] 命中 %d 条服药任务(预期4):%s' % (len(b), [x[0] for x in b]))
+    for tid, title, cat, act in b:
+        run('UPDATE tasks SET category=%s, action_type=%s WHERE id=%s', ('使用任务', 'use', tid))
+        print('[2] 任务 %s「%s」: %s/%s -> 使用任务/use' % (tid, title, cat, act))
+    # 同步 plan_json
+    pj = q('SELECT plan_json FROM health_plans WHERE id=%s', (PLAN_ID,))[0][0]
+    root = pj if isinstance(pj, dict) else json.loads(pj)
+    changed = 0
+    for sec in root.get('sections', []):
+        for t in sec.get('tasks', []):
+            if t.get('title', '').startswith('服用:'):
+                if t.get('action_type') != 'use':
+                    t['action_type'] = 'use'
+                    changed += 1
+    if changed:
+        run('UPDATE health_plans SET plan_json=%s, updated_at=%s WHERE id=%s',
+            (json.dumps(root, ensure_ascii=False), now, PLAN_ID))
+        print('[2] plan_json 已同步 %d 条服药任务 action_type -> use' % changed)
+    else:
+        print('[2] plan_json 无需变更')
+
+conn.commit()
+print('=== 完成 ===')
+conn.close()

+ 15 - 2
docs/superpowers/api/API_REFERENCE.md

@@ -670,6 +670,7 @@ find cfc-backend/src/main/java -name "*XxxService.java" -o -name "*XxxController
 | `POST /api/product/order/ship` | 服务商/管理端发货(填物流单号+快递公司)。发货成功后自动调用微信「小程序交易管理服务」`upload_shipping_info` 同步物流到微信订单管理(用户在微信侧收发货通知/查物流/确认收货);自提订单或无单号跳过;失败只记日志不阻塞(fail-open);`wechat.test-mode=true` 或 `wechat.fulfillment-enabled=false`(环境变量 `WECHAT_FULFILLMENT_ENABLED`)时跳过 |
 | `POST /api/product/order/review/update` | 供应商审核修改待支付订单(修改价格/配送方式/添加优惠券/赠品) |
 | `POST /api/product/review/create` | 创建商品订单评价(能力键 `shop.review.create`;普通商品订单 completed 后一单一评:综合星级1-5+文字≤500字+晒图≤3张、确认收货90天内,独立表 product_reviews,活动评价零污染) |
+| `POST /api/product/review/detail` | 商品评价详情/去评价按钮态(能力键 `shop.review.detail`;入参 `{orderId}`,出参 `ProductReviewResponse`:review 已评记录未评为 null / canReview 可评态(completed 且 90 天窗口内且未评时 true)/ reviewHint 提示文案) |
 | `POST /api/product/review/my` | 我的评价 + 待评价入口(能力键 `shop.review.my`;登录买家本人:`{reviews[], reviewableOrders[], reviewableCount}`,reviews=按评价时间倒序分页的我的评价列表,reviewableOrders=待评价订单(completed 且 90 天内且未评且非 activity 的买家本人订单),reviewableCount=待评价条数) |
 | `POST /api/cart/add` | 加入购物车 |
 | `POST /api/cart/list` | 购物车列表 |
@@ -1082,6 +1083,18 @@ find cfc-backend/src/main/java -name "*XxxService.java" -o -name "*XxxController
 | `POST /api/coupon/checkout-list` | 结算页可兑换未拥有券 |
 | `POST /api/coupon/available-templates` | 领券中心可取券模板:上架(status 空/ACTIVE)、有效期内、未领完(total_count 空/≤0 视为不限量,否则 used_count<total_count)、grant_type 为空(非自动发放/兑换)、family_id 为空(全平台模板)、本家庭未领取(family_coupon 任意状态有记录即排除)。返回 `List<Coupon>`(字段为 `id` 等模板字段),与 `/claim` 去重口径对齐(COUPON-C3) |
 
+**会员券分享转赠(`/api/coupon/gift/share/*`,ARCH-CFC-COUPON-SHARE-GIFT-001 §5)**
+
+> 在「定向转赠」之上新增「分享转赠」通道,不修改定向转赠逻辑。统一 `@PostMapping`,响应统一 `Result<T>`(code 200 成功 / 500 业务错误 / 404 资源不存在 / 401 未登录由拦截器返回),入参统一 `Map<String,Object>` + `ParamUtils`。契约先行登记,供 T02(后端接口)/T03(前端落地页)并行开工。
+
+| 路径 | 登录 | 入参 | 返回 data | 主要错误(500 + message,前端原样 toast) |
+|------|------|------|-----------|------------------------------------------|
+| `POST /api/coupon/gift/share/create` | 是 | `{ familyCouponId: Long }` | `{ shareToken, sharePath: "/pages/coupon/share-claim?shareToken=xxx", expireAt(ISO8601) }` | "参数不完整"、"请先加入家庭"、"该优惠券不可用或不属于你"、"优惠券已失效"、"优惠券已过期"、"仅会员专属券可分享";幂等:同 giver+familyCouponId 已有 PENDING → 返回既有 token(不报错) |
+| `POST /api/coupon/gift/share/detail` | **否(公开,匿名可浏览)** | `{ shareToken }` | `ShareDetailVO`: `{ shareToken, status(PENDING/CLAIMED/REVOKED/EXPIRED), couponName, couponValue, couponType, minSpend, validUntil, giverNickname, giverAvatar, expireAt, claimable(boolean) }` | 404 "分享不存在或已失效"(token 无记录) |
+| `POST /api/coupon/gift/share/claim` | 是 | `{ shareToken }` | `{ transferId: Long }` | "分享不存在或已失效"、"该分享已被领取"、"该分享已撤回"、"该分享已过期"、"优惠券已失效"、"不能领取自己分享的券"、"不能领取同家庭成员的券"、"领取失败,请联系客服";并发防重领:条件更新 PENDING→CLAIMED 影响 1 行才继续(一个 token 只能被领一次) |
+| `POST /api/coupon/gift/share/revoke` | 是 | `{ shareToken }` | `Void` | "分享不存在"、"无权操作该分享"、"该分享已被领取,无法撤回"、"该分享已撤回";仅置 status=REVOKED,不动券实例 |
+| `POST /api/coupon/gift/share/list` | 是 | `{}` | `List<ShareRecordVO>`: `[{ shareToken, couponName, couponValue, status, expireAt, claimTime, createdAt, claimNickname }]`(created_at DESC) | — |
+
 ---
 
 ### 4.33 CF 值分佣(`/api/commission/cf/*`)
@@ -3181,7 +3194,7 @@ W0.2 双配置中心合并:`product_config` 已并入 `service_config`(唯
 
 | SC | 场景 | 现状 | 处置 |
 |----|------|------|------|
-| SC-A-04 | 关系类型 CRUD | 已落地:`POST /api/admin/family-relation/types/{list,save,update,disable}`(`AdminFamilyRelationController`,字典表 `family_relation_types`,迁移494);v2 辈分重构后 `relationship_types` 表已废弃 DROP,关系仍由 `family_relationships` 承载 | 已实现(S-cfc-387 GREEN,2026-11-16;见 §4.66) |
+| SC-A-04 | 关系类型 CRUD | 已落地:`POST /api/admin/family-relation/types/{list,save,update,disable}`(`AdminFamilyRelationController`,字典表 `family_relation_types`,迁移497);v2 辈分重构后 `relationship_types` 表已废弃 DROP,关系仍由 `family_relationships` 承载 | 已实现(S-cfc-387 GREEN,2026-11-16;见 §4.66) |
 | SC-A-14 | 系统监控/告警 | 仅 `POST /api/system/health`(JVM/内存/CPU 探活),无告警规则/记录端点 | 无端点载体,需产品侧确认 |
 | SC-A-19 | 账号注销/数据导出工单处理 | 无运营工单端点;用户侧自助 `POST /api/user/deactivate`、`POST /api/user/data-export` 已实现 | 无端点载体,需产品侧确认 |
 | SC-A-20 | 限流/熔断配置 | 无 HTTP 配置端点;`RateLimitInterceptor`(Redis 滑动窗口)+ `AiGateway` 熔断为代码内置 | 无端点载体,需产品侧确认 |
@@ -3770,7 +3783,7 @@ W0.2 双配置中心合并:`product_config` 已并入 `service_config`(唯
 ## 4.66 管理端-家庭关系类型(`/api/admin/family-relation`,SC-A-04,2026-11-16)
 > 来源:契约测试 `AdminFamilyRelationManageContractTest`(S-cfc-308 RED → S-cfc-387 GREEN,能力键 `admin.familyRelation.manage`);
 > 用例绑定 `tests/test-cases/admin.md` TC-A-10(功能)/ TC-A-10-E(异常)/ TC-A-10-P(权限);场景 `tests/user-scenarios/应用场景总览.md` SC-A-04。
-> v2 辈分重构后 `relationship_types` 表已废弃 DROP(迁移169),字典重建为 `family_relation_types`(迁移494,表名避开历史 DROP 防启动清表)。
+> v2 辈分重构后 `relationship_types` 表已废弃 DROP(迁移169),字典重建为 `family_relation_types`(迁移497,表名避开历史 DROP 防启动清表)。
 
 | 路径 | 说明 |
 |------|------|

+ 32 - 0
docs/tdd/orchestration/notice-2026-11-15-R222-研发通知.md

@@ -0,0 +1,32 @@
+# 研发通知 R222(2026-11-15 21:25 · 自动化闭环)
+
+> 测试负责人:陆谨(软件测试专家团)|基线 `c582cdb16`(窗口 4 提交,**零 src/main 变更**)|本轮测试结果有变化,提请研发关注。
+
+## 本轮变化摘要(R221 → R222)
+
+1. 🔴 **langgraph 红集 0→3(环境型复现,B-222-1)**:251 上 pytest 43 例 40 过 3 红,`test_auto_tag` 的 content_relevance / short_content / empty_content 全红,根因 `429 AgnesAI free rate limit`(免费配额耗尽,124.19s)。**请运维升级 AgnesAI Token Plan 或轮换 key**——这是连续多轮反复出现的上游配额问题(B-220-1/B-216-3 同源),恢复后 lg 43 例复跑即可销号。
+
+2. 🟢 **health 首跑即 13/13 全绿**:上轮首跑 4×502(B-218-3 第 4 轮),本轮首跑无 502 → 观察 1/3,请运维继续排查线上周期性 502 根因(nginx/后端重启/OOM/端口漂移)。
+
+3. 🟢 **189 admin 连续 2 轮首跑 5/5**(B-208-1 好转观察 3/3);189 节点仓库 HEAD 仍落后基线(B-221-4,请在该节点用 `git worktree` 专用目录跑 E2E 或授权测试侧处理)。
+
+## 承袭待修(持续未闭环,请优先)
+
+| 编号 | 级别 | 问题 | 位置 |
+|---|---|---|---|
+| B-218-1 | **P0** | `CoachRecommendService` `@Resource` 字段名撞 Bean 名 → 运行期 `BeanNotOfRequiredTypeException` | `CoachRecommendService.java`(守卫 `ResourceBeanNameCollisionGuardTest` 1/1 红) |
+| B-218-2 | **P1** | 支付配置缺失仍创建真实订单(131400 分)| `MembershipOrderService` / `PaymentService`(两键 9 例红)|
+| G11 | **P1** | `.gitlab-ci.yml:61` `BACKEND_OBSERVED_CLASSES` 漏拦 62 / 陈旧 26 | CI 清单需按 surefire 自动生成 |
+| B-218-3 | P1 | 线上瞬时 502 周期窗口(本轮未复现,观察 1/3)| 运维排查 |
+| B-218-10 | P1 | lg pytest 进程不退出(第 23 轮观察)| 251 派发器 + `client.aclose()` |
+
+## 门禁结论
+
+**⛔ 不通过(有条件)**:G1 全量 92.00%(剔契约前瞻 99.58%)❌;G2 实红 33 ❌;G7 lg 93.0%(环境型 3 红)❌;G9 覆盖 27.5% ❌;G11 CI 失真 ❌。**复评条件**:B-218-1/B-218-2 修复 + lg 配额恢复 + CI 清单对齐。
+
+## 覆盖台账
+
+- 控制器 373|handler 2026(覆盖 557 = 27.5%)|测试文件 515(@Test 4395)|用例合计 **5740**
+- G12:窗口 SRS/场景/用例文档零变更,无需新增用例。
+
+*详细证据:`docs/tdd/orchestration/report-test-2026-11-15-R222.md`*

+ 69 - 0
docs/tdd/orchestration/notice-2026-11-16-R224-研发通知.md

@@ -0,0 +1,69 @@
+# 研发通知 · R224(2026-11-16 01:xx GMT+8)
+
+> 发起:测试负责人(软件测试专家团 · 测试架构师)|执行档:review(离线白名单)+ 内网三节点浏览器 E2E 实跑
+> 基线:`origin/cfclub` **`3ff62e324`**,本轮窗口 **0 新增提交**(R223 基线即该提交),零 SRS/场景变更
+
+## 一、需要研发处置(按优先级)
+
+### 1) 🟢 已闭环(无需处置,仅告知):SC-X-19 跨家庭越权读取已被修复
+- **实现**:`EnergyController#overview`(`cfc-backend/src/main/java/com/etotem/cfc/controller/EnergyController.java:174`)在 `d39aa5282`(S-cfc-390 `energy.ledger.guard`)加入归属校验:
+  ```java
+  if (!memberId.equals(currentMemberId) && !energyService.isMemberInFamily(memberId, familyId)) {
+      return Result.forbidden("无权访问该成员的能量数据");
+  }
+  ```
+- **测试侧已同步**:`tests/e2e/api/dimension-energy-contract.spec.js` 原「观察钉住」用例断言旧缺陷行为(跨家庭 `memberId=999999` → 200),实现修复后该用例长期假红;本轮改为断言 `code=403 / message 含「无权访问」/ 不返回能量数据` → 复跑 **14/14 绿**。
+- **给研发的提示**:新增「观察钉住(pin)」用例时请在规格或注释写明「缺陷修复后转断言」的责任人,避免 pin 变成长期噪声。
+
+### 2) 🔴 P1(流程)R223 派生用例台账未入库,已由测试侧回收
+- R223 声明派生 24 条行为级用例(`shop.review.detail` / `shop.review.my` / `shop.order.receiptTimeout`),但文件 `tests/test-cases/2026-11-16-review-detail-my-receipt-timeout.md` 只提交在本地分支 `fix/scenario-coverage`(`c1f20bc2a`),**未进 `origin/cfclub`**。
+- 本轮已随报告一并入库(资产回收)。**请研发/测试在推送时以 `origin/cfclub` 为唯一事实源**,避免台账断层导致 G12 追溯失真。
+
+### 3) 🔴 P0(环境)251 节点 langgraph 仍有 8 例环境型红(AgnesAI 免费配额 429)
+- 251(`3ff62e324`,与本轮基线同版)`pytest tests --ignore=tests/qna --ignore=tests/test_chat.py`:
+  **43 例 / 35 过 / 8 红 / 107.37s**,红集 = `test_auto_tag` ×4 + `test_intent` ×4。
+- 日志:`RateLimitError("Error code: 429 ... You've reached the API rate limit for free users ... AgnesAI_error")`;`app/middleware.py:113`;intent 分类器 429 后兜底 `chat` 导致 4 条意图断言失败。
+- **处置**:给 251 的 LLM 凭据升级 Token Plan 或轮换有配额 key(**不是改测试断言**)。
+- 补充:`intent_classifier.py` 在 429 时应显式失败/重试,而不是静默兜底 `chat` —— 静默兜底会把「上游不可用」伪装成「分类错误」,掩盖真实故障。
+
+### 4) 🔴 P1(装置 + 数据安全,本轮最重要)后端测试直连共享库 251:3306/zxyj,且每个 Spring 上下文重跑全量迁移
+- **事实链**:
+  1. `cfc-backend/src/test/resources/` **不存在**(`ls -d` 报 No such file)→ 测试无独立测试配置,直接落到 `src/main/resources/application*.yml`;
+  2. 该配置数据源为 **`jdbc:mysql://192.168.16.251:3306/zxyj`**(`createDatabaseIfNotExist=true`,两处 profile 同值)→ 即 **251 上的共享库**;
+  3. 测试启动日志 `wechat.test-mode=true in non-production profile (dev)` → 以 `dev` profile 读写该共享库;
+  4. 每次 `@SpringBootTest` 新建上下文都会跑 `DatabaseInitializer` 全量迁移:日志 `DatabaseInitializer` 输出 **24987 行**、已观察 **25+** 次上下文启动;`schema.sql` 含 **433** 条 DDL、`DatabaseInitializer` 有 **650** 处迁移段;
+  5. `jstack` 抓主线程:`main` RUNNABLE 阻塞在 `java.net.SocketInputStream.socketRead0` → `com.mysql.cj.protocol.ReadAheadInputStream` → **正在等 251 的 MySQL 网络往返**。
+- **后果**:① 全量 JUnit 从 40min 劣化到 >2h(per-class 20~200s,绝大部分耗在网络 DDL 往返);② **测试数据写进共享库**,与线上/演示数据混用,存在污染与误删风险;③ 并行会话同时跑测试时会互相锁表,表现为「随机卡在某类几分钟」。
+- **建议**(按性价比排序):
+  1. 新增 `cfc-backend/src/test/resources/application-test.yml`:指向本地 MySQL/H2 + `spring.datasource.hikari.maximum-pool-size` 调小 + 关闭自动迁移(`migration.enabled=false`),schema 由一次性 `@Sql`/`schema-test.sql` 建;
+  2. 新增 `src/test/resources/logback-test.xml`,把 `com.etotem` 降到 `WARN`(本轮日志 **14.6MB**,绝大部分是 MyBatis DEBUG SQL);
+  3. `DatabaseInitializer` 迁移加「同 JVM 只跑一次」静态闸(`AtomicBoolean`/`@PostConstruct` 单例),避免每上下文重跑;
+  4. controller 层用例改 `@WebMvcTest`,service 层用切片测试。
+- **验收**:连续 2 轮全量 ≤40min、类数/例数不变、且测试不再连 `192.168.16.251:3306`。
+
+### 5) 🟡 P2(CI)`backend-blocking-junit` 清单继续失真(G11 第 26 轮)
+- CI `BACKEND_OBSERVED_CLASSES` 仍为 33 类固定清单;本轮实测确定性红类与契约前瞻红类叠加后远超清单,**清单内多个类实际已全绿**(陈旧),清单外仍有确定性红(漏拦)。
+- **处置**:把清单改为「由 surefire 结果自动生成」,或改为 `-Dtest=!<动态清单>` + 契约前瞻类打 `@Tag("forward-contract")` 单独跑 observed。
+
+### 6) ⚪ P3(节点)189 代码版本落后
+- 189 `c:/code/cfc` HEAD = `1e3bea680`,落后 `origin/cfclub`(`3ff62e324`);但 `admin-live.spec.js` blob = `4703d73fb`(与本机同版),故本轮 189 的 5/5 结论**跨节点可比**。
+- **处置**:189 定期 `git pull --ff-only`(`cfclub` 被其他 worktree 占用时改用 `git -C` 指定 worktree 或直接 fetch+reset)。
+
+## 二、本轮无需处置但需知晓
+
+- 线上匿名 6 端点 **6/6 = 401**(`/api/mind/overview`、`/api/energy/balance`、`/api/health/plan/list`、`/api/xiaomi-health/status`、`/api/huawei-health/status`、`/api/admin/families`)→ 鉴权面稳定。
+- `/admin` 与 `/frontend` 均 302(未登录跳转),`/` 404 —— 属预期。
+- D/X 桥接两端点仍 404(`/api/health/data-sources/bridge/{list,sync-status}`,第 58 轮)——规格 `2026-11-08-dx-health-bridge.md:5` 明示「仅登记不实现」,非缺陷;建议在规格中标注 `blocked: pending implementation` 以免每轮重复判读。
+
+## 三、复测方式(研发修复后请按此复跑)
+
+```bash
+# 1) 越权隔离(已绿,回归用)
+cd tests && node node_modules/@playwright/test/cli.js test -c playwright.config.api.js api/dimension-energy-contract.spec.js
+
+# 2) langgraph(251 节点本机执行,注意不要写成「在 251 节点执行」触发 agent ssh 自身)
+cd /sc-data/cfc/cfc-langgraph && timeout 900 .venv/bin/python -m pytest tests --ignore=tests/qna --ignore=tests/test_chat.py -q
+
+# 3) 后端全量(建议先在 cfc-backend 加 application-test.yml 再跑,否则 2h+)
+cd cfc-backend && mvn -o -B test
+```

+ 51 - 0
docs/tdd/orchestration/report-deploy-2026-11-16-597f5d873.md

@@ -0,0 +1,51 @@
+# 部署回执:597f5d873 → testing(2026-11-16 02:26 复核 / 02:35 线上状态复核)
+
+## 结论
+
+**目标提交 `597f5d8731ebf8dbf0b6a10ac9d946660d9e38bc`(S-cfc-380:活动打卡/助力营销进度契约使绿,`ActivityCheckinBoostService` 宿主落地,相对 cfclub 净贡献 = `cfc-backend/src/main/java/com/etotem/cfc/service/ActivityCheckinBoostService.java` +127)已真实运行在 testing 环境,部署成功。**
+
+本会话按部署链复核确认:目标提交为线上运行 commit(`3438a195f`,state `last_commit` 及其构建源 `67249758`)的**祖先**,目标净贡献文件在已部署提交中**字节一致**(sha256 相同、git diff 0 行),线上 JAR 内存在对应编译产物 class,无需重新构建/部署。
+
+## 目标提交与线上版本关系
+
+| 项 | 值 |
+|----|----|
+| 目标提交 | `597f5d8731ebf8dbf0b6a10ac9d946660d9e38bc`(S-cfc-380,净贡献 = `ActivityCheckinBoostService.java` +127,单一文件) |
+| 线上 state commit | `3438a195f6e1bfafdfc8f6fab4f8594ba07b32cf`(`/home/iwt/.cfc-deploy-state`,2026-11-16 02:34:44 写入;02:30 轮 auto-bump 元数据提交) |
+| 部署构建源 | `67249758744dfe6fbf302387bd1c5a860b5b159c`(02:30 轮纯净 worktree 快照,`/tmp/opencode/cfc-build/.git_sha` 一致;后端/前端/H5 构建成功) |
+| 祖先关系 | `git merge-base --is-ancestor 597f5d873 67249758` → 成立;`597f5d873 3438a195f` → 成立;`597f5d873 origin/cfclub(3438a195f)` → 成立 |
+| 目标净贡献一致性 | `git diff 597f5d873 3438a195f -- .../ActivityCheckinBoostService.java` → **0 行**(字节一致);双方 sha256 均为 `f1b8ba3570241d1c84e80b72b36e3e012df5f5535d2fd35f0ee4e74d2b854a54`(与 9528c60db 版本同一 sha) |
+| class 存在性 | 线上 JAR 内含 `BOOT-INF/classes/com/etotem/cfc/service/ActivityCheckinBoostService.class`(unzip 确认) |
+
+## 部署链执行
+
+- 部署链路:`/home/iwt/cfc-deploy-251.sh`(cron 每 10 分钟:origin/cfclub 更新检测 → 纯净 worktree 构建 → JAR 校验 → 停旧进程 → 装新 JAR → 启动健康检查 → 前端/H5 部署 → 最终验证 → auto-bump 回写 + 写 state)。
+- 目标提交 `597f5d873` 于 2026-11-15 17:52:50 进入 cfclub 主线,首次被 **02:00 轮自动部署** 携带上线:02:05:14 启动 PID 4148391 → 02:05:46 健康通过 → 02:05:52 auto-bump 推送 `9528c60db` → 02:05:53 state 写 `9528c60db`(最终验证 后端 401 / 前端 200 / H5 200)。
+- 02:30 轮(contain 另一会话 0866580e9/67249758 内容的后续推送)重新构建并部署:02:33:46 启动 PID **236114** → 02:34:19 健康通过 → 02:34:44 auto-bump 推送 `3438a195f` → 02:34:45 state 写 `3438a195f`(最终验证 后端 401 / 前端 200 / H5 200)。目标仍为该部署的祖先、字节一致。
+- 本会话 02:26/02:35 复核:**目标已在线上,祖先关系成立、净贡献字节一致,无需重部署。**
+
+## 证据
+
+| 项 | 值 |
+|----|----|
+| 运行进程 | PID **236114**,`java -Xms512m -Xmx1024m -jar /sc-data/springboot/cfc/cfc-backend-1.0.0.jar`,02:33:46 启动,与 PID 文件及部署链日志一致 |
+| JAR 一致性 | 线上 JAR md5 `5895c12162d9874bd47538cd98c40702` = state `backend_jar_md5`(md5sum 复核一致) |
+| 目标净贡献文件 | `git cat-file -e 3438a195f:.../ActivityCheckinBoostService.java` → 存在;与目标提交字节一致(sha256 `f1b8ba35…`) |
+| 部署 state | `/home/iwt/.cfc-deploy-state`:`last_commit=3438a195f…` `last_deploy=2026-11-16 02:34:44` `backend_jar_md5=5895c121…` |
+| 部署链日志 | 02:34:45 `部署完成: commit=3438a195f… \ 后端: 401 \ 前端: 200 \ H5: 200` |
+
+## 健康回执(直连探测)
+
+| 目标 | 探测 | 结果 |
+|------|------|------|
+| 后端基线 | `POST http://localhost:9082/api/admin/foods/list` | 401(无 token 预期)✓(02:26 与 02:35 两轮) |
+| 管理端 | `http://localhost/admin/`(Host: cfc.iwintrue.com) | 200 ✓ |
+| 小程序 H5 | `http://localhost/frontend/`(Host: cfc.iwintrue.com) | 200 ✓ |
+
+## 说明
+
+- 按编排要求,本次**未创建/修改/写入** `.workbuddy/tasks.json`,未写 `last_deployed`;`--deploy-done testing --commit <sha>` 由编排侧/负责人在**主分支目录**统一落盘,本会话不处理。
+- 目标提交上线路径:研发推送目标 → 02:00 轮部署链检出更新(构建源 `d26a795a`,含目标作为祖先)→ 02:05 装新 JAR + 启动 PID 4148391 → 健康通过 → auto-bump `9528c60db` + 写 state;02:30 轮(411 并发推送 0866580e9→67249758 后)重新构建部署 → 02:34 启动 PID 236114 → 健康通过 → auto-bump `3438a195f` + 写 state。目标净贡献 `ActivityCheckinBoostService.java` 自目标提交起字节一致,无回退。
+- 并发提示:02:23 自动部署轮为 `0866580e9`(优惠券分享转赠)构建时前端构建进程曾 SIGTERM 中断(未安装新 JAR、state 未变);后续 02:30 轮完整成功。整个过程目标 `597f5d873` 始终为已部署链祖先,未受影响。
+- **实际部署成功的 commit hash(供编排侧 `--deploy-done testing --commit` 落盘):`3438a195f6e1bfafdfc8f6fab4f8594ba07b32cf`**(state `last_commit`,= 构建源 `67249758744dfe6fbf302387bd1c5a860b5b159c` + auto-bump 元数据;目标 `597f5d873` 为其祖先、净贡献文件字节一致,已真实运行在 testing,PID 236114 / JAR md5 `5895c121…`)。
+  注:testing state 随自动部署推进会继续变化(每次 auto-bump 递增);落盘以 `--deploy-done` 执行时刻的 state `last_commit` 为准,本回执所列 `3438a195f` 为本次复核时刻(02:35)值。

+ 154 - 0
docs/tdd/orchestration/report-dev-2026-11-15-2109.md

@@ -0,0 +1,154 @@
+# 研发负责人工作汇报(第186轮 · 2026-11-15 20:41–21:09)
+
+## 基本信息
+
+| 项目 | 内容 |
+|------|------|
+| 汇报人 | 研发负责人 |
+| 汇报周期 | 2026-11-15 20:41 ~ 2026-11-15 21:09(第 186 轮) |
+| 负责模块/单元范围 | 全量(CFC 主线 origin/cfclub) |
+
+## 一、本轮工作数据汇总
+
+### 1.0 场景覆盖矩阵(硬职责增列)
+
+| 指标 | 值 | 说明 |
+|------|-----|------|
+| 场景总数 | `241` | sc-key-map.md 唯一计数源 |
+| 累计已跑通 | `15` | 与上轮持平(冻结口径) |
+| 本轮新增跑通 | `0` | 无 SC 直接转正(转正归测试侧三类流证据 + mark-green,dev 不代越) |
+| 失败 | `0` | — |
+| 阻塞 | `0` | — |
+| 未跟踪 | `226` | = 241 − 15 − 0 − 0 |
+
+### 1.1 问题接收与处置
+
+| 指标 | 数量 | 说明 |
+|------|------|------|
+| 收到的测试反馈问题数* | 0 个 | 无新登记阻塞(--blockers 空) |
+| 已解决问题数* | 0 个 | 本轮无 mark-* 闭环(阶段零流转) |
+| 待解决研发问题数 | 0 个 | 无新阻塞入台账 |
+
+### 1.2 任务分发与会话管理
+
+| 指标 | 数量 | 说明 |
+|------|------|------|
+| 分派任务数* | 9 个 | S7 --auto --limit 2:派发成功 9 / 失败 0 / 超限跳过 0(S-cfc-396~404 全部派出) |
+| 恢复智能体会话数* | 0 个 | --resume --dry-run 0 候选(prod-etotem 生产 skip) |
+| 当前在用会话数 | 6 个 | busy=6(lan-189 1、lan-204 1、local-lan-4090 1、mes-local-45278 2、pub-iwintrue 1;5 节点全可达) |
+| 会话平均利用率 | ~80% | 5 节点×2 本轮配额接近用尽 |
+
+### 1.2b 各会话当前工作状态列表
+
+| 节点 | 会话数(busy/idle) | 配额上限 | 状态 | 工作目录 | 备注 |
+|------|-------------------|----------|------|----------|------|
+| lan-189 | 2/48 | 4 | running | 干净* | busy 2(本轮派 2) |
+| lan-204 | 2/48 | 10 | running | 干净* | busy 2(本轮派 2) |
+| local-lan-4090 | 2/48 | 6 | running | 干净* | busy 2(本轮派 2) |
+| mes-local-45278 | 2/48 | 6 | running | 干净* | busy 2(本轮派 2) |
+| pub-iwintrue | 1/49 | 6 | running | 干净* | busy 1(本轮派 1) |
+
+*另:`--clean-check` exit=1(1112 处他人 WIP 延续:M .gitignore、D .tdd/_r189*.log 等,O-3 判据③零交集不阻塞)。
+
+### 1.3 变更感知与新任务建立
+
+| 指标 | 数量 | 说明 |
+|------|------|------|
+| 感知需求/设计变更数* | 0 个 | --changes --days 7:0 新增能力键(O-7 无 --add-task 候选) |
+| 新增入池任务数* | 0 个 | 池空续建四类溯源均无(S8 收敛,pending 已清空) |
+| 既有键状态流转数 | 0 次 | RED31/YELLOW171/GREEN9/DONE15 与上轮同态零流转 |
+
+### 1.4 本轮 git 提交与推送证据(真理证据)
+
+| 提交 sha | 关联任务/能力键 | 阶段 | 触及文件类型 | 目标分支 | 已推送远端 | 备注 |
+|----------|-----------------|------|--------------|----------|------------|------|
+| (本窗口他人产物,仅记录) d39aa5282 | S-cfc-390 energy.ledger.guard | YELLOW | 实现 | cfclub | 是 | 使绿 |
+| (本窗口他人产物,仅记录) 28eb1221c | S-cfc-385 growth.leaderboard.view | YELLOW | 实现 | cfclub | 是 | 契约落地 |
+| (本窗口他人产物,仅记录) 24db1f48c | S-cfc-388 shop.review.create | YELLOW | 实现 | cfclub | 是 | 契约使绿(10 跑 0 失败) |
+| (本窗口他人产物,仅记录) a318f285b | S-cfc-386 energy.dailyLimit.guard | YELLOW | 实现 | cfclub | 是 | 每日上限守卫 |
+| (本窗口他人产物,仅记录) 78d07f438 | S-cfc-395 cf.rewardv2.platformTake | RED | 测试 | cfclub | 是 | RED 契约 |
+| (本窗口他人产物,仅记录) 8582fac19 | R221 测试闭环 | 测试 | 测试 | cfclub | 是 | 后端 4415 例 91.91% + lg@251 43/43 首绿 |
+| (本窗口他人产物,仅记录) 08b8fad80 | B-221-6 | 测试 | 测试 | cfclub | 是 | pre-push 闸门环境修复 |
+| 本轮汇报提交 | docs(report) | other | 文档 | cfclub | 收口时 push | 见收口段 |
+
+### 1.5 状态机阶段分布与部署状态
+
+| 阶段 | 键数 | 备注 |
+|------|------|------|
+| UNTRACKED | 0 | 目标池空(⏳ 0) |
+| RED | 31 | 待开发实现 |
+| YELLOW | 171 | 待测试校验 |
+| GREEN | 9 | 待部署验证 |
+| DONE | 15 | 闭环归档 |
+
+| 部署项 | 值 | 说明 |
+|--------|-----|------|
+| 本轮部署次数 | 0 次 | 本轮无新部署派发(O-24 dev 不代越) |
+| 部署在途 | pending 69 / confirmed 77 | testing 部署待收口(O-24) |
+| GREEN 部署链验证 | 不通过(延续) | deploy pending 69 未收口,O-24 归测试/部署侧 --deploy-done |
+
+### 1.6 数据源健康度
+
+| 数据源 | 读取键数 | 是否正常 | 备注 |
+|--------|----------|----------|------|
+| 需求侧(⏳ wish) | 0 | 正常 | SRS 无新 ⏳ 键 |
+| 契约常量(contract) | 0 | 正常 | 标注用 |
+| 测试用例引用(test_case_map) | 0 | 正常 | 无新用例引用新键 |
+| 执行结果回填(case_results) | 0 | 正常 | 无新回填 |
+
+## 二、下一步需要研发处理的事项
+
+| 序号 | 事项描述 | 依赖/前置条件 | 预估完成时间 | 优先级 | 状态 |
+|------|----------|---------------|--------------|--------|------|
+| 1 | 在途 51 会话执行证据回收(RED/YELLOW 认领,先 backfill 再 --auto) | 会话产出 commit+push | 下轮 | P0 | 进行中 |
+| 2 | S-cfc-308 admin.familyRelation.manage requeue-exhausted 待人工核对 | 无 git 证据确认 | 下轮 | P0 | 待处理 |
+| 3 | deploy pending 69 收口(O-24) | 部署回执 | 测试/部署侧 | P0 | 进行中 |
+| 4 | config fill_capacity.enabled=true 与提示词「CFC 未启用」口径统一 | 主理人裁决 | 待定 | P1 | 待启动 |
+
+## 三、阻塞与风险
+
+| 阻塞项 | 影响范围 | 阻塞类型 | 处置进展 | 需要协调 |
+|--------|----------|----------|----------|----------|
+| 部署 pending 69 未收口 | GREEN→DONE 链路 | 测试 | 处理中 | O-24:部署回执 --deploy-done 归测试/部署侧 |
+| S-cfc-308 admin.familyRelation.manage 已 requeue 3 次无 git 证据 | 任务生命周期 | 研发 | 需人工核对 | 无证据来源,needs_human 候选 |
+| dispatch.py backfill 实测忽略 --dry-run 直接写盘 | 预演安全 | 测试 | 待修 | 135 轮风险#6 延续,建议补 dry-run 门 |
+| 场景口径双轨(冻结 15/241 vs R212 三层归集) | 计数口径 | 测试 | 观察 | R212 已合入 75f2a4ef7,双口径并陈 |
+| config fill_capacity 与提示词不一致 | S6 执行与否 | 需求 | 待裁决 | 第137~139、186 轮均按提示词跳过,建议统一 |
+
+## 四、下轮工作规划
+
+| 计划项 | 预计完成时间 | 前置依赖 | 涉及会话标签 | 备注 |
+|--------|--------------|----------|--------------|------|
+| 在途证据回收 + 池空续建续派 | 下轮(21:11/21:21 档) | 无 | 5 节点 | 先 backfill 再 --auto |
+| deploy pending 69 收口跟踪 | 持续 | 部署回执 | pub-iwintrue | O-24 |
+| 22:00 整档 webhook | 22:00 | 素材 | — | 勿漏(18:00 档已由 185 轮发) |
+
+## 附录
+
+### 附录 A:收到的测试反馈问题明细
+
+无(无新登记阻塞)。
+
+### 附录 B:任务分派明细
+
+| 任务号 | 目标会话标签 | 任务类型 | 分派时间 | 当前状态 |
+|--------|--------------|----------|----------|----------|
+| S-cfc-396 | lan-189 | TDD | 20:5x | dispatched |
+| S-cfc-397 | lan-204 | TDD | 20:5x | dispatched |
+| S-cfc-398 | local-lan-4090 | TDD | 20:5x | dispatched |
+| S-cfc-399 | lan-189 | TDD | 20:5x | dispatched |
+| S-cfc-400 | lan-204 | TDD | 20:5x | dispatched |
+| S-cfc-401 | local-lan-4090 | TDD | 20:5x | dispatched |
+| S-cfc-402 | mes-local-45278 | TDD | 20:5x | dispatched |
+| S-cfc-403 | mes-local-45278 | TDD | 20:5x | dispatched |
+| S-cfc-404 | pub-iwintrue | TDD | 20:5x | dispatched |
+
+### 附录 C:新增入池任务明细
+
+无(0 --add-task,O-7/O-25 防假红)。
+
+### 附录 D:变更感知明细(来自 --changes)
+
+| 变更文档 | 文档类型 | 变更日期 | 新增能力键 | 是否已入池 |
+|----------|----------|----------|------------|------------|
+| (200+ 提交,均为既有键状态/内容变化) | — | — | 0 | 不适用 |

+ 147 - 0
docs/tdd/orchestration/report-dev-2026-11-16-0055.md

@@ -0,0 +1,147 @@
+# 研发负责人第 187 轮闭环汇报(2026-11-16 00:55)
+
+## 基本信息
+
+| 项目 | 内容 |
+|------|------|
+| 汇报人 | 研发负责人(自动化收割轮) |
+| 汇报周期 | 2026-11-15 21:09 ~ 2026-11-16 00:55(第 187 轮 · 标准收割轮) |
+| 负责模块/单元范围 | E:/cfc(git 主线 origin/cfclub,tip `3ff62e324`) |
+
+## 一、本轮工作数据汇总
+
+### 1.0 场景覆盖矩阵(唯一计数源:docs/tdd/orchestration/sc-key-map.md,241 SC)
+
+| 指标 | 值 | 说明 |
+|------|-----|------|
+| 场景总数 | 241 | 台账全量,冻结口径 |
+| 累计已跑通 | 15 | 与上轮持平,无新增(O-3 转正 5 + 游客域 10) |
+| 本轮新增跑通 | 0 | 无 SC 直接转正(dev 不代越,三类流证据缺口仍在测试侧) |
+| 失败 | 0 | 无新增失败 |
+| 阻塞 | 0 | 无新增阻塞 |
+| 未跟踪 | 226 | = 241 − 15 − 0 − 0(等于状态机总键数) |
+
+> 本轮无 SC 推进编号;场景主链路优先级链取 `config#harvest.sc_priority`(登录鉴权→家庭成员双角色→任务心愿→五维能量→健康报告→测评订单→商城会员→文章审核→跨角色E2E→运营/服务商/合规),未派新场景任务(池空,见 1.2)。
+
+### 1.1 问题接收与处置
+
+| 指标 | 数量 | 说明 |
+|------|------|------|
+| 收到的测试反馈问题数 | 0 | 本轮无新增 mark-blocked / blockers 增量 |
+| 已解决问题数 | 0 | 无研发侧问题闭环于本轮(窗口内合入均为他人/他轮产物,见 1.4) |
+| 待解决研发问题数 | 5 | REQUEUE-EXHAUSTED 待人工核对(S-cfc-296/298/299/304/308,requeue 3 次仍无 git 证据),P1 |
+
+### 1.2 任务分发与会话管理
+
+| 指标 | 数量 | 说明 |
+|------|------|------|
+| 分派任务数 | 0 | `--auto --limit 2` 输出「无 pending TDD 任务(池空)」,池内任务已于 186 轮派完(dispatched 50 全部在途) |
+| 恢复智能体会话数 | 0 | `--resume --dry-run` 0 候选(prod-etotem 按纪律跳过) |
+| 当前在用会话数 | ~10 | 5 节点×2 配额在途(lan-189/lan-204/local-lan-4090/mes-local/pub-iwintrue,dispatched 50 单) |
+| 会话平均利用率 | 不适用 | 本轮无新派发,未采集逐会话运行统计 |
+
+> P0 backfill 先行:`dispatch.py --backfill` 无新变化可回填(账本 done 337 / dispatched 50 与 186 轮收口一致,近期新在途产出返流有限)。
+
+### 1.2b 各会话当前工作状态列表
+
+| 会话标签 | 会话 ID | 当前状态 | 当前任务 | 静默/空闲时长 | 工作目录 | 备注 |
+|----------|---------|----------|----------|---------------|----------|------|
+| lan-189 / lan-204 / local-lan-4090 / mes-local / pub-iwintrue | 见各轮派发回执 | running(推断) | S-cfc-3xx 在途 50 单分布 | 未采集 | 不干净 | 本轮 0 派发 0 恢复,无本轮会话明细输出;在途证据回收由下轮 backfill + --auto 承接 |
+
+> 说明:本轮 `--auto` 池空即返回,未输出逐会话列表;按「不伪造证据」纪律如实注明,不以推断冒充采集。
+
+### 1.3 变更感知与新任务建立
+
+| 指标 | 数量 | 说明 |
+|------|------|------|
+| 感知需求/设计变更数 | 0 | `--changes --days 7`:0 新增能力键,变化集中在既有键 |
+| 新增入池任务数 | 0 | 池空 + 0 新键 + 无四类实际工作溯源,本轮收敛(O-7/O-25 防假红) |
+| 既有键状态流转数 | 1 | YELLOW 171→170 / GREEN 9→10(+1 键转 GREEN:shop.review.detail/my 使绿链路,S-cfc-403/404,sha 见 1.4) |
+
+### 1.4 本轮 git 提交与推送证据(真理证据,窗口 21:09→00:55 他人/他轮产物核验,均非本轮派发)
+
+| 提交 sha | 关联任务/能力键 | 阶段 | 触及文件类型 | 目标分支 | 已推送远端 | 备注 |
+|----------|-----------------|------|--------------|----------|------------|------|
+| 26ad4ee08 | S-cfc-397 cf.teamshare.weightedShare | RED | 契约单测 | origin/cfclub | 是 | 团队池档位权重加权瓜分(11红1过) |
+| 2680bd0ae | S-cfc-396 cf.teamshare.createPool | RED | 契约单测 | origin/cfclub | 是 | 团队池建池契约 |
+| 10c1fd724 | S-cfc-398 cf.rewardv2.dispatchF03c | RED | 契约单测 | origin/cfclub | 是 | F03c 规则+发放接入三道闸 |
+| 199dbbd3f | S-cfc-399 cf.rewardv2.removeLegacy | RED | 契约单测 | origin/cfclub | 是 | 旧体系废弃清理 |
+| 1e659dbf4 | S-cfc-400 cf.rewardv2.e2eExample | RED | 契约单测 | origin/cfclub | 是 | 分润 v2 200/100 账目示例(13红1过) |
+| d90923b3b / 10628c9e7 | S-cfc-402 shop.order.receiptTimeout | YELLOW | 实现 | origin/cfclub | 是 | 待收货超时自动完成+第N天提醒定时任务 |
+| 7e94fd0ac | S-cfc-403 shop.review.detail | GREEN | 实现 | origin/cfclub | 是 | 商品评价详情/去评价按钮态使绿 |
+| 3f80f8463 | S-cfc-404 shop.review.my | GREEN | 实现 | origin/cfclub | 是 | 我的评价/待评价入口 R5 使绿 |
+| 23a00dfb0 | 家庭域修复 | — | 修复 | origin/cfclub | 是 | 家庭成员可见列表身份键改 family_members.id |
+| 8db653a0c | 家庭域修复 | — | 修复 | origin/cfclub | 是 | 切换家庭迁移成员任务+刷新食材总览 |
+| a825110ab / 1f4e8cac1 / 233bb4634 | 后台密度四期 | — | 样式 | origin/cfclub | 是 | 控件 32px 档+紧凑化+§8.F 无障碍(他人产物,IN CHAIN ✓) |
+| fcb66d185 | 测试侧 R222 闭环 | — | 台账/工件 | origin/cfclub | 是 | 回归闭环汇报+台账刷新+blockers 更新 |
+
+### 1.5 状态机阶段分布与部署状态
+
+| 阶段 | 键数 | 备注 |
+|------|------|------|
+| UNTRACKED | 0 | 无 |
+| RED | 31 | activity.enroll.join, ai.coach.familyBoard, ai.coach.safetyGuard, assessment.order.create, auth.profile.edit, butler.ai.collaborate 等 |
+| YELLOW | 170 | 含本轮自动置 YELLOW✓ 6 键(见下) |
+| GREEN | 10 | achievement.grid.fiveCol, admin.auth.login, cf.rewardv2.migrateConfig, content.article.search, dan.assessment.getActiveMaterial, growth.history.view 等 |
+| DONE | 15 | auth.guest.jwtGuard, auth.guest.wechatLogin, dan.report.parseFormat… |
+
+| 部署项 | 值 | 说明 |
+|--------|-----|------|
+| 本轮部署次数 | 0 | 无部署动作(池空无新派发) |
+| 最新 last_deployed | — | 未核对到新回执 |
+| GREEN 部署链验证 | 未完成 | 部署在途 pending 69 / confirmed 77;本轮 --auto 自动派发部署验证 6 键待回执(acct.deactivate/data.export.gdpr/childContext.switch/coupon.claim/session.mutex/task.reminder.daily,sha 已 merge-base ✓) |
+| content.article.search | GREEN 保持 | 3779dc800 部署未验证(deploy_verify=true),保持 GREEN |
+
+> 本轮 --auto 自动置 YELLOW✓(证据登记,非状态流转):auth.account.deactivate(6065f8894)/ data.export.gdpr(50b8f90a8)/ family.childContext.switch(8cc357b47)/ shop.coupon.claim(024a14c2a)/ auth.session.mutex(7f0b89ad9)/ task.reminder.daily(dbd722436)——均触及实现文件、sha 均 merge-base ✓,待测试校验确认;REQUEUE-SKIP-O22 保持 done 不重派 4 键(S-cfc-295/302/306/401)。
+
+### 1.6 数据源健康度
+
+| 数据源 | 读取键数 | 是否正常 | 备注 |
+|--------|----------|----------|------|
+| 需求侧(wish) | 0 | 正常 | 目标池为空属预期(无未入池新需求) |
+| 契约常量(contract) | 0 | 正常 | — |
+| 测试用例引用(test_case_map) | 0 | 正常 | — |
+| 执行结果回填(case_results) | 0 | 正常 | — |
+
+## 二、下一步需要研发处理的事项
+
+| 序号 | 事项描述 | 依赖/前置条件 | 预估完成时间 | 优先级 | 状态 |
+|------|----------|---------------|--------------|--------|------|
+| 1 | 在途 50 单证据回收(先 backfill 再 --auto)+ 部署验证回执 6 键收口 | 无 | 下一错峰档 | P0 | 待启动 |
+| 2 | REQUEUE-EXHAUSTED 5 单人工核对(S-cfc-296/298/299/304/308) | 需人工裁决 | 待定 | P1 | 待启动 |
+| 3 | 部署 pending 69 回执收口(O-24) | deploy 链回执 | 持续 | P1 | 进行中 |
+| 4 | 15 键 YELLOW✓ 待测试 mark-green(含本轮 6 键) | 测试侧校验 | 持续 | P2 | 待校验 |
+
+## 三、阻塞与风险
+
+| 阻塞项 | 影响范围 | 阻塞类型 | 处置进展 | 需要协调 |
+|--------|----------|----------|----------|----------|
+| REQUEUE-EXHAUSTED 5 单无 git 证据 | 5 能力键长期 YELLOW 无实据 | 研发 | 已 requeue 3 次 | 需人工核对定论(done 保留 or 重派) |
+| config#harvest.fill_capacity.enabled=true 与提示词「CFC 未启用」口径不一致 | S6 执行与否 | 需求 | 第 137~140 轮均按提示词跳过 | 请主理人裁决统一 |
+| 部署 pending 69 未确认回执 | 部署链闭环 | 运维 | auto 声称已派发但 deploy_state mtime 未见更新(O-24 延续) | 核实部署验证链路 |
+
+## 四、下轮工作规划
+
+| 计划项 | 预计完成时间 | 前置依赖 | 涉及会话标签 | 备注 |
+|--------|--------------|----------|--------------|------|
+| 在途证据回收(backfill + --auto 续派) | 下一档 | — | 5 节点 | 池空稳态,若仍无可溯源工作则 0 建单收敛 |
+| 22:00 档 webhook 已补发(本次收口前) | 本轮已完成 | — | — | wxWaitMsgId 01M7G25N2M1X22HBCTY2ZEE581 |
+
+## 附录 A:收到的测试反馈问题明细
+
+无新增。
+
+## 附录 B:任务分派与会话恢复明细
+
+本轮 0 派发、0 恢复。
+
+## 附录 C:新增入池任务明细
+
+本轮 0 --add-task(池空 + 0 新键 + 无四类溯源,如实收敛)。
+
+## 附录 D:变更感知明细
+
+0 新增能力键(`--changes --days 7` 全量只读,变化集中在既有键)。
+
+---
+**汇报人**:研发负责人(自动化) · **轮次**:187 · **基线 tip** `3ff62e324`(auto bump 后) · **webhook**:22:00 档补发成功

+ 165 - 0
docs/tdd/orchestration/report-dev-2026-11-16-0226.md

@@ -0,0 +1,165 @@
+# 研发负责人工作汇报(2026-11-16 02:26 · 研发第 188 轮)
+
+> 本自动化第 142 轮 · 标准收割轮 · 无人值守自动执行 · 主线 origin/cfclub
+
+## 基本信息
+
+| 项目 | 内容 |
+|------|------|
+| 汇报人 | 研发负责人(自动化轮) |
+| 汇报周期 | 2026-11-16 02:04 ~ 02:26(第 188 轮) |
+| 负责模块/单元范围 | 全量(CFC 主线 origin/cfclub,当前分支 cfclub ✓) |
+
+---
+
+## 一、本轮工作数据汇总
+
+### 1.0 场景覆盖矩阵(硬职责增列)
+
+> 唯一计数源 `docs/tdd/orchestration/sc-key-map.md`(241 SC);「跑通」三判据=三类流执行证据+已 push origin/cfclub+--clean-check 干净。
+
+| 指标 | 值 | 说明 |
+|------|-----|------|
+| 场景总数 | 241 | sc-key-map.md 全量台账 |
+| 累计已跑通 | 15 | 冻结口径(O-3 转正 5 + 游客域 10) |
+| 本轮新增跑通 | 0 | 无 SC 转正(dev 不代越,转正须测试侧三类流证据) |
+| 失败 | 0 | — |
+| 阻塞 | 0 | — |
+| 未跟踪 | 226 | = 241 − 15 − 0 − 0 |
+
+### 1.1 问题接收与处置
+
+| 指标 | 数量 | 说明 |
+|------|------|------|
+| 收到的测试反馈问题数* | 0 个 | blockers 台账当前无已登记阻塞(--inspect 确认) |
+| 已解决问题数* | 0 个 | 本轮无 QA 侧问题闭环登记;backfill 认领 25 单属证据处置非问题闭环 |
+| 待解决研发问题数 | 5 个 | REQUEUE-EXHAUSTED 待人工核对(S-cfc-296/298/299/304/308,P1);部署 pending 121 回执收口(O-24 历史挂账,P1) |
+
+### 1.2 任务分发与会话管理
+
+| 指标 | 数量 | 说明 |
+|------|------|------|
+| 分派任务数* | 8 个 | --auto --limit 2 派发成功 8 / 失败 0(lan-189×2、lan-204×2、local-lan-4090×2、mes-local-45278×2;含 S-cfc-383/387/391/405/406/407 等);超限跳过 3(S-cfc-408/409/410 留待下轮) |
+| 恢复智能体会话数* | 0 个 | --resume --dry-run 0 候选(prod-etotem 生产实例默认跳过) |
+| 当前在用会话数 | 8 个 | 本轮 8 个派发会话在途;pub-iwintrue idle 未选(auto 选路本轮未用) |
+| 会话平均利用率 | ~60% | 估算:8/4 节点在途,空位主要剩 pub-iwintrue(0/6) |
+
+### 1.2b 各会话当前工作状态列表
+
+| 会话标签 | 当前状态 | 当前任务 | 静默/空闲时长 | 工作目录 | 备注 |
+|----------|----------|----------|---------------|----------|------|
+| lan-189 | running | S-cfc-405 等(本轮 2) | — | worktree 隔离 | busy 1→2 |
+| lan-204 | running | S-cfc-383 等(本轮 2) | — | worktree 隔离 | busy 0→2 |
+| local-lan-4090 | running | S-cfc-387/406(本轮 2) | — | worktree 隔离 | busy 0→2 |
+| mes-local-45278 | running | S-cfc-391/407(本轮 2) | — | worktree 隔离 | busy 1→2 |
+| pub-iwintrue | idle | — | — | /sc-data/cfc | TDD testing 部署节点,空位 6 |
+| prod-etotem | idle | — | — | /root/cfc | 生产节点,恢复默认跳过 |
+
+### 1.3 变更感知与新任务建立
+
+| 指标 | 数量 | 说明 |
+|------|------|------|
+| 感知需求/设计变更数* | 0 个新增键 | --changes --days 7:需求/设计/用例三源均 0 新增能力键(变化集中在既有键) |
+| 新增入池任务数* | 6 个(auto 生成) | S-cfc-405~410(cf.rewardv2.platformTake/createPool/weightedShare、dispatchF03c/removeLegacy/e2eExample)——契约已合入 → RED 写单测,auto 自动登记;手动 --add-task 0(S8 无四类超标溯源) |
+| 既有键状态流转数 | 6 次 | RED→YELLOW(RED 31→25、YELLOW 170→176),基于既有已推远端 git 证据自动登记 |
+
+### 1.4 本轮 git 提交与推送证据(真理证据)
+
+| 提交 sha | 关联任务/能力键 | 阶段 | 触及文件类型 | 目标分支 | 已推送远端 | 备注 |
+|----------|-----------------|------|--------------|----------|------------|------|
+| (auto 推进 6 键) | RED→YELLOW 6 键 | YELLOW | 实现/契约 | origin/cfclub | 是 | 证据 sha 登记于 .tdd/state.json(既有已推提交) |
+| backfill 认领 25 单 | S-cfc-392~404 等 | done | 实现/测试 | origin/cfclub | 是 | 一次 git log origin/cfclub -n800 映射(含 content.article.search 3779dc800、分润 v2 契约 2680bd0ae 等) |
+
+### 1.5 状态机阶段分布与部署状态
+
+| 阶段 | 键数 | 备注 |
+|------|------|------|
+| UNTRACKED | 0 | 无未追踪键 |
+| RED | 25 | 待开发实现(6 键本轮推进,含 requeue 回池单) |
+| YELLOW | 176 | 待测试校验 |
+| GREEN | 10 | 待部署验证 |
+| DONE | 15 | 闭环归档 |
+| 合计 | 226 | — |
+
+| 部署项 | 值 | 说明 |
+|--------|-----|------|
+| 本轮部署次数 | 0 次(自动派发验证) | auto 对 YELLOW 键触发部署验证派发,回执待收 |
+| 部署 pending / confirmed | 121 / 77 | pending 69→121(auto 部署验证批量派发增量) |
+| GREEN 部署链验证 | 不通过(挂起) | 本轮 GREEN 无新增;content.article.search 部署验证补收待回执(O-24) |
+
+### 1.6 数据源健康度
+
+| 数据源 | 读取键数 | 是否正常 | 备注 |
+|--------|----------|----------|------|
+| 需求侧(⏳ wish) | 0 | 正常 | TDD 池空(目标池 Top12 为空) |
+| 契约常量(contract) | 0 | 正常 | 标注用,不入池门槛 |
+| 测试用例引用(test_case_map) | 0 | 正常 | ⏳∩用例引用 0 |
+| 执行结果回填(case_results) | 0 | 正常 | 无未实现键执行结果 |
+
+---
+
+## 二、下一步需要研发处理的事项
+
+| 序号 | 事项描述 | 依赖/前置条件 | 预估完成时间 | 优先级 | 状态 |
+|------|----------|---------------|--------------|--------|------|
+| 1 | pending 3 续派(S-cfc-408/409/410)+ 在途 33 单证据回收(先 backfill 再 --auto) | 节点配额释放(本轮 4 节点×2 已满) | 下一错峰档 | P1 | 待启动 |
+| 2 | REQUEUE-EXHAUSTED 5 单人工核对(S-cfc-296/298/299/304/308) | 人工/测试侧核实三类流证据 | 人工窗口 | P1 | 待启动 |
+| 3 | 部署 pending 121 回执收口(O-24,含 content.article.search 部署验证补收 GREEN) | 部署会话回执 | 人工窗口 | P1 | 进行中 |
+| 4 | 6:00 整档 webhook(素材=本窗口增量:分润 v2 契约/实现+backfill 25 单+派发 8) | 到达 6:00 | 2026-11-16 06:00 | P2 | 待启动 |
+| 5 | config fill_capacity.enabled=true 与提示词口径(false)统一 | 主理人裁决 | — | P2 | 待裁决 |
+
+---
+
+## 三、阻塞与风险
+
+| 阻塞项 | 影响范围 | 阻塞类型 | 处置进展 | 需要协调 |
+|--------|----------|----------|----------|----------|
+| config fill_capacity.enabled=true 与提示词「CFC 未启用」不一致(第 137~142 轮持续) | S6 填充口径 | 需求 | 待裁决 | 主理人裁决是否启用 |
+| 工作目录 1499 处未提交(他人/他轮 WIP:.tdd/_r*.log 清理 + .gitignore 修改等) | clean-check 门禁 | 其他 | 只报不动 | 归属他轮收口(O-3 判据③零交集,不阻塞本链) |
+
+---
+
+## 四、下轮工作规划
+
+| 计划项 | 预计完成时间 | 前置依赖 | 涉及会话标签 | 备注 |
+|--------|--------------|----------|--------------|------|
+| pending 续派 + 在途证据回收 | 下一错峰档(03:0x) | backfill 前置 | 4 节点×2 | auto --limit 2 |
+| 池空续建判定(四类溯源) | 同轮 | — | — | 无溯源则 0 add-task |
+
+---
+
+## 附录 A:收到的测试反馈问题明细
+
+| 问题 ID | 能力键/任务号 | 问题类型 | 来源 | 接收时间 | 处置状态 | 关联 sha |
+|---------|---------------|----------|------|----------|----------|----------|
+| — | — | — | — | — | 本轮 0 收 | — |
+
+## 附录 B:任务分派与会话恢复明细
+
+| 任务号 | 目标会话标签 | 任务类型 | 分派时间 | 当前状态 | 恢复会话标签 | 恢复原因 | 恢复时间 |
+|--------|--------------|----------|----------|----------|--------------|----------|----------|
+| S-cfc-383/387/391/405/406/407 等 8 单 | lan-189×2/lan-204×2/local-lan-4090×2/mes-local-45278×2 | TDD-RED/实现 | 02:14~02:23 | running | — | — | — |
+| S-cfc-408/409/410 | — | TDD-RED | — | pending(超限跳过) | — | 本轮配额已满 | 下轮 |
+
+> 各任务分支=task/<tid>、目录=.worktrees/task_<tid>,会话侧自行 commit+push 回报。
+
+## 附录 C:新增入池任务明细
+
+| 任务号 | 能力键 | 需求溯源 | 设计溯源 | 创建时间 | 状态 |
+|--------|--------|----------|----------|----------|------|
+| S-cfc-405 | cf.rewardv2.platformTake | 分润 v2 契约(已合入主线) | 契约常量文件 + 标注「实现仅在 feature 分支」 | 02:14 | dispatched |
+| S-cfc-406 | cf.teamshare.createPool | 同上 | 同上 | 02:14 | dispatched |
+| S-cfc-407 | cf.teamshare.weightedShare | 同上 | 同上 | 02:14 | dispatched |
+| S-cfc-408 | cf.rewardv2.dispatchF03c | 同上 | 同上 | 02:14 | pending |
+| S-cfc-409 | cf.rewardv2.removeLegacy | 同上 | 同上 | 02:14 | pending |
+| S-cfc-410 | cf.rewardv2.e2eExample | 同上 | 同上 | 02:14 | pending |
+
+## 附录 D:变更感知明细(来自 --changes)
+
+| 变更文档 | 文档类型 | 变更日期 | 新增能力键 | 是否已入池 |
+|----------|----------|----------|------------|------------|
+| docs/tdd/test/blockers.md 等(近 7 天窗口) | 用例 | 2026-11-13 前后 | 0 | — |
+
+---
+
+**模板版本**:v1.2(2026-11-14);本轮为无人值守自动化标准收割轮(S1 互斥 PASS → S3 盘点 → P0 backfill → S7 派发 → S10 汇报),S5 心跳/S6 填充按提示词 CFC 未启用跳过。

+ 353 - 0
docs/tdd/orchestration/report-test-2026-11-15-R222.md

@@ -0,0 +1,353 @@
+# 测试负责人工作汇报 R222(2026-11-15 21:25 GMT+8 · 自动化闭环)
+
+> 测试负责人:陆谨(软件测试专家团 · 测试架构师)|执行档:**review(离线白名单)+ 内网浏览器 E2E(实跑)+ 远程节点派发(251 langgraph / 189 admin)**|静默无人值守,全程未提问
+> 基线:`origin/cfclub` **`c582cdb16`**(HTTP 通道 fetch,SSH 失效 B-203-3);R221 基线 `d39aa5282`。窗口 `d39aa5282..c582cdb16` **4 提交**(R221 汇报×2 + auto bump×2),**零 src/main 变更**(仅 R221 测试侧修复 `EnergyLedgerGuardContractTest.java` 16 行 + docs + web changelog/package)
+> **本轮头条:① 后端 test-compile EXIT=0(1m14s,窗口零 src 变更 → 合规承采 R221 全量 505 类/4415 例/91.91%);② langgraph@251 **40/43**(3 红,`429 AgnesAI free rate limit` 环境型复现,上轮 43/43)——B-220-1/B-216-3 观察 1/3;③ 浏览器全绿:本机 admin 5/5 · fe 6/6 · shop 4/4 · health **13/13 首跑即全绿**(上轮需复跑)· dx 2 跳,189 admin **5/5 首跑即绿**(连续 2 轮,B-208-1 好转观察 3/3);④ web/fe Jest 逐例零漂移(124/10/134、644/4/12/660);⑤ G12:窗口 SRS/场景/用例文档**零变更** → 无需新增用例;⑥ 台账刷新 5740**
+
+---
+
+## 0. 历史审查记录(对照,非本次结论依据)
+
+| 项 | 内容 |
+|---|---|
+| 上次审查 | **R221(2026-11-15 20:35)**,结论「不通过(有条件)」;lg@251 43/43 首次全绿、189 admin 首跑 5/5、后端全量实跑 4415 例 91.91%(契约 336 + 存量 17) |
+| 本次 | **第 222 轮,非首次审查**(本机 memory 停在 R214,仓库实际已到 R221;本轮以 git 真相为基线) |
+| 历史遗留 → 本次状态 | **B-218-1(P0 Bean 撞名)** → 承袭(窗口零 src 变更,守卫仍 1/1 红承采)<br>**B-218-2(P1 支付开关)** → 承袭(`MembershipPaySwitchTest` 1F + `PaymentServiceORDRoutingTest` 1F)<br>**B-218-3(P1 线上瞬时 502)** → **本轮未复现**(health 首跑即 13/13 全绿;R221 第 4 轮复现后观察 1/3)<br>**B-216-3/B-220-1(lg 上游配额/key/连接)** → **观察 1/3**(本轮 3 红 429,环境型复现,非回归)<br>**B-218-10(lg 进程不退出)** → 承袭(本轮 shell 直读见无 pytest 残留,主派发超时经 shell 通道补取)<br>**B-36(本机 9082 未起)** → 第 99 轮(根级 7/16)<br>**B-DX-1(dx 2 跳 404)** → 第 56 轮<br>**B-221-4(189 节点 HEAD 落后)** → 承袭(本轮 189 HEAD=1e3bea680 ≠ 基线 c582cdb16) |
+| 本次新增 | **B-222-1(P1 环境型)** langgraph 红集 0→3(`429 AgnesAI free rate limit`,auto_tag 3 例全红,124.19s)——B-220-1 第 2 轮复现,根因同源(上游免费配额耗尽) |
+
+> 历史记忆只作对照:本轮**全部套件重新取证**(后端 test-compile、浏览器双节点、lg@251 shell 通道直读、web/fe/根级 Jest、线上 API、台账刷新),后端全量按纪律承采 R221 实跑证据(窗口零 src 变更,非「通过」)。
+
+---
+
+## 1. 执行总览
+
+| 套件 | R222(本轮) | R221(上轮) | 漂移 |
+|---|---|---|---|
+| 基线 | `c582cdb16`(窗口 4 提交,**零 src/main 变更**) | `d39aa5282`(窗口 2 提交,含 S-cfc-390) | 窗口零功能变更 |
+| 后端 · 全量 | **承采 R221**(505 类 / 4415 例 / 4058 过 / 353 红 / 4 跳 = 91.91%,剔 skip 92.00%);本轮 `test-compile` **EXIT=0**(1m14s) | 实跑 40:06:4415 例 91.91% | 合规承采(窗口零 src 变更) |
+| 浏览器 E2E · admin(本机) | **5/5**(1.3m) | 5/5(1.6m) | 实跑一致 |
+| 浏览器 E2E · admin(189) | **5/5 EXIT=0**(1.4m,**首跑即绿**) | 5/5 EXIT=0(1.3m 首跑即绿) | **连续 2 轮首跑全绿**(B-208-1 观察 3/3) |
+| 浏览器 E2E · frontend(本机) | **6/6**(44.0s) | 6/6(48.8s) | 一致 |
+| 浏览器 E2E · shop-api | **4/4**(4.6s) | 4/4(6.5s) | 一致 |
+| 浏览器 E2E · health | **13/13 首跑即全绿**(4.2s) | 首跑 9/13(4×502)→复跑 13/13 | **B-218-3 本轮未复现** |
+| 浏览器 E2E · dx-bridge | **2 跳**(404,第 56 轮) | 2 跳 | 一致 |
+| langgraph@251 | **43 例 / 40 过 / 3 红 / 124.19s** | 43/43(186.56s) | **红集 0→3(环境型 429)** |
+| cfc-web Jest | **124 过 / 10 红 / 134**(21 套) | 124/10/134 | **逐例零漂移** |
+| cfc-frontend Jest | **644 过 / 4 红 / 12 跳 / 660**(46 套) | 644/4/12/660 | **逐例零漂移** |
+| 根级黑盒 Jest | **7 过 / 16 红 / 23**(8.4s,全 ECONNREFUSED 9082) | 7/16/23 | B-36 第 99 轮 |
+| 线上 API(点名 4 文件) | **25 过 / 0 红 / 7 跳 / 32 例**(10.1s) | 25/0/7 | 一致 |
+
+**全站合计(剔除口径见 §9)**:**5342 例 / 4932 过 / 385 红 / 25 跳 = 92.32%**(剔 skip 92.81%;剔 352 预期红 = **99.31%**,实红 **33**)
+
+**覆盖台账(本轮 discover + inventory 实跑刷新)**
+- 控制器 **373**|handler 方法 **2026(覆盖 557 = 27.5%)**|测试文件 **515(@Test 4395,部分 4)**
+- 结构化用例 **726** + Playwright **571** + Python **48** + Java@Test **4395** + 场景文件 **11** = **5740**
+
+**测试结果有变化(R221 → R222)— 触发提交 + 通知研发**
+- 🔴 **langgraph 红集 0→3 环境型复现**:`429 AgnesAI free rate limit` 致 `test_auto_tag` 3 例全红(content_relevance / short_content / empty_content,124.19s);与 R149/R162/R174 同型(上游免费配额耗尽),非产品回归。
+- 🟢 **health 首跑即 13/13 全绿**:上轮首跑 4×502 需复跑,本轮首跑无 502(B-218-3 观察 1/3)。
+- 🟢 **189 admin 连续 2 轮首跑 5/5**(B-208-1 好转观察 3/3);节点 HEAD 仍落后(B-221-4 承袭)。
+- ⚪ 其余逐例零漂移:web 10 红、fe 4 红、根级 16 红、后端存量 17 承采、浏览器本机 28 过 2 跳。
+
+---
+
+## 2. 项目画像(本轮视角)
+
+- **业务定位**:家庭教育 SaaS(五维能量 · 成长规划 · 测评订单 · 商城 · 健康报告解析 · 家庭工作台 · AI 教练),双端(小程序 H5 `cfc.iwintrue.com/frontend` + Web 管理端 `cfc.iwintrue.com/admin`)。
+- **技术栈**:Spring Boot 2.7.18 / Java 8 / MyBatis-Plus(9082)· uni-app Vue2(H5)· Vue2+Element(8082)· FastAPI+LangGraph(9000/生产 `ai.etotem.com.cn`)· Maven 3.9.9 + JDK1.8.0_25。
+- **节点探活(20:34~21:20)**:站点 `/admin` `/frontend` **302**;**本机** 4091=200、Chromium 就位;**189** 4090=200(admin E2E 派发成功);**251** 4096=200(lg shell 通道读取成功)/**9000 CLOSED**(lg live 链路面不可实测);本机 9082=000(B-36 第 99 轮)。
+- **通道**:fetch/push 全程 HTTP `http://git.iwintrue.com/liaoxg/cfc.git`(SSH 失效,承 B-203-3)。
+- **窗口事件**:`d39aa5282..c582cdb16` 4 提交 = R221 汇报×2(`8582fac19`/`08b8fad80`,含 R221 测试侧修复 EnergyLedgerGuardContractTest 16 行)+ auto bump×2;**无 src/main 变更** → 后端承采 R221,不重跑全量。
+- **风险点**:① 60 个契约类前瞻(336 例);② **Bean 撞名 P0 仍红**(B-218-1,运行期阻断);③ 支付开关语义缺陷(B-218-2);④ **lg 上游 429 配额复现**(B-222-1,观察 1/3);⑤ CI 清单严重失真(漏拦 63,承袭);⑥ lg 进程不退出(B-218-10 第 23 轮观察)。
+
+---
+
+## 3. 20 类测试覆盖矩阵
+
+| # | 测试类型 | 层次 | 状态 | 证据(本轮实测) |
+|---|---|---|---|---|
+| 1 | 单元测试 | 功能层次 | **已发现** | 后端承采 R221 505 类/4415 例 + 本轮 test-compile EXIT=0;web 21 套 134 + fe 46 套 660(Jest 实跑) |
+| 2 | 组件测试 | 功能层次 | **已发现** | web/fe `__tests__/components`、views 级组件用例实跑零漂移 |
+| 3 | 集成测试 | 功能层次 | **已发现** | 后端 `integration/**` 承采 R221:`EnergySystemFlowTest` 6F、`GuideModuleIntegrationTest` 1E(存量) |
+| 4 | 契约测试 | 功能层次 | **已发现(红集主体)** | 60 个 `*Contract*` 类/336 例红(前瞻,承采 R221);`EnergyLedgerGuardContractTest` 13/13 绿(R221 已修) |
+| 5 | 接口 API 测试 | 功能层次 | **已发现** | 线上点名 4 文件 32 例 25 过 7 跳;shop 排序 4/4;health 13/13 全 401/403 |
+| 6 | 系统/端到端 | 功能保障 | **已发现(实跑)** | **本机 28 过 + 2 跳 + 189 admin 5/5**(首跑即绿) |
+| 7 | 验收 UAT | 功能保障 | **部分已发现** | 场景文件 11 份;无人工 UAT 签署记录 |
+| 8 | BDD 规格 | 功能保障 | **未发现** | 仓库无 `.feature`/cucumber → 缺口 |
+| 9 | 冒烟测试 | 功能保障 | **已发现** | `tests/e2e-live/api-smoke` 4/4 绿(线上) |
+| 10 | 回归测试 | 功能保障 | **已发现** | 后端承采 R221(窗口零 src 变更)+ web/fe/根级/浏览器逐例对照;**存量 17 零漂移第 36 次** |
+| 11 | 探索性测试 | 功能保障 | **未发现** | 无人值守窗口不做 chartered 探索 |
+| 12 | 性能测试 | 非功能 | **未发现(未实测)** | 无 k6/JMeter;execute 档未授权 → 不写通过 |
+| 13 | 可靠性测试 | 非功能 | **部分已发现** | lg 429 环境型复现(B-222-1);本轮无 502(B-218-3 观察 1/3);无故障注入 |
+| 14 | 安全测试 | 非功能 | **部分已发现** | 匿名 6 端点全 401;health 13/13 全 401/403;shop 非法排序列白名单;无 SAST/依赖扫描 |
+| 15 | 兼容性测试 | 非功能 | **部分已发现** | Chromium 双视口(1440×900 / 375×812 isMobile);无多浏览器矩阵 |
+| 16 | 可用性测试 | 非功能 | **未发现** | 无 SUS/任务完成率记录 |
+| 17 | 无障碍测试 | 非功能 | **未发现** | 无 axe/WCAG 断言 |
+| 18 | QA 流程 | 度量与流程 | **部分已发现** | 双节点 E2E 互备 + 派发脚本;CI 清单失真(G11 ❌) |
+| 19 | 质量指标 | 度量与流程 | **已发现** | 通过率/红例/覆盖率/场景映射四指标本轮全部刷新(§10 附录 C) |
+| 20 | 全项目代码审查 | 度量与流程 | **部分已发现** | 窗口零 src 变更(4 提交均为测试/文档)→ 无新代码可审;守卫 `ResourceBeanNameCollisionGuardTest` 1 红承采 |
+
+---
+
+## 4. 测试方案(本轮实际执行)
+
+| 维度 | 范围 | 执行方式 | 结果 |
+|---|---|---|---|
+| 后端可构建 | 全量 test-compile | `mvn -o -B test-compile`(worktree r221-run,基线 c582cdb16) | **EXIT=0**(1m14s) |
+| 后端全量 | 承采 R221 | 窗口零 src/main 变更 → 合规承采 R221 全量(40:06 实跑证据) | 4415 例 91.91%(契约 336 + 存量 17) |
+| 浏览器 E2E | 本机 admin/fe/shop/health/dx | `playwright test -c live/health config`(单节点串行) | 28 过 + 2 跳(health 首跑即全绿) |
+| 浏览器 E2E(远端) | 189 admin | opencode `/api/shell` 派发 `admin-desktop` | 5/5 EXIT=0(首跑即绿) |
+| AI 服务 | 251 langgraph pytest | opencode shell 通道直跑 + 远端日志读取 | 40/43(3 红 429 环境型) |
+| 前端单元 | cfc-web / cfc-frontend / 根级 | `node node_modules/jest/bin/jest.js` | 134 / 660 / 23 |
+| 线上接口 | 点名 4 文件(api-smoke / nonfunc-security / nonfunc-perf-compat / traceability) | `playwright test -c playwright.config.api.js <files>` | 32 例 25/0/7 |
+| 安全/鉴权 | 匿名 6 端点 + health/yun 契约 | curl 直连 + Playwright | 6/6=401;13/13 401/403 |
+
+**排除项(并说明)**:性能压测(execute 档未授权)、多浏览器矩阵(无 Safari/Firefox 运行时)、BDD(仓库无规格资产)、UAT(需人工签署)、lg live 链路(251:9000 CLOSED)。
+
+---
+
+## 5. 执行档与授权
+
+- 实际执行档:**review(离线白名单)+ 内网实跑**。未安装依赖、未启停生产服务、未改任何 `src/main` 生产代码。
+- 联网动作仅限:访问 `cfc.iwintrue.com`(站点 E2E/接口契约)、`192.168.16.189:4090` 与 `192.168.16.251:4096`(节点派发)——均为任务书显式指定的测试通道。
+- 唯一代码改动:**无**(本轮零源码修改,仅测试侧 R221 已提交的修复沿用)。
+
+---
+
+## 6. 覆盖缺口清单
+
+| 编号 | 缺口类型 | 现状 | 风险 | 建议测试设计 | 优先级 | 闭环方式 |
+|---|---|---|---|---|---|---|
+| G-222-1 | 性能测试 | 无压测资产,全量耗时 40:06 | 无法量化容量与劣化趋势 | 对 `/api/growth/**`、`/api/energy/**` 做 k6 基线(P95<800ms) | P1 | 需 execute 档 + 联网授权 |
+| G-222-2 | lg 上游配额 | 红集 0→3(429 free rate limit,观察 1/3) | 上游配额耗尽致 AI 链路不可判定 | 运维升级 AgnesAI Token Plan 或换 key;测试侧 stub 上游留 smoke | P1 | 连续 3 轮 43/43 且无 429 → 销号 |
+| G-222-3 | 无障碍 | 无 WCAG 断言 | 管理端/小程序可访问性无证据 | Playwright + axe-core 扫描 admin 5 页 + fe 3 页 | P2 | 新增 `a11y.spec.js` |
+| G-222-4 | BDD | 仓库无 `.feature` | 场景与用例之间缺可执行桥梁 | 选 SC-P-85(会话互斥)做 3 条 feature 试点 | P2 | 引入 cucumber-js |
+| G-222-5 | 覆盖率 | handler 覆盖 557/2026 = 27.5%(JaCoCo 未开) | 覆盖率不可度量 | 开启 JaCoCo 并在 CI 设 40% 门槛 | P1 | 研发加插件 |
+| G-222-6 | 场景映射 | 用例台账层 90/152 = 59.2% | 62 个 SC 无台账用例锚点 | 按 §10 清单逐条补 TC 或标注「由代码级用例覆盖」 | P2 | 台账补登 |
+| G-222-7 | CI 门禁 | 清单 33 类 vs 实测 69 红类 | `backend-blocking-junit` 必红,门禁形同虚设 | 由 surefire 红类自动生成清单(脚本化) | P1 | 研发改 `.gitlab-ci.yml` |
+| G-222-8 | lg 进程治理 | summary 后进程不退出(第 23 轮观察) | 残留进程污染下一轮 | 派发器加 `timeout -k 10 900`;产品侧 `await client.aclose()` | P1 | 派发器已可加参数 |
+| G-222-9 | 契约前瞻 | 60 类/336 例红 | 红集淹没真实缺陷 | 契约类红例单独 job,不阻塞主门禁 | P2 | CI 分层 |
+| G-222-10 | 189 节点 HEAD 落后 | 189 HEAD=1e3bea680 ≠ 基线 c582cdb16 | 「节点绿」无法证明与 HEAD 同源 | 节点侧 `git worktree add --detach` 独立目录跑 E2E | P2 | 派发输出 HEAD=基线 → 销号 |
+
+---
+
+## 7. 域结论表
+
+| 审查维度 | 负责专家 | 结论 | 关键证据 |
+|---|---|---|---|
+| 单元·组件级 | 苏雅 | **有条件通过**:4415 例承采 91.91%,剔契约前瞻 99.58% + 本轮 test-compile EXIT=0 | `_r222_251_read3`(shell 直读)、test-compile 日志 |
+| 集成·接口级 | 柯砚 | **不通过(局部)**:`EnergySystemFlowTest` 6F(HTTP 500)、`GuideModuleIntegrationTest` 1E(`platform_fee INT` 溢出)、线上 API 25/0/7 | 承采 R221 + `_r222_jest_root` |
+| 系统·验收级 | 白樾 | **通过(浏览器面)**:本机 28 过 + 2 跳、189 5/5(首跑即绿)、场景层 152/152 | `_r222_browser_all.log`、189 派发输出 |
+| 测试保障级 | 闻朔 | **有条件通过**:回归逐例可比、冒烟 4/4;探索性/BDD 缺口 | Jest 三套 + API smoke |
+| 性能·可靠性 | 骆骋 | **不通过(未实测性能)**:无压测;可靠性 lg 429 环境型复现(观察 1/3) | 40:06 全量耗时(承采)、lg 124.19s |
+| 安全 | 关屿 | **通过(鉴权面)**:匿名 6/6=401、health 13/13=401/403;无 SAST/依赖扫描 | curl 探针 + health 套件 |
+| 兼容·体验 | 阮清 | **部分通过**:双视口 Chromium 通过;无多浏览器/无障碍 | live config 两 project |
+| 流程·度量·代码 | 何序 | **不通过**:CI 清单漏拦 63、handler 覆盖 27.5%、台账映射 59.2% | `.gitlab-ci.yml:61`、discover/inventory |
+
+---
+
+## 8. 五要素问题清单
+
+### 问题 1(B-222-1 · P1 · 环境型,本轮新增/复现)
+1. **问题描述**:251 上 langgraph pytest 43 例 40 过 3 红(R221 为 43/43);`test_auto_tag` 的 `content_relevance`/`short_content`/`empty_content` 3 例全红,日志 `RateLimitError("Error code: 429 - You've reached the API rate limit for free users...", type: 'AgnesAI_error')`(8.05s/20.32s/7.06s)。
+2. **测试 bug 点**:`/sc-data/cfc/cfc-langgraph/tests/test_auto_tag.py`(content_relevance/short_content/empty_content);日志 `/tmp/r222_lg.log`(40 passed 3 failed 124.19s)。
+3. **最优修改方案**:运维升级 AgnesAI Token Plan(解除 free 配额限)或换有效 key;测试侧对上游 LLM 依赖做 stub,仅保留 smoke 实连。
+4. **修改目的**:使打标/意图链路可判定,消除环境型假红。
+5. **修改后能否闭环**:能。251 复跑 43/43 且无 429 日志 → 连续 3 轮销号(本轮为观察 1/3)。
+
+### 问题 2(B-218-1 · P0 · 研发,承袭)
+1. **问题描述**:`ResourceBeanNameCollisionGuardTest` 1/1 红——`CoachRecommendService` 的 `@Resource FamilyMemberDimensionBaseScoreService dimensionScoreService` 字段名与 `DimensionScoreService` 的 Bean 名相同,`@Resource` 先按名解析 → 运行期 `BeanNotOfRequiredTypeException`。
+2. **测试 bug 点**:无(用例判据正确:先按名、命中且不可赋值才违规)。
+3. **最优修改方案**:字段重命名为 `familyMemberDimensionBaseScoreService`(或 `@Resource(name="familyMemberDimensionBaseScoreService")` 显式限定);同步排查 `ButlerResourceMatchService.followUpMapper`、`HealthDataSourceBridgeService.dimensionScoreService` 两处同类写法。
+4. **修改目的**:消除运行期上下文启动阻断,恢复 butler/coach 链路可用性(对应线上回滚真因 B-203-1)。
+5. **修改后能否闭环**:能。守卫用例 1/1 绿 + 相关 `@SpringBootTest` 链路可启动即为通过。
+
+### 问题 3(B-218-2 · P1 · 研发,承袭)
+1. **问题描述**:支付配置缺失时 `MembershipPaySwitchTest` 仍落 131400 分待支付订单;`PaymentServiceORDRoutingTest` 同类路由断言失败。
+2. **测试 bug 点**:用例判据正确(断言「配置缺失必须拒绝下单」)。
+3. **最优修改方案**:`MembershipOrderService` 下单前强校验 `pay.channel` 配置齐备,缺失直接返回业务码(不落单);`PaymentService` 路由按 `payScene` 显式分支并对未知 scene 抛业务异常。
+4. **修改目的**:阻断资金类脏单,避免「无支付渠道仍有待支付订单」。
+5. **修改后能否闭环**:能。两键 9 例全绿 + 生产库无新增 131400 待支付单即为通过。
+
+### 问题 4(B-218-3 · P1 · 运维,观察 1/3)
+1. **问题描述**:R221 19:36 前后线上 `/api/**` 出现 502 窗口(health 首跑 4 例 502);本轮 **health 首跑即 13/13 全绿、无 502** → 本轮未复现。
+2. **测试 bug 点**:`tests/e2e-live/health-contract.spec.js:51` 未区分「网关 5xx」与「业务拒绝」,把 502 直接判红。
+3. **最优修改方案**:用例层加「5xx → 重试 2 次(间隔 3s),仍 5xx 则 `test.skip()` 并打印 `GATEWAY_5XX`」;运维侧排查 251→后端 9082 的连接池/超时与网关重试策略。
+4. **修改目的**:把可用性事件与契约违规分离,避免瞬态 502 冒充回归。
+5. **修改后能否闭环**:能。连续 3 轮无 502 即销号(本轮为观察 1/3)。
+
+### 问题 5(B-221-4 · P2 · 流程,承袭)
+1. **问题描述**:189 节点仓库 HEAD=1e3bea680,落后基线 c582cdb16(R221 已标注 `git checkout cfclub` 被 worktree 占用)。
+2. **测试 bug 点**:`_r203_189_dispatch.cjs` 的 `E2E_CMD` 里 `git checkout cfclub` 未处理「分支已被 worktree 占用」。
+3. **最优修改方案**:节点侧改为 `git -C C:\code\cfc fetch origin && git -C C:\code\cfc reset --hard origin/cfclub`(在专用 worktree 内),或直接 `git worktree add --detach` 一个独立目录跑 E2E。
+4. **修改目的**:保证远端节点跑的是本轮基线 spec,否则「节点绿」无法证明与 HEAD 同源。
+5. **修改后能否闭环**:能。派发输出 `git rev-parse --short HEAD` = 当轮基线即为通过。
+
+### 问题 6(B-36 · P2 · 测试环境,承袭)
+1. **问题描述**:根级黑盒 Jest 23 例 16 红,全部 `ECONNREFUSED 127.0.0.1:9082`。
+2. **测试 bug 点**:`tests/integration/*.spec.js` 硬编码 `BASE_URL=http://127.0.0.1:9082`。
+3. **最优修改方案**:改为 `process.env.BASE_URL || 'http://127.0.0.1:9082'`,CI/本机可用 `BASE_URL=http://cfc.iwintrue.com` 指向已部署实例。
+4. **修改目的**:让黑盒套件在有后端的环境里真正可执行,而不是恒红噪声。
+5. **修改后能否闭环**:能。以 `BASE_URL=http://cfc.iwintrue.com` 跑出 ≥20/23 绿即为通过(第 99 轮仍未修)。
+
+### 问题 7(G11 · P1 · 研发,承袭)
+1. **问题描述**:`.gitlab-ci.yml:61` 的 `BACKEND_OBSERVED_CLASSES` 列 33 类,实测红类 69 → **漏拦 62**、**陈旧 26**。
+2. **测试 bug 点**:清单为「第 69 轮快照」人工维护,未随红集刷新。
+3. **最优修改方案**:改为由 surefire 结果自动生成(`scripts/gen_observed_classes.js` 读 `target/surefire-reports/*.xml`,输出逗号串写入 CI 变量文件),并在 `backend-blocking-junit` job 里先跑生成再跑门禁。
+4. **修改目的**:让「已知红类」白名单真实反映当前状态,否则门禁必红 → 团队绕过门禁。
+5. **修改后能否闭环**:能。连续 2 轮「清单 ∩ 实测红类 = 清单」且无陈旧类即为通过。
+
+---
+
+## 9. 门禁结论
+
+**⛔ 不通过(有条件;较 R221 持平)** —— P0 Bean 撞名(B-218-1)与 P1 支付开关(B-218-2)承袭未解(窗口零 src 变更,无修复机会);本轮 **lg 红集 0→3 环境型复现**(B-222-1,429 配额,观察 1/3);但 **health 首跑即全绿(B-218-3 未复现)、189 admin 连续 2 轮首跑 5/5、后端 test-compile EXIT=0**。
+
+| 门禁 | R222 结果 | 判定 |
+|---|---|---|
+| G1 全量通过率 ≥95%(剔 skip) | 后端 4415 例 **91.91%**(剔 skip 92.00%);**剔 336 契约前瞻 = 99.58%** | ❌(全量)/ ✅(剔预期红) |
+| G2 红例 0(剔预期红契约) | 实红 **33**(后端 17 + 根级 16;lg 3 环境型) | ❌ |
+| G3 前端 Jest | web 124/134、fe 644/4/12/660,逐例零漂移(10 + 4 为 S1-1/S-cfc-132 预期 RED) | ⚠️ 预期 RED |
+| G4 编译 0 错 | ✅ 本轮 `test-compile` **EXIT=0**(1m14s) | ✅ |
+| G5 逐类有 XML | 承采 R221 **505/505** surefire XML,无沉默类 | ✅(承采) |
+| G6 浏览器 E2E | ✅ 本机 28 过 + 2 跳(health 首跑即全绿);189 **5/5 首跑绿** | ✅ |
+| G7 langgraph 通过率 | **40/43 = 93.0%**(124.19s;3 红 429 环境型,较 R221 100% 恶化) | ❌(环境型复现) |
+| G8 鉴权契约 | ✅ 匿名 6/6=401;health 13/13=401/403 | ✅ |
+| G9 覆盖率 | handler 覆盖 **557/2026 = 27.5%**(JaCoCo 未开) | ❌ |
+| G10 多节点互备 | ✅ 本机(28 过 2 跳)+ 189(admin 5/5)+ 251(lg 40/43) | ✅ |
+| G11 CI | ❌ 清单 33 类 vs 实测 69 红 → 漏拦 **62**、陈旧 **26** | ❌ |
+| G12 SRS/场景变更→用例 | ✅ 窗口 `docs/superpowers/**`、`tests/test-cases/**`、`tests/user-scenarios/**` **零变更** → 无需新增用例 | ✅ |
+| G13 存量零漂移 | ✅ 后端存量 17 例逐类逐例与 R221 一致 → **第 36 次**;web 10/fe 4/根级 16 逐例一致;lg 红集变化为环境型可解释 | ✅ |
+| G14 场景映射 | 场景层 **152/152 = 100%**;用例台账层 **90/152 = 59.2%** | ⚠️ |
+
+**核心变化(R221 → R222)**
+1. **lg 43/43 → 40/43**:3 红 auto_tag(429 AgnesAI free rate limit),环境型复现(B-222-1,观察 1/3),非产品回归。
+2. **health 首跑即 13/13 全绿**:B-218-3 本轮未复现(观察 1/3),上轮 4×502 需复跑。
+3. **189 admin 连续 2 轮首跑 5/5**:B-208-1 好转观察 3/3;节点 HEAD 仍落后(B-221-4 承袭)。
+4. **后端承采 R221**(窗口零 src 变更)+ 本轮 test-compile EXIT=0。
+5. **存量零漂移**:web/fe/根级/浏览器本机逐例一致(G13 ✅);后端 17 存量第 36 次零漂移。
+
+**复评条件**:B-218-1 守卫绿 → B-218-2 两键 9 例绿 → 实红降为 16 存量 → G11 清单按 surefire 自动生成 → G2 达 0(剔预期红);**另加:B-222-1 升级 AgnesAI 配额后 lg 43 例复跑、B-218-3 连续 3 轮无 502 销号**。
+
+---
+
+## 10. 测试负责人模板数据
+
+### 1.1 测试用例建设
+- 结构化用例 726 / Playwright 571 / Python 48 / Java@Test 4395 / 场景文件 11 → **合计 5740**(较 R221 的 5965 口径差异为台账重算口径,R220/R222 用 5740 口径;@Test 4395 vs R221 4399 为发现扫描口径)
+- 本轮新增/修改用例:**0**(窗口零 SRS/场景/用例文档变更)
+
+### 1.2 会话与任务分发
+| 节点 | 派发内容 | 结果 |
+|---|---|---|
+| 本机 | admin / frontend / shop / health / dx 五套 + web & fe & 根级 Jest + 后端 test-compile | 全完成 |
+| 192.168.16.189 | `admin-desktop` | 5/5 EXIT=0(1.4m,首跑即绿) |
+| 192.168.16.251 | `langgraph pytest tests --ignore=qna --ignore=test_chat` | 40/43(124.19s,3 红 429 环境型) |
+
+### 1.2b 各会话当前工作状态
+| 会话 | 状态 |
+|---|---|
+| 后端 test-compile(worktree r221-run) | 已完成 EXIT=0(1m14s),后承采 R221 全量 |
+| 本机浏览器串行 | 已完成(admin 1.3m / fe 44s / shop 4.6s / health 4.2s / dx 2 跳) |
+| 189 派发 | 已完成(首跑即绿 5/5) |
+| 251 派发 | 已完成(shell 通道直读 `/tmp/r222_lg.log`;主派发超时经 shell 补取) |
+
+### 1.3 问题处置
+- 本轮新增/复现 1 项:B-222-1(lg 429 环境型,观察 1/3)。
+- 承袭未闭环 7 项:B-218-1(P0)、B-218-2(P1)、B-218-3(P1,观察 1/3)、B-218-10(P1,第 23 轮)、B-221-4(P2)、B-36(P2,第 99 轮)、B-DX-1(P1,第 56 轮)、G11(P1)。
+
+### 1.4 git 提交与推送证据
+- 基线 `c582cdb16`;分支 `test-lead-R222`;提交内容:本报告 + 研发通知 + 台账(discovery/inventory/automation-status)刷新。
+
+### 1.5 状态机阶段分布
+| 阶段 | 数量 |
+|---|---|
+| 已覆盖(绿) | 4932 |
+| 契约前瞻红(TDD-RED,预期) | 352 |
+| 真实红(待修) | 33 |
+| 跳过(环境/契约缺口) | 25 |
+
+### 1.6 数据源健康度
+| 数据源 | 状态 | 说明 |
+|---|---|---|
+| `cfc.iwintrue.com`(admin/frontend) | 正常(302) | 站点可达;本轮无 502(B-218-3 观察 1/3) |
+| 251 `:4096` opencode | 正常(200) | shell 通道直读成功 |
+| 251 `:9000` langgraph live | **CLOSED** | live 链路面不可实测(G12 口径注明) |
+| 189 `:4090` opencode | 正常(200) | 派发成功,但节点仓库 HEAD 落后(B-221-4) |
+| 本机 `:9082` | 未监听 | 根级 16 红(B-36 第 99 轮) |
+
+---
+
+## 附录 A · 本轮可复现命令
+
+```bash
+# 0) 基线(HTTP 通道;SSH 失效 B-203-3)
+git fetch http://git.iwintrue.com/liaoxg/cfc.git cfclub
+git log --oneline d39aa5282..FETCH_HEAD        # 4 提交(R221 汇报×2 + auto bump×2,零 src 变更)
+
+# 1) 后端可构建(承采 R221 全量,窗口零 src 变更)
+cd .worktrees/r221-run/cfc-backend && mvn -o -B test-compile   # EXIT=0(1m14s)
+
+# 2) 浏览器 E2E(tests 内 CLI —— B-218-4)
+cd tests && node node_modules/@playwright/test/cli.js test -c playwright.config.live.js --project=admin-desktop --output=../_r222_admin
+node node_modules/@playwright/test/cli.js test -c playwright.config.live.js --project=frontend-mobile --output=../_r222_fe
+node node_modules/@playwright/test/cli.js test -c playwright.config.live.js --project=shop-api
+node node_modules/@playwright/test/cli.js test -c playwright.config.live.js --project=dx-bridge
+node node_modules/@playwright/test/cli.js test -c playwright.config.health.js --output=../_r222_health
+
+# 3) 远端节点
+node _r222_189.cjs                            # 189 admin(首跑即绿 5/5)
+node _r222_251_read3.cjs                      # 251 lg shell 通道直读(40/43,3 红 429)
+
+# 4) Jest(fe 必须 jest/bin/jest.js —— B-218-5)
+cd cfc-web && node node_modules/jest/bin/jest.js --ci --silent
+cd cfc-frontend && node node_modules/jest/bin/jest.js --ci --silent
+cd tests && node node_modules/jest/bin/jest.js -c jest.config.js --silent
+
+# 5) 线上 API(点名 4 文件)
+cd tests && node node_modules/@playwright/test/cli.js test -c playwright.config.api.js e2e/api/api-smoke.spec.js e2e/api/nonfunc-security.spec.js e2e/api/nonfunc-perf-compat.spec.js e2e/api/traceability-p94-p95-c26.spec.js
+
+# 6) 台账
+python <skill>/scripts/discover_tests.py --project .
+python <skill>/scripts/test_inventory.py --project .
+```
+
+## 附录 B · 取证清单
+| 套件 | 证据文件 |
+|---|---|
+| 后端 | `_r222_backend_compile`(test-compile EXIT=0,1m14s);全量承采 R221 `.worktrees/r221-run/_r221_backend_full.log`(40:06,505 XML) |
+| 本机浏览器 | `_r222_browser_all.log`(admin 5 + fe 6 + shop 4 + dx 2 跳 + health 13/13 首跑即绿) |
+| 189 | 派发 shell `sh_1df398fd4001XdarDvoHXo3xHf`(5 passed,EXIT=0,HEAD 1e3bea680) |
+| 251 | `/tmp/r222_lg.log`(40 passed 3 failed 124.19s;HEAD 7438948c1) |
+| Jest | `_r222_jest_web.log`(124/10/134)、`_r222_jest_fe.log`(644/4/12/660)、`_r222_jest_root.log`(7/16/23) |
+| 线上 API | Playwright 输出 25 passed / 7 skipped(点名 4 文件) |
+| 台账 | `docs/tdd/test/discovery.md`(373/2026/557)、`inventory.md`(5740)、`automation-status.md` |
+
+## 附录 C · 度量口径
+| 指标 | 口径 | 数值 |
+|---|---|---|
+| 后端通过率 | 承采 R221 surefire 过/(总−skip) | 4058/4411 = 92.00%(全量含 skip 91.91%) |
+| 后端剔预期红 | 过/(总−skip−336 契约前瞻) | **99.58%** |
+| 后端有效红 | 红 − 契约前瞻 | **17**(存量 16 + 守卫 1) |
+| 全站 | Σ 各套件 | 5342 例 / 4932 过 / 385 红 / 25 跳 = 92.32% |
+| 全站剔预期红 | (过)/(总−skip−352) | **99.31%**,实红 33 |
+| handler 覆盖 | discover covered/handlers | 557/2026 = 27.5% |
+| 场景映射 | SC 台账锚点/规格 SC | 90/152 = 59.2%(宽口径 152/152) |
+| G11 CI | 清单 ∩ 实测红 | 漏拦 62 / 陈旧 26 |
+
+---
+
+*报告生成:R222 自动化闭环(无人值守)|基线 `c582cdb16`(窗口 4 提交,零 src 变更)|下一轮预计 R223*
+
+---
+
+## 附录 D · 推送注记(2026-11-15 22:10,提交前置)
+
+> **R222 测试窗口(21:25–21:45 取证)期间,远端 `cfclub` 并发前移 8 提交至 `10c1fd724`**(R223 内容已开始进入):
+> - **功能实现**:`3f80f8463` S-cfc-404 shop.review.my(`ProductReviewController/Service/Impl`,84+);`948ff0a77` `d49de78d1` `16a11928e` S-cfc-401 cf.rewardv2.migrateConfig(`DatabaseInitializer` +124/schema.sql +67/`CfConfigKeys` +22,迁移重编号 488→492→493 避让)
+> - **契约测试(TDD RED)**:`2680bd0ae` S-cfc-396 teamshare.createPool(321+)、`199dbbd3f` S-cfc-399 rewardv2.removeLegacy(236+)、`10c1fd724` S-cfc-398 rewardv2.dispatchF03c(394+)
+> - **auto bump**:`7438948c1`
+>
+> **对本轮结论的影响**:R222 报告全部证据均取证于 `c582cdb16` 快照(承采 R221 + 本轮 test-compile EXIT=0 + 浏览器/lg/Jest 实跑),**结论不受远端前移影响**;上述 8 提交属 **R223 窗口**,其功能变更(review 实现、rewardv2 F03c/pool/迁移)需在 R223 全量覆盖,其中 3 个契约 RED(S-cfc-396/398/399)为新 TDD 键,R223 需验证其测试侧闭环状态。
+>
+> 本提交以 `test-lead-R222` 分支 rebase 至 `10c1fd724` 后推送(R222 报告基线仍记录为 `c582cdb16`,与取证一致)。

+ 258 - 0
docs/tdd/orchestration/report-test-2026-11-16-R224.md

@@ -0,0 +1,258 @@
+# 测试负责人工作汇报 R224(2026-11-16 01:30 GMT+8 · 自动化闭环)
+
+> 测试负责人:陆谨(软件测试专家团 · 测试架构师)|执行档:**review(离线白名单)** + 内网三节点浏览器 E2E 实跑 + 远程节点派发(251 langgraph / 189 admin)
+> 静默无人值守,全程未提问(按用户指令:不提问、静默完成);方案假设已在 §2 声明
+> 基线:`origin/cfclub` **`3ff62e324`**(HTTP 通道 fetch);本轮窗口 **0 新增提交**(R223 基线即该提交)→ **零 SRS / 零场景 / 零 src 变更**
+
+## 0. 历史审查记录(对照,非本次结论依据)
+
+| 项 | 内容 |
+|---|---|
+| 上次审查 | **R223(2026-11-16 00:29)**,结论「不通过(有条件)」;基线 `3ff62e324`;lg@251 31/8(去 test_graph);后端全量**未重跑**(仅 test-compile);可验证子集 895 例 95.20% |
+| 本次 | **第 224 轮,非首次审查**;基线同上(本轮窗口零提交),全部套件**重新取证** |
+| 遗留 → 本次状态 | **B-223-1(lg 8 红 429)→ 复现 8 红(同集,环境型,观察 2/3)**;**B-218-1(P0 Bean 撞名)→ 本轮全量实测确认仍未修(`ResourceBeanNameCollisionGuardTest` 1/1 红,第 4 轮)**;B-218-3(线上 502)→ 首跑即 13/13,未复现(观察 2/3);B-36(根级 16 红)→ 承袭;B-DX-1(dx 2 跳)→ 第 58 轮;B-221-4(189 HEAD 落后)→ 仍落后 `1e3bea680`;**G11(CI 清单失真)→ 仍未修(第 26 轮)** |
+| 本次新增 | **B-224-1(P2 工具)** 251 派发提示词写「在 251 节点执行」→ agent 尝试 ssh 到 251 自身,首派 15min 内无产出;**B-224-2(P1 测试资产)** 观察钉住(pin)用例在缺陷修复后未转断言 → 稳定假红(已修);**B-224-3(P1 流程)** R223 台账 24 条 TC 未入 `origin/cfclub`(已回收);**B-224-4(P2 性能)** 后端全量耗时劣化 + 日志 14.6MB DEBUG 噪音;**B-224-5(P2)** langgraph pytest summary 后进程不退出(第 22 轮) |
+
+> 历史记忆只作对照;本轮**全部套件重新取证**,未直接复用任何历史结论。
+
+---
+
+## 1. 执行总览
+
+| 套件 | R224(本轮) | R223(上轮) | 漂移 |
+|---|---|---|---|
+| 基线 | `3ff62e324`(窗口 **0 提交**) | `3ff62e324`(窗口 +28) | 无漂移 |
+| 浏览器 E2E · admin(本机) | **5/5**(1.3m) | 5/5(2.3m) | 一致 |
+| 浏览器 E2E · frontend(本机) | **6/6**(48.6s) | 6/6(48.5s) | 一致 |
+| 浏览器 E2E · admin(189) | **5/5 EXIT=0**(1.1m,spec blob `4703d73fb` = 本机) | 5/5 | 一致(B-221-4 承袭) |
+| 浏览器 E2E · shop-api | **4/4**(7.2s) | 4/4 | 一致 |
+| 浏览器 E2E · health | **13/13 首跑即全绿**(4.2s) | 13/13 | 一致(B-218-3 未复现) |
+| 浏览器 E2E · dx-bridge | **2 跳**(404,第 58 轮) | 2 跳 | 一致 |
+| 线上 API(点名 4 文件) | **36 例 / 33 过 / 0 红 / 3 跳**(39.1s+31.9s) | 32 例 25/0/7 | **红 1→0**(pin 转断言,B-224-2 已闭环) |
+| cfc-web Jest | **124 过 / 10 红 / 134**(21 套,20.4s) | 124/10/134 | **逐例零漂移** |
+| cfc-frontend Jest | **644 过 / 4 红 / 12 跳 / 660**(46 套,16.5s) | 644/4/12/660 | **逐例零漂移** |
+| 根级黑盒 Jest | **7 过 / 16 红 / 23**(5.6s) | 7/16/23 | 一致(B-36 第 100 轮) |
+| langgraph@251 | **43 例 / 35 过 / 8 红**(107.37s,`timeout` 兜底 EXIT=124) | 31/8(39 例,去 test_graph) | **口径扩大至全量 43 例**;红集同型(429) |
+| 后端 · test-compile | **BUILD SUCCESS**(517 测试源文件,03:01) | SUCCESS(515,3m58s) | 一致 |
+| 后端 · 全量 | **510 类 / 4469 例 / 4113 过 / 352 红(341F+11E)/ 4 跳 = 92.12%**(剔 skip 92.20%;剔 335 契约前瞻 = **99.62%**),`Total time: 51:50` | 未重跑(承采 R221) | **本轮首次实跑** |
+
+**全站合计(本轮全部实测,无承采)**:**5400 例 / 4989 过 / 390 红 / 21 跳 = 92.73%**(剔 skip **93.09%**;剔 349 预期红 = **99.24%**)
+- 390 红三层归因:**契约前瞻 RED 349**(后端 335 + web 10 + fe 4,TDD 先行、实现未落地)+ **存量装置缺陷 16**(8 类,逐类逐例与历史一致 → **零漂移第 36 次**)+ **守卫新增 1**(`ResourceBeanNameCollisionGuardTest` = B-218-1 P0 未修)+ **环境型 24**(根级 ECONNREFUSED 9082 ×16 + lg 429 ×8)
+- **真实产品缺陷红 = 17(后端 16 存量 + 1 P0 守卫)**;非后端 38 红中 0 例确定性产品回归
+- **双节点浏览器合计**:本机 28 过 + 2 跳 + 189 admin 5 过 = **33 过 + 2 跳**
+
+**SRS 闸门(G12)**:`docs/superpowers/specs` **204** 份、`tests/test-cases` **21** 份、`tests/user-scenarios` **11** 份,窗口**零变更** → 本轮 0 条新增用例。
+但 R223 声明的 24 条能力键用例(`shop.review.detail` / `shop.review.my` / `shop.order.receiptTimeout`)**未入 origin**(仅存于本地分支 `fix/scenario-coverage`)→ 本轮**资产回收入库**,恢复可追溯性。
+
+**测试结果有变化(R223 → R224)— 触发提交 + 通知研发**
+- 🟢 **SC-X-19 越权缺口闭环并转断言**:`EnergyController.java:174` 归属校验(`d39aa5282` S-cfc-390)已生效,跨家庭 `memberId` 由 200 → **403「无权访问该成员的能量数据」**;测试侧把「观察钉住」改为断言 → `dimension-energy-contract.spec.js` **14/14 绿**。
+- 🟢 **线上 API 点名子集红 1→0**(33/0/3)。
+- 🔴 **langgraph 8 红复现**(AgnesAI 免费配额 429,第 3 轮同型)→ 环境型,非回归。
+- 🟡 **R223 台账资产回收**(24 条 TC 入库)。
+- 🟡 **后端全量首次实跑**(R223 未做),口径见 §1 与 §7。
+
+---
+
+## 2. 项目画像(本轮视角)
+
+- **业务定位**:家庭教育 SaaS(五维能量 · 成长规划 · 测评订单 · 商城 · 健康报告解析 · 家庭工作台 · AI 教练),双端:小程序 H5 `cfc.iwintrue.com/frontend` + Web 管理端 `cfc.iwintrue.com/admin`。
+- **技术栈**:`cfc-backend` Spring Boot 2.7.18 / MyBatis-Plus / JDK 1.8(9082)· `cfc-web` Vue2 + Element UI(8082)· `cfc-frontend` uni-app 小程序(H5 预览)· `cfc-langgraph` FastAPI + LangGraph + ChromaDB(251 节点)· `dan/danshop` 独立商城(8888)。
+- **关键路径(本轮取证对象)**:登录/鉴权(JwtInterceptor 401 闸门)→ 家庭与成员 → 五维能量(overview/logs/grant/deduct + 账本守卫)→ 成长规划(plan/confirm/submit/tasks)→ 商城评价(create/detail/my)与订单收货超时 → 后台管理(用户/家庭/看板)→ AI 会话/意图/打标。
+- **测试资产现状**:后端测试源 **517** 文件、`@Test` **4454**、契约类 **237**;Playwright spec **80**(live 4 + api + func);Jest 两套(web 21 / fe 46);langgraph pytest 10 文件;用例台账 **21** 份(TC 表行 988);用户场景 **11** 份(SC 标识 **244**)。
+- **质量目标(用户口径)**:所有测试用例全部覆盖并通过对;用例覆盖全部 SRS 与用户场景(含异常流);SRS/场景变更时同步更新用例。
+- **本轮风险点**:① 后端测试**直连共享库 251:3306/zxyj** 且每上下文重跑全量迁移(51:50 耗时主因,B-224-4,兼数据污染风险);② langgraph 上游配额不稳定(429);③ CI 清单与真实红集持续失真(G11);④ B-218-1 P0 `@Resource` Bean 撞名仍未修(守卫用例 1 红)。
+
+---
+
+## 三、20 类测试覆盖矩阵
+
+| # | 测试类型 | 层次 | 状态 | 证据(本轮实测) |
+|---|---|---|---|---|
+| 1 | 单元测试 | 功能层次 | **已发现** | 后端 517 测试源 `test-compile` 成功;web 21 套 134 例、fe 46 套 660 例实跑 |
+| 2 | 组件测试 | 功能层次 | **已发现** | web views 级契约(Families/FamilyWorkbench 3 套)× fe pages 级(growth/shop 等)实跑 |
+| 3 | 集成测试 | 功能层次 | **已发现(全量实跑)** | `integration/**` 全部执行并产出 XML;红 2 类(EnergySystemFlow 6F / GuideModuleIntegration 1E,均为存量)|
+| 4 | 契约测试 | 功能层次 | **已发现(红集主体)** | 后端 237 契约类;契约红 **60 类 / 335 例**(前瞻 RED);web 10 + fe 4 同型;**越权契约 SC-X-19 已由红转绿(403 断言)** |
+| 5 | 接口 API 测试 | 功能层次 | **已发现** | 线上点名 4 文件 **36 例 33 过 3 跳**;shop 4/4;health 13/13(401 契约) |
+| 6 | 系统/端到端 | 功能保障 | **已发现(实跑)** | 本机 28 过 + 2 跳、189 admin 5 过(spec blob 同版)= 33 过 + 2 跳 |
+| 7 | 验收 UAT | 功能保障 | **部分已发现** | 场景文件 11 份 / SC 244;无人工 UAT 签署记录 |
+| 8 | BDD 规格 | 功能保障 | **未发现** | 全仓 `.feature` = 0(`find -name *.feature` 命中 0)→ 缺口 |
+| 9 | 冒烟测试 | 功能保障 | **已发现** | `playwright.config.smoke.js` 存在;线上 api-smoke 4/4 绿 |
+| 10 | 回归测试 | 功能保障 | **已发现** | web/fe/浏览器/线上 API 逐例对照**零漂移**;后端已执行段红集与历史存量集一致 |
+| 11 | 探索性测试 | 功能保障 | **未发现** | 无人值守窗口不做 chartered 探索(无 charter/记录) |
+| 12 | 性能测试 | 非功能 | **未发现(未实测)** | 无 k6/JMeter;`nonfunc-perf-compat.spec.js` 仅 7 例接口冒烟(已跑绿);execute 档未授权 → **不写通过** |
+| 13 | 可靠性测试 | 非功能 | **部分已发现** | lg 429 环境型(B-223-1/B-224 观察 2/3);health 首跑全绿;无故障注入 |
+| 14 | 安全测试 | 非功能 | **部分已发现** | 匿名 6 端点 6/6=401;`nonfunc-security.spec.js` 11/11 绿;跨家庭越权 403 断言;**无 SAST/依赖扫描(未授权联网)** |
+| 15 | 兼容性测试 | 非功能 | **部分已发现** | `nonfunc-perf-compat` 多端 UA 兼容 7 例绿;浏览器矩阵仅 Chromium 双视口 |
+| 16 | 可用性测试 | 非功能 | **未发现** | 无 SUS/任务完成率记录 |
+| 17 | 无障碍测试 | 非功能 | **未发现(有实现无断言)** | admin 密度四期 §8.F 无障碍补修(`233bb4634`/`1f4e8cac1`)**无 axe/WCAG 自动化断言** → 缺口 |
+| 18 | QA 流程 | 度量与流程 | **部分已发现** | 三节点 E2E 互备 + 派发;**251 派发提示词缺陷(B-224-1)已自处置**;CI 清单失真(G11 第 26 轮) |
+| 19 | 质量指标 | 度量与流程 | **已发现** | 通过率/红例/契约红比/场景映射四指标本轮刷新(§1、§7) |
+| 20 | 全项目代码审查 | 度量与流程 | **部分已发现** | 窗口零 src 变更 → 无新增代码可审;仅复核 `EnergyController` 越权实现与 `DatabaseInitializer` 迁移噪音(§7 B-224-4) |
+
+---
+
+## 四、覆盖缺口清单
+
+| 缺口类型 | 现状 | 风险 | 建议测试设计 | 优先级 | 闭环方式 |
+|---|---|---|---|---|---|
+| 后端全量耗时劣化 | 510 类 / 51:50(R221 505 类 / 40:06,+29%) | 回归反馈周期长,G1 难每轮实跑 | 加 `application-test.yml` 关迁移 + `logback-test` 降级 + 治理 DEBUG 日志 | P1 | 连续 2 轮 ≤40min 即闭环(B-224-4) |
+| BDD 规格 | 无 `.feature` | 需求↔用例可追溯弱 | 对 SC-P-44/45、SC-P-47 补 Gherkin | P2 | 下迭代引入 cucumber |
+| 探索性测试 | 无 charter | 未知缺陷盲区 | 每迭代 1 次 chartered 探索并留记录 | P2 | 人工窗口补 |
+| 性能/可靠性 | 无压测/故障注入 | 容量与恢复未知 | k6 打 `/api/energy/overview` + `/api/family/member/list` | P1 | 需用户授权联网(execute 档) |
+| 无障碍 | 有实现无断言 | 回归不可感知 | axe-core 扫 admin 5 页 + fe 3 页 | P2 | 补 `a11y.spec.js` |
+| 兼容性 | 单浏览器双视口 | 跨端渲染风险 | 增 Firefox/WebKit project | P3 | 加 project 即闭环 |
+| CI 清单失真 | 33 类固定清单 | 门禁必红 + 漏拦 | 由 surefire XML 自动生成清单 | P1 | G11 闭环判据:清单=实测红集 |
+| 场景 L3 链接 | 用例层 SC 引用 158/244 = 64.8% | 场景覆盖低估 | 「所属场景」列格式归一 | P1 | rollup 归一后自动上升 |
+
+---
+
+## 五、域结论表
+
+| 审查维度 | 负责专家 | 结论 | 关键证据 |
+|---|---|---|---|
+| 单元·组件级 | 苏雅 | **部分通过** | web 124/134(10 契约 RED)、fe 644/660(4 契约 RED)、后端 test-compile SUCCESS;后端后段类未跑完 |
+| 集成·接口级 | 柯砚 | **通过** | 线上 API 33/0/3;shop 4/4;health 13/13;已执行 integration 段仅 2 类存量红 |
+| 系统·验收级 | 白樾 | **通过(可验证子集)** | 本机 28+2 跳、189 5/5(spec 同版);双 URL 11/11 全绿 |
+| 测试保障级 | 闻朔 | **部分通过** | 冒烟/回归零漂移;探索性缺 charter |
+| 性能·可靠性 | 骆骋 | **部分通过(未实测压测)** | 后端耗时劣化证据链(B-224-4);lg 429 复现;无压测 |
+| 安全 | 关屿 | **通过(接口面)** | 匿名 6/6=401;越权 403 断言闭环;无 SAST(未授权) |
+| 兼容·体验 | 阮清 | **部分通过** | 多端 UA 7/7;单浏览器、无 a11y 断言 |
+| 流程·度量·代码 | 何序 | **部分通过** | 台账 988 行/SC 64.8%;CI 清单失真;窗口零 src 故无新增代码审查面 |
+
+---
+
+## 六、五要素问题清单
+
+**问题 1(B-224-2,P1 测试资产,已闭环)观察钉住用例未随实现修复转断言 → 稳定假红**
+- ① 问题描述:`tests/e2e/api/dimension-energy-contract.spec.js` 的 `_pinsObserved` 用例断言「跨家庭 `memberId=999999` 返回 200(无归属校验)」;该缺口已于 `d39aa5282` 修复,用例因此**每轮必红**,且与真实回归混在同一红色池中。
+- ② 测试 bug 点:`tests/e2e/api/dimension-energy-contract.spec.js:154-158`(原 `expect(r.code).toBe(200)`)。
+- ③ 最优修改方案:pin 转断言——改为 `expect(r.code).toBe(403)` + `message` 含「无权访问」+ `data` 为空;describe 更名「越权隔离(SC-X-19)」(已实施)。
+- ④ 修改目的:把「记录缺陷」的用例升级为「守护修复」,消除假红、恢复该文件 100% 通过。
+- ⑤ 闭环:复跑 `dimension-energy-contract.spec.js` → **14/14 绿**(31.9s),已闭环。
+
+**问题 2(B-224-1,P2 工具,已自处置)251 派发提示词致 agent ssh 自身**
+- ① 问题描述:首派提示词为「请在 251 节点执行以下 shell 命令」,而 opencode 服务本身就跑在 251 → agent 反复尝试 `ssh 192.168.16.251` 并思考 8 分钟,15min cap 内只拿到中间态,误判为「节点不可用」。
+- ② 测试 bug 点:`_r224_251_lg.cjs` 提示词首行(派发脚本层,非产品代码)。
+- ③ 最优修改方案:提示词改为「**你在本机直接执行以下命令(不要 ssh、不要连其他节点)**」;模型固定 `etotem/deepseek`(`/api/model` 校验 `status=active` 后才派发)。
+- ④ 修改目的:消除节点=执行机的语义混淆,保证派发结果可确定性取回。
+- ⑤ 闭环:修正后首派即取回完整 summary(43 例 35 过 8 红 / 107.37s)。**注:首个会话实际在 16min 后自行成功**,故判「延迟成功」而非失败,但仍须改提示词以免每轮浪费 15 分钟。
+
+**问题 3(P0 环境)langgraph 8 红为上游 429,非产品缺陷**
+- ① 问题描述:43 例中 `test_auto_tag` ×4、`test_intent` ×4 失败;红集与 R223 完全同型。
+- ② 测试 bug 点:`cfc-langgraph/app/middleware.py:113` 捕获 `RateLimitError 429 AgnesAI_error`;`app/agents/intent_classifier.py` 429 后兜底 `chat` → 4 条意图断言被联动打红。
+- ③ 最优修改方案:运维为 251 升级 Token Plan / 轮换有配额 key;研发把 429 改为「显式失败 + 可重试」,**不静默兜底**。
+- ④ 修改目的:区分「上游不可用」与「分类错误」,恢复 AI 域可验证性。
+- ⑤ 闭环:配额恢复后 251 连跑 2 轮 43/43 全绿 → 销 B-223-1(当前观察 2/3)。
+
+**问题 4(B-224-4,P1 装置 + 数据安全,本轮最重要)后端测试直连共享库 251:3306 且每上下文重跑全量迁移**
+- ① 问题描述:`mvn -o -B test` 全量 **510 类 / 4469 例 / 51:50**;`controller`/`integration` 段 20~150s/类、`service` 段 100~200s/类;日志体积 **14.6MB**,`DatabaseInitializer` 输出 **24987 行**、Spring 上下文启动 **25+** 次;`jstack 8060` 显示 `main` 线程 RUNNABLE 阻塞于 `SocketInputStream.socketRead0 → com.mysql.cj.protocol.ReadAheadInputStream`,即**在等远端 MySQL 网络往返**。
+- ② 测试 bug 点:`cfc-backend/src/test/resources/` **不存在**(无 `application-test.yml`/`logback-test.xml`)→ 测试直接继承 `src/main/resources/application*.yml:22,47` 的 **`jdbc:mysql://192.168.16.251:3306/zxyj`(createDatabaseIfNotExist=true)**,以 `dev` profile 读写共享库;每次 `@SpringBootTest` 新建上下文重跑 `schema.sql`(433 条 DDL)+ `DatabaseInitializer`(650 处迁移段)。
+- ③ 最优修改方案:① 新增 `src/test/resources/application-test.yml`(本地 MySQL/H2 + 关闭自动迁移,schema 由一次性 `schema-test.sql`/`@Sql` 建);② 新增 `logback-test.xml` 把 `com.etotem` 降 `WARN`(当前 MyBatis DEBUG SQL 全落盘);③ `DatabaseInitializer` 加「同 JVM 只跑一次」静态闸;④ controller 用例改 `@WebMvcTest`。
+- ④ 修改目的:把全量回归压到 CI 可承受窗口(目标 ≤40min),同时**消除测试对共享库的写入**(当前测试会向 251 的 `zxyj` 造用户/订单/家庭数据,存在污染与误删风险)。
+- ⑤ 闭环:连续 2 轮全量 ≤40min、类数/例数不变(510/4469±),且进程内不再出现 `192.168.16.251:3306` 连接 → 销号。
+
+**问题 5(B-224-3,P1 流程)R223 用例台账未入 origin**
+- ① 问题描述:R223 报告声明派生 24 条 TC 并写入 `tests/test-cases/2026-11-16-review-detail-my-receipt-timeout.md`,但该文件仅存在于本地分支 `fix/scenario-coverage`(`c1f20bc2a`),`origin/cfclub` 无此文件 → 台账断层。
+- ② 测试 bug 点:`tests/test-cases/2026-11-16-review-detail-my-receipt-timeout.md`(69 行)在 origin 缺失。
+- ③ 最优修改方案:随本轮报告提交入库(已实施);推送以 `origin/cfclub` 为唯一事实源。
+- ④ 修改目的:恢复 G12 可追溯性(SRS 变更 → 用例 → 执行结果闭环)。
+- ⑤ 闭环:`git ls-tree origin/cfclub tests/test-cases/` 命中该文件即闭环。
+
+**问题 6(G11,P1 流程,第 26 轮)CI 排除清单与实际红集双向失真**
+- ① 问题描述:`.gitlab-ci.yml:61` 固定 33 类 `BACKEND_OBSERVED_CLASSES`;清单外仍有确定性红(漏拦),清单内多类已全绿(陈旧)→ `backend-blocking-junit` 长期必红,门禁失效。
+- ② 测试 bug 点:`.gitlab-ci.yml:61`(静态清单)+ `145-170`(blocking job 依赖该清单)。
+- ③ 最优修改方案:清单由 surefire XML 自动生成纳入仓库(`ci/gen-observed-classes.sh`),或契约前瞻类统一 `@Tag("forward-contract")` 后 blocking 用 `-Dgroups='!forward-contract'`。
+- ④ 修改目的:让 CI 红=真实回归,恢复阻断门禁的可信度。
+- ⑤ 闭环:连续 2 轮 CI blocking 绿且清单与实测红集差集为 0。
+
+**问题 7(B-218-1,P0 仍未修,第 4 轮)`@Resource` 字段名撞 Bean 名 → 运行期 `BeanNotOfRequiredTypeException`**
+- ① 问题描述:`ResourceBeanNameCollisionGuardTest` 本轮全量实跑 **1/1 红**;`CoachRecommendService.java:71-72` 字段 `dimensionScoreService`(类型 `FamilyMemberDimensionBaseScoreService`)与 `DimensionScoreService` 的默认 Bean 名相同,`@Resource` 先按名解析 → 类型不匹配抛 `BeanNotOfRequiredTypeException`,使依赖该链路的 `@SpringBootTest` 上下文启动失败(R203 已确认是线上 `d363df8056` 回滚真因)。
+- ② 测试 bug 点:`cfc-backend/src/main/java/com/etotem/cfc/service/CoachRecommendService.java:71-72`;守卫用例 `src/test/java/com/etotem/cfc/unit/ResourceBeanNameCollisionGuardTest.java`。
+- ③ 最优修改方案:字段加显式限定(`@Resource(name = "familyMemberDimensionBaseScoreService")`)或改名 `familyMemberDimensionBaseScoreService`;同步排查同类第二处(`HealthDataSourceBridgeService.dimensionScoreService`)。
+- ④ 修改目的:消除启动期 Bean 解析失败,恢复 49 个 `@SpringBootTest` 类的可判定性,避免线上回滚复现。
+- ⑤ 闭环:守卫用例转绿 + 全量 `mvn -o -B test` 中 `BeanNotOfRequiredTypeException` 出现次数 = 0 → 销号。
+
+---
+
+## 七、门禁结论
+
+**结论:不通过(有条件)**
+
+- ✅ **G3 浏览器 E2E**:本机 28 过 + 2 跳、189 admin 5/5(spec blob 同版)= 33 过 + 2 跳
+- ✅ **G4 可构建**:后端 `test-compile` BUILD SUCCESS(517 测试源,03:01)
+- ✅ **G5 surefire 覆盖**:已执行类 510/510 全部产出 XML,无沉默类
+- ✅ **G6 浏览器不回归**:双节点、双 URL、spec 同版,逐例通过
+- ✅ **G8 鉴权面**:匿名 6 端点 6/6 = 401
+- ✅ **G10 节点可用**:本机 + 189:4090(200)+ 251:4096(200)
+- ✅ **G12 SRS 同步**:窗口零 SRS/场景变更 → 0 新增;R223 台账 24 TC 已回收入库
+- ⚠️ **G1 通过率**:全站 **5400 例 / 4989 过 / 390 红 / 21 跳 = 92.73%**(剔 skip 93.09%;**剔 349 预期红 = 99.24%**)→ 未达「全部通过」,但**真实缺陷红仅 17**(后端 16 存量 + 1 P0 守卫)
+- ⚠️ **G2 实红**:390 = 契约前瞻 349 + 存量 16 + 守卫 1 + 环境 24;**非契约非环境红 17**,与 R221 逐类逐例一致(零漂移)
+- ⚠️ **G7 AI 域**:35/43(8 红=429 环境型,观察 2/3)
+- ✅ **G13 零漂移(第 36 次)**:后端 8 类存量红(WebConfigGrowthExcludeRemoved 2E / EnergySystemFlow 6F / GuideModuleIntegration 1E / OrchestrationEngine 1F / OrchestrationIntegration 1F / MembershipPaySwitch 1F / PaymentServiceORDRouting 1F / UserServiceWechatLogin 3E)逐类逐例与 R221/R213 一致;web 10 + fe 4 契约 RED 逐例一致
+- ❌ **G9 / G14 覆盖**:用例层 SC 引用 158/244 = **64.8%**;BDD/探索/性能/可用性/无障碍 5 类未覆盖
+- ❌ **G11 CI 门禁**:清单 33 类 vs 实测红类 **69** → **漏拦 + 陈旧**双向失真(第 26 轮未修)
+
+**不通过原因**:① 用户目标「所有用例全部覆盖并通过」未达成(390 红:349 契约前瞻 + 17 真实缺陷 + 24 环境);② 「覆盖全部 SRS + 场景」未达成(SC 用例层 64.8%,BDD/探索/性能/可用性/无障碍 5 类空缺);③ CI 门禁失真使「回归可信」无法外部证明。
+
+**复评条件(4 项全绿才可转「通过」)**
+1. 后端 17 例真实缺陷红(含 B-218-1 P0 Bean 撞名)修复,且装置改造后全量 ≤40min;
+2. langgraph 251 连续 2 轮 43/43(销 B-223-1);
+3. web 10 + fe 4 契约 RED 由研发实现转绿;
+4. CI 清单与实测红集差集为 0(销 G11)。
+
+---
+
+## 八、增量复验(收尾 fetch 发现远端 +6 提交,含 src/main 变更)
+
+- **发现**:提交前二次 fetch,`origin/cfclub` 由 `3ff62e324` → **`a1aa51d19`**(+6 提交),其中 **`98ca36287 feat(db): 优惠券分享转赠 T01 数据层`(迁移 494 `coupon_share` 表 + 495 `coupon_gift_transfer` 扩展列)** 命中 `src/main`(`DatabaseInitializer.java`、`schema.sql`、`CouponShare.java`、`CouponGiftTransfer.java`、`CouponShareMapper.java`)→ 触发增量复验(R184/R191 纪律:命中 `src/` 必须定向复跑,不能只报告主窗口数字)。
+- **处置**:worktree rebase 至 `a1aa51d19` 后定向复跑受影响面:
+  `mvn -o -B test -Dtest='*Coupon*,*Migration*'` → **77 例 / 68 过 / 8F / 1 跳**(`BUILD FAILURE`)
+  | 类 | 结果 |
+  |---|---|
+  | `CouponClaimScP75ContractTest` | **8/8 绿** |
+  | `CouponUseScP57ScP75ContractTest` | **11/11 绿** |
+  | `ShopCouponApplyContractTest` | **20/20 绿** |
+  | `ShopCouponClaimApiContractTest` | **7/7 绿**(0.018s,存疑:存在性断言风险,见 B-213-5 同类) |
+  | `ShopCouponClaimContractTest` | **11/11 绿**(0.001s,同上) |
+  | `AdminDataMigrationContractTest` | **8F / 10**(**与主窗口逐例一致,非新增回归**) |
+- **结论**:新增 T01 数据层**未引入回归**;`AdminDataMigrationContractTest` 8 红为主窗口已存在的迁移契约前瞻 RED(迁移编号/表结构契约未落地),属既有欠账,不因本次变更恶化。
+- **口径**:§1 的全量数字对应 `3ff62e324`;`a1aa51d19` 仅做受影响面定向复验,**不把定向结果外推为全量结论**。
+
+---
+
+## 附录 A:本轮命令(可复现)
+
+```bash
+# 后端(隔离 worktree,避免主工作区 20+ 未跟踪文件污染)
+git worktree add .worktrees/test-lead-R224 --detach 3ff62e324
+cd .worktrees/test-lead-R224/cfc-backend
+mvn -o -B test-compile          # BUILD SUCCESS 03:01(517 测试源)
+mvn -o -B test                  # 全量 510 类 / 4469 例,Total time: 51:50
+
+# 浏览器(每节点单任务,串行)
+cd tests && node node_modules/@playwright/test/cli.js test -c playwright.config.live.js --project=admin-desktop
+node node_modules/@playwright/test/cli.js test -c playwright.config.live.js --project=frontend-mobile
+node node_modules/@playwright/test/cli.js test -c playwright.config.live.js --project=shop-api --project=dx-bridge
+node node_modules/@playwright/test/cli.js test -c playwright.config.health.js
+
+# Jest
+cd cfc-web && node node_modules/jest/bin/jest.js --ci --silent
+cd cfc-frontend && node node_modules/jest/bin/jest.js --ci --silent
+cd .. && node tests/node_modules/jest/bin/jest.js -c tests/jest.config.js --ci --silent
+
+# 线上 API 点名 4 文件(36 例)
+cd tests && node node_modules/@playwright/test/cli.js test -c playwright.config.api.js \
+  api/api-smoke.spec.js api/nonfunc-security.spec.js api/nonfunc-perf-compat.spec.js api/dimension-energy-contract.spec.js
+
+# langgraph(251 节点本机执行;派发模型 etotem/deepseek)
+cd /sc-data/cfc/cfc-langgraph && timeout 900 .venv/bin/python -m pytest tests \
+  --ignore=tests/qna --ignore=tests/test_chat.py -q
+```
+
+## 附录 B:口径声明
+
+1. **后端全量为完整实跑**:`mvn -o -B test` → `Total time: 51:50`,**510 类 / 4469 例**全部产出 `TEST-*.xml`(`_r224_agg.cjs` 聚合,510/510 无沉默类);测试源 517 文件中 7 个为无 `@Test` 的辅助类,故「510 测试类」与「517 测试源」不矛盾。
+2. **「红」的三层归因**:契约前瞻 RED(TDD 先行,实现未落地,预期红)/ 存量装置缺陷(逐轮零漂移)/ 环境型(429、ECONNREFUSED、502)。仅第三类与产品健康无关;第二类为真实缺陷但非本轮新增。
+3. **线上 API 例数**:必须点名文件,否则 `testMatch` 会展开 990 例(B-173-2);本轮点名 4 文件 36 例。
+4. **Playwright 版本**:必须 `node tests/node_modules/@playwright/test/cli.js`(1.61.1),不能用根级 `npx playwright`(B-218-4)。
+5. **langgraph 例数 43 vs 39**:本轮 `--ignore=tests/qna --ignore=tests/test_chat.py` 得 43 例(含 `test_graph.py`),R223 额外忽略 `test_graph.py` 得 39 例 —— 分母差异属口径,非新增用例。

+ 30 - 0
docs/tdd/test/_r224_agg.cjs

@@ -0,0 +1,30 @@
+const fs = require('fs'), path = require('path');
+const dir = process.argv[2] || '.worktrees/test-lead-R224/cfc-backend/target/surefire-reports';
+const files = fs.readdirSync(dir).filter(f => /^TEST-.*\.xml$/.test(f));
+let tot = { tests: 0, fail: 0, err: 0, skip: 0 };
+const reds = [];
+for (const f of files) {
+  const x = fs.readFileSync(path.join(dir, f), 'utf8');
+  const m = x.match(/<testsuite[\s\S]*?>/);
+  if (!m) continue;
+  const attr = k => {
+    const r = new RegExp('\\b' + k + '="(\\d+)"');
+    const mm = m[0].match(r);
+    return mm ? parseInt(mm[1], 10) : 0;
+  };
+  const t = attr('tests'), fa = attr('failures'), er = attr('errors'), sk = attr('skipped');
+  tot.tests += t; tot.fail += fa; tot.err += er; tot.skip += sk;
+  if (fa + er > 0) reds.push({ cls: f.replace(/^TEST-/, '').replace(/\.xml$/, ''), t, fa, er, sk });
+}
+const pass = tot.tests - tot.fail - tot.err - tot.skip;
+const denom = tot.tests - tot.skip;
+console.log(`CLASSES=${files.length} TESTS=${tot.tests} PASS=${pass} FAIL=${tot.fail} ERR=${tot.err} SKIP=${tot.skip} RATE=${denom ? (pass / denom * 100).toFixed(2) : '0'}`);
+const contract = reds.filter(r => /Contract/i.test(r.cls));
+const other = reds.filter(r => !/Contract/i.test(r.cls));
+console.log(`RED_CLASSES=${reds.length} CONTRACT_RED=${contract.length} NONCONTRACT_RED=${other.length}`);
+console.log('--- NONCONTRACT ---');
+other.forEach(r => console.log(`${r.cls} (${r.fa}F/${r.er}E of ${r.t})`));
+if (process.env.SHOW_CONTRACT) {
+  console.log('--- CONTRACT ---');
+  contract.forEach(r => console.log(`${r.cls} (${r.fa}F/${r.er}E of ${r.t})`));
+}

+ 38 - 0
docs/tdd/test/automation-run-2026-11-15-R222.md

@@ -0,0 +1,38 @@
+# 自动化执行记录 · R222(2026-11-15 21:25 → 22:05 GMT+8,无人值守)
+
+## 触发与授权
+- 触发:定时自动化「测试负责人闭环(全部用例通过 + 覆盖 SRS/场景含异常流)+ 浏览器走 cfc.iwintrue.com/admin 与 /frontend(189/本机每节点单任务)+ langgraph 派 251 + 结果有变提交远程并通知研发」。
+- 执行档:review(离线白名单)+ 内网浏览器 E2E 实跑 + 节点派发。**未装依赖、未启停生产服务、未改 src/main**。
+
+## 时间线
+| 时间 | 动作 |
+|---|---|
+| 21:25 | 读记忆(R214 段,过时)+ 仓库状态;发现仓库实际到 R221(已推 20:35),本机 worktree `r221-run` 存在 |
+| 21:26 | HTTP fetch → 远端 `c582cdb16`(窗口 `d39aa5282..c582cdb16` 4 提交,**零 src/main 变更**,仅 R221 测试侧修复 + docs + bump) |
+| 21:27 | 建隔离 worktree `.worktrees/test-lead-R222`(detach `c582cdb16`);探活:189:4090 / 251:4096 / 本机 4091 Open、251:9000 CLOSED、本机 9082=000 |
+| 21:28 | 后端 test-compile(worktree r221-run)后台启动 |
+| 21:29 | 本机 admin 5/5(1.3m);189 派发 admin(`_r222_189.cjs`) |
+| 21:31 | 本机 frontend 6/6(44.0s);shop 4/4(4.6s) |
+| 21:32 | health **13/13 首跑即全绿**(4.2s,无 502);dx 2 跳(404,第 56 轮) |
+| 21:33 | 251 主派发超时(`_r222_251_lg.cjs` 返回 `[object Object]`)→ 改用 shell 通道 `_r222_251_read3.cjs` 直读 `/tmp/r222_lg.log` |
+| 21:35 | 189 返回 5/5 EXIT=0(首跑即绿,HEAD 1e3bea680 落后,B-221-4) |
+| 21:36 | 251 日志:**40 passed / 3 failed / 124.19s**;3 红全 `429 AgnesAI free rate limit`(auto_tag,B-222-1) |
+| 21:38 | 本机 Jest:web 124/10/134、fe 644/4/12/660、根级 7/16/23(tests 内 jest) |
+| 21:40 | 线上 API 点名 4 文件:25 passed / 7 skipped(10.1s) |
+| 21:42 | 后端 test-compile **EXIT=0**(1m14s)→ 按纪律承采 R221 全量(窗口零 src 变更) |
+| 21:45 | discover(373/2026/557)+ inventory(5740)+ 台账刷新 |
+| 21:50 | 生成报告 + 研发通知 + blockers R222 段 |
+| 22:05 | 提交推送 + 通知 |
+
+## 关键判定依据
+- **判「后端合规承采」而非「重跑」**:窗口 `d39aa5282..c582cdb16` 仅 4 提交(R221 汇报×2 + auto bump×2),**零 src/main 变更** → 按纪律承采 R221 全量实跑证据(40:06 / 4415 例 / 91.91%),本轮单独重跑 `test-compile` EXIT=0 作为可构建证据。
+- **判「lg 3 红是环境」而非「回归」**:3 红全为 `429 AgnesAI free rate limit`(`test_auto_tag` content_relevance/short_content/empty_content),与 R149/R162/R174 同型上游免费配额耗尽,非产品缺陷。
+- **判「health 首跑即绿可信」**:本轮无 502(B-218-3 未复现),13/13 全绿,R221 的 4×502 未再现。
+- **判「189 5/5 首跑即绿」**:派发日志 HEAD=1e3bea680(≠ 基线),但仍为节点独立证据;连续 2 轮首跑全绿(B-208-1 观察 3/3)。
+
+## 产出
+- `docs/tdd/orchestration/report-test-2026-11-15-R222.md`
+- `docs/tdd/orchestration/notice-2026-11-15-R222-研发通知.md`
+- `docs/tdd/test/blockers.md`(R222 段 11 条,含 B-222-1 新增)
+- `docs/tdd/test/{discovery,inventory,automation-status}.md`(刷新)
+- 临时取证:`_r222_189.cjs`、`_r222_251_read3.cjs`、`_r222_backend_compile`、`_r222_browser_all.log`、`_r222_jest_*.log`、`_r222_lg.log`(均未入库)

+ 45 - 0
docs/tdd/test/automation-run-2026-11-16-R224.md

@@ -0,0 +1,45 @@
+# 自动化执行日志 R224(2026-11-16 00:31 ~ 01:45 GMT+8)
+
+- **触发**:定时自动化「测试负责人闭环(全部用例通过 + 覆盖 SRS/场景含异常流)+ 浏览器走 cfc.iwintrue.com/admin 与 /frontend(189/本机每节点单任务)+ langgraph 派 251 + 结果有变提交远程并通知研发」
+- **执行档**:review(离线白名单)+ 内网三节点浏览器 E2E 实跑;未联网装依赖、未启停服务、未改 src/main
+- **静默**:全程未提问(用户指令「全程不要提问,静默完成」);方案假设(review 档、否授权联网压测)已在报告 §2 声明
+- **基线**:`origin/cfclub` `3ff62e324`;窗口 **0 提交**(与 R223 基线同一提交)→ 零 SRS / 零 src 变更
+- **隔离**:`git worktree add .worktrees/test-lead-R224 --detach 3ff62e324`(主工作区 20+ 未跟踪文件零干扰)
+
+## 时间线
+
+| 时间 | 动作 | 结果 |
+|---|---|---|
+| 00:31 | 读自动化记忆 + `git fetch`(HTTP 通道) | 基线 `3ff62e324`;窗口 0 提交 |
+| 00:33 | 建隔离 worktree | OK |
+| 00:34~00:37 | `mvn -o -B test-compile` | **BUILD SUCCESS**(517 测试源,03:01) |
+| 00:37~01:28 | `mvn -o -B test` 后台全量 | **510 类 / 4469 例 / 4113 过 / 352 红 / 4 跳 = 92.12%,51:50** |
+| 00:38 | 线上探活 | `/admin` 302、`/frontend` 302、`/` 404;匿名 6 端点 6/6=401 |
+| 00:39~00:41 | 本机 admin 浏览器 5 例 | **5/5**(1.3m) |
+| 00:42~00:43 | 本机 frontend 浏览器 6 例 | **6/6**(48.6s) |
+| 00:44~00:45 | shop-api + dx-bridge | **4/4 + 2 跳**(7.2s) |
+| 00:45 | health 契约(独立配置) | **13/13**(4.2s) |
+| 00:46 | cfc-web Jest | **124/10/134**(20.4s) |
+| 00:47 | cfc-frontend Jest | **644/4/12/660**(16.5s) |
+| 00:48 | 根级 Jest(`-c tests/jest.config.js`) | **7/16/23**(5.6s,全 ECONNREFUSED 9082) |
+| 00:49 | 线上 API 点名 4 文件 | **36 例 32 过 3 跳 1 红**(红=pin 未转断言) |
+| 00:50~00:52 | 189 admin 浏览器派发 | **5/5 EXIT=0**(1.1m),spec blob `4703d73fb` = 本机 |
+| 00:40~00:56 | 251 langgraph 首派(提示词含「在 251 节点执行」) | cap 超时未取回;**16min 后会话自行 succeeded**(B-224-1) |
+| 00:57~01:00 | 251 langgraph 重派(提示词修正,`etotem/deepseek`) | 会话零 token 未启动(上一会话占位)→ 直接用首派结果 |
+| 01:00~01:15 | 复核 251 首派结果 | **43 例 / 35 过 / 8 红 / 107.37s**,8 红全 429(环境) |
+| 01:15~01:18 | 修 `dimension-energy-contract.spec.js` pin→断言 | 复跑 **14/14 绿**(31.9s) |
+| 01:20~01:28 | 等后端全量收尾 + `jstack` 定位慢因 | 主线程阻塞于 MySQL socket(B-224-4) |
+| 01:30~01:45 | 报告 / 通知 / blockers / 台账回收入库 | 提交并推送 |
+
+## 关键处置
+
+1. **B-224-2(已闭环)**:pin 转断言,线上 API 点名子集红 1→0。
+2. **B-224-1(已处置)**:251 派发提示词改「你在本机直接执行(不要 ssh)」;模型固定 `etotem/deepseek` 并前置 `/api/model` 校验(free 模型全 429,`retryAfterMs`≈8.3h)。
+3. **B-224-4(新发现 P1)**:后端测试无 `src/test/resources`,直连 `192.168.16.251:3306/zxyj` 共享库 + 每上下文重跑全量迁移 → 51:50 耗时与数据污染风险。
+4. **B-224-3(已回收)**:R223 台账 `2026-11-16-review-detail-my-receipt-timeout.md`(24 TC)仅存本地分支,已随本轮入库。
+
+## 未做(明确声明)
+
+- 未执行任何需联网的依赖漏洞扫描 / 压测(execute 档未授权)。
+- 未启动/重启任何服务;未修改 `src/main`;未安装依赖。
+- 后端全量使用隔离 worktree 的 `target/`,未触碰主工作区产物。

File diff suppressed because it is too large
+ 731 - 952
docs/tdd/test/automation-status.md


+ 37 - 0
docs/tdd/test/blockers.md

@@ -1681,3 +1681,40 @@
 | **B-DX-1(第 55 轮 · P1)** | dx-bridge 端点 404 | 部署/研发 | `/api/health/data-sources/bridge/list`、`/sync-status` 均 **404** → 2 跳(规格 `2026-11-08-dx-health-bridge.md` 标注「仅登记不实现」,属待派发实现)。 | 部署/研发 | 2026-11-15 19:38 | 待处理 |
 | **B-221-6(新增 · P2 工具/门禁)** | `githooks/pre-push` 编译闸门执行环境失效 | 测试/运维 | 本轮 push 被闸门拦截:`[pre-push 编译闸门] ❌ 编译失败(exit=1)`,实际错误为 `找不到或无法加载主类 org.codehaus.plexus.classworlds.launcher.Launcher`(git hook 子进程 PATH/MAVEN_HOME 与登录 shell 不一致)。**手工复核**:同一 worktree 内 `mvn -q -DskipTests test-compile` **EXIT=0**;且本轮 `mvn -o -B clean test` 全量 4415 例已完整跑完(编译 0 错)。**处置**:以 `XAF_CI_GATE=0` 推送并在报告披露(闸门失效≠未编译)。**修法**:hook 内显式 `export MAVEN_HOME`/`PATH`,或用绝对路径 `$MAVEN_HOME/bin/mvn`;并把「闸门自身报错」与「编译失败」区分为两种退出码。 | 测试(R221 实测) | 2026-11-15 20:42 | 待修(P2) |
 | **R221 门禁** | 全站 **5342 例 / 4935 过 / 382 红 / 25 跳** | 测试 | **不通过(有条件,正向)**。剔 skip **92.81%**(4935/5317);**剔 349 预期红 = 99.34%**,实红 **33**(后端 17 + 根级 16)。✅G4 0 错 / G5 505-505 / G6 本机 28+2跳 + 189 5/5 / **G7 43/43 全绿** / G8 6/6=401 + health 13/13 / G10 三节点 / G12 窗口零 SRS 变更 / G13 第 35 次;❌G1 91.91%(剔预期红 99.58%)/ G2 33 / G9 27.4% / G11 漏拦 63 陈旧 26 / G14 用例层 59.2%。**核心变化 = lg 8 红→0 红(首次全绿)+ 后端首次全量覆盖 S-cfc-390 + 测试侧闭环 B-221-1**。 | 测试(R221 闭环) | 2026-11-15 20:35 | 已记录 |
+
+## R222 段(2026-11-15 21:25~22:00,基线 `c582cdb16`,窗口 4 提交,零 src/main 变更)
+
+> 说明:R222 窗口 `d39aa5282..c582cdb16` 仅含 R221 汇报×2 + auto bump×2,**无 src/main 变更** → 后端全量按纪律**承采 R221**(505 类 / 4415 例 / 4058 过 / 353 红 / 4 跳 = 91.91%),本轮单独重跑 `test-compile` **EXIT=0**(1m14s)作为可构建证据。**结果有变化 → 提交 + 通知研发**。
+
+| 编号 | 关联键/对象 | 类型 | 描述与处置 | 经办 | 登记时间 | 状态 |
+|---|---|---|---|---|---|---|
+| **B-222-1(新增 · P1 环境型 · 观察 1/3)** | langgraph `test_auto_tag` 3 例 | 运维/研发 | 251 上 lg pytest 43 例 **40 过 3 红**(R221 为 43/43);`content_relevance`/`short_content`/`empty_content` 3 例全红(8.05s/20.32s/7.06s),日志 `RateLimitError("Error code: 429 - You've reached the API rate limit for free users...", type: 'AgnesAI_error')`。**性质**:上游免费配额耗尽,与 R149/R162/R174 同型,**非产品回归**(承 B-220-1/B-216-3 第 2 轮复现)。**修法**:运维升级 AgnesAI Token Plan 或换 key;测试侧对上游 LLM stub 仅留 smoke 实连。**销号**:连续 3 轮 43/43 且无 429。 | 测试(R222 实派) | 2026-11-15 21:26 | 观察中(1/3) |
+| **B-218-1(第 3 轮 · P0)** | `@Resource` Bean 撞名 | 研发 | 承袭:`ResourceBeanNameCollisionGuardTest` 1/1 红(窗口零 src 变更,无修复机会)。`CoachRecommendService.java:71-72` 字段 `dimensionScoreService` 撞 `DimensionScoreService` Bean 名。 | 研发 | 2026-11-15 21:26 | 待研发修复(P0) |
+| **B-218-2(第 3 轮 · P1 资金)** | 支付开关语义 | 研发 | 承袭:`MembershipPaySwitchTest` 1F、`PaymentServiceORDRoutingTest` 1F(配置缺失仍落 131400 分待支付订单)。 | 研发 | 2026-11-15 21:26 | 待研发修复(P1) |
+| **B-218-3(观察 1/3 · 好转)** | 线上 `/api/**` 502 窗口 | 运维 | 本轮 **health 首跑即 13/13 全绿**(4.2s),无 502 → R221 第 4 轮复现后本轮未复现,转观察 1/3。 | 运维/测试 | 2026-11-15 21:26 | 观察中(1/3) |
+| **B-208-1(好转观察 3/3)** | 189 节点 admin 链路 | 运维 | 本轮 **首跑即 5/5 全绿**(1.4m,EXIT=0)→ 连续 2 轮首跑全绿 → 观察 3/3。但节点 HEAD 仍落后基线(B-221-4 承袭)。 | 测试(R222 实派) | 2026-11-15 21:26 | 观察中(3/3) |
+| **B-221-4(第 2 轮 · P2 流程)** | 189 节点仓库 HEAD 落后 | 测试/运维 | 承袭:节点以 `1e3bea680`(≠ 基线 `c582cdb16`)运行,5/5 绿但**非同源证据**。`git checkout cfclub` 被 worktree 占用。**修法**:节点改独立 worktree/detach 拉取。 | 测试(R222 实派) | 2026-11-15 21:26 | 待修(P2) |
+| **B-218-10(第 24 轮 · P1)** | lg pytest 进程不退出 | 研发/测试 | 承袭观察:本轮 shell 通道直读 `/tmp/r222_lg.log` 见 124.19s 已出 summary(40P/3F),主派发器超时经 shell 补取;无残留 pytest(已清理)。线索:`JavaClient._get_client` 协程未 await。 | 研发 | 2026-11-15 21:26 | 待修(P1) |
+| **B-36(第 99 轮 · P2)** | 根级黑盒 16 红 | 测试 | `tests` 内 `jest -c jest.config.js` → **7 过 / 16 红 / 23**(8.4s),全 `ECONNREFUSED 127.0.0.1:9082`。必须用 `tests/node_modules/jest/bin/jest.js`。 | 测试 | 2026-11-15 21:26 | 待处理 |
+| **B-DX-1(第 56 轮 · P1)** | dx-bridge 端点 404 | 部署/研发 | `/api/health/data-sources/bridge/list`、`/sync-status` 均 **404** → 2 跳(规格标注「仅登记不实现」)。 | 部署/研发 | 2026-11-15 21:26 | 待处理 |
+| **G11(第 26 轮 · P1)** | CI 排除清单失真 | 研发 | 承袭:`.gitlab-ci.yml:61` 列 **33 类** vs 实测红类 **69** → **漏拦 62**、**陈旧 26**。建议由 surefire XML 自动生成清单。 | 研发 | 2026-11-15 21:26 | 待研发(P1) |
+| **R222 门禁** | 全站 **5342 例 / 4932 过 / 385 红 / 25 跳** | 测试 | **不通过(有条件;较 R221 持平)**。剔 skip **92.81%**(4932/5317);**剔 352 预期红 = 99.31%**,实红 **33**(后端 17 + 根级 16)。✅G4 test-compile **EXIT=0** / G5 承采 505/505 / G6 本机 28+2跳 + 189 **5/5 首跑绿** / G8 6/6=401 + health 13/13 首跑即绿 / G10 三节点 / G12 窗口零 SRS 变更 / G13 第 36 次;❌G1 91.91%(剔预期红 99.58%)/ G2 33 / **G7 40/43(3 红 429 环境型,较 R221 100% 恶化)** / G9 27.5% / G11 漏拦 62 陈旧 26 / G14 用例层 59.2%。**核心变化 = lg 红集 0→3 环境型复现(B-222-1)+ health 首跑即全绿(B-218-3 未复现)+ 189 连续 2 轮首跑 5/5(B-208-1 观察 3/3)+ 后端承采 R221 且 test-compile EXIT=0**。 | 测试(R222 闭环) | 2026-11-15 21:26 | 已记录 |
+
+## R224 段(2026-11-16 00:31~01:45,基线 `origin/cfclub` `3ff62e324`,窗口 **0 提交**,零 SRS/src 变更)
+
+> 说明:本轮窗口与 R223 基线同为 `3ff62e324`(R223 报告亦以该提交为基线)→ **零新提交、零 SRS 变更、零 src 变更**。但 R223 **未跑后端全量**(仅 test-compile),故本轮**首次实跑后端全量**作为主要增量证据。全部非后端套件重新取证,未采信上轮。
+
+| 编号 | 关联键/对象 | 类型 | 描述与处置 | 经办 | 登记时间 | 状态 |
+|---|---|---|---|---|---|---|
+| **B-224-1(新增 · P2 工具 · 已自处置)** | 251 派发提示词 | 测试 | 首派提示词「请在 251 节点执行以下 shell 命令」→ opencode 服务本身即在 251,agent 反复尝试 `ssh 192.168.16.251` 并思考 ~8min,15min cap 内只回中间态(**该会话 16min 后自行 succeeded**,属延迟成功非失败)。**修法**:提示词改「你在本机直接执行(不要 ssh、不要连其他节点)」+ 派发前 `GET /api/model` 校验 `status=active`。另:251 上 `opencode/*-free` 全部 `provider.free-limit`(429,`retryAfterMs` ≈8.3h),`nvidia/deepseek-v4.1-flash` 报 `model not found`,**必须用 `etotem/deepseek`**(探针 `etotem/deepseek`=OK / `opencode/longcat-2.5-free`=OK)。 | 测试(R224 实派) | 2026-11-16 01:00 | 已处置 |
+| **B-224-2(新增 · P1 测试资产 · 已闭环)** | `dimension-energy-contract.spec.js:154` pin | 测试 | 原「观察钉住」断言跨家庭 `memberId=999999` → **200**(无归属校验);实现已于 `d39aa5282`(S-cfc-390)在 `EnergyController.java:174` 加归属校验返回 **403「无权访问该成员的能量数据」** → 该 pin **每轮必红**。**修法**:pin 转断言(403 + message 含「无权访问」+ data 为空),describe 更名「越权隔离(SC-X-19)」→ 复跑 **14/14 绿**(31.9s)。**教训**:缺口修复后必须把 pin 转断言,否则 pin 变噪声并掩盖真实回归。 | 测试(R224 修复) | 2026-11-16 01:15 | 已闭环 |
+| **B-224-3(新增 · P1 流程 · 已回收)** | R223 台账 24 条 TC | 测试/研发 | `tests/test-cases/2026-11-16-review-detail-my-receipt-timeout.md`(69 行 / 24 TC)只提交在本地分支 `fix/scenario-coverage`(`c1f20bc2a`),**`origin/cfclub` 无此文件** → G12 追溯断层。**处置**:随 R224 报告一并入库。**纪律**:推送以 `origin/cfclub` 为唯一事实源。 | 测试 | 2026-11-16 01:20 | 已回收 |
+| **B-224-4(新增 · P1 装置+数据安全)** | 后端测试直连共享库 | 研发 | `mvn -o -B test` **510 类 / 4469 例 / 51:50**;`jstack 8060` 主线程阻塞于 `SocketInputStream.socketRead0 → mysql.cj.protocol.ReadAheadInputStream`(等远端 MySQL)。**根因链**:`cfc-backend/src/test/resources/` **不存在** → 继承 `src/main/resources/application*.yml:22,47` 的 **`jdbc:mysql://192.168.16.251:3306/zxyj`**(`createDatabaseIfNotExist=true`),以 `dev` profile 读写**共享库**;每上下文重跑 `schema.sql`(433 DDL)+ `DatabaseInitializer`(650 迁移段);`com.etotem` DEBUG 全落盘(日志 14.6MB / 迁移日志 24987 行 / 25+ 上下文)。**风险**:① 全量 40min→51:50 且随机卡顿;② 测试向共享库造数据,污染/误删风险。**修法**:加 `application-test.yml`(本地库 + 关迁移)+ `logback-test.xml` 降 WARN + `DatabaseInitializer` 同 JVM 只跑一次 + controller 改 `@WebMvcTest`。**判据**:连续 2 轮 ≤40min、类/例数不变、进程内无 `192.168.16.251:3306` 连接。 | 测试(R224 实测) | 2026-11-16 01:35 | 待研发修(P1) |
+| **B-224-5(第 22 轮 · P2)** | lg pytest 进程不退出 | 研发 | 251 上 summary 已打印(`8 failed, 35 passed in 107.37s`)但进程不退出 → `timeout 900` 兜底 `EXIT=124`。线索仍为 `RuntimeWarning: coroutine 'JavaClient._get_client' was never awaited`(`pytest/stash.py:108`)。**修法**:`shutdown` 时 `await client.aclose()`。 | 研发 | 2026-11-16 01:00 | 待修(P2) |
+| **B-223-1(第 2 轮 · P1 环境型 · 观察 2/3)** | langgraph 8 红 429 | 运维/研发 | 43 例 **35 过 8 红**(`test_auto_tag`×4 + `test_intent`×4),`RateLimitError 429 AgnesAI_error`(`app/middleware.py:113`);429 后 intent 兜底 chat 联动打红。R223 同型 → 观察 2/3。**销号**:连续 2 轮 43/43 全绿。 | 测试(251 实派) | 2026-11-16 01:00 | 观察中(2/3) |
+| **B-218-3(观察 2/3 · 好转)** | 线上 `/api/**` 502 | 运维 | health 首跑即 **13/13**(4.2s),shop 4/4 首跑即绿,无 502 → 连续 2 轮未复现。 | 测试 | 2026-11-16 00:45 | 观察中(2/3) |
+| **B-208-1 / B-221-4(承袭)** | 189 节点 | 运维/测试 | 189 admin **5/5 EXIT=0**(1.1m),spec blob `4703d73fb` = 本机同版(跨节点可比);但节点 HEAD `1e3bea680` ≠ 基线 `3ff62e324`。 | 测试(189 实派) | 2026-11-16 00:50 | B-208-1 好转 / B-221-4 待修 |
+| **B-36(第 100 轮 · P2)** | 根级黑盒 16 红 | 测试 | `node tests/node_modules/jest/bin/jest.js -c tests/jest.config.js` → **7 过 / 16 红 / 23**(5.6s),全 `ECONNREFUSED 127.0.0.1:9082`(本机后端未起)。 | 测试 | 2026-11-16 00:44 | 待处理 |
+| **B-DX-1(第 58 轮 · P1)** | dx-bridge 404 | 部署/研发 | `/api/health/data-sources/bridge/{list,sync-status}` 均 **404** → 2 跳。规格 `2026-11-08-dx-health-bridge.md:5` 明示「仅登记不实现」→ 非缺陷,建议标 `blocked: pending implementation`。 | 部署/研发 | 2026-11-16 00:47 | 待处理 |
+| **G11(第 26 轮 · P1)** | CI 排除清单失真 | 研发 | `.gitlab-ci.yml:61` 固定 **33 类** `BACKEND_OBSERVED_CLASSES` vs 实测红集 → 双向失真(漏拦 + 陈旧)。建议由 surefire XML 自动生成,或契约前瞻类打 `@Tag("forward-contract")`。 | 研发 | 2026-11-16 01:30 | 待研发(P1) |
+| **R224 门禁** | 非后端 931 例 / 876 过 / 38 红 / 17 跳 = 94.09% | 测试 | **不通过(有条件)**。✅G3 33+2 跳 / G4 test-compile SUCCESS(517 源 03:01)/ G5 已执行类全覆盖 XML / G6 / G8 6-6=401 / G10 三节点 / G12 窗口零变更+R223 台账回收;⚠️G1 94.09%(后端全量截断不可判)/ G2 38(0 确定性回归)/ G7 35-43;❌G9、G14 用例层 64.8%、G11、G13 中断(后端未跑完)。 | 测试(R224 闭环) | 2026-11-16 01:45 | 已记录 |

+ 13 - 10
docs/tdd/test/discovery.md

@@ -7,22 +7,22 @@
 
 | 指标 | 数值 |
 | --- | --- |
-| 控制器总数 | 374 |
-| handler 方法总数 | 2029 |
+| 控制器总数 | 373 |
+| handler 方法总数 | 2026 |
 | handler 方法已覆盖 | 557 (27.5%) |
 | 单元-全覆盖(handler 方法) | 47 |
 | 单元-部分覆盖(handler 方法) | 206 |
-| 单元-未覆盖(handler 方法) | 120 |
+| 单元-未覆盖(handler 方法) | 119 |
 | 单元-无handler 方法 | 1 |
-| 测试文件数 | 512 |
-| @Test 方法总数 | 4399 |
+| 测试文件数 | 515 |
+| @Test 方法总数 | 4395 |
 | 含跳过/假设项(test 级 partial) | 4 |
 
 ## 二、未覆盖控制器(发现「缺口」· 非发明)
 
 > 以下控制器在当前测试源中**没有任何handler 方法被命中**。这是真实扫描得到的覆盖缺口。
 
-共 120 个:
+共 119 个:
 
 - `OrchestrationController`(`cfc-backend/src/main/java/com/etotem/cfc/controller/OrchestrationController.java`,15 方法)
 - `KeyPersonController`(`cfc-backend/src/main/java/com/etotem/cfc/controller/KeyPersonController.java`,14 方法)
@@ -84,7 +84,7 @@
 - `AdminGrowthArchiveProductController`(`cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminGrowthArchiveProductController.java`,3 方法)
 - `AssessmentController`(`cfc-backend/src/main/java/com/etotem/cfc/controller/guide/AssessmentController.java`,3 方法)
 - `ContactImportController`(`cfc-backend/src/main/java/com/etotem/cfc/controller/ContactImportController.java`,3 方法)
-- …(其余 60 个见完整扫描)
+- …(其余 59 个见完整扫描)
 
 ## 三、部分覆盖控制器(已做一部分测试)
 
@@ -119,7 +119,6 @@
 - `WishController`:覆盖 11/12,未覆盖方法:priceAlias
 - `AIChatController`:覆盖 8/11,未覆盖方法:reportAnalyze、deleteConversation、transcribe
 - `BadgeController`:覆盖 1/11,未覆盖方法:getAllBadges、getBadgeDetail、createBadge、updateBadge、deleteBadge、grantBadge、getMemberBadges、toggleFavorite、getMemberStats、getFamilyRanking
-- `GrowthPlanController`:覆盖 2/11,未覆盖方法:createPlan、getChildPlans、getActivePlan、getPlanProgress、getPlanDetail、updatePlan、reviewPlan、confirmPlan、submitPlan
 - `PaymentController`:覆盖 5/11,未覆盖方法:createWechatNativePay、getPaymentStatus、getOAuth2Url、oauth2Callback、handleV3Notify、generateQrCode
 - `SupplyHierarchyController`:覆盖 2/11,未覆盖方法:setHierarchy、removeRelation、getDirectChildren、getAllChildren、getParentChain、getTree、getChangeRequests、applyChange、reviewChange
 - `TrainingPlanController`:覆盖 1/11,未覆盖方法:getPlanDetail、createPlan、updatePlan、addItem、updateItem、deleteItem、generateFromRecommendations、deployPlan、getExecutionBoard、deletePlan
@@ -137,6 +136,7 @@
 - `EnergyController`:覆盖 7/9,未覆盖方法:configureSourceRatios、getWealthDetail
 - `FileRecordController`:覆盖 1/9,未覆盖方法:upload、update、deleteFile、getTags、tagCreate、tagUpdate、tagDelete、stats
 - `FiveDimensionSelfCheckController`:覆盖 4/9,未覆盖方法:getHistory、ignoreSelfCheck、generatePlan、getTrendAnalysis、aiGenerateQuestions
+- `GrowthPlanController`:覆盖 2/9,未覆盖方法:createPlan、getChildPlans、getActivePlan、getPlanProgress、getPlanDetail、updatePlan、reviewPlan
 - `KnowledgeBaseController`:覆盖 1/9,未覆盖方法:backfillTags、get、save、delete、bindDimensions、bindTags、uploadFile、fetchUrl
 - `ProductController`:覆盖 6/9,未覆盖方法:updateImages、specMap、relatedProducts
 - `AdminActivityController`:覆盖 5/8,未覆盖方法:review、detail、backfillTags
@@ -390,7 +390,6 @@
 | `cfc-backend/src/test/java/com/etotem/cfc/integration/service/GuidePackageServiceTest.java` | com | 13 | 0 | 0 | GuideController | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/unit/HealthReportDetailContractTest.java` | com | 13 | 13 | 1 | HealthReportController | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/unit/ManualDimensionScoreContractTest.java` | com | 13 | 6 | 2 | ManualDimensionScoreController | — |
-| `cfc-backend/src/test/java/com/etotem/cfc/unit/OrderReceiptTimeoutContractTest.java` | com | 13 | 0 | 0 | — | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/unit/PersonalLayerDualAssertionTest.java` | com | 13 | 4 | 0 | — | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/controller/ScG03LoginMethodContractTest.java` | com | 13 | 1 | 4 | — | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/unit/SupplierNutritionSupplyContractTest.java` | com | 13 | 1 | 4 | — | — |
@@ -497,7 +496,6 @@
 | `cfc-backend/src/test/java/com/etotem/cfc/controller/AuthSessionMutexContractTest.java` | com | 9 | 0 | 0 | AuthController | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/controller/BadgeControllerGetMemberBadgesTest.java` | com | 9 | 1 | 0 | BadgeController | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/controller/ai/ButlerControllerGateTest.java` | com | 9 | 4 | 6 | ButlerController | — |
-| `cfc-backend/src/test/java/com/etotem/cfc/unit/CfRewardV2PlatformTakeContractTest.java` | com | 9 | 0 | 0 | — | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/integration/controller/DimensionRegistryTreeTest.java` | com | 9 | 6 | 0 | DimensionRegistryController | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/unit/EnergyGrantContractTest.java` | com | 9 | 4 | 1 | EnergyController | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/controller/growth/GrowthHistoryViewContractTest.java` | com | 9 | 3 | 0 | GrowthController | — |
@@ -671,11 +669,13 @@
 | `cfc-backend/src/test/java/com/etotem/cfc/unit/FamilyNamingSupportTest.java` | com | 5 | 0 | 0 | FamilyController | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/service/FamilyPlatformPointsServiceCouponTest.java` | com | 5 | 0 | 0 | FamilyController | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/unit/GlobalSearchScP82ContractTest.java` | com | 5 | 12 | 0 | — | — |
+| `cfc-backend/src/test/java/com/etotem/cfc/config/GrowthPublicEndpointMappingTest.java` | com | 5 | 0 | 0 | GrowthController | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/unit/GuheVersionSplitContractTest.java` | com | 5 | 0 | 0 | — | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/unit/GuideFamilyTaskReviewContractTest.java` | com | 5 | 2 | 2 | GuideController | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/unit/HealthPlanLazyBackfillTest.java` | com | 5 | 0 | 0 | HealthPlanController | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/controller/HealthReportControllerCreateReportTest.java` | com | 5 | 2 | 0 | HealthReportController | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/service/HealthReportServiceBackfillResilienceTest.java` | com | 5 | 7 | 0 | HealthReportController | — |
+| `cfc-backend/src/test/java/com/etotem/cfc/config/JwtInterceptorGrowthPolicyTest.java` | com | 5 | 0 | 0 | — | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/config/JwtInterceptorLoginRequiredTest.java` | com | 5 | 0 | 0 | — | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/unit/LangGraphErrorPropagateContractTest.java` | com | 5 | 1 | 0 | — | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/integration/service/MiniGameServiceTest.java` | com | 5 | 0 | 0 | MiniGameController | — |
@@ -729,7 +729,9 @@
 | `cfc-backend/src/test/java/com/etotem/cfc/dto/ActivityDTOTest.java` | com | 3 | 0 | 0 | ActivityController | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/unit/ActivityRegistrationListTest.java` | com | 3 | 5 | 0 | ActivityController | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/unit/ActivityRegistrationRejectTest.java` | com | 3 | 0 | 0 | ActivityController | — |
+| `cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminFamilyOverviewControllerTest.java` | com | 3 | 2 | 0 | AdminFamilyOverviewController | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/integration/controller/AdminFamilyOverviewControllerTest.java` | com | 3 | 0 | 2 | AdminFamilyOverviewController | — |
+| `cfc-backend/src/test/java/com/etotem/cfc/controller/shop/AfterSalesCancelControllerTest.java` | com | 3 | 1 | 0 | AfterSalesController | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/service/ArticleAudioServiceAutoGenTest.java` | com | 3 | 0 | 0 | ArticleController | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/service/ArticleAudioServiceChunkFilterTest.java` | com | 3 | 0 | 0 | ArticleController | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/integration/controller/ArticleCategoryControllerTest.java` | com | 3 | 0 | 1 | ArticleCategoryController | — |
@@ -768,6 +770,7 @@
 | `cfc-backend/src/test/java/com/etotem/cfc/service/UserServiceOpenidIsolationTest.java` | com | 3 | 3 | 0 | UserController | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminCommissionConfigPartialUpdateTest.java` | com | 2 | 0 | 1 | AdminCommissionConfigController | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/unit/ArticleBackfillTest.java` | com | 2 | 0 | 0 | ArticleController | — |
+| `cfc-backend/src/test/java/com/etotem/cfc/integration/controller/ArticleTagsContractTest.java` | com | 2 | 0 | 1 | ArticleController | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/unit/AssessmentAppointmentCreateContractTest.java` | com | 2 | 0 | 0 | AssessmentAppointmentController | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/unit/AttributionPipelineMockTest.java` | com | 2 | 38 | 0 | AttributionController | — |
 | `cfc-backend/src/test/java/com/etotem/cfc/unit/AttributionPlanServiceTest.java` | com | 2 | 8 | 0 | AttributionController | — |

File diff suppressed because it is too large
+ 730 - 951
docs/tdd/test/inventory.md


+ 11 - 6
tests/e2e/api/dimension-energy-contract.spec.js

@@ -148,13 +148,18 @@ test.describe('O-7 五维能量 三类流(SC-P-17/18/89/93, SC-T-31/32, SC-X-1
     });
   });
 
-  // ==================== 观察钉住(gap,只读验证,不修改实现) ====================
-
-  test.describe('_pinsObserved(契约缺口观察)', () => {
-    test('overview 传跨家庭 memberId(999999)→ 观察返回 200(无归属校验,仅登记)', async ({ request }) => {
+  // ==================== 越权隔离(G-10 已闭环:观察钉住转为断言) ====================
+  // R224 更新:原「观察钉住」用例断言 overview 传跨家庭 memberId 返回 200(无归属校验)。
+  // 该缺口已由 d39aa5282(S-cfc-390 energy.ledger.guard)修复:
+  // EnergyController#overview 增加 SC-X-19 跨角色数据隔离(本人放行 / 同家庭成员放行 / 跨家庭 403)。
+  // 故本用例由「记录缺陷行为」升级为「断言修复后行为」,闭环 SC-X-19 越权面。
+
+  test.describe('越权隔离(SC-X-19)', () => {
+    test('overview 传跨家庭 memberId(999999)→ 403 无权访问该成员的能量数据', async ({ request }) => {
       const r = await apiPost(request, '/api/energy/overview', { memberId: 999999 }, parent.token);
-      expect(r.code).toBe(200);
-      expect(r.data && r.data.dimensions).toBeTruthy();
+      expect(r.code, r.message).toBe(403);
+      expect(String(r.message)).toContain('无权访问');
+      expect(!r.data, '403 时不得返回任何能量数据').toBe(true);
     });
   });
 });

+ 69 - 0
tests/test-cases/2026-11-16-review-detail-my-receipt-timeout.md

@@ -0,0 +1,69 @@
+# 测试用例台账 · shop.review.detail / shop.review.my / shop.order.receiptTimeout(R223 派生)
+
+> 派生日期:2026-11-16|派生角色:测试负责人(自动化闭环 R223)
+> 派生来源:`origin/cfclub` `c582cdb16..3ff62e324` 窗口新增能力键(G12 / 用户"SRS 变更→更新用例"要求)
+> 派生依据:
+> ① `docs/superpowers/api/API_REFERENCE.md` 新增 `POST /api/product/review/detail`(`shop.review.detail`)、`POST /api/product/review/my`(`shop.review.my`);
+> ② 后端契约 `ProductReviewDetailContractTest` / `ProductReviewMyContractTest` / `OrderReceiptTimeoutContractTest`(S-cfc-403/404/402);
+> ③ 需求正本:商品评价详情/去评价按钮态(§3.1 R2)、我的评价+待评价入口(§3.1 R5)、待收货超时自动完成(架构设计 §2.4/§6)。
+> 用途:把契约级 RED 用例升级为**行为级**用例台账,避免仅靠结构性断言假绿;异常流/权限流为本次重点补齐维度。
+
+## 一、背景与覆盖判定
+
+| 能力键 | 需求溯源 | 设计溯源 | 现有资产 | 覆盖判定 |
+|---|---|---|---|---|
+| `shop.review.detail`(S-cfc-403) | API_REFERENCE `POST /api/product/review/detail`;去评价按钮态 R2 | `ProductReviewDetailContractTest`(10 例:结构/路由/出参字段) | 契约 RED(存在性) | **部分覆盖**:缺 canReview 判定(completed+90天+未评)真实行为、缺越权、缺未登录、缺 orderId 非法 |
+| `shop.review.my`(S-cfc-404) | API_REFERENCE `POST /api/product/review/my`;我的评价+待评价 R5 | `ProductReviewMyContractTest`(11 例:路由/Mapper/schema/权限说明) | 契约 RED(存在性) | **部分覆盖**:缺分页倒序、缺 reviewableOrders 过滤(90天/非 activity/本人)、缺越权、缺未登录 |
+| `shop.order.receiptTimeout`(S-cfc-402) | 待收货超时自动完成 + 第 N 天提醒 | `OrderReceiptTimeoutContractTest` / `OrderReceiptTimeoutTaskContractTest`;application.yml 4 配置键 | 契约 RED(结构/配置) | **部分覆盖**:缺超时置态真实行为、缺幂等、缺灰度开关、缺提醒幂等 |
+
+> 三能力均为窗口内新落地(feat 已合入主线),契约测试为结构性断言;本台账补齐**行为级 + 异常流 + 权限流**。用例状态记为 `待执行`,本轮由契约实跑取证,行为级留待研发环境补测。
+
+## 二、TC-RD(shop.review.detail)用例
+
+| ID | 类型 | 场景 | 前置 | 步骤 | 期望 | 优先级 | 现有资产 |
+|---|---|---|---|---|---|---|---|
+| TC-RD-01 | 正常 | 已评订单查详情 | orderId 已有评价 | 调 `detail(orderId, buyerId)` | `review` 非空;星级/文字/图回显;`canReview=false` | P0 | 部分(DTO 字段在) |
+| TC-RD-02 | 正常 | 未评 completed 订单(窗口内)→ 可评 | orderId=completed 且 89 天内未评 | 调 detail | `review=null`;`canReview=true`;`reviewHint` 含引导文案 | **P0** | ❌ 缺行为断言 |
+| TC-RD-03 | 边界 | completed 超 90 天未评 | orderId completed 91 天前 | 调 detail | `canReview=false`;`reviewHint` 提示超期 | P1 | ❌ 缺 |
+| TC-RD-04 | 边界 | 非 completed 订单 | orderId=pending_receipt | 调 detail | `canReview=false`;不 5xx | P1 | ❌ 缺 |
+| TC-RD-05 | 异常 | orderId 不存在 | orderId=999999999 | 调 detail | 明确业务码,不含堆栈 | P1 | ❌ 缺 |
+| TC-RD-06 | 异常 | orderId=null | — | 调 detail | 参数校验失败码,不 NPE | P1 | ❌ 缺 |
+| TC-RD-07 | **权限** | 查他人订单详情 | A token + B 的 orderId | 调 detail | 拒绝(403/业务码),不返回他人评价 | **P0** | ❌ 缺(越权风险) |
+| TC-RD-08 | 权限 | 未登录 | 无 token | `POST /api/product/review/detail` | 401 | P0 | 部分(JwtInterceptor 通用) |
+| TC-RD-09 | 正常 | 路由与身份载体 | — | 反射检查 | `@PostMapping("/detail")` + `@RequestAttribute("userId")` | P1 | ✅ 契约正常流3/4 |
+
+## 三、TC-RM(shop.review.my)用例
+
+| ID | 类型 | 场景 | 前置 | 步骤 | 期望 | 优先级 | 现有资产 |
+|---|---|---|---|---|---|---|---|
+| TC-RM-01 | 正常 | 我的评价列表倒序分页 | 买家有 ≥3 条评价 | 调 `my(buyerId,...)` | `reviews` 按评价时间倒序;分页参数生效 | P0 | 部分(Mapper 存在性) |
+| TC-RM-02 | 正常 | 待评价订单集合 | 有 completed 90天内未评非 activity 订单 | 调 my | `reviewableOrders` 含该单;`reviewableCount` 正确 | **P0** | ❌ 缺行为断言 |
+| TC-RM-03 | 边界 | activity 订单不进待评 | 有 activity 类型 completed 订单 | 调 my | 该单**不**出现在 `reviewableOrders` | **P0** | ❌ 缺(活动评价零污染) |
+| TC-RM-04 | 边界 | 超 90 天订单不进待评 | completed 91 天前 | 调 my | 不出现在待评集合 | P1 | ❌ 缺 |
+| TC-RM-05 | 正常 | 空集(无评价无待评) | 新买家 | 调 my | `reviews=[]`、`reviewableOrders=[]`、`reviewableCount=0`,不 500/不 null | P0 | ❌ 缺 |
+| TC-RM-06 | **权限** | 仅本人可见 | A token | 调 my | 只返回 A 的评价/待评,无 B 数据 | **P0** | 部分(权限流说明) |
+| TC-RM-07 | 权限 | 未登录 | 无 token | `POST /api/product/review/my` | 401(R5 为登录买家私有,非 R3 公开路径) | P0 | ❌ 缺 |
+| TC-RM-08 | 正常 | schema 独立表 + 索引 | — | 检查 schema.sql | `product_reviews` 表 + `idx_reviewer_id` 索引存在 | P1 | ✅ 契约边界流3 |
+
+## 四、TC-ROT(shop.order.receiptTimeout)用例
+
+| ID | 类型 | 场景 | 前置 | 步骤 | 期望 | 优先级 | 现有资产 |
+|---|---|---|---|---|---|---|---|
+| TC-ROT-01 | 正常 | 超时订单自动完成 | 有 pending_receipt 超 N 天订单 | 跑 `processTimeoutOrders` | 订单置 completed;可追溯日志记录 | P0 | 部分(结构设计) |
+| TC-ROT-02 | **异常/幂等** | 重复执行不重复完成 | 已 completed 订单 | 再跑 2 次 | 不再被扫中;无重复日志 | **P0** | ❌ 缺行为断言 |
+| TC-ROT-03 | 边界 | 第 N 天提醒幂等 | `receipt_remind_at` 非空 | 再跑任务 | 不重复推送;失败仅日志下一轮重试 | P1 | ❌ 缺 |
+| TC-ROT-04 | 边界 | 灰度总开关 | `receipt-auto-complete-enabled=false` | 跑任务 | 仅提醒不自动完成 | **P0** | 部分(配置键在) |
+| TC-ROT-05 | 正常 | Spring 定时任务注册 | — | 检查注解 | `@Component` + `@Scheduled(fixedRate=60000)` + `@Transactional` | P1 | ✅ 契约正常流2/3/4 |
+| TC-ROT-06 | 异常 | 批量置态原子性 | 批量中 1 条失败 | 跑任务 | 整批回滚或跳过失败不产生半成品(依设计口径) | P1 | ❌ 缺(需设计确认口径) |
+| TC-ROT-07 | 正常 | 4 配置键齐备 | — | 检查 yml | `receipt-timeout-days`/`receipt-remind-days`/`receipt-remind-template-id`/总开关均存在 | P1 | ✅ 契约数据契约1 |
+
+## 五、执行状态与闭环
+
+| 能力 | 用例数 | 已自动化(契约结构) | 行为级/异常/权限 | 状态 |
+|---|---|---|---|---|
+| shop.review.detail | 9 | 3 | 6 待补 | 契约 RED,行为待验 |
+| shop.review.my | 8 | 2 | 6 待补 | 契约 RED,行为待验 |
+| shop.order.receiptTimeout | 7 | 2 | 5 待补 | 契约 RED,行为待验 |
+| 合计 | **24** | 7 | 17 待补 | — |
+
+> 闭环方式:本轮契约测试实跑取证(结构性通过≠行为正确);行为级/异常/权限用例待研发测试环境补测,任何失败入 `docs/tdd/test/blockers.md` 并标注是否为实现缺口。用例锚点供 `test_inventory.py` 编目与 `rollup_sc_l3.py` 场景归集。

Some files were not shown because too many files changed in this diff