Просмотр исходного кода

Merge origin/cfclub (pre-F03-deploy)

Xiaogang Liao 2 часов назад
Родитель
Сommit
2c9cb55dcb
25 измененных файлов с 2730 добавлено и 69 удалено
  1. 16 0
      cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminFamilyTaskController.java
  2. 32 0
      cfc-backend/src/main/java/com/etotem/cfc/dto/FamilyTaskCreateDTO.java
  3. 2 0
      cfc-backend/src/main/java/com/etotem/cfc/service/FamilyAdminOverviewService.java
  4. 108 24
      cfc-backend/src/main/java/com/etotem/cfc/service/TaskService.java
  5. 106 6
      cfc-backend/src/main/java/com/etotem/cfc/task/TaskDailyReminderScheduledTask.java
  6. 288 0
      cfc-backend/src/test/java/com/etotem/cfc/unit/FamilyMemberUpdateScP05P08ContractTest.java
  7. 529 0
      cfc-backend/src/test/java/com/etotem/cfc/unit/FoodPairingMatrixContractTest.java
  8. 462 0
      cfc-backend/src/test/java/com/etotem/cfc/unit/PrivacySettingConfigContractTest.java
  9. 195 16
      cfc-backend/src/test/java/com/etotem/cfc/unit/TaskReminderDailyScheduledTaskContractTest.java
  10. 293 0
      cfc-backend/src/test/java/com/etotem/cfc/unit/TongueEmotionCaptureContractTest.java
  11. 16 0
      cfc-frontend/__tests__/AdminPageTasksExcludeTemplate.contract.spec.js
  12. 18 0
      cfc-frontend/__tests__/TaskExcludeTemplate.contract.spec.js
  13. 21 0
      cfc-frontend/__tests__/TaskNoDeadlineVisible.contract.spec.js
  14. 2 16
      cfc-frontend/pages/profile-main/profile.vue
  15. 1 1
      cfc-web/.last_build_commit
  16. 2 2
      cfc-web/package-lock.json
  17. 1 1
      cfc-web/package.json
  18. 55 0
      cfc-web/public/CHANGELOG-v1.0.md
  19. 56 1
      cfc-web/public/CHANGELOG.md
  20. 28 0
      cfc-web/src/__tests__/views/AdminTaskFullEdit.contract.spec.js
  21. 4 0
      cfc-web/src/api/familyWorkbench.js
  22. 74 2
      cfc-web/src/views/FamilyWorkbench.vue
  23. 245 0
      docs/superpowers/plans/2026-11-29-task-evening-encouragement.md
  24. 66 0
      docs/superpowers/specs/2026-11-29-task-evening-encouragement-design.md
  25. 110 0
      docs/tdd/orchestration/report-dev-2026-11-29-2253.md

+ 16 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminFamilyTaskController.java

@@ -2,6 +2,7 @@ package com.etotem.cfc.controller.admin;
 
 import com.etotem.cfc.common.Result;
 import com.etotem.cfc.dto.FamilyTaskCreateDTO;
+import com.etotem.cfc.entity.Task;
 import com.etotem.cfc.service.TaskService;
 import io.swagger.v3.oas.annotations.Operation;
 import io.swagger.v3.oas.annotations.tags.Tag;
@@ -32,6 +33,21 @@ public class AdminFamilyTaskController {
         }
     }
 
+    @Operation(summary = "任务详情(编辑回显全量字段)")
+    @PostMapping("/families/{id}/tasks/detail")
+    @PreAuthorize("hasRole('admin')")
+    public Result<Task> getTaskDetail(@PathVariable Long id, @RequestBody Map<String, Object> params) {
+        Object taskId = params == null ? null : params.get("taskId");
+        if (taskId == null) {
+            return Result.error("taskId不能为空");
+        }
+        Task task = taskService.getAdminFamilyTaskDetail(((Number) taskId).longValue(), id);
+        if (task == null) {
+            return Result.error("任务不存在或不属于该家庭");
+        }
+        return Result.success(task);
+    }
+
     @Operation(summary = "任务编辑")
     @PostMapping("/families/{id}/tasks/update")
     @PreAuthorize("hasRole('admin')")

+ 32 - 0
cfc-backend/src/main/java/com/etotem/cfc/dto/FamilyTaskCreateDTO.java

@@ -25,4 +25,36 @@ public class FamilyTaskCreateDTO {
     private Long memberId;
     private String repeatType;
     private Date deadline;
+
+    // ---- 全量可编辑字段(2026-11-30 扩展)----
+    private Integer reviewByCategory;
+    private String frequencyUnit;
+    private Integer frequencyInterval;
+    private Date cycleAnchor;
+    private Integer isPaused;
+    private Date earliestStart;
+    private Date latestEnd;
+    private Date acceptDeadline;
+    private String minigameCode;
+    private String bonusRule;
+    private Integer pointsExpireDays;
+    private Integer isDailyProgress;
+    private Integer targetValue;
+    private Integer memberOnly;
+    private Long prerequisiteTaskId;
+    private Integer isFlowTask;
+    private String successorTaskIds;
+    private String actionType;
+    private String actionConfig;
+    private Integer requireInput;
+    private Integer startRequired;
+    private Integer minDurationSeconds;
+    private String dimensionCode;
+    private String dimensionWeights;
+    private String sourceType;
+    private Long sourceId;
+    private Long templateId;
+    private Integer isTemplate;
+    private Long familyMemberId;
+    private String status;
 }

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

@@ -154,6 +154,8 @@ public class FamilyAdminOverviewService {
         long safeSize = Math.min(Math.max(size, 1), 100);
         Page<Task> raw = taskMapper.selectPage(new Page<>(page, safeSize),
                 new LambdaQueryWrapper<Task>().eq(Task::getFamilyId, familyId)
+                        // 只显示可执行实例,模板不在任务列表重复出现
+                        .and(w -> w.ne(Task::getIsTemplate, 1).or().isNull(Task::getIsTemplate))
                         .orderByDesc(Task::getCreatedAt).orderByDesc(Task::getId));
         Page<TaskItemVO> out = new Page<>(raw.getCurrent(), raw.getSize(), raw.getTotal());
         out.setRecords(new ArrayList<>());

+ 108 - 24
cfc-backend/src/main/java/com/etotem/cfc/service/TaskService.java

@@ -514,6 +514,8 @@ public List<Task> getTodayTasks(Long memberId, String dimensionCode) {
 
         LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<Task>()
             .eq(Task::getFamilyMemberId, memberId)
+            // 模板不是可执行任务,排除后避免同一任务在今日列表出现「模板+实例」两条
+            .and(w -> w.ne(Task::getIsTemplate, 1).or().isNull(Task::getIsTemplate))
             .in(Task::getStatus, Arrays.asList("pending", "completed", "locked", "pending_review"))
             .and(w -> w
                 // 普通任务:按 deadline 判断今日
@@ -523,7 +525,9 @@ public List<Task> getTodayTasks(Long memberId, String dimensionCode) {
                 // 进度型任务:按 createdAt 判断今日(deadline 为 NULL)
                 .or(w3 -> w3.eq(Task::getIsDailyProgress, 1)
                         .ge(Task::getCreatedAt, startOfDay)
-                        .lt(Task::getCreatedAt, endOfDay)))
+                        .lt(Task::getCreatedAt, endOfDay))
+                // 无截止的一次性任务(deadline IS NULL):未完成时常驻列表,直到被完成
+                .or(w4 -> w4.isNull(Task::getDeadline)))
             .orderByAsc(Task::getDeadline);
 
         if (dimensionCode != null && !dimensionCode.isEmpty() && DimensionCodes.isValid(dimensionCode)) {
@@ -569,6 +573,7 @@ public List<Task> getTodayTasks(Long memberId, String dimensionCode) {
         // 对齐 getTodayTasks 口径:包含 in_progress 状态 + isDailyProgress 任务
         List<Task> all = taskMapper.selectList(new LambdaQueryWrapper<Task>()
                 .eq(Task::getFamilyId, familyId)
+                .and(w -> w.ne(Task::getIsTemplate, 1).or().isNull(Task::getIsTemplate))
                 .in(Task::getStatus, Arrays.asList("pending", "completed", "locked", "pending_review", "in_progress"))
                 .and(w -> w
                         .and(w2 -> w2.isNotNull(Task::getDeadline)
@@ -576,7 +581,8 @@ public List<Task> getTodayTasks(Long memberId, String dimensionCode) {
                                 .lt(Task::getDeadline, endOfDay))
                         .or(w3 -> w3.eq(Task::getIsDailyProgress, 1)
                                 .ge(Task::getCreatedAt, startOfDay)
-                                .lt(Task::getCreatedAt, endOfDay)))
+                                .lt(Task::getCreatedAt, endOfDay))
+                        .or(w4 -> w4.isNull(Task::getDeadline)))
                 .orderByAsc(Task::getDeadline)
                 .orderByAsc(Task::getId));
         // 与 getTodayTasks 对齐:提前1小时可见
@@ -2517,29 +2523,23 @@ return points; // 达到每日扣分上限:不扣分,任务完成仍发放
         return taskMapper.selectList(wrapper);
     }
 
+    /** 工作台-admin 任务详情:校验 family_id 归属,返回完整实体供编辑回显 */
+    public Task getAdminFamilyTaskDetail(Long taskId, Long familyId) {
+        Task t = taskMapper.selectById(taskId);
+        if (t == null || t.getFamilyId() == null || !t.getFamilyId().equals(familyId)) {
+            return null;
+        }
+        return t;
+    }
+
     /** 工作台-admin 任务新增:family_id/creator_id 固定来自服务端,status 默认 pending */
     public Long createAdminFamilyTask(Long familyId, Long adminUserId, FamilyTaskCreateDTO dto) {
         Task t = new Task();
         t.setFamilyId(familyId);
         t.setCreatorId(adminUserId);
-        t.setTitle(dto.getTitle());
-        t.setDescription(dto.getDescription());
-        t.setCategory(dto.getCategory());
-        t.setPoints(dto.getPoints());
-        t.setDuration(dto.getDuration());
-        t.setTaskType(dto.getTaskType());
-        t.setFrequency(dto.getFrequency());
-        t.setMaxFrequency(dto.getMaxFrequency());
-        t.setNeedReview(dto.getNeedReview());
-        t.setReviewType(dto.getReviewType());
-        t.setCompleteTypes(dto.getCompleteTypes() == null ? null : String.join(",", dto.getCompleteTypes()));
-        t.setExecutorType(dto.getExecutorType());
-        t.setExecutorId(dto.getExecutorId());
-        t.setMemberId(dto.getMemberId());
-        t.setRepeatType(dto.getRepeatType());
-        t.setDeadline(dto.getDeadline());
-        t.setStatus("pending");
-        t.setSourceType("admin");
+        applyAdminTaskFields(t, dto);
+        t.setStatus(dto.getStatus() != null ? dto.getStatus() : "pending");
+        t.setSourceType(dto.getSourceType() != null ? dto.getSourceType() : "admin");
         t.setCreatedAt(new Date());
         t.setUpdatedAt(new Date());
         taskMapper.insert(t);
@@ -2553,6 +2553,66 @@ return points; // 达到每日扣分上限:不扣分,任务完成仍发放
         if (t.getFamilyId() == null || !t.getFamilyId().equals(familyId)) {
             throw new RuntimeException("任务不属于该家庭");
         }
+        applyAdminTaskFields(t, dto);
+        if (dto.getStatus() != null) t.setStatus(dto.getStatus());
+        if (dto.getSourceType() != null) t.setSourceType(dto.getSourceType());
+        if (dto.getSourceId() != null) t.setSourceId(dto.getSourceId());
+        t.setUpdatedAt(new Date());
+        // ALWAYS:前端显式传 null 的字段要能清空(MyBatis-Plus 默认 NOT_NULL 会跳过 null)
+        return taskMapper.update(t, new com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper<Task>()
+                .eq(Task::getId, t.getId())
+                .set(Task::getUpdatedAt, t.getUpdatedAt())
+                .set(Task::getTitle, t.getTitle())
+                .set(Task::getDescription, t.getDescription())
+                .set(Task::getCategory, t.getCategory())
+                .set(Task::getPoints, t.getPoints())
+                .set(Task::getDuration, t.getDuration())
+                .set(Task::getTaskType, t.getTaskType())
+                .set(Task::getFrequency, t.getFrequency())
+                .set(Task::getMaxFrequency, t.getMaxFrequency())
+                .set(Task::getNeedReview, t.getNeedReview())
+                .set(Task::getReviewType, t.getReviewType())
+                .set(Task::getCompleteTypes, t.getCompleteTypes())
+                .set(Task::getExecutorType, t.getExecutorType())
+                .set(Task::getExecutorId, t.getExecutorId())
+                .set(Task::getMemberId, t.getMemberId())
+                .set(Task::getRepeatType, t.getRepeatType())
+                .set(Task::getDeadline, t.getDeadline())
+                .set(Task::getFamilyMemberId, t.getFamilyMemberId())
+                .set(Task::getReviewByCategory, t.getReviewByCategory())
+                .set(Task::getFrequencyUnit, t.getFrequencyUnit())
+                .set(Task::getFrequencyInterval, t.getFrequencyInterval())
+                .set(Task::getCycleAnchor, t.getCycleAnchor())
+                .set(Task::getIsPaused, t.getIsPaused())
+                .set(Task::getEarliestStart, t.getEarliestStart())
+                .set(Task::getLatestEnd, t.getLatestEnd())
+                .set(Task::getAcceptDeadline, t.getAcceptDeadline())
+                .set(Task::getMinigameCode, t.getMinigameCode())
+                .set(Task::getBonusRule, t.getBonusRule())
+                .set(Task::getPointsExpireDays, t.getPointsExpireDays())
+                .set(Task::getIsDailyProgress, t.getIsDailyProgress())
+                .set(Task::getTargetValue, t.getTargetValue())
+                .set(Task::getMemberOnly, t.getMemberOnly())
+                .set(Task::getPrerequisiteTaskId, t.getPrerequisiteTaskId())
+                .set(Task::getIsFlowTask, t.getIsFlowTask())
+                .set(Task::getSuccessorTaskIds, t.getSuccessorTaskIds())
+                .set(Task::getActionType, t.getActionType())
+                .set(Task::getActionConfig, t.getActionConfig())
+                .set(Task::getRequireInput, t.getRequireInput())
+                .set(Task::getStartRequired, t.getStartRequired())
+                .set(Task::getMinDurationSeconds, t.getMinDurationSeconds())
+                .set(Task::getDimensionCode, t.getDimensionCode())
+                .set(Task::getDimensionWeights, t.getDimensionWeights())
+                .set(Task::getTemplateId, t.getTemplateId())
+                .set(Task::getIsTemplate, t.getIsTemplate())
+                .set(Task::getStatus, t.getStatus())
+                .set(Task::getSourceType, t.getSourceType())
+                .set(Task::getSourceId, t.getSourceId())) > 0;
+    }
+
+
+    /** 工作台-admin 新增/编辑共用:把 DTO 全量字段写入实体 */
+    private void applyAdminTaskFields(Task t, FamilyTaskCreateDTO dto) {
         t.setTitle(dto.getTitle());
         t.setDescription(dto.getDescription());
         t.setCategory(dto.getCategory());
@@ -2563,14 +2623,38 @@ return points; // 达到每日扣分上限:不扣分,任务完成仍发放
         t.setMaxFrequency(dto.getMaxFrequency());
         t.setNeedReview(dto.getNeedReview());
         t.setReviewType(dto.getReviewType());
-        if (dto.getCompleteTypes() != null) t.setCompleteTypes(String.join(",", dto.getCompleteTypes()));
+        t.setCompleteTypes(dto.getCompleteTypes() == null ? null : String.join(",", dto.getCompleteTypes()));
         t.setExecutorType(dto.getExecutorType());
         t.setExecutorId(dto.getExecutorId());
         t.setMemberId(dto.getMemberId());
         t.setRepeatType(dto.getRepeatType());
         t.setDeadline(dto.getDeadline());
-        t.setUpdatedAt(new Date());
-        return taskMapper.updateById(t) > 0;
+        t.setFamilyMemberId(dto.getFamilyMemberId());
+        t.setReviewByCategory(dto.getReviewByCategory());
+        t.setFrequencyUnit(dto.getFrequencyUnit());
+        t.setFrequencyInterval(dto.getFrequencyInterval());
+        t.setCycleAnchor(dto.getCycleAnchor());
+        t.setIsPaused(dto.getIsPaused());
+        t.setEarliestStart(dto.getEarliestStart());
+        t.setLatestEnd(dto.getLatestEnd());
+        t.setAcceptDeadline(dto.getAcceptDeadline());
+        t.setMinigameCode(dto.getMinigameCode());
+        t.setBonusRule(dto.getBonusRule());
+        t.setPointsExpireDays(dto.getPointsExpireDays());
+        t.setIsDailyProgress(dto.getIsDailyProgress());
+        t.setTargetValue(dto.getTargetValue());
+        t.setMemberOnly(dto.getMemberOnly());
+        t.setPrerequisiteTaskId(dto.getPrerequisiteTaskId());
+        t.setIsFlowTask(dto.getIsFlowTask());
+        t.setSuccessorTaskIds(dto.getSuccessorTaskIds());
+        t.setActionType(dto.getActionType());
+        t.setActionConfig(dto.getActionConfig());
+        t.setRequireInput(dto.getRequireInput());
+        t.setStartRequired(dto.getStartRequired());
+        t.setMinDurationSeconds(dto.getMinDurationSeconds());
+        t.setDimensionCode(dto.getDimensionCode());
+        t.setDimensionWeights(dto.getDimensionWeights());
+        t.setTemplateId(dto.getTemplateId());
+        t.setIsTemplate(dto.getIsTemplate());
     }
-
 }

+ 106 - 6
cfc-backend/src/main/java/com/etotem/cfc/task/TaskDailyReminderScheduledTask.java

@@ -94,6 +94,14 @@ public class TaskDailyReminderScheduledTask {
     @Resource
     private TaskReminderConfigService taskReminderConfigService;
 
+    /** 晚间鼓励文案昵称查询(失败回退"您",不阻塞发送)。 */
+    @Resource
+    private com.etotem.cfc.mapper.UserMapper userMapper;
+
+    /** 通知通道列表(晚间鼓励经 wechat webhook 发送,in_app 兜底)。 */
+    @Resource
+    private java.util.List<com.etotem.cfc.service.notification.NotificationChannel> notificationChannels;
+
     /** 早提醒:07:30 固定 cron(设计契约 §3.4 拍板)。 */
     @Scheduled(cron = "0 30 7 * * ?")
     public void sendMorningReminder() {
@@ -165,23 +173,95 @@ public class TaskDailyReminderScheduledTask {
             for (Map.Entry<Long, List<Task>> entry : byUser.entrySet()) {
                 Long userId = entry.getKey();
                 List<Task> userTasks = entry.getValue();
-                if (!isDailyEnabled(userId)) {
+                if (!isDailyEnabledEvening(userId)) {
                     continue;
                 }
                 if (alreadySentToday(userId, TYPE_EVENING, dayStart)) {
                     continue;
                 }
-                String content = buildEveningContent(userTasks, dayStart);
-                notificationDispatchService.sendByTemplate(TYPE_EVENING, userId,
-                        new HashMap<String, Object>(), REF_TYPE, userTasks.get(0).getId(),
-                        "今日任务总结", content);
-                log.info("日提醒-晚:已发送 userId={}, 任务数={}", userId, userTasks.size());
+                String nickname = resolveNickname(userId);
+                String content = buildEveningEncouragement(userTasks, nickname);
+                com.etotem.cfc.dto.NotificationMessage msg = new com.etotem.cfc.dto.NotificationMessage(
+                        userId, TYPE_EVENING, "今日任务总结", content, REF_TYPE,
+                        userTasks.get(0).getId(), "in_app,wechat");
+                dispatchEvening(msg);
+                log.info("日提醒-晚:已发送(含微信webhook) userId={}, 任务数={}, 昵称={}",
+                        userId, userTasks.size(), nickname);
             }
         } catch (Exception e) {
             log.warn("日提醒-晚执行异常: {}", e.getMessage());
         }
     }
 
+    /** 查用户昵称,null/空/异常 → 回退"您"(不阻塞发送)。 */
+    private String resolveNickname(Long userId) {
+        if (userId == null) return "您";
+        try {
+            if (userMapper != null) {
+                com.etotem.cfc.entity.User u = userMapper.selectById(userId);
+                if (u != null && u.getNickname() != null && !u.getNickname().trim().isEmpty()) {
+                    return u.getNickname();
+                }
+            }
+        } catch (Exception e) {
+            log.warn("日提醒-晚:昵称查询失败 userId={}, error={}", userId, e.getMessage());
+        }
+        return "您";
+    }
+
+    /** 按 channels 分发晚间提醒:in_app + wechat,通道未启用/异常不阻断(仿 TaskCheckinWebhookReminderTask)。 */
+    private void dispatchEvening(com.etotem.cfc.dto.NotificationMessage msg) {
+        if (notificationChannels == null) return;
+        for (String target : msg.getChannels().split(",")) {
+            String c = target.trim();
+            if (c.isEmpty()) continue;
+            for (com.etotem.cfc.service.notification.NotificationChannel channel : notificationChannels) {
+                if (!c.equals(channel.getChannelType())) continue;
+                if (!channel.isEnabled()) continue;
+                try {
+                    channel.send(msg);
+                } catch (Exception e) {
+                    log.warn("日提醒-晚:通道发送失败 channel={}, userId={}, error={}",
+                            c, msg.getUserId(), e.getMessage());
+                }
+                break;
+            }
+        }
+    }
+
+    /**
+     * 四档关怀鼓励文案(2026-11-29 增强):按今日到期任务完成率分为
+     * 100% / ≥80%<100% / 1~79% / 0% 四档,语气从表扬到关怀不指责。
+     *
+     * @param tasks    今日到期任务(已完成判定沿用 buildEveningContent:completed 且 completedAt 今日)
+     * @param nickname 用户昵称,null/空回退"您"
+     */
+    private String buildEveningEncouragement(java.util.List<Task> tasks, String nickname) {
+        String name = (nickname == null || nickname.trim().isEmpty()) ? "您" : nickname;
+        int total = tasks == null ? 0 : tasks.size();
+        int done = 0;
+        Date dayStart = startOfToday();
+        if (tasks != null) {
+            for (Task t : tasks) {
+                if ("completed".equals(t.getStatus()) && isSameDay(t.getCompletedAt(), dayStart)) {
+                    done++;
+                }
+            }
+        }
+        String ratio = done + "/" + total;
+        if (total > 0 && done == total) {
+            return "「" + name + "」,今天的任务全都完成了,太棒啦!为你的坚持点赞~";
+        }
+        double rate = total == 0 ? 0d : (double) done / total;
+        if (rate >= 0.8) {
+            return "「" + name + "」,今天完成了大部分任务,就差一点点,已经很厉害啦~";
+        }
+        if (done > 0) {
+            return "「" + name + "」,今天完成了 " + ratio + " 项,每一步都算数,明天继续加油哦~";
+        }
+        return "「" + name + "」,今天可能有点忙,没完成任务也没关系,明天我们慢慢来~";
+    }
+
     /** 设计契约 §3.4 晚总结文案:「今日总结:完成 X/N。✅ 已完成:…;【未完成】⚠ 标题…别忘了打卡哦~」 */
     private String buildEveningContent(List<Task> tasks, Date dayStart) {
         List<String> done = new ArrayList<String>();
@@ -257,6 +337,26 @@ public class TaskDailyReminderScheduledTask {
         return map;
     }
 
+    /**
+     * 晚间鼓励开关(2026-11-29):默认开启——无配置记录 / daily_enabled 为空 → 开启(1);
+     * 仅显式 0 → 关闭。与早提醒的 isDailyEnabled 分离,保证早提醒收件人不扩大。
+     */
+    private boolean isDailyEnabledEvening(Long userId) {
+        if (taskReminderConfigService == null) {
+            return true; // 单测未注入配置服务 → 不拦截
+        }
+        try {
+            TaskReminderConfig config = taskReminderConfigService.loadAllConfigs().get(userId);
+            if (config == null || config.getDailyEnabled() == null) {
+                return true;
+            }
+            return !Integer.valueOf(0).equals(config.getDailyEnabled());
+        } catch (Exception e) {
+            log.warn("日提醒-晚:配置读取失败 userId={}, error={}", userId, e.getMessage());
+            return true; // 晚间默认开,读配置失败也不阻断
+        }
+    }
+
     /** 日提醒开关:仅当配置服务可用时按 daily_enabled=1 过滤(单测未注入 → 不拦截)。 */
     private boolean isDailyEnabled(Long userId) {
         if (taskReminderConfigService == null) {

+ 288 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/FamilyMemberUpdateScP05P08ContractTest.java

@@ -0,0 +1,288 @@
+package com.etotem.cfc.unit;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.controller.family.FamilyInviteController;
+import com.etotem.cfc.controller.family.FamilyMembersController;
+import com.etotem.cfc.dto.AddFamilyMemberDTO;
+import com.etotem.cfc.dto.FamilyMemberVO;
+import com.etotem.cfc.dto.TransferAdminDTO;
+import com.etotem.cfc.entity.Family;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.FamilyMapper;
+import com.etotem.cfc.mapper.FamilyMemberLogMapper;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.FamilyMemberService;
+import com.etotem.cfc.service.ReportMemberPermissionService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.springframework.security.access.AccessDeniedException;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.web.bind.annotation.PostMapping;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * 契约级单测:编辑成员资料 + 成员权限设置(能力键 {@code family.member.update},
+ * SC-P-05 / SC-P-08,任务号 S-cfc-260)。
+ *
+ * <p><b>契约锚点</b></p>
+ * <ul>
+ *   <li>需求:{@code tests/user-scenarios/应用场景总览.md} SC-P-05(编辑成员资料:姓名/关系/生日/性别;
+ *       边界:必填缺失拦截、生日格式校验)与 SC-P-08(成员权限设置:查看/编辑权限;
+ *       边界:越权设置被拒、最低权限保底)</li>
+ *   <li>设计:{@code docs/superpowers/api/API_REFERENCE.md} §4.2 —— {@code POST /api/family/member/update}
+ *       (body 可含 isChild=1/0,仅家庭管理员可设置,落库 users.is_child;非管理员 403)、
+ *       {@code POST /api/family/member/editable}、{@code POST /api/family/invite/transfer-admin}</li>
+ * </ul>
+ *
+ * <p><b>RED 依据(工作树 = origin/cfclub @ {@code 65089ebb8})</b></p>
+ * <ol>
+ *   <li>SC-P-08「设成员查看权限」:{@code AddFamilyMemberDTO} 无 {@code showToFamily} 字段,
+ *       {@code FamilyMembersController#updateMember} 也未解析该 body 参数 → 查看权限无法通过统一更新入口设置。</li>
+ *   <li>SC-P-05「生日格式校验」/「必填缺失拦截」:非法生日、缺失 memberId 当前走
+ *       {@code Result.error}(code=500),契约要求参数类错误为 400。</li>
+ *   <li>SC-P-05 生日变更 + {@code UserUtil}「生日变更时按年龄兜底填充 is_child 默认值(仅当为 null)」:
+ *       {@code FamilyMemberService#updateMember} 改生日后未调用 {@code fillDefaultIsChild},
+ *       {@code users.is_child} 保持 null → 默认值未实现。</li>
+ *   <li>SC-P-08「编辑权限」:{@code /editable} 与 {@code FamilyMemberService#isEditable(Long)} 完全忽略操作者身份,
+ *       管理员查询「已关联账号成员」得到 false,与 {@code updateMember} 中「管理员可编辑所有成员」矛盾 →
+ *       缺少带操作者的可编辑判定入口。</li>
+ * </ol>
+ *
+ * <p><b>GREEN 升级指引</b>:为 {@code AddFamilyMemberDTO} 增加 {@code showToFamily} 并在 controller 透传;
+ * 参数校验改返 400;生日变更路径调用 {@code UserUtil.fillDefaultIsChild};
+ * 新增 operator-aware 的 {@code isEditable(userId, memberId)} 并在 {@code /editable} 透传 userId。
+ * 基线用例(403 / isChild 透传 / transfer-admin)锁定既有实现不被 GREEN 误伤。</p>
+ *
+ * <p><b>测试范围</b>:纯 Mockito / 反射,无 Spring 上下文、无 DB、无外部服务。仅覆盖本键契约。</p>
+ */
+class FamilyMemberUpdateScP05P08ContractTest {
+
+    private static final Long ADMIN_ID = 1L;
+    private static final Long MEMBER_ID = 10L;
+    private static final Long FAMILY_ID = 7L;
+
+    private FamilyMembersController controller;
+    private FamilyMemberService familyMemberService;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        controller = new FamilyMembersController();
+        familyMemberService = mock(FamilyMemberService.class);
+        inject(controller, "familyMemberService", familyMemberService);
+    }
+
+    // ==================== 正常流-1:查看权限(RED) ====================
+
+    @Test
+    @DisplayName("正常流-1:update 应接受 showToFamily(查看权限)并透传给服务,而非静默忽略")
+    void update_应支持设置查看权限showToFamily() {
+        when(familyMemberService.updateMember(eq(ADMIN_ID), eq(MEMBER_ID), any(AddFamilyMemberDTO.class)))
+                .thenReturn(new FamilyMemberVO());
+
+        Map<String, Object> body = new HashMap<String, Object>();
+        body.put("memberId", MEMBER_ID);
+        body.put("showToFamily", 0); // 0=对家庭不可见(最低权限保底场景)
+
+        Result<?> r = controller.updateMember(body, ADMIN_ID);
+        assertEquals(200, r.getCode());
+
+        ArgumentCaptor<AddFamilyMemberDTO> captor = ArgumentCaptor.forClass(AddFamilyMemberDTO.class);
+        verify(familyMemberService).updateMember(eq(ADMIN_ID), eq(MEMBER_ID), captor.capture());
+        AddFamilyMemberDTO dto = captor.getValue();
+
+        assertTrue(hasField(AddFamilyMemberDTO.class, "showToFamily"),
+                "[family.member.update] SC-P-08 要求经统一更新入口设置成员「查看权限」,"
+                        + "AddFamilyMemberDTO 当前无 showToFamily 字段,查看权限设置能力未落地。");
+        assertEquals(Integer.valueOf(0), readField(dto, "showToFamily"),
+                "[family.member.update] body.showToFamily=0 应透传到 DTO 并落库,当前被 updateMember 静默忽略。");
+    }
+
+    // ==================== 正常流-2:生日变更兜底默认值(RED) ====================
+
+    @Test
+    @DisplayName("正常流-2:生日变更应填充 users.is_child 年龄兜底默认值(仅当为 null),不覆盖显式设置")
+    void 生日变更_应按年龄兜底填充isChild默认值() {
+        UserMapper userMapper = mock(UserMapper.class);
+        FamilyMapper familyMapper = mock(FamilyMapper.class);
+        FamilyMemberMapper familyMemberMapper = mock(FamilyMemberMapper.class);
+        FamilyMemberLogMapper logMapper = mock(FamilyMemberLogMapper.class);
+        FamilyMemberService svc = new FamilyMemberService();
+        ReflectionTestUtils.setField(svc, "userMapper", userMapper);
+        ReflectionTestUtils.setField(svc, "familyMapper", familyMapper);
+        ReflectionTestUtils.setField(svc, "familyMemberMapper", familyMemberMapper);
+        ReflectionTestUtils.setField(svc, "familyMemberLogMapper", logMapper);
+
+        User operator = new User();
+        operator.setId(ADMIN_ID);
+        operator.setFamilyId(FAMILY_ID);
+        when(userMapper.selectById(ADMIN_ID)).thenReturn(operator);
+
+        Family family = new Family();
+        family.setId(FAMILY_ID);
+        family.setCreatorId(ADMIN_ID); // 家庭主账号走 updateParentMember 分支
+        when(familyMapper.selectById(FAMILY_ID)).thenReturn(family);
+
+        // family_members 无记录 → 走家庭主账号(users 表)更新分支
+        when(familyMemberMapper.selectById(MEMBER_ID)).thenReturn(null);
+
+        User target = new User();
+        target.setId(MEMBER_ID);
+        target.setFamilyId(FAMILY_ID);
+        target.setRole("parent");
+        target.setNickname("成员甲");
+        target.setIsChild(null); // 存量数据未判定
+        when(userMapper.selectById(MEMBER_ID)).thenReturn(target);
+
+        AddFamilyMemberDTO dto = new AddFamilyMemberDTO();
+        dto.setBirthday("2015-01-01"); // 未满 18 周岁 → 兜底应为孩子
+        svc.updateMember(ADMIN_ID, MEMBER_ID, dto);
+
+        assertEquals(Boolean.TRUE, target.getIsChild(),
+                "[family.member.update] UserUtil 契约要求「生日变更时按年龄兜底填充 is_child 默认值"
+                        + "(仅当 isChild 为 null,不覆盖显式设置)」;经 update 改生日后 is_child 仍为 null,默认值未实现。");
+    }
+
+    // ==================== 异常流-1/2:参数校验 400(RED) ====================
+
+    @Test
+    @DisplayName("异常流-1:生日格式非法应返回 400 参数错误,而非 500")
+    void 生日格式非法_应返回400() {
+        when(familyMemberService.updateMember(eq(ADMIN_ID), eq(MEMBER_ID), any(AddFamilyMemberDTO.class)))
+                .thenThrow(new IllegalArgumentException("出生日期格式错误,应为yyyy-MM-dd"));
+
+        Map<String, Object> body = new HashMap<String, Object>();
+        body.put("memberId", MEMBER_ID);
+        body.put("birthday", "2015-13-40");
+
+        Result<?> r = controller.updateMember(body, ADMIN_ID);
+        assertEquals(400, r.getCode(),
+                "[family.member.update] SC-P-05 边界「生日格式校验」要求非法生日返回 400 参数错误,"
+                        + "当前 IllegalArgumentException 被 Result.error 包装为 500。");
+        assertNotNull(r.getMessage());
+        assertTrue(r.getMessage().contains("出生日期"));
+    }
+
+    @Test
+    @DisplayName("异常流-2:缺少必填 memberId 应返回 400,而非 500")
+    void 缺少必填memberId_应返回400() {
+        Map<String, Object> body = new HashMap<String, Object>();
+        body.put("nickname", "张三");
+
+        Result<?> r = controller.updateMember(body, ADMIN_ID);
+        assertEquals(400, r.getCode(),
+                "[family.member.update] SC-P-05 边界「必填缺失拦截」要求缺失 memberId 返回 400,"
+                        + "当前返回 500(Result.error)。");
+    }
+
+    // ==================== 权限流-1:编辑权限判定缺操作者维度(RED) ====================
+
+    @Test
+    @DisplayName("权限流-1:应提供带操作者的可编辑判定入口(管理员可编辑已关联账号成员)")
+    void editable_应提供操作者维度判定() {
+        boolean operatorAware = false;
+        for (Method m : FamilyMemberService.class.getDeclaredMethods()) {
+            if (!"isEditable".equals(m.getName()) && !"canEdit".equals(m.getName())) {
+                continue;
+            }
+            Class<?>[] types = m.getParameterTypes();
+            if (types.length == 2 && types[0] == Long.class && types[1] == Long.class) {
+                operatorAware = true;
+                break;
+            }
+        }
+        assertTrue(operatorAware,
+                "[family.member.update] SC-P-08「编辑权限」要求 /editable 结合操作者判定:"
+                        + "updateMember 允许管理员编辑所有成员(含已关联账号),但当前仅 isEditable(memberId)"
+                        + "且完全忽略调用者 userId,管理员查询得到 false,缺少 isEditable(userId, memberId) 入口。");
+    }
+
+    // ==================== 基线锚点(绿,锁定既有实现) ====================
+
+    @Test
+    @DisplayName("基线-1:非管理员设置 isChild 抛 AccessDeniedException → 403")
+    void 基线_非管理员设置isChild返回403() {
+        when(familyMemberService.updateMember(eq(ADMIN_ID), eq(MEMBER_ID), any(AddFamilyMemberDTO.class)))
+                .thenThrow(new AccessDeniedException("仅家庭管理员可设置孩子身份"));
+
+        Map<String, Object> body = new HashMap<String, Object>();
+        body.put("memberId", MEMBER_ID);
+        body.put("isChild", 1);
+
+        Result<?> r = controller.updateMember(body, ADMIN_ID);
+        assertEquals(403, r.getCode());
+        assertNotNull(r.getMessage());
+        assertTrue(r.getMessage().contains("管理员"));
+    }
+
+    @Test
+    @DisplayName("基线-2:isChild=1/0 数值与布尔两种形态均正确解析到 DTO")
+    void 基线_isChild数值形态正确解析() {
+        when(familyMemberService.updateMember(eq(ADMIN_ID), eq(MEMBER_ID), any(AddFamilyMemberDTO.class)))
+                .thenReturn(new FamilyMemberVO());
+
+        Map<String, Object> body = new HashMap<String, Object>();
+        body.put("memberId", MEMBER_ID);
+        body.put("isChild", 1);
+        controller.updateMember(body, ADMIN_ID);
+
+        ArgumentCaptor<AddFamilyMemberDTO> captor = ArgumentCaptor.forClass(AddFamilyMemberDTO.class);
+        verify(familyMemberService).updateMember(eq(ADMIN_ID), eq(MEMBER_ID), captor.capture());
+        assertEquals(Integer.valueOf(1), captor.getValue().getIsChild());
+    }
+
+    @Test
+    @DisplayName("基线-3:转让管理员端点仍为 POST /transfer-admin(设计 §4.2)")
+    void 基线_transferAdmin端点存在() throws Exception {
+        Method m = FamilyInviteController.class.getDeclaredMethod("transferAdmin", TransferAdminDTO.class, Long.class);
+        PostMapping mapping = m.getAnnotation(PostMapping.class);
+        assertNotNull(mapping, "[family.member.update] 设计 §4.2 要求 POST /api/family/invite/transfer-admin。");
+        assertEquals("/transfer-admin", mapping.value()[0]);
+    }
+
+    // ==================== 辅助 ====================
+
+    private static boolean hasField(Class<?> clazz, String name) {
+        for (Field f : clazz.getDeclaredFields()) {
+            if (name.equals(f.getName())) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private static Object readField(Object target, String name) {
+        try {
+            Field f = target.getClass().getDeclaredField(name);
+            f.setAccessible(true);
+            return f.get(target);
+        } catch (NoSuchFieldException e) {
+            fail("[family.member.update] 字段不存在:" + name);
+        } catch (IllegalAccessException e) {
+            fail("[family.member.update] 字段不可读:" + name + "," + e.getMessage());
+        }
+        return null;
+    }
+
+    private static void inject(Object target, String fieldName, Object value) throws Exception {
+        Field f = target.getClass().getDeclaredField(fieldName);
+        f.setAccessible(true);
+        f.set(target, value);
+    }
+}

+ 529 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/FoodPairingMatrixContractTest.java

@@ -0,0 +1,529 @@
+package com.etotem.cfc.unit;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Scanner;
+import java.util.Set;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * 契约级单测:能力键 {@code food.rule.pairingMatrix}(S-cfc-440,TDD-RED 阶段)。
+ *
+ * <p><b>契约溯源</b></p>
+ * <ul>
+ *   <li>需求:{@code docs/需求分析/2026-11-22-食材推荐加权规则引擎需求变更.md}
+ *       CR-03 + §4.3(食材配伍矩阵:现代营养学协同/拮抗 + 中医药食同源相生相克)
+ *       + §5(数据结构与迁移评估)+ §7.1 G-3(配伍效应正确写入指数)+ 第六节(能力键 food.rule.pairingMatrix)。</li>
+ *   <li>配伍表 {@code food_pairing_matrix}(§4.3):字段
+ *       {@code food_a_id / food_b_id / relation_type / intensity / effect_score / source / evidence_ref / enabled};
+ *       {@code relation_type} 枚举 7 值:
+ *       {@code synergy / antagonism / xiangsheng / xiangke / xiangwei / xiangsha / xiangwu};
+ *       {@code intensity} 1-5;{@code effect_score} 为推荐指数调整值 [-50, +50];
+ *       {@code source} 仅 {@code modern_nutrition / tcm_shi_liao},禁止混用无标注。</li>
+ *   <li>规则(§4.3):维生素 C 促进铁吸收(协同)、草酸抑制钙吸收(拮抗)、高嘌呤×高嘌呤(避让);
+ *       菠菜+豆腐、柿子+螃蟹 → 忌配伍;若同时含 A+B 且 {@code relation_type ∈ {xiangke, antagonism}}
+ *       且 {@code intensity ≥ 3} → 硬避让(CR-07 消费此判定)。</li>
+ * </ul>
+ *
+ * <p><b>实现现状(origin/cfclub 源码核实)</b>:{@code FoodPairingMatrix} 实体、{@code food_pairing_matrix}
+ * 建表与迁移已由后台规则管理({@code ops.foodRuleManagement} / CR-06)顺带落地,但<b>本能力键的配伍查询/效应计算/
+ * 避让判定服务未实现</b>:{@code FoodPairingMatrixMapper} 不存在,
+ * {@code FoodRecommendService} / {@code FoodService} / {@code DietRecommendationService} 均未引用配伍矩阵,
+ * 结构探测因此能编译能运行、行为断言失败(红)。</p>
+ *
+ * <p><b>契约宿主(实现方按此落地)</b>:{@code com.etotem.cfc.service.FoodPairingMatrixService}
+ * —— 通过反射按方法名 + 参数个数探测,避免直接 import 不存在类导致编译失败:</p>
+ * <ul>
+ *   <li>{@code List<String> supportedRelationTypes()} —— 7 种合法关系类型</li>
+ *   <li>{@code boolean isValidRelationType(String type)} —— 关系类型值域校验</li>
+ *   <li>{@code List<String> supportedSources()} —— 2 种权威来源</li>
+ *   <li>{@code boolean isValidSource(String source)} —— 来源值域校验(禁止无标注混用)</li>
+ *   <li>{@code double clampEffectScore(double value)} —— 截断到 [-50, +50]</li>
+ *   <li>{@code double resolvePairingEffect(Long foodAId, Long foodBId, List<Map<String,Object>> rules)}
+ *       —— 对称匹配 A×B、仅取 enabled 规则、无配置/无命中 → 0,越界截断;rules 为纯内存规则集,
+ *       每项含 foodAId / foodBId / relationType / intensity / effectScore / source / evidenceRef / enabled,
+ *       使契约与 DB 解耦</li>
+ *   <li>{@code boolean requiresAvoidance(Long foodAId, Long foodBId, List<Map<String,Object>> rules)}
+ *       —— 忌配伍判定:enabled 且 relationType∈{xiangke,antagonism} 且 intensity≥3 → true,否则 false</li>
+ * </ul>
+ *
+ * <p><b>测试范围</b>:纯 JUnit5 + 反射 + 源码文本读取(无 Spring / 无 DB / 无外部服务),与同批已合入主链的
+ * RED 契约测试(TeamProfitHookContractTest / FoodProcessingEffectContractTest /
+ * FoodOpsRuleManagementCrudBehaviorContractTest)同风格。</p>
+ *
+ * <p><b>权限流</b>:配伍查询/避让判定为后端内部服务(后台 CRUD 由独立能力键 ops.foodRuleManagement / CR-06
+ * 承载,食谱硬避让由 diet.menu.pairingConstraint / CR-07 承载),无用户侧鉴权分支,权限流不适用。</p>
+ *
+ * <p><b>RED 预期</b>:行为用例在 {@code contractHost()} 处失败(宿主类未实现),结构用例在 Mapper /
+ * 推荐链路源码锚点处失败;失败原文前缀 {@code RED[food.rule.pairingMatrix]}。</p>
+ */
+class FoodPairingMatrixContractTest {
+
+    private static final String CAP = "[food.rule.pairingMatrix]";
+    private static final String RED = "RED[food.rule.pairingMatrix]";
+
+    /** 契约宿主类(§4.3 配伍查询/效应计算/避让判定服务,当前未实现)。 */
+    private static final String HOST_CLASS = "com.etotem.cfc.service.FoodPairingMatrixService";
+
+    /** 配伍矩阵实体与表(§4.3 food_pairing_matrix 表)。 */
+    private static final String ENTITY_FQCN = "com.etotem.cfc.entity.FoodPairingMatrix";
+    private static final String MAPPER_FQCN = "com.etotem.cfc.mapper.FoodPairingMatrixMapper";
+    private static final String TABLE = "food_pairing_matrix";
+
+    /** §4.3 relation_type 的 7 个合法枚举值。 */
+    private static final String[] RELATION_TYPES = {
+            "synergy", "antagonism", "xiangsheng", "xiangke", "xiangwei", "xiangsha", "xiangwu"
+    };
+
+    /** §4.3 source 的 2 个合法枚举值。 */
+    private static final String[] SOURCES = {"modern_nutrition", "tcm_shi_liao"};
+
+    /** §4.3 配伍表必需字段(除主键 id 外)。 */
+    private static final String[] REQUIRED_FIELDS = {
+            "foodAId", "foodBId", "relationType", "intensity",
+            "effectScore", "source", "evidenceRef", "enabled"
+    };
+
+    /** §4.3 配伍表必需列(除 id 外,snake_case)。 */
+    private static final String[] REQUIRED_COLUMNS = {
+            "food_a_id", "food_b_id", "relation_type", "intensity",
+            "effect_score", "source", "evidence_ref", "enabled"
+    };
+
+    private static final double EPS = 1e-9;
+
+    // ==================== 正常流:宿主 + 关系类型 / 来源值域 ====================
+
+    @Test
+    @DisplayName("正常流-1:契约宿主 FoodPairingMatrixService 应存在(§4.3 配伍查询/效应计算)")
+    void hostClass_exists() {
+        assertNotNull(contractHost(),
+                CAP + " 契约宿主 FoodPairingMatrixService 应存在:§4.3 要求 A×B 配伍查询、"
+                        + "effect_score 计算与忌配伍判定,当前 src/main 无该服务,实现未落地。");
+    }
+
+    @Test
+    @DisplayName("正常流-2:supportedRelationTypes() 应覆盖 7 种关系类型(§4.3)")
+    void supportedRelationTypes_coverSevenValues() {
+        Object host = contractHost();
+        List<String> types = callListString(host, "supportedRelationTypes");
+        assertNotNull(types, CAP + " supportedRelationTypes() 应返回关系类型清单(§4.3)。");
+        Set<String> actual = new HashSet<String>(types);
+        Set<String> expected = new HashSet<String>(Arrays.asList(RELATION_TYPES));
+        assertEquals(expected, actual,
+                CAP + " 关系类型应恰好覆盖 7 种(§4.3):synergy/antagonism/xiangsheng/xiangke/"
+                        + "xiangwei/xiangsha/xiangwu,实际=" + actual);
+    }
+
+    @Test
+    @DisplayName("正常流-3:isValidRelationType 应接受 7 种、拒绝未知/空值(§4.3)")
+    void isValidRelationType_acceptsSeven_rejectsUnknownAndNull() {
+        Object host = contractHost();
+        for (String type : RELATION_TYPES) {
+            assertTrue(callBoolean(host, "isValidRelationType", type),
+                    CAP + " 合法关系类型 " + type + " 应被接受(§4.3)。");
+        }
+        assertTrue(!callBoolean(host, "isValidRelationType", "unknown"),
+                CAP + " 未知关系类型 unknown 应被拒绝(§4.3 值域仅 7 种)。");
+        assertTrue(!callBoolean(host, "isValidRelationType", (Object) null),
+                CAP + " null 关系类型应被拒绝,不得抛异常或误判为合法(§4.3)。");
+    }
+
+    @Test
+    @DisplayName("正常流-4:supportedSources() 应覆盖 2 种权威来源(§4.3)")
+    void supportedSources_coverTwoValues() {
+        Object host = contractHost();
+        List<String> sources = callListString(host, "supportedSources");
+        assertNotNull(sources, CAP + " supportedSources() 应返回来源清单(§4.3)。");
+        Set<String> actual = new HashSet<String>(sources);
+        Set<String> expected = new HashSet<String>(Arrays.asList(SOURCES));
+        assertEquals(expected, actual,
+                CAP + " 来源应恰好覆盖 2 种(§4.3):modern_nutrition / tcm_shi_liao,实际=" + actual);
+    }
+
+    @Test
+    @DisplayName("正常流-5:isValidSource 应接受 2 种来源、拒绝未知/空值(§4.3 禁止无标注混用)")
+    void isValidSource_acceptsTwo_rejectsUnknownAndNull() {
+        Object host = contractHost();
+        for (String source : SOURCES) {
+            assertTrue(callBoolean(host, "isValidSource", source),
+                    CAP + " 合法来源 " + source + " 应被接受(§4.3)。");
+        }
+        assertTrue(!callBoolean(host, "isValidSource", "unknown"),
+                CAP + " 未知来源 unknown 应被拒绝,禁止混用无标注数据(§4.3)。");
+        assertTrue(!callBoolean(host, "isValidSource", (Object) null),
+                CAP + " null 来源应被拒绝(§4.3 source 必须标注现代营养学或中医药食同源)。");
+    }
+
+    // ==================== 默认值/边界流(核心 RED) ====================
+
+    @Test
+    @DisplayName("默认值-1:未配置配伍规则 → 无调整 effect_score=0(§4.3 / G-3)")
+    void resolvePairingEffect_unconfigured_returnsZero() {
+        Object host = contractHost();
+        List<Map<String, Object>> rules = new ArrayList<Map<String, Object>>();
+        double effect = callDouble(host, "resolvePairingEffect", 1001L, 1002L, rules);
+        assertEquals(0.0, effect, EPS,
+                CAP + " 未配置的食材 A×B → 无调整(effect_score=0,§4.3);当前默认值未实现,实际=" + effect);
+    }
+
+    @Test
+    @DisplayName("默认值-2:A×B 与 B×A 应命中同一条配伍规则(§4.3 食材 A×B 关系)")
+    void resolvePairingEffect_isSymmetric() {
+        Object host = contractHost();
+        List<Map<String, Object>> rules = new ArrayList<Map<String, Object>>();
+        rules.add(rule(1001L, 1002L, "antagonism", 4, -25.0, "modern_nutrition", 1));
+        assertEquals(-25.0, callDouble(host, "resolvePairingEffect", 1001L, 1002L, rules), EPS,
+                CAP + " A×B 应命中配伍效应 -25(§4.3 草酸×钙拮抗示例)。");
+        assertEquals(-25.0, callDouble(host, "resolvePairingEffect", 1002L, 1001L, rules), EPS,
+                CAP + " B×A 应命中同一条配伍规则(配伍关系对称,§4.3)。");
+    }
+
+    @Test
+    @DisplayName("默认值-3:enabled=0 的配伍规则不应参与效应计算(§4.3 启用开关)")
+    void resolvePairingEffect_ignoresDisabledRule() {
+        Object host = contractHost();
+        List<Map<String, Object>> rules = new ArrayList<Map<String, Object>>();
+        rules.add(rule(1001L, 1002L, "xiangke", 5, -50.0, "tcm_shi_liao", 0));
+        assertEquals(0.0, callDouble(host, "resolvePairingEffect", 1001L, 1002L, rules), EPS,
+                CAP + " enabled=0 的规则必须被忽略,未命中时返回 0(§4.3 enabled 启用开关)。");
+    }
+
+    @Test
+    @DisplayName("边界流-1:clampEffectScore 应截断到 [-50, +50](§4.3 effect_score 取值域)")
+    void clampEffectScore_boundsAreFifty() {
+        Object host = contractHost();
+        assertEquals(50.0, callDouble(host, "clampEffectScore", 80.0), EPS,
+                CAP + " clampEffectScore(80) 应 = 50(§4.3 上界 +50)。");
+        assertEquals(-50.0, callDouble(host, "clampEffectScore", -80.0), EPS,
+                CAP + " clampEffectScore(-80) 应 = -50(§4.3 下界 -50)。");
+        assertEquals(12.5, callDouble(host, "clampEffectScore", 12.5), EPS,
+                CAP + " 区间内值应保持原值(§4.3)。");
+    }
+
+    @Test
+    @DisplayName("忌配伍-1:xiangke/antagonism 且 intensity≥3 → requiresAvoidance=true(§4.3 / G-3)")
+    void requiresAvoidance_xiangkeIntensityThree_returnsTrue() {
+        Object host = contractHost();
+        List<Map<String, Object>> rules = new ArrayList<Map<String, Object>>();
+        rules.add(rule(2001L, 2002L, "xiangke", 3, -30.0, "tcm_shi_liao", 1));
+        assertTrue(callBoolean(host, "requiresAvoidance", 2001L, 2002L, rules),
+                CAP + " 柿子+螃蟹(xiangke, intensity=3)应判定为忌配伍、需硬避让(§4.3 / CR-07)。");
+
+        List<Map<String, Object>> nutrition = new ArrayList<Map<String, Object>>();
+        nutrition.add(rule(3001L, 3002L, "antagonism", 4, -25.0, "modern_nutrition", 1));
+        assertTrue(callBoolean(host, "requiresAvoidance", 3001L, 3002L, nutrition),
+                CAP + " 菠菜+豆腐(antagonism, intensity≥3)应判定为忌配伍、需硬避让(§4.3 / G-3)。");
+    }
+
+    @Test
+    @DisplayName("忌配伍-2:协同/低强度/停用规则不应触发硬避让(§4.3)")
+    void requiresAvoidance_nonAvoidableCases_returnFalse() {
+        Object host = contractHost();
+        List<Map<String, Object>> cases = new ArrayList<Map<String, Object>>();
+        cases.add(rule(11L, 12L, "synergy", 5, 20.0, "modern_nutrition", 1));     // 协同,高强度也不避让
+        cases.add(rule(21L, 22L, "antagonism", 2, -10.0, "modern_nutrition", 1)); // 拮抗但强度 < 3
+        cases.add(rule(31L, 32L, "xiangke", 5, -50.0, "tcm_shi_liao", 0));        // 忌配伍但已停用
+        for (Map<String, Object> r : cases) {
+            Long a = (Long) r.get("foodAId");
+            Long b = (Long) r.get("foodBId");
+            List<Map<String, Object>> one = new ArrayList<Map<String, Object>>();
+            one.add(r);
+            assertTrue(!callBoolean(host, "requiresAvoidance", a, b, one),
+                    CAP + " relationType=" + r.get("relationType") + "/intensity=" + r.get("intensity")
+                            + "/enabled=" + r.get("enabled") + " 不应触发硬避让(§4.3 仅忌配伍且强度≥3)。");
+        }
+    }
+
+    @Test
+    @DisplayName("忌配伍-3:避让判定应对称(§4.3 A×B 关系双向有效)")
+    void requiresAvoidance_isSymmetric() {
+        Object host = contractHost();
+        List<Map<String, Object>> rules = new ArrayList<Map<String, Object>>();
+        rules.add(rule(4001L, 4002L, "antagonism", 3, -20.0, "modern_nutrition", 1));
+        assertTrue(callBoolean(host, "requiresAvoidance", 4001L, 4002L, rules),
+                CAP + " A×B 应命中忌配伍判定(§4.3)。");
+        assertTrue(callBoolean(host, "requiresAvoidance", 4002L, 4001L, rules),
+                CAP + " B×A 应命中同一条忌配伍判定(§4.3 配伍关系对称)。");
+    }
+
+    // ==================== 结构契约:实体 / Mapper / schema / 迁移 ====================
+
+    @Test
+    @DisplayName("结构-1:FoodPairingMatrix 实体应含 8 个契约字段(§4.3)")
+    void entity_hasContractFields() {
+        Class<?> entity = loadClass(ENTITY_FQCN);
+        if (entity == null) {
+            fail(RED + " FoodPairingMatrix 实体不存在:§4.3/§5 要求 food_pairing_matrix 表映射实体。");
+            throw new IllegalStateException("unreachable");
+        }
+        for (String field : REQUIRED_FIELDS) {
+            assertNotNull(findField(entity, field),
+                    CAP + " FoodPairingMatrix 缺少字段 " + field + "(§4.3 配伍表字段清单)。");
+        }
+    }
+
+    @Test
+    @DisplayName("结构-2:FoodPairingMatrix 应以 @TableName 映射 food_pairing_matrix(§4.3)")
+    void entity_hasTableNameAnnotation() {
+        Class<?> entity = loadClass(ENTITY_FQCN);
+        if (entity == null) {
+            fail(RED + " FoodPairingMatrix 实体不存在,无法验证 @TableName 映射(§4.3)。");
+            throw new IllegalStateException("unreachable");
+        }
+        boolean mapped = false;
+        for (Annotation a : entity.getDeclaredAnnotations()) {
+            if ("TableName".equals(a.annotationType().getSimpleName())) {
+                try {
+                    Object value = a.annotationType().getMethod("value").invoke(a);
+                    if (TABLE.equals(value)) {
+                        mapped = true;
+                    }
+                } catch (Exception ignored) {
+                    // 反射取值失败即视为未满足契约
+                }
+            }
+        }
+        assertTrue(mapped, CAP + " FoodPairingMatrix 应标注 @TableName(\"" + TABLE + "\")(§4.3 表映射)。");
+    }
+
+    @Test
+    @DisplayName("结构-3:FoodPairingMatrixMapper 应存在(分层 Mapper,§4.3 配伍查询)")
+    void mapper_exists() {
+        assertNotNull(loadClass(MAPPER_FQCN),
+                RED + " FoodPairingMatrixMapper 不存在:契约要求配伍查询走分层 Mapper"
+                        + "(§4.3 配伍查询 + 后端分层约定);当前仅有后台 CRUD 内存服务,实现未落地。");
+    }
+
+    @Test
+    @DisplayName("结构-4:schema.sql 应声明 food_pairing_matrix 建表及 8 个契约列(§4.3/§5)")
+    void schemaSql_declaresTableAndColumns() {
+        String schema = readSchemaSql();
+        assertTrue(schema.contains(TABLE),
+                CAP + " schema.sql 缺少 " + TABLE + " 建表(§4.3/§5 配伍表)。");
+        String block = tableBlock(schema, TABLE);
+        for (String col : REQUIRED_COLUMNS) {
+            assertTrue(block.contains(col),
+                    CAP + " " + TABLE + " 缺少列 " + col + "(§4.3 配伍表字段定义)。");
+        }
+    }
+
+    @Test
+    @DisplayName("结构-5:schema.sql 应标注 7 种关系类型、2 种来源与强度/效应取值域(§4.3)")
+    void schemaSql_declaresRelationTypesSourcesAndRanges() {
+        String block = tableBlock(readSchemaSql(), TABLE).toLowerCase();
+        for (String type : RELATION_TYPES) {
+            assertTrue(block.contains(type),
+                    CAP + " " + TABLE + " 未标注 relation_type 合法值 " + type + "(§4.3)。");
+        }
+        for (String source : SOURCES) {
+            assertTrue(block.contains(source),
+                    CAP + " " + TABLE + " 未标注 source 合法值 " + source + "(§4.3)。");
+        }
+        assertTrue(block.contains("1-5"), CAP + " " + TABLE + ".intensity 应标注取值域 1-5(§4.3)。");
+        assertTrue(block.contains("-50") && block.contains("50"),
+                CAP + " " + TABLE + ".effect_score 应标注取值域 [-50, +50](§4.3)。");
+    }
+
+    @Test
+    @DisplayName("结构-6:DatabaseInitializer 应登记 food_pairing_matrix 迁移(§5)")
+    void migration_registeredInDatabaseInitializer() {
+        String src = readMainSource("config/DatabaseInitializer.java");
+        assertTrue(src.contains(TABLE),
+                CAP + " DatabaseInitializer.runMigrations() 未登记 " + TABLE + " 迁移(§5 迁移要求):"
+                        + "契约要求 DDL 唯一入口并同步 schema.sql。");
+    }
+
+    @Test
+    @DisplayName("结构-7:推荐/食谱链路应接入配伍矩阵查询或配伍效应计算(§1.4/§4.3)")
+    void recommendChain_consultsPairingMatrix() {
+        String[] services = {
+                "service/FoodRecommendService.java",
+                "service/FoodService.java",
+                "service/DietRecommendationService.java"
+        };
+        boolean wired = false;
+        for (String path : services) {
+            String src = readMainSource(path).toLowerCase();
+            if (src.contains("foodpairingmatrix") || src.contains(TABLE)
+                    || src.contains("pairingeffect") || src.contains("pairingmatrix")) {
+                wired = true;
+                break;
+            }
+        }
+        assertTrue(wired,
+                CAP + " 推荐/食谱链路未接入配伍矩阵查询(§1.4「配伍效应查询」+ §4.3"
+                        + "「pairing_effect × w4」):当前 FoodRecommendService / FoodService /"
+                        + " DietRecommendationService 均无引用,实现未落地。");
+    }
+
+    // ==================== 权限流(不适用):内部查询/判定服务 ====================
+
+    @Test
+    @DisplayName("权限流:配伍查询/避让判定为内部服务,无用户侧鉴权分支,权限流不适用")
+    void permissionFlow_notApplicable() {
+        assertTrue(true,
+                "权限流不适用:food.rule.pairingMatrix 为后端内部配伍查询/效应计算/避让判定服务;"
+                        + "后台 CRUD/灰度由 ops.foodRuleManagement(CR-06)承载,"
+                        + "食谱硬避让由 diet.menu.pairingConstraint(CR-07)承载。");
+    }
+
+    // ==================== 辅助 ====================
+
+    /** 构造一条内存配伍规则(与 DB 解耦,供 resolvePairingEffect / requiresAvoidance 契约驱动)。 */
+    private Map<String, Object> rule(Long foodAId, Long foodBId, String relationType,
+                                     int intensity, double effectScore, String source, int enabled) {
+        Map<String, Object> r = new HashMap<String, Object>();
+        r.put("foodAId", foodAId);
+        r.put("foodBId", foodBId);
+        r.put("relationType", relationType);
+        r.put("intensity", Integer.valueOf(intensity));
+        r.put("effectScore", Double.valueOf(effectScore));
+        r.put("source", source);
+        r.put("evidenceRef", "ref-" + relationType);
+        r.put("enabled", Integer.valueOf(enabled));
+        return r;
+    }
+
+    private Object contractHost() {
+        try {
+            Class<?> clazz = Class.forName(HOST_CLASS, false, Thread.currentThread().getContextClassLoader());
+            return clazz.getDeclaredConstructor().newInstance();
+        } catch (ClassNotFoundException e) {
+            fail(RED + " 契约宿主 FoodPairingMatrixService 未实现(实现未落地):" + e.getMessage());
+            throw new IllegalStateException("unreachable");
+        } catch (Exception e) {
+            fail(RED + " 契约宿主 FoodPairingMatrixService 实例化失败:" + 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(RED + " 契约方法 " + HOST_CLASS + "#" + method + " 调用失败:" + e.getMessage());
+                    throw new IllegalStateException("unreachable");
+                }
+            }
+        }
+        fail(RED + " 契约方法 " + HOST_CLASS + "#" + method + " 未实现");
+        throw new IllegalStateException("unreachable");
+    }
+
+    private double callDouble(Object host, String method, Object... args) {
+        Object r = call(host, method, args);
+        if (r instanceof Number) {
+            return ((Number) r).doubleValue();
+        }
+        fail(CAP + " 契约方法 " + method + " 应返回数值,实际 " + r);
+        throw new IllegalStateException("unreachable");
+    }
+
+    private boolean callBoolean(Object host, String method, Object... args) {
+        Object r = call(host, method, args);
+        if (r instanceof Boolean) {
+            return ((Boolean) r).booleanValue();
+        }
+        fail(CAP + " 契约方法 " + method + " 应返回布尔,实际 " + r);
+        throw new IllegalStateException("unreachable");
+    }
+
+    @SuppressWarnings("unchecked")
+    private List<String> callListString(Object host, String method) {
+        Object r = call(host, method);
+        if (r instanceof List) {
+            return (List<String>) r;
+        }
+        fail(CAP + " 契约方法 " + method + " 应返回 List<String>,实际 " + r);
+        throw new IllegalStateException("unreachable");
+    }
+
+    private Class<?> loadClass(String name) {
+        try {
+            return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
+        } catch (ClassNotFoundException e) {
+            return null;
+        }
+    }
+
+    private Field findField(Class<?> clazz, String name) {
+        try {
+            return clazz.getDeclaredField(name);
+        } catch (NoSuchFieldException 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 "";
+        }
+    }
+
+    /** 截取 CREATE TABLE 片段:从表名首次出现处到 ENGINE= 或结尾;表不存在返回空串 */
+    private String tableBlock(String schema, String table) {
+        int start = schema.indexOf(table);
+        if (start < 0) {
+            return "";
+        }
+        int end = schema.indexOf("ENGINE=", start);
+        if (end < 0) {
+            end = Math.min(schema.length(), start + 2000);
+        }
+        return schema.substring(start, end);
+    }
+
+    /** 读取 src/main 源码文件(surefire 工作目录 = cfc-backend 模块目录),找不到返回空串。 */
+    private String readMainSource(String relative) {
+        String[] candidates = {
+                "src/main/java/com/etotem/cfc/" + relative,
+                "src/main/resources/" + relative.replace("resources/", ""),
+                "cfc-backend/src/main/java/com/etotem/cfc/" + relative,
+                "cfc-backend/src/main/resources/" + relative.replace("resources/", ""),
+                "../cfc-backend/src/main/java/com/etotem/cfc/" + relative,
+                "../cfc-backend/src/main/resources/" + relative.replace("resources/", "")
+        };
+        for (String candidate : candidates) {
+            File file = new File(candidate);
+            if (file.isFile()) {
+                try {
+                    return new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
+                } catch (IOException e) {
+                    return "";
+                }
+            }
+        }
+        return "";
+    }
+}

+ 462 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/PrivacySettingConfigContractTest.java

@@ -0,0 +1,462 @@
+package com.etotem.cfc.unit;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+
+import java.io.InputStream;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.Scanner;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * 契约级单测:隐私设置 / 数据共享范围(能力键 {@code privacy.setting.config},S-cfc-287,TDD-RED 阶段)。
+ *
+ * <p><b>需求 / 设计锚点</b></p>
+ * <ul>
+ *   <li>{@code tests/user-scenarios/应用场景总览.md} SC-P-66(隐私设置:设数据共享范围,最小权限保底);
+ *       {@code tests/user-scenarios/02-parent.md} P-66;业务域 H 设置与通知</li>
+ *   <li>{@code tests/test-cases/parent.md} TC-P-66(设数据共享范围 → 最小权限保底)、
+ *       TC-P-66-E(非法范围 400;敏感字段最小权限保底不外露)、TC-P-66-P(越权访问他人数据 403/401)</li>
+ *   <li>{@code docs/superpowers/api/API_REFERENCE.md} §4.15 统计与通知({@code /api/notification} list/read,
+ *       范围变更通知通道)+ §4.2 家庭与成员可见性({@code family-member-editable} /
+ *       {@code show_to_family},数据共享范围的下游载体);模块:隐私设置</li>
+ *   <li>{@code docs/tdd/orchestration/sc-key-map.md} SC-P-66 → {@code privacy.setting.config}(S-cfc-287)</li>
+ * </ul>
+ *
+ * <p><b>契约目标(GREEN 阶段按此实现,本测试即验收口径)</b></p>
+ * <ol>
+ *   <li>实体 {@code com.etotem.cfc.entity.PrivacySetting}、DTO
+ *       {@code com.etotem.cfc.dto.PrivacySettingDTO}:字段 {@code userId / dataSharingScope /
+ *       sensitiveFieldsExposed / allowFamilyView / notifyOnScopeChange}</li>
+ *   <li>服务 {@code com.etotem.cfc.service.PrivacySettingService}:
+ *       {@code getConfig(Long)} 返回 DTO(未配置回显最小权限默认值);{@code saveConfig(Long, DTO)} 保存;
+ *       {@code effectiveSharingScope(Long userId, int requestedScope)} 返回
+ *       {@code min(用户配置范围, 请求范围)}(不得超过用户配置,未配置/脏数据降级 0);
+ *       {@code isSensitiveFieldExposed(Long userId)} 告知下游敏感字段是否可外露(恒 false)</li>
+ *   <li>默认值(最小权限保底):{@code dataSharingScope=0}(0=仅自己 / 1=家庭成员 / 2=全部、
+ *       由用户主动放大)、{@code sensitiveFieldsExposed=0}、{@code allowFamilyView=0}、
+ *       {@code notifyOnScopeChange=0}</li>
+ *   <li>校验:{@code dataSharingScope} 仅允许 0/1/2,其他(含 -1/3)抛
+ *       {@code IllegalArgumentException("数据共享范围不合法")};
+ *       {@code sensitiveFieldsExposed=1} 一律拒绝,抛
+ *       {@code IllegalArgumentException("敏感字段不可外露")}(TC-P-66-E)</li>
+ *   <li>保底:即使配置被脏写为超范围值(如 99),{@code effectiveSharingScope} 仍降级为 0,
+ *       {@code isSensitiveFieldExposed} 仍为 false(不得放大共享范围 / 外露敏感字段)</li>
+ *   <li>控制器 {@code com.etotem.cfc.controller.PrivacySettingController}:
+ *       POST {@code /api/privacy/setting/get|save},参数带 {@code @RequestAttribute("userId")}
+ *       (只能读写本人配置,越权被拒,TC-P-66-P)</li>
+ *   <li>DB:{@code schema.sql} 含 {@code privacy_settings} 表与上述配置列,全部 {@code DEFAULT 0}</li>
+ * </ol>
+ *
+ * <p><b>RED 预期</b>:本分支 src/main 尚无上述服务/DTO/控制器/表(已有 {@code ConsentController}
+ * 隐私授权同意与 {@code show_to_family} 可见性,但无独立的「数据共享范围配置 + 最小权限保底」载体),
+ * 全部用例以反射/结构探测断言失败(红),失败信息清晰可贴。
+ * 纯 Mockito + 反射,无 Spring 上下文 / 无 DB / 无外部服务。</p>
+ */
+class PrivacySettingConfigContractTest {
+
+    private static final String TAG = "RED[privacy.setting.config] ";
+
+    private static final String SERVICE = "com.etotem.cfc.service.PrivacySettingService";
+    private static final String ENTITY = "com.etotem.cfc.entity.PrivacySetting";
+    private static final String DTO = "com.etotem.cfc.dto.PrivacySettingDTO";
+    private static final String CONTROLLER = "com.etotem.cfc.controller.PrivacySettingController";
+    private static final String TABLE = "privacy_settings";
+
+    /** 数据共享范围枚举:0=仅自己(最小权限)/ 1=家庭成员 / 2=全部。 */
+    private static final int SCOPE_PRIVATE = 0;
+    private static final int SCOPE_FAMILY = 1;
+    private static final int SCOPE_ALL = 2;
+
+    private static final String MSG_BAD_SCOPE = "数据共享范围不合法";
+    private static final String MSG_SENSITIVE = "敏感字段不可外露";
+
+    private static final Long USER_ID = 100L;
+
+    // ==================== 正常流:契约载体应落地 ====================
+
+    @Test
+    @DisplayName("正常流-1:PrivacySettingService 配置服务类应存在")
+    void service_classExists() {
+        requireClass(SERVICE, "配置服务 PrivacySettingService 不存在:契约要求提供"
+                + " getConfig/saveConfig/effectiveSharingScope/isSensitiveFieldExposed"
+                + "(SC-P-66 数据共享范围 + 最小权限保底)。");
+    }
+
+    @Test
+    @DisplayName("正常流-2:配置服务应提供 getConfig/saveConfig/effectiveSharingScope/isSensitiveFieldExposed 入口")
+    void service_hasContractMethods() {
+        Class<?> service = requireClass(SERVICE, "无法验证服务方法:配置服务类未落地。");
+        assertTrue(findMethod(service, "getConfig", 1) != null,
+                TAG + "应提供 getConfig(Long userId) 读取用户隐私配置(含最小权限默认值回显)。");
+        assertTrue(findMethod(service, "saveConfig", 2) != null,
+                TAG + "应提供 saveConfig(Long userId, DTO dto) 保存数据共享范围配置。");
+        Method effective = findMethod(service, "effectiveSharingScope", 2);
+        assertTrue(effective != null && effective.getReturnType() == int.class,
+                TAG + "应提供 int effectiveSharingScope(Long userId, int requestedScope)"
+                        + " 返回 min(配置范围, 请求范围)(最小权限保底)。");
+        Method sensitive = findMethod(service, "isSensitiveFieldExposed", 1);
+        assertTrue(sensitive != null && sensitive.getReturnType() == boolean.class,
+                TAG + "应提供 boolean isSensitiveFieldExposed(Long userId)"
+                        + " 告知下游敏感字段是否可外露(恒 false,TC-P-66-E)。");
+    }
+
+    @Test
+    @DisplayName("正常流-3:实体与 DTO 应声明五项配置字段")
+    void entityAndDto_haveConfigFields() {
+        String[] fields = {"userId", "dataSharingScope", "sensitiveFieldsExposed",
+                "allowFamilyView", "notifyOnScopeChange"};
+        for (String fqcn : new String[]{ENTITY, DTO}) {
+            Class<?> clazz = requireClass(fqcn, "配置载体未落地,无法验证字段契约。");
+            for (String field : fields) {
+                boolean found = false;
+                for (Field f : clazz.getDeclaredFields()) {
+                    if (f.getName().equals(field)) {
+                        found = true;
+                        break;
+                    }
+                }
+                assertTrue(found, TAG + simpleName(fqcn) + " 缺字段 " + field
+                        + ":契约要求 userId/dataSharingScope/sensitiveFieldsExposed/"
+                        + "allowFamilyView/notifyOnScopeChange(SC-P-66)。");
+            }
+        }
+    }
+
+    @Test
+    @DisplayName("正常流-4:未配置用户 getConfig 应回显最小权限默认值(全 0)")
+    void getConfig_unconfigured_returnsLeastPrivilegeDefaults() throws Exception {
+        Object service = newServiceWithMockMapper();
+        Object dto = invoke(service, "getConfig", 1, USER_ID);
+        assertNotNull(dto, TAG + "getConfig 未配置时应返回带默认值的 DTO,而非 null。");
+
+        assertEquals(SCOPE_PRIVATE, intProp(dto, "getDataSharingScope"),
+                TAG + "dataSharingScope 默认必须为 0(仅自己,最小权限保底;由用户主动放大)。");
+        assertEquals(0, intProp(dto, "getSensitiveFieldsExposed"),
+                TAG + "sensitiveFieldsExposed 默认必须为 0(敏感字段不外露)。");
+        assertEquals(0, intProp(dto, "getAllowFamilyView"),
+                TAG + "allowFamilyView 默认必须为 0(家庭成员不可见,对齐 show_to_family 保底口径)。");
+        assertEquals(0, intProp(dto, "getNotifyOnScopeChange"),
+                TAG + "notifyOnScopeChange 默认必须为 0(范围变更通知默认关闭)。");
+    }
+
+    @Test
+    @DisplayName("正常流-5:合法范围(家庭成员=1)配置应可保存")
+    void saveConfig_acceptsValidScope() throws Exception {
+        Object service = newServiceWithMockMapper();
+        Object dto = newDto();
+        setProp(dto, "setDataSharingScope", SCOPE_FAMILY);
+        setProp(dto, "setSensitiveFieldsExposed", 0);
+        setProp(dto, "setAllowFamilyView", 1);
+        setProp(dto, "setNotifyOnScopeChange", 0);
+
+        invoke(service, "saveConfig", 2, USER_ID, dto);
+    }
+
+    // ==================== 异常流:非法范围 + 敏感字段不外露 ====================
+
+    @Test
+    @DisplayName("异常流-1:saveConfig 应拒绝非法范围 -1(枚举越界)")
+    void saveConfig_rejectsScopeNegative() throws Exception {
+        assertRejectsBadScope(-1);
+    }
+
+    @Test
+    @DisplayName("异常流-2:saveConfig 应拒绝非法范围 3(枚举越界)")
+    void saveConfig_rejectsScopeThree() throws Exception {
+        assertRejectsBadScope(3);
+    }
+
+    @Test
+    @DisplayName("异常流-3:即使设为完全公开(2),敏感字段仍不可外露")
+    void saveConfig_cannotExposeSensitiveFields() throws Exception {
+        Object service = newServiceWithMockMapper();
+        Object dto = newDto();
+        setProp(dto, "setDataSharingScope", SCOPE_ALL);
+        setProp(dto, "setSensitiveFieldsExposed", 1); // 试图连敏感字段一起公开 → 必须被拒
+        setProp(dto, "setAllowFamilyView", 1);
+        setProp(dto, "setNotifyOnScopeChange", 0);
+
+        try {
+            invoke(service, "saveConfig", 2, USER_ID, dto);
+            fail(TAG + "sensitiveFieldsExposed=1 被接受:违反「敏感字段最小权限保底不外露」"
+                    + "(SC-P-66 / TC-P-66-E)。");
+        } catch (InvocationTargetException e) {
+            Throwable cause = e.getCause();
+            assertTrue(cause instanceof IllegalArgumentException,
+                    TAG + "外露敏感字段应抛 IllegalArgumentException,实际=" + cause);
+            assertTrue(cause.getMessage() != null && cause.getMessage().contains(MSG_SENSITIVE),
+                    TAG + "拒绝文案应含「" + MSG_SENSITIVE + "」,实际=" + cause.getMessage());
+        }
+    }
+
+    // ==================== 边界流:最小权限保底(不放大 / 脏数据降级) ====================
+
+    @Test
+    @DisplayName("边界流-1:effectiveSharingScope 不得超过用户配置,未配置恒为 0")
+    void effectiveSharingScope_neverExceedsConfigured() throws Exception {
+        Object service = newServiceWithMockMapper();
+        // 未配置:Mapper.selectOne 默认返回 null → 请求完全公开也只能拿到最小权限 0
+        assertEquals(SCOPE_PRIVATE, intInvoke(service, "effectiveSharingScope", 2, USER_ID, SCOPE_ALL),
+                TAG + "未配置用户请求范围 2 时,effective 必须降级为 0(最小权限保底)。");
+
+        // 配置为家庭成员(1):请求 2 也只能拿到 1;请求 0 则为 0
+        stubMapperConfig(service, configEntity(SCOPE_FAMILY, 0, 1, 0));
+        assertEquals(SCOPE_FAMILY, intInvoke(service, "effectiveSharingScope", 2, USER_ID, SCOPE_ALL),
+                TAG + "配置范围 1 时请求 2,effective 必须被夹到 1(不得超过用户配置)。");
+        assertEquals(SCOPE_PRIVATE, intInvoke(service, "effectiveSharingScope", 2, USER_ID, SCOPE_PRIVATE),
+                TAG + "请求范围 0 时 effective 应为 0。");
+    }
+
+    @Test
+    @DisplayName("边界流-2:脏配置范围 99 应降级为 0,不得放大共享范围")
+    void effectiveSharingScope_dirtyConfigDowngradesToLeastPrivilege() throws Exception {
+        Object service = newServiceWithMockMapper();
+        stubMapperConfig(service, configEntity(99, 0, 0, 0));
+        assertEquals(SCOPE_PRIVATE, intInvoke(service, "effectiveSharingScope", 2, USER_ID, SCOPE_ALL),
+                TAG + "脏配置范围 99 必须降级为 0(最小权限保底),不得被当作「完全公开」放大。");
+    }
+
+    @Test
+    @DisplayName("边界流-3:脏配置 sensitiveFieldsExposed=1 时敏感字段仍不外露")
+    void isSensitiveFieldExposed_dirtyConfigStillFalse() throws Exception {
+        Object service = newServiceWithMockMapper();
+        stubMapperConfig(service, configEntity(SCOPE_ALL, 1, 1, 0));
+        assertEquals(Boolean.FALSE, invoke(service, "isSensitiveFieldExposed", 1, USER_ID),
+                TAG + "即使落库脏数据 sensitiveFieldsExposed=1,仍须返回 false"
+                        + "(敏感字段最小权限保底不外露,TC-P-66-E)。");
+    }
+
+    // ==================== 权限流:本人配置只能本人读写 ====================
+
+    @Test
+    @DisplayName("权限流-1:设置端点应为 POST /api/privacy/setting/get|save 且按 userId 隔离")
+    void controller_scopesConfigByUserId() {
+        Class<?> controller = requireClass(CONTROLLER,
+                "配置控制器未落地:无法验证「家长只能读写本人隐私设置」的权限契约(TC-P-66-P)。");
+
+        for (String suffix : new String[]{"/get", "/save"}) {
+            String path = "/api/privacy/setting" + suffix;
+            boolean mapped = false;
+            boolean userIdScoped = false;
+            for (Method m : controller.getDeclaredMethods()) {
+                PostMapping post = m.getAnnotation(PostMapping.class);
+                if (post == null || !Arrays.asList(post.value()).contains(path)) {
+                    continue;
+                }
+                mapped = true;
+                for (Annotation[] paramAnns : m.getParameterAnnotations()) {
+                    for (Annotation ann : paramAnns) {
+                        if (ann instanceof RequestAttribute
+                                && "userId".equals(((RequestAttribute) ann).value())) {
+                            userIdScoped = true;
+                        }
+                    }
+                }
+            }
+            assertTrue(mapped, TAG + "缺少 POST " + path + " 端点(SC-P-66 隐私设置读写)。");
+            assertTrue(userIdScoped, TAG + "POST " + path
+                    + " 参数须带 @RequestAttribute(\"userId\"),按当前登录用户隔离配置,禁止跨用户读写(TC-P-66-P)。");
+        }
+    }
+
+    // ==================== DB 迁移契约 ====================
+
+    @Test
+    @DisplayName("DB 迁移-1:schema.sql 应含 privacy_settings 表及五项配置列(默认全 0)")
+    void schemaSql_hasPrivacySettingsTableWithLeastPrivilegeDefaults() {
+        String schema = readSchemaSql();
+        int idx = schema.indexOf("CREATE TABLE IF NOT EXISTS " + TABLE);
+        if (idx < 0) {
+            idx = schema.indexOf("CREATE TABLE `" + TABLE + "`");
+        }
+        assertTrue(idx >= 0, TAG + "schema.sql 缺 " + TABLE + " 建表(隐私设置持久化未落地)。");
+        String tableDef = schema.substring(idx, Math.min(idx + 1500, schema.length()));
+
+        assertColumnDefaultZero(tableDef, "user_id");
+        assertColumnDefaultZero(tableDef, "data_sharing_scope");
+        assertColumnDefaultZero(tableDef, "sensitive_fields_exposed");
+        assertColumnDefaultZero(tableDef, "allow_family_view");
+        assertColumnDefaultZero(tableDef, "notify_on_scope_change");
+    }
+
+    // ==================== 辅助 ====================
+
+    private void assertRejectsBadScope(int badScope) throws Exception {
+        Object service = newServiceWithMockMapper();
+        Object dto = newDto();
+        setProp(dto, "setDataSharingScope", badScope);
+        setProp(dto, "setSensitiveFieldsExposed", 0);
+        setProp(dto, "setAllowFamilyView", 0);
+        setProp(dto, "setNotifyOnScopeChange", 0);
+
+        try {
+            invoke(service, "saveConfig", 2, USER_ID, dto);
+            fail(TAG + "非法数据共享范围 " + badScope + " 未被拒绝:仅允许 0/1/2"
+                    + "(SC-P-66 / TC-P-66-E)。");
+        } catch (InvocationTargetException e) {
+            Throwable cause = e.getCause();
+            assertTrue(cause instanceof IllegalArgumentException,
+                    TAG + "非法范围 " + badScope + " 应抛 IllegalArgumentException,实际=" + cause);
+            assertEquals(MSG_BAD_SCOPE, cause.getMessage(), TAG + "非法范围报错文案");
+        }
+    }
+
+    private void assertColumnDefaultZero(String tableDef, String col) {
+        for (String line : tableDef.split("\\r?\\n")) {
+            if (line.contains(col)) {
+                assertTrue(line.contains("DEFAULT 0"),
+                        TAG + TABLE + "." + col + " 默认必须为 0(最小权限保底),实际定义=" + line.trim());
+                return;
+            }
+        }
+        fail(TAG + TABLE + " 缺列 " + col + "(SC-P-66 配置契约)。");
+    }
+
+    /** 无配置用户:service 的 Mapper 字段全部注入 mock(selectOne 默认返回 null)。 */
+    private Object newServiceWithMockMapper() throws Exception {
+        Class<?> clazz = requireClass(SERVICE, "无法构造配置服务:服务类未落地。");
+        Object service = clazz.getDeclaredConstructor().newInstance();
+        for (Field f : clazz.getDeclaredFields()) {
+            if (f.getType().isInterface() && f.getType().getName().endsWith("Mapper")) {
+                f.setAccessible(true);
+                f.set(service, mock(f.getType()));
+            }
+        }
+        return service;
+    }
+
+    /** 把 mock Mapper 的 selectOne 桩为返回指定配置,用于「已配置 / 脏配置」边界场景。 */
+    private void stubMapperConfig(Object service, Object config) throws Exception {
+        Field mapperField = null;
+        for (Field f : service.getClass().getDeclaredFields()) {
+            if (f.getType().isInterface() && f.getType().getName().endsWith("Mapper")) {
+                mapperField = f;
+                break;
+            }
+        }
+        assertNotNull(mapperField, TAG + "配置服务未注入 Mapper,无法读取用户配置。");
+        mapperField.setAccessible(true);
+        Object mapper = mapperField.get(service);
+        Method selectOne = null;
+        for (Method m : mapper.getClass().getMethods()) {
+            if (m.getName().equals("selectOne") && m.getParameterCount() == 1) {
+                selectOne = m;
+                break;
+            }
+        }
+        assertNotNull(selectOne, TAG + "Mapper 缺 selectOne(Wrapper) 查询入口。");
+        try {
+            when(selectOne.invoke(mapper, new Object[]{null})).thenReturn(config);
+        } catch (Exception e) {
+            fail(TAG + "无法桩接 Mapper.selectOne:" + e);
+        }
+    }
+
+    private Object configEntity(int scope, int sensitive, int familyView, int notify) throws Exception {
+        Class<?> clazz = requireClass(ENTITY, "无法构造配置实体:实体未落地。");
+        Object entity = clazz.getDeclaredConstructor().newInstance();
+        setProp(entity, "setUserId", USER_ID);
+        setProp(entity, "setDataSharingScope", scope);
+        setProp(entity, "setSensitiveFieldsExposed", sensitive);
+        setProp(entity, "setAllowFamilyView", familyView);
+        setProp(entity, "setNotifyOnScopeChange", notify);
+        return entity;
+    }
+
+    private Object newDto() throws Exception {
+        Class<?> clazz = requireClass(DTO, "无法构造配置 DTO:DTO 未落地。");
+        return clazz.getDeclaredConstructor().newInstance();
+    }
+
+    private Class<?> requireClass(String fqcn, String reason) {
+        try {
+            return Class.forName(fqcn, false, Thread.currentThread().getContextClassLoader());
+        } catch (ClassNotFoundException e) {
+            fail(TAG + reason + " 期望类:" + fqcn);
+            throw new IllegalStateException("unreachable");
+        }
+    }
+
+    private Method findMethod(Class<?> clazz, String name, int paramCount) {
+        for (Method m : clazz.getDeclaredMethods()) {
+            if (m.getName().equals(name) && m.getParameterCount() == paramCount) {
+                return m;
+            }
+        }
+        return null;
+    }
+
+    private Object invoke(Object target, String name, int paramCount, Object... args) throws Exception {
+        Method m = findMethod(target.getClass(), name, paramCount);
+        assertNotNull(m, TAG + target.getClass().getName() + " 缺方法 " + name + "(参数 " + paramCount + ")。");
+        m.setAccessible(true);
+        return m.invoke(target, args);
+    }
+
+    private int intInvoke(Object target, String name, int paramCount, Object... args) throws Exception {
+        Object value = invoke(target, name, paramCount, args);
+        assertTrue(value instanceof Number, TAG + name + " 应返回数值,实际=" + value);
+        return ((Number) value).intValue();
+    }
+
+    private Object prop(Object target, String getter) throws Exception {
+        try {
+            Method m = target.getClass().getMethod(getter);
+            return m.invoke(target);
+        } catch (NoSuchMethodException e) {
+            fail(TAG + target.getClass().getName() + " 缺访问器 " + getter + "(配置字段契约未落地)。");
+            throw new IllegalStateException("unreachable");
+        }
+    }
+
+    private int intProp(Object target, String getter) throws Exception {
+        Object value = prop(target, getter);
+        assertTrue(value instanceof Number, TAG + getter + " 应返回数值,实际=" + value);
+        return ((Number) value).intValue();
+    }
+
+    private void setProp(Object target, String setter, Object value) throws Exception {
+        Method found = null;
+        for (Method m : target.getClass().getMethods()) {
+            if (m.getName().equals(setter) && m.getParameterCount() == 1) {
+                found = m;
+                break;
+            }
+        }
+        assertNotNull(found, TAG + target.getClass().getName() + " 缺写入器 " + setter + "。");
+        found.invoke(target, value);
+    }
+
+    private String simpleName(String fqcn) {
+        int idx = fqcn.lastIndexOf('.');
+        return idx >= 0 ? fqcn.substring(idx + 1) : fqcn;
+    }
+
+    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 "";
+        }
+    }
+}

+ 195 - 16
cfc-backend/src/test/java/com/etotem/cfc/unit/TaskReminderDailyScheduledTaskContractTest.java

@@ -23,6 +23,7 @@ import java.util.Map;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.junit.jupiter.api.Assertions.fail;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyInt;
@@ -224,17 +225,27 @@ class TaskReminderDailyScheduledTaskContractTest {
     // ==================== 晚总结行为(§四 验收 3) ====================
 
     @Test
-    @DisplayName("晚总结-1:今日到期任务按已完成/未完成分组,未完成含催补打卡文案")
+    @DisplayName("晚总结-1:今日到期任务按完成率发四档鼓励(2026-11-29),经wechat分发")
+    @SuppressWarnings("unchecked")
     void eveningSummary_todayDue_groupedCompletedAndUncompleted() throws Exception {
         Object host = contractHost();
         TaskMapper taskMapper = mock(TaskMapper.class);
         UserNotificationMapper unMapper = mock(UserNotificationMapper.class);
-        NotificationDispatchService dispatch = mock(NotificationDispatchService.class);
         inject(host, "taskMapper", taskMapper);
         inject(host, "userNotificationMapper", unMapper);
-        inject(host, "notificationDispatchService", dispatch);
 
-        // 今日到期:1 已完成(completedAt 今日)+ 1 未完成(pending)
+        com.etotem.cfc.mapper.UserMapper userMapper = mock(com.etotem.cfc.mapper.UserMapper.class);
+        when(userMapper.selectById(anyLong())).thenReturn(null); // 昵称回退"您"
+        inject(host, "userMapper", userMapper);
+
+        com.etotem.cfc.service.notification.NotificationChannel wechat =
+                mock(com.etotem.cfc.service.notification.NotificationChannel.class);
+        when(wechat.getChannelType()).thenReturn("wechat");
+        when(wechat.isEnabled()).thenReturn(true);
+        inject(host, "notificationChannels",
+                new ArrayList<>(java.util.Collections.singletonList(wechat)));
+
+        // 今日到期:1 已完成(completedAt 今日)+ 1 未完成(pending)→ 50% 部分完成档
         Task done = task(2L, "已完成的今日任务", todayDeadline(9, 0), "completed");
         done.setCompletedAt(new Date());
         Task undone = task(3L, "未完成的今日任务", todayDeadline(18, 0), "pending");
@@ -244,19 +255,13 @@ class TaskReminderDailyScheduledTaskContractTest {
 
         call(host, "sendEveningSummary");
 
-        ArgumentCaptor<String> typeCaptor = ArgumentCaptor.forClass(String.class);
-        ArgumentCaptor<String> contentCaptor = ArgumentCaptor.forClass(String.class);
-        verify(dispatch, atLeastOnce()).sendByTemplate(typeCaptor.capture(), anyLong(), any(),
-                any(), anyLong(), any(), contentCaptor.capture());
-        assertEquals("task_daily_evening", typeCaptor.getValue(),
-                "晚总结通知 type 应为 task_daily_evening(§3.4)");
-        String content = contentCaptor.getValue();
-        // 设计 §3.4 晚总结文案:「今日总结:完成 X/N。✅ 已完成:…;【未完成】⚠ 标题…别忘了打卡哦~」
+        ArgumentCaptor<com.etotem.cfc.dto.NotificationMessage> msgCaptor =
+                ArgumentCaptor.forClass(com.etotem.cfc.dto.NotificationMessage.class);
+        verify(wechat, atLeastOnce()).send(msgCaptor.capture());
+        String content = msgCaptor.getValue().getContent();
         assertNotNull(content, "晚总结内容不应为空");
-        if (!content.contains("未完成") || !content.contains("已完成")) {
-            fail("RED[task.reminder.daily] 晚总结应区分「已完成/未完成」两组"
-                    + "(设计契约 §四 验收 3,实际内容=" + content + ")");
-        }
+        assertTrue(content.contains("每一步都算数"), "50%档应为温和加油,实际=" + content);
+        assertTrue(content.contains("您"), "昵称缺失应回退您,实际=" + content);
     }
 
     @Test
@@ -303,6 +308,180 @@ class TaskReminderDailyScheduledTaskContractTest {
                 any(), anyLong(), any(), any());
     }
 
+    // ==================== 晚默认开 / 早不变 拆开关(2026-11-29 增强) ====================
+
+    /** 装配一个带 wechat channel + 指定 config service 的 host */
+    @SuppressWarnings("unchecked")
+    private Object hostWithConfigAndChannel(TaskReminderConfigService cfgService,
+                                            com.etotem.cfc.service.notification.NotificationChannel wechat) {
+        Object host = contractHost();
+        inject(host, "taskReminderConfigService", cfgService);
+        inject(host, "userMapper", mock(com.etotem.cfc.mapper.UserMapper.class));
+        inject(host, "notificationChannels", new ArrayList<>(
+                java.util.Collections.singletonList(wechat)));
+        return host;
+    }
+
+    @Test
+    @DisplayName("晚默认开-1:无配置记录用户(configService 返回空map)→ 晚提醒仍发送")
+    @SuppressWarnings("unchecked")
+    void eveningDefaultOn_noConfig() throws Exception {
+        TaskReminderConfigService cfg = mock(TaskReminderConfigService.class);
+        when(cfg.loadAllConfigs()).thenReturn(new java.util.HashMap<>());
+        com.etotem.cfc.service.notification.NotificationChannel wechat =
+                mock(com.etotem.cfc.service.notification.NotificationChannel.class);
+        when(wechat.getChannelType()).thenReturn("wechat");
+        when(wechat.isEnabled()).thenReturn(true);
+        Object host = hostWithConfigAndChannel(cfg, wechat);
+
+        TaskMapper tm = mock(TaskMapper.class);
+        UserNotificationMapper un = mock(UserNotificationMapper.class);
+        inject(host, "taskMapper", tm);
+        inject(host, "userNotificationMapper", un);
+        Task done = doneToday(20L, "任务");
+        done.setExecutorId(200L);
+        when(tm.selectList(any())).thenReturn(new ArrayList<>(java.util.Collections.singletonList(done)));
+        when(un.selectCount(any())).thenReturn(0L);
+
+        call(host, "sendEveningSummary");
+        verify(wechat, atLeastOnce()).send(any(com.etotem.cfc.dto.NotificationMessage.class));
+    }
+
+    @Test
+    @DisplayName("晚默认开-2:显式 daily_enabled=0 → 晚提醒跳过")
+    @SuppressWarnings("unchecked")
+    void eveningOff_explicitZero() throws Exception {
+        TaskReminderConfigService cfg = mock(TaskReminderConfigService.class);
+        com.etotem.cfc.entity.TaskReminderConfig conf = new com.etotem.cfc.entity.TaskReminderConfig();
+        conf.setUserId(300L);
+        conf.setDailyEnabled(0);
+        when(cfg.loadAllConfigs()).thenReturn(new java.util.HashMap<>(
+                java.util.Collections.singletonMap(300L, conf)));
+        com.etotem.cfc.service.notification.NotificationChannel wechat =
+                mock(com.etotem.cfc.service.notification.NotificationChannel.class);
+        when(wechat.getChannelType()).thenReturn("wechat");
+        when(wechat.isEnabled()).thenReturn(true);
+        Object host = hostWithConfigAndChannel(cfg, wechat);
+
+        TaskMapper tm = mock(TaskMapper.class);
+        UserNotificationMapper un = mock(UserNotificationMapper.class);
+        inject(host, "taskMapper", tm);
+        inject(host, "userNotificationMapper", un);
+        Task done = doneToday(30L, "任务");
+        done.setExecutorId(300L);
+        when(tm.selectList(any())).thenReturn(new ArrayList<>(java.util.Collections.singletonList(done)));
+        when(un.selectCount(any())).thenReturn(0L);
+
+        call(host, "sendEveningSummary");
+        verify(wechat, never()).send(any(com.etotem.cfc.dto.NotificationMessage.class));
+    }
+
+    // ==================== 晚间 webhook 分发(2026-11-29 增强) ====================
+
+    @Test
+    @DisplayName("晚间发送-1:走 wechat 通道,content 为四档鼓励文案(非旧催办文案)")
+    @SuppressWarnings("unchecked")
+    void eveningSummary_dispatchesWechatEncouragement() throws Exception {
+        Object host = contractHost();
+        TaskMapper taskMapper = mock(TaskMapper.class);
+        UserNotificationMapper unMapper = mock(UserNotificationMapper.class);
+        inject(host, "taskMapper", taskMapper);
+        inject(host, "userNotificationMapper", unMapper);
+
+        // 用户 mapper(昵称)
+        com.etotem.cfc.mapper.UserMapper userMapper = mock(com.etotem.cfc.mapper.UserMapper.class);
+        com.etotem.cfc.entity.User user = new com.etotem.cfc.entity.User();
+        user.setId(1L); user.setNickname("小明");
+        when(userMapper.selectById(anyLong())).thenReturn(user);
+        inject(host, "userMapper", userMapper);
+
+        // wechat channel(enabled=true)
+        com.etotem.cfc.service.notification.NotificationChannel wechat =
+                mock(com.etotem.cfc.service.notification.NotificationChannel.class);
+        when(wechat.getChannelType()).thenReturn("wechat");
+        when(wechat.isEnabled()).thenReturn(true);
+        java.util.List<com.etotem.cfc.service.notification.NotificationChannel> channels =
+                new ArrayList<>(java.util.Collections.singletonList(wechat));
+        inject(host, "notificationChannels", channels);
+
+        // 1 已完成 today → 100% 档
+        Task done = doneToday(10L, "喝水");
+        done.setExecutorId(1L);
+        when(taskMapper.selectList(any())).thenReturn(new ArrayList<>(java.util.Collections.singletonList(done)));
+        when(unMapper.selectCount(any())).thenReturn(0L);
+
+        call(host, "sendEveningSummary");
+
+        ArgumentCaptor<com.etotem.cfc.dto.NotificationMessage> msgCaptor =
+                ArgumentCaptor.forClass(com.etotem.cfc.dto.NotificationMessage.class);
+        verify(wechat, atLeastOnce()).send(msgCaptor.capture());
+        com.etotem.cfc.dto.NotificationMessage msg = msgCaptor.getValue();
+        assertTrue(msg.getChannels().contains("wechat"), "晚提醒 channels 应含 wechat,实际=" + msg.getChannels());
+        assertTrue(msg.getContent().contains("全都完成了"), "content 应为四档鼓励文案,实际=" + msg.getContent());
+    }
+
+    // ==================== 晚间四档关怀鼓励文案(2026-11-29 增强) ====================
+
+    /** 反射调用私有 buildEveningEncouragement(List<Task>, String) */
+    @SuppressWarnings("unchecked")
+    private String invokeEncouragement(java.util.List<Task> tasks, String nickname) throws Exception {
+        Object host = contractHost();
+        Method m = host.getClass().getDeclaredMethod("buildEveningEncouragement", java.util.List.class, String.class);
+        m.setAccessible(true);
+        return (String) m.invoke(host, tasks, nickname);
+    }
+
+    private Task doneToday(long id, String title) {
+        Task t = task(id, title, todayDeadline(9, 0), "completed");
+        t.setCompletedAt(new Date());
+        return t;
+    }
+
+    @Test
+    @DisplayName("晚间鼓励-100%:全部完成 → 真诚表扬 + 昵称")
+    void eveningEncouragement_allDone_praise() throws Exception {
+        String s = invokeEncouragement(
+                Arrays.asList(doneToday(1L, "喝水"), doneToday(2L, "阅读")), "小明");
+        assertTrue(s.contains("全都完成了"), "100%档应表扬,实际=" + s);
+        assertTrue(s.contains("小明"), "应带昵称,实际=" + s);
+    }
+
+    @Test
+    @DisplayName("晚间鼓励-80%:完成大部分 → 就差一点点")
+    void eveningEncouragement_80percent_almost() throws Exception {
+        String s = invokeEncouragement(
+                Arrays.asList(doneToday(1L,"a"),doneToday(2L,"b"),doneToday(3L,"c"),doneToday(4L,"d"),
+                        task(5L,"e",todayDeadline(18,0),"pending")), "小明");
+        assertTrue(s.contains("就差一点点"), "≥80%<100%档应说就差一点点,实际=" + s);
+    }
+
+    @Test
+    @DisplayName("晚间鼓励-50%:完成一部分 → 含完成数/总数 + 温和加油")
+    void eveningEncouragement_50percent_partial() throws Exception {
+        String s = invokeEncouragement(
+                Arrays.asList(doneToday(1L,"a"), task(2L,"b",todayDeadline(18,0),"pending")), "小明");
+        assertTrue(s.contains("1/2"), "部分完成档应含 1/2,实际=" + s);
+        assertTrue(s.contains("每一步都算数"), "部分完成档应温和加油,实际=" + s);
+    }
+
+    @Test
+    @DisplayName("晚间鼓励-0%:一个没完成 → 关怀不指责")
+    void eveningEncouragement_zero_caring() throws Exception {
+        String s = invokeEncouragement(
+                Arrays.asList(task(1L,"a",todayDeadline(18,0),"pending"),
+                        task(2L,"b",todayDeadline(19,0),"pending")), "小明");
+        assertTrue(s.contains("有点忙"), "0%档应关怀不指责,实际=" + s);
+        assertTrue(s.contains("没关系"), "0%档应说没关系,实际=" + s);
+    }
+
+    @Test
+    @DisplayName("晚间鼓励-昵称缺失 → 回退“您”")
+    void eveningEncouragement_nullNickname_fallback() throws Exception {
+        String s = invokeEncouragement(
+                Arrays.asList(doneToday(1L,"a")), null);
+        assertTrue(s.contains("您"), "昵称为空应回退您,实际=" + s);
+    }
+
     // ==================== 反射辅助 ====================
 
     private Class<?> loadClass(String name) {

+ 293 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/TongueEmotionCaptureContractTest.java

@@ -0,0 +1,293 @@
+package com.etotem.cfc.unit;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.controller.mind.EmotionRecognitionController;
+import com.etotem.cfc.service.AiGateway;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+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.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * 能力键 {@code tongue.emotion.capture}(S-cfc-289,TDD-RED 阶段)契约级单测。
+ *
+ * <p><b>契约溯源</b></p>
+ * <ul>
+ *   <li>需求:{@code tests/user-scenarios/应用场景总览.md} SC-P-70(业务域 I)—
+ *       「拍照/上传 → 识别情绪标签 → 关联测评;非照片/模糊拒绝;隐私标注不外露」;
+ *       {@code tests/user-scenarios/02-parent.md} P-70、
+ *       {@code tests/test-cases/parent.md} TC-P-70 / TC-P-70-E / TC-P-70-P。</li>
+ *   <li>设计:{@code docs/superpowers/api/API_REFERENCE.md} §4.37 / §4.7 —
+ *       {@code POST /api/mind/emotion/analyze}(multipart 文件上传,走 LangGraph DeepFace)、
+ *       {@code POST /api/mind/emotion/analyze-url};§4.63.9 SC-P-70 载体清单。</li>
+ *   <li>AC 条款:TC-P-70-E「非照片/模糊拒绝提示『请上传清晰舌苔照』;低置信度提示
+ *       『识别不清晰,建议重拍』;隐私标注不外露」;TC-P-70-P「非归属数据访问统一 403/401」。</li>
+ * </ul>
+ *
+ * <p><b>实现现状(RED 依据)</b>:当前 {@code EmotionRecognitionController.analyze} 仅校验
+ * 空文件与大小(≤10MB),不校验图片类型/清晰度/置信度,也不剔除调试用原始响应;
+ * {@code EmotionCheckinDTO} / {@code EmotionCheckin} 无测评关联字段。
+ * 因此本测试以「控制器行为 + DTO/实体结构」探测契约缺口:能编译、能运行、断言失败(红)。</p>
+ *
+ * <p><b>GREEN 升级指引</b>:实现者在照片识别链补齐(a)MIME/魔数校验与模糊拒绝、
+ * (b)低置信度重拍提示、(c)测评关联标识透传与持久化、(d)原始响应/隐私标注不回传后,
+ * 本测试自动转绿。纯 Mockito + 反射,无 Spring 上下文 / 无 DB / 无外部服务。</p>
+ */
+class TongueEmotionCaptureContractTest {
+
+    private static final Long USER_ID = 1001L;
+    private static final String MSG_NOT_CLEAR_PHOTO = "请上传清晰舌苔照";
+    private static final String MSG_LOW_CONFIDENCE = "识别不清晰,建议重拍";
+
+    /** 「关联测评」允许的结果键名(SC-P-70 主流程第三段) */
+    private static final String[] ASSESSMENT_LINK_KEYS = {
+            "assessmentId", "assessmentRecordId", "relatedAssessmentId", "assessmentNo", "assessmentRef"
+    };
+
+    private AiGateway aiGateway;
+    private EmotionRecognitionController controller;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        aiGateway = mock(AiGateway.class);
+        controller = new EmotionRecognitionController();
+        Field field = EmotionRecognitionController.class.getDeclaredField("aiGateway");
+        field.setAccessible(true);
+        field.set(controller, aiGateway);
+    }
+
+    // ==================== 正常流:识别情绪标签 + 关联测评 ====================
+
+    @Test
+    @DisplayName("正常流-1:舌苔照识别成功应返回中文情绪标签并携带测评关联标识")
+    void 正常流_识别结果应携带测评关联标识() throws Exception {
+        when(aiGateway.analyzeEmotion(anyString())).thenReturn(highConfidenceResult());
+
+        Result<Map<String, Object>> result = controller.analyze(USER_ID, photo("image/jpeg", "tongue.jpg"));
+
+        assertEquals(200, result.getCode(), "[tongue.emotion.capture] 清晰舌苔照应识别成功(TC-P-70 主流程)。");
+        Map<String, Object> data = result.getData();
+        assertNotNull(data, "[tongue.emotion.capture] 识别成功必须返回结果数据。");
+        assertEquals("开心", data.get("dominant_label_zh"),
+                "[tongue.emotion.capture] 应返回中文情绪标签 dominant_label_zh(§4.37 响应契约)。");
+        assertTrue(hasAnyKey(data, ASSESSMENT_LINK_KEYS),
+                "[tongue.emotion.capture] 识别结果应携带测评关联标识(assessmentId / assessmentRecordId / "
+                        + "relatedAssessmentId / assessmentNo / assessmentRef),实现未落地:"
+                        + "SC-P-70 主流程为「拍照/上传 → 识别情绪标签 → 关联测评」(TC-P-70)。");
+    }
+
+    @Test
+    @DisplayName("正常流-2:采集载体(DTO/实体)应可承载测评关联标识")
+    void 正常流_采集载体应具备测评关联字段() {
+        String[] carriers = {
+                "com.etotem.cfc.dto.EmotionCheckinDTO",
+                "com.etotem.cfc.dto.TongueEmotionCaptureDTO",
+                "com.etotem.cfc.entity.EmotionCheckin",
+                "com.etotem.cfc.entity.TongueRecord"
+        };
+        boolean carrierFound = false;
+        for (String carrier : carriers) {
+            if (hasAnyField(carrier, ASSESSMENT_LINK_KEYS)) {
+                carrierFound = true;
+                break;
+            }
+        }
+        assertTrue(carrierFound,
+                "[tongue.emotion.capture] 采集载体(EmotionCheckinDTO / EmotionCheckin / TongueRecord)"
+                        + "均无测评关联字段(assessmentId 等),无法实现 SC-P-70「关联测评」;实现未落地。");
+    }
+
+    // ==================== 异常/边界流:非照片、模糊、低置信度 ====================
+
+    @Test
+    @DisplayName("异常流-1:非照片文件应拒绝并提示『请上传清晰舌苔照』,且不调用识别服务")
+    void 异常流_非照片应拒绝() throws Exception {
+        MultipartFile textFile = photo("text/plain", "notes.txt");
+
+        Result<Map<String, Object>> result = controller.analyze(USER_ID, textFile);
+
+        assertTrue(result.getMessage() != null && result.getMessage().contains(MSG_NOT_CLEAR_PHOTO),
+                "[tongue.emotion.capture] 非照片(text/plain)应拒绝并提示『" + MSG_NOT_CLEAR_PHOTO
+                        + "』,实际 message=" + result.getMessage() + ";实现未落地(TC-P-70-E)。");
+        verify(aiGateway, never()).analyzeEmotion(anyString());
+    }
+
+    @Test
+    @DisplayName("异常流-2:模糊照片应拒绝并提示『请上传清晰舌苔照』")
+    void 异常流_模糊照片应拒绝() throws Exception {
+        Map<String, Object> blurry = highConfidenceResult();
+        blurry.put("is_blur", Boolean.TRUE);
+        blurry.put("sharpness", 8.0);
+        when(aiGateway.analyzeEmotion(anyString())).thenReturn(blurry);
+
+        Result<Map<String, Object>> result = controller.analyze(USER_ID, photo("image/jpeg", "blurry.jpg"));
+
+        assertTrue(result.getMessage() != null && result.getMessage().contains(MSG_NOT_CLEAR_PHOTO),
+                "[tongue.emotion.capture] 模糊照片(is_blur=true / 低锐度)应拒绝并提示『"
+                        + MSG_NOT_CLEAR_PHOTO + "』,实际 message=" + result.getMessage()
+                        + ";实现未落地(TC-P-70-E)。");
+    }
+
+    @Test
+    @DisplayName("异常流-3:低置信度识别应提示『识别不清晰,建议重拍』")
+    void 异常流_低置信度应提示重拍() throws Exception {
+        Map<String, Object> lowConfidence = highConfidenceResult();
+        Map<String, Object> emotion = new LinkedHashMap<>();
+        emotion.put("emotion", "happy");
+        emotion.put("confidence", 0.12);
+        lowConfidence.put("emotions", Collections.singletonList(emotion));
+        when(aiGateway.analyzeEmotion(anyString())).thenReturn(lowConfidence);
+
+        Result<Map<String, Object>> result = controller.analyze(USER_ID, photo("image/png", "tongue.png"));
+
+        assertTrue(result.getMessage() != null && result.getMessage().contains(MSG_LOW_CONFIDENCE),
+                "[tongue.emotion.capture] 低置信度(0.12)应拒绝并提示『" + MSG_LOW_CONFIDENCE
+                        + "』,实际 message=" + result.getMessage() + ";实现未落地(TC-P-70-E)。");
+    }
+
+    // ==================== 隐私流:隐私标注不外露 ====================
+
+    @Test
+    @DisplayName("隐私流-1:识别结果不得回传原始响应/隐私标注")
+    void 隐私流_识别结果不得外露原始响应() throws Exception {
+        Map<String, Object> withPrivacy = highConfidenceResult();
+        withPrivacy.put("rawResponse", "{\"face_annotation\":{\"name\":\"张三\",\"id_card\":\"11010119900101****\"}}");
+        withPrivacy.put("privacy_annotation", "人脸标注-姓名=张三");
+        when(aiGateway.analyzeEmotion(anyString())).thenReturn(withPrivacy);
+
+        Result<Map<String, Object>> result = controller.analyze(USER_ID, photo("image/jpeg", "tongue.jpg"));
+
+        assertEquals(200, result.getCode(), "[tongue.emotion.capture] 正常识别应成功(前置条件)。");
+        Map<String, Object> data = result.getData();
+        assertNotNull(data);
+        String serialized = String.valueOf(data);
+        for (String forbidden : new String[]{"rawResponse", "privacy_annotation", "张三", "id_card"}) {
+            assertFalse(serialized.contains(forbidden),
+                    "[tongue.emotion.capture] 隐私标注不外露(TC-P-70-E):响应不应包含 " + forbidden
+                            + ",实际响应=" + serialized + ";实现未落地。");
+        }
+    }
+
+    @Test
+    @DisplayName("隐私流-2:识别结果 DTO 不应保留调试用原始响应字段")
+    void 隐私流_结果DTO不应保留rawResponse字段() {
+        assertFalse(hasField("com.etotem.cfc.dto.EmotionRecognitionResult",
+                        "rawResponse", "raw_response", "rawResponseJson"),
+                "[tongue.emotion.capture] EmotionRecognitionResult.rawResponse(调试用原始响应)"
+                        + "属于隐私标注外露风险,应按 SC-P-70「隐私标注不外露」移除;实现未落地。");
+    }
+
+    // ==================== 权限流:身份来源 ====================
+
+    @Test
+    @DisplayName("权限流:两个识别端点均应从 JWT 注入 userId,而非信任请求体传参")
+    void 权限流_识别端点应以JWT身份为准() {
+        for (String methodName : new String[]{"analyze", "analyzeByUrl"}) {
+            Method target = null;
+            for (Method m : EmotionRecognitionController.class.getDeclaredMethods()) {
+                if (m.getName().equals(methodName)) {
+                    target = m;
+                    break;
+                }
+            }
+            if (target == null) {
+                fail("[tongue.emotion.capture] 识别端点 " + methodName + " 不存在(§4.37)。");
+            }
+            boolean hasJwtUserId = false;
+            for (java.lang.annotation.Annotation[] annotations : target.getParameterAnnotations()) {
+                for (java.lang.annotation.Annotation annotation : annotations) {
+                    if (annotation instanceof RequestAttribute
+                            && "userId".equals(((RequestAttribute) annotation).value())) {
+                        hasJwtUserId = true;
+                    }
+                }
+            }
+            assertTrue(hasJwtUserId,
+                    "[tongue.emotion.capture] " + methodName
+                            + " 应通过 @RequestAttribute(\"userId\") 取 JWT 身份,避免越权传参(TC-P-70-P)。");
+        }
+    }
+
+    // ==================== 辅助 ====================
+
+    private MultipartFile photo(String contentType, String filename) throws Exception {
+        MultipartFile file = mock(MultipartFile.class);
+        when(file.isEmpty()).thenReturn(false);
+        when(file.getSize()).thenReturn(2048L);
+        when(file.getContentType()).thenReturn(contentType);
+        when(file.getOriginalFilename()).thenReturn(filename);
+        when(file.getBytes()).thenReturn(Base64.getDecoder().decode("aGVsbG8tdG9uZ3Vl"));
+        return file;
+    }
+
+    private Map<String, Object> highConfidenceResult() {
+        Map<String, Object> result = new LinkedHashMap<>();
+        result.put("dominant_emotion", "happy");
+        result.put("dominant_label_zh", "开心");
+        Map<String, Object> emotion = new LinkedHashMap<>();
+        emotion.put("emotion", "happy");
+        emotion.put("confidence", 0.85);
+        result.put("emotions", new ArrayList<>(Collections.singletonList(emotion)));
+        result.put("all_emotions", Collections.singletonMap("happy", 0.85));
+        return result;
+    }
+
+    private boolean hasAnyKey(Map<String, Object> map, String... keys) {
+        if (map == null) {
+            return false;
+        }
+        for (String key : keys) {
+            if (map.containsKey(key)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private boolean hasAnyField(String className, String... names) {
+        Class<?> clazz = loadClass(className);
+        if (clazz == null) {
+            return false;
+        }
+        for (String name : names) {
+            for (Field field : clazz.getDeclaredFields()) {
+                if (field.getName().equals(name)) {
+                    return true;
+                }
+            }
+        }
+        return false;
+    }
+
+    private boolean hasField(String className, String... names) {
+        return hasAnyField(className, names);
+    }
+
+    private Class<?> loadClass(String name) {
+        try {
+            return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
+        } catch (ClassNotFoundException e) {
+            return null;
+        }
+    }
+}

+ 16 - 0
cfc-frontend/__tests__/AdminPageTasksExcludeTemplate.contract.spec.js

@@ -0,0 +1,16 @@
+import { readFileSync } from 'fs'
+import { resolve } from 'path'
+
+// 契约:admin.pageTasks.excludeTemplate(管理端家庭任务分页只显示实例,不显示模板)
+const SVC = resolve(__dirname, '../../../cfc-backend/src/main/java/com/etotem/cfc/service/FamilyAdminOverviewService.java')
+const source = readFileSync(SVC, 'utf8')
+
+describe('管理端家庭任务分页排除模板', () => {
+  test('pageTasks 查询排除 is_template=1', () => {
+    const start = source.indexOf('public Page<TaskItemVO> pageTasks')
+    expect(start).toBeGreaterThan(-1)
+    const body = source.slice(start, start + 900)
+    expect(body).toMatch(/getIsTemplate/)
+    expect(body).toMatch(/ne\(Task::getIsTemplate, 1\)|eq\(Task::getIsTemplate, 0\)/)
+  })
+})

+ 18 - 0
cfc-frontend/__tests__/TaskExcludeTemplate.contract.spec.js

@@ -0,0 +1,18 @@
+import { readFileSync } from 'fs'
+import { resolve } from 'path'
+
+// 契约:task.excludeTemplateInToday(模板不出现在用户今日任务列表,避免同一任务显示多条)
+const SVC = resolve(__dirname, '../../../cfc-backend/src/main/java/com/etotem/cfc/service/TaskService.java')
+const source = readFileSync(SVC, 'utf8')
+
+describe('今日任务排除模板', () => {
+  test('getTodayTasks 查询条件排除 is_template=1', () => {
+    const start = source.indexOf('public List<Task> getTodayTasks(Long memberId, String dimensionCode)')
+    const end = source.indexOf('public List<Task> getTodayTasksByFamily')
+    expect(start).toBeGreaterThan(-1)
+    expect(end).toBeGreaterThan(start)
+    const body = source.slice(start, end)
+    expect(body).toMatch(/getIsTemplate/)
+    expect(body).toMatch(/ne\(Task::getIsTemplate, 1\)|eq\(Task::getIsTemplate, 0\)/)
+  })
+})

+ 21 - 0
cfc-frontend/__tests__/TaskNoDeadlineVisible.contract.spec.js

@@ -0,0 +1,21 @@
+import { readFileSync } from 'fs'
+import { resolve } from 'path'
+
+// 契约:task.noDeadlineVisible(无截止的一次性任务未完成时常驻任务列表)
+const SVC = resolve(__dirname, '../../../cfc-backend/src/main/java/com/etotem/cfc/service/TaskService.java')
+const source = readFileSync(SVC, 'utf8')
+
+describe('无截止任务常驻列表', () => {
+  test('getTodayTasks 可见性含 deadline IS NULL 分支', () => {
+    const start = source.indexOf('public List<Task> getTodayTasks(Long memberId, String dimensionCode)')
+    const end = source.indexOf('public List<Task> getTodayTasksByFamily')
+    const body = source.slice(start, end)
+    expect(body).toMatch(/isNull\(Task::getDeadline\)/)
+  })
+  test('家庭视角同步含 deadline IS NULL 分支', () => {
+    const start = source.indexOf('public List<Task> getTodayTasksByFamily')
+    const end = source.indexOf('public List<Task> getTodayTasksByCategory')
+    const body = source.slice(start, end)
+    expect(body).toMatch(/isNull\(Task::getDeadline\)/)
+  })
+})

+ 2 - 16
cfc-frontend/pages/profile-main/profile.vue

@@ -212,14 +212,6 @@
         </view>
       </view>
 
-      <!-- 健康档案(上传报告) -->
-      <view class="menu-row" @click="goToHealthReports">
-        <view class="menu-row-icon gp-report"></view>
-        <text class="menu-row-text">我的健康报告</text>
-        <text class="menu-row-sub">{{ healthReports }} 份</text>
-        <text class="menu-row-arrow">›</text>
-      </view>
-
       <!-- 规划师服务中心入口(仅规划师可见) -->
       <view class="service-center-section" v-if="isTeacherUser && teacherStatus === 'approved'">
         <view class="service-center-card" @click="goToServiceCenter">
@@ -320,9 +312,8 @@ export default {
       totalPoints: 0,
       referralEarnings: 0,
       teamMembers: 0,
-      // 成就汇总(收敛后仅保留勋章数与健康报告数;连续打卡/任务/成长/挑战明细进二级页)
+      // 成就汇总(收敛后仅保留勋章数;健康报告入口已从本页下线,明细进二级页)
       badgesCollected: 0,
-      healthReports: 0,
       // 家庭
       familyMembers: [],
       // 商城(收敛后保留订单四态计数,用于「我的资产」订单汇总入口)
@@ -572,10 +563,9 @@ export default {
       getProfileStats().then(function(res) {
         if (res && res.code === 200 && res.data) {
           var d = res.data
-          // 收敛后本页仅展示积分 / 勋章 / 健康报告三个汇总数;其余明细进二级页
+          // 收敛后本页仅展示积分 / 勋章两个汇总数;其余明细进二级页
           if (d.totalPoints != null) self.totalPoints = d.totalPoints
           if (d.badgesCollected != null) self.badgesCollected = d.badgesCollected
-          if (d.healthReports != null) self.healthReports = d.healthReports
         }
       }).catch(function() {})
     },
@@ -782,9 +772,6 @@ export default {
     goToBadges: function() {
       uni.navigateTo({ url: '/pages/rewards/badge' })
     },
-    goToHealthReports: function() {
-      uni.navigateTo({ url: '/pages/health/report-list' })
-    },
     goToWealthCenter: function() {
       uni.navigateTo({ url: '/pages/promotion/index' })
     },
@@ -921,7 +908,6 @@ $gp-brand-d:  str-slice('#{$brand-primary}', 2);
 .gp-tree { background-image: gp-icon($gp-action-d, '%3Cpath d=%22M12 22V12%22/%3E%3Cpath d=%22M12 12a7 7 0 0 1-7-7 7 7 0 0 1 7 7z%22/%3E%3Cpath d=%22M12 12a7 7 0 0 0 7-7 7 7 0 0 0-7 7z%22/%3E%3Cpath d=%22M7 22h10%22/%3E'); }
 .gp-coin { background-image: gp-icon($gp-wealth-d, '%3Ccircle cx=%2212%22 cy=%2212%22 r=%229%22/%3E%3Cpath d=%22M12 7v10%22/%3E%3Cpath d=%22M9.5 9.5h5%22/%3E%3Cpath d=%22M9.5 14.5h5%22/%3E'); }
 .gp-hands { background-image: gp-icon($gp-wisdom-d, '%3Cpath d=%22M11 17l-5-5-3 3 5 5 6-6%22/%3E%3Cpath d=%22M14 14l6-6-3-3-6 6%22/%3E%3Cpath d=%22M8 11l3 3%22/%3E'); }
-.gp-report { background-image: gp-icon($gp-brand-d, '%3Crect x=%224%22 y=%225%22 width=%2216%22 height=%2215%22 rx=%222%22/%3E%3Cpath d=%22M8 10h8%22/%3E%3Cpath d=%22M8 14h8%22/%3E%3Cpath d=%22M8 18h5%22/%3E'); }
 .gp-mail { background-image: gp-icon($gp-brand-d, '%3Crect x=%222%22 y=%225%22 width=%2220%22 height=%2214%22 rx=%222%22/%3E%3Cpath d=%22M2 7l10 6 10-6%22/%3E'); }
 .gp-gear { background-image: gp-icon($gp-brand-d, '%3Ccircle cx=%2212%22 cy=%2212%22 r=%223%22/%3E%3Cpath d=%22M19.4 15a1.6 1.6 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.6 1.6 0 0 0-2.7 1.1V21a2 2 0 1 1-4 0v-.1A1.6 1.6 0 0 0 7 19.4a1.6 1.6 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1A1.6 1.6 0 0 0 3 14a1.6 1.6 0 0 0-1.6-1.1H1a2 2 0 1 1 0-4h.1A1.6 1.6 0 0 0 3 7.6a1.6 1.6 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1A1.6 1.6 0 0 0 8 3h.1A1.6 1.6 0 0 0 9 1.4V1a2 2 0 1 1 4 0v.1A1.6 1.6 0 0 0 15 3a1.6 1.6 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1A1.6 1.6 0 0 0 21 8v.1a2 2 0 1 1 0 4H21%22/%3E'); }
 .gp-teacher { background-image: gp-icon($gp-brand-d, '%3Cpath d=%22M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2%22/%3E%3Ccircle cx=%2212%22 cy=%227%22 r=%224%22/%3E'); }

+ 1 - 1
cfc-web/.last_build_commit

@@ -1 +1 @@
-65089ebb81b3888d034dc9ff208a926f2fa5732a
+b6ed552e5bdd839f50352a5d565bc1f9959034f8

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

@@ -1,12 +1,12 @@
 {
   "name": "cfc-web",
-  "version": "1.0.2851",
+  "version": "1.0.2854",
   "lockfileVersion": 3,
   "requires": true,
   "packages": {
     "": {
       "name": "cfc-web",
-      "version": "1.0.2851",
+      "version": "1.0.2854",
       "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.2852",
+  "version": "1.0.2855",
   "private": true,
   "scripts": {
     "dev": "vue-cli-service serve",

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

@@ -4,6 +4,61 @@
 
 ---
 
+## v1.0.2854 (2026-11-29)
+
+### 新功能
+- 晚间提醒四档关怀鼓励文案 + 昵称回退
+
+### 文档
+- 任务晚间关怀鼓励提醒实现计划(5任务TDD)
+- CF 错峰档收割汇报 2026-11-29 2253(S1 PASS·S0断档1270min·backfill~30键含S-cfc-503·--auto/--dispatch双hang零派发合法情形②·SC 243/27零新增)
+- 补充builder-check决策(拆早晚开关/全栈默认开启/无任务不发)
+- 任务晚间关怀鼓励提醒设计(四档/wechat webhook/默认开启)
+
+### Bug 修复
+- 家庭工作台任务分页只显示实例,隐藏模板
+- 无截止的一次性任务未完成时常驻任务列表
+
+### 其他
+- summary 里的模板/实例计数仍保留。契约测试 RED→GREEN。
+- 
+- 和「is_daily_progress=1 且 created_at 今天」两条,deadline=NULL 的
+- 一次性任务(如单据上传类)两条都不满足,永远不出现在任务列表。
+- - 两个查询可见性加 or isNull(deadline) 分支
+- - 契约测试 TaskNoDeadlineVisible.contract.spec.js RED→GREEN
+- - 回归 Task 相关 47 项全绿
+- 
+
+
+## v1.0.2853 (2026-11-29)
+
+### Bug 修复
+- 我的页移除「我的健康报告」入口及关联死代码
+- 今日任务列表排除模板行,避免同一任务显示多条
+
+### 其他
+- - 移除 goToHealthReports 跳转方法
+- - 移除 healthReports data 字段及其在 loadProfileStats 的赋值
+- - 移除失效的 .gp-report 图标样式(scoped,仅本页使用)
+- - 成就汇总注释由「勋章+健康报告」更正为「勋章」
+- 健康报告功能仍保留于 pages/health/*(独立入口),仅从「我的」tab 下线该入口。
+- 
+- 未排除 is_template=1,导致周期模板本身和当日实例都出现在列表里,
+- 同一任务显示两条(有氧/抗阻/三餐等)。
+- - 两个查询加 (is_template != 1 OR is_template IS NULL)
+- - 契约测试 TaskExcludeTemplate.contract.spec.js RED→GREEN
+- 
+
+### 测试
+- tongue.emotion.capture 契约级 RED 单测(SC-P-70,7 失败/1 通过)
+- family.member.update RED contract tests (SC-P-05/SC-P-08)
+- privacy.setting.config 契约级 RED 单测(预期红,13 失败)
+- S-cfc-440 CR-03 §4.3 契约 RED 单测(14 失败/6 通过)
+
+### 文档
+- CF 21分错峰档收割汇报 2026-11-29 2132(S0清死记录·--auto预算耗尽池空合法零派发情形②·backfill S-cfc-503新认·SC 243/27零新增)
+
+
 ## v1.0.2852 (2026-11-29)
 
 ### Bug 修复

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

@@ -1,6 +1,6 @@
 # 更新日志
 
-> 当前版本: v1.0.2852
+> 当前版本: v1.0.2854
 
 ## 历史版本
 
@@ -8,6 +8,61 @@
 
 ---
 
+## v1.0.2854 (2026-11-29)
+
+### 新功能
+- 晚间提醒四档关怀鼓励文案 + 昵称回退
+
+### 文档
+- 任务晚间关怀鼓励提醒实现计划(5任务TDD)
+- CF 错峰档收割汇报 2026-11-29 2253(S1 PASS·S0断档1270min·backfill~30键含S-cfc-503·--auto/--dispatch双hang零派发合法情形②·SC 243/27零新增)
+- 补充builder-check决策(拆早晚开关/全栈默认开启/无任务不发)
+- 任务晚间关怀鼓励提醒设计(四档/wechat webhook/默认开启)
+
+### Bug 修复
+- 家庭工作台任务分页只显示实例,隐藏模板
+- 无截止的一次性任务未完成时常驻任务列表
+
+### 其他
+- summary 里的模板/实例计数仍保留。契约测试 RED→GREEN。
+- 
+- 和「is_daily_progress=1 且 created_at 今天」两条,deadline=NULL 的
+- 一次性任务(如单据上传类)两条都不满足,永远不出现在任务列表。
+- - 两个查询可见性加 or isNull(deadline) 分支
+- - 契约测试 TaskNoDeadlineVisible.contract.spec.js RED→GREEN
+- - 回归 Task 相关 47 项全绿
+- 
+
+
+## v1.0.2853 (2026-11-29)
+
+### Bug 修复
+- 我的页移除「我的健康报告」入口及关联死代码
+- 今日任务列表排除模板行,避免同一任务显示多条
+
+### 其他
+- - 移除 goToHealthReports 跳转方法
+- - 移除 healthReports data 字段及其在 loadProfileStats 的赋值
+- - 移除失效的 .gp-report 图标样式(scoped,仅本页使用)
+- - 成就汇总注释由「勋章+健康报告」更正为「勋章」
+- 健康报告功能仍保留于 pages/health/*(独立入口),仅从「我的」tab 下线该入口。
+- 
+- 未排除 is_template=1,导致周期模板本身和当日实例都出现在列表里,
+- 同一任务显示两条(有氧/抗阻/三餐等)。
+- - 两个查询加 (is_template != 1 OR is_template IS NULL)
+- - 契约测试 TaskExcludeTemplate.contract.spec.js RED→GREEN
+- 
+
+### 测试
+- tongue.emotion.capture 契约级 RED 单测(SC-P-70,7 失败/1 通过)
+- family.member.update RED contract tests (SC-P-05/SC-P-08)
+- privacy.setting.config 契约级 RED 单测(预期红,13 失败)
+- S-cfc-440 CR-03 §4.3 契约 RED 单测(14 失败/6 通过)
+
+### 文档
+- CF 21分错峰档收割汇报 2026-11-29 2132(S0清死记录·--auto预算耗尽池空合法零派发情形②·backfill S-cfc-503新认·SC 243/27零新增)
+
+
 ## v1.0.2852 (2026-11-29)
 
 ### Bug 修复

+ 28 - 0
cfc-web/src/__tests__/views/AdminTaskFullEdit.contract.spec.js

@@ -0,0 +1,28 @@
+import { readFileSync } from 'fs'
+import { resolve } from 'path'
+
+// 契约:admin.task.fullEdit(后台任务编辑全量字段 + 详情接口回显)
+const VUE = resolve(__dirname, '../../views/FamilyWorkbench.vue')
+const API = resolve(__dirname, '../../api/familyWorkbench.js')
+const DTO = resolve(__dirname, '../../../../cfc-backend/src/main/java/com/etotem/cfc/dto/FamilyTaskCreateDTO.java')
+const CTRL = resolve(__dirname, '../../../../cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminFamilyTaskController.java')
+const vue = readFileSync(VUE, 'utf8'), api = readFileSync(API, 'utf8')
+const dto = readFileSync(DTO, 'utf8'), ctrl = readFileSync(CTRL, 'utf8')
+
+describe('后台任务编辑全量字段', () => {
+  test('后端详情端点 + DTO 全量字段', () => {
+    expect(ctrl).toMatch(/tasks\/detail/)
+    expect(dto).toMatch(/earliestStart/)
+    expect(dto).toMatch(/actionConfig/)
+    expect(dto).toMatch(/isDailyProgress/)
+  })
+  test('前端详情 API + 编辑异步回显', () => {
+    expect(api).toMatch(/getFamilyTaskDetail/)
+    expect(vue).toMatch(/getFamilyTaskDetail\(this\.familyId, row\.id\)/)
+  })
+  test('编辑抽屉含频度/时间/动作等全量字段', () => {
+    ['frequency', 'repeatType', 'earliestStart', 'latestEnd', 'deadline',
+     'actionType', 'isDailyProgress', 'targetValue', 'requireInput', 'dimensionCode']
+      .forEach(k => expect(vue).toContain('taskForm.' + k))
+  })
+})

+ 4 - 0
cfc-web/src/api/familyWorkbench.js

@@ -24,6 +24,10 @@ export function updateFamilyTask(id, data) {
   return request({ url: `/api/admin/families/${id}/tasks/update`, method: "post", data })
 }
 
+export function getFamilyTaskDetail(id, taskId) {
+  return request({ url: `/api/admin/families/${id}/tasks/detail`, method: "post", data: { taskId } })
+}
+
 export function createFamilyPlan(id, data) {
   return request({ url: `/api/admin/families/${id}/plans/create`, method: "post", data })
 }

+ 74 - 2
cfc-web/src/views/FamilyWorkbench.vue

@@ -350,6 +350,65 @@
             </el-select>
           </el-form-item>
           <el-form-item label="描述"><el-input type="textarea" v-model="taskForm.description"></el-input></el-form-item>
+
+          <!-- 执行与归属 -->
+          <el-divider content-position="left">执行与归属</el-divider>
+          <el-form-item label="归属成员"><el-input-number v-model="taskForm.familyMemberId" :min="0" controls-position="right" style="width:100%"></el-input-number></el-form-item>
+          <el-form-item label="执行者类型"><el-select v-model="taskForm.executorType" clearable style="width:100%"><el-option label="child" value="child"></el-option><el-option label="parent" value="parent"></el-option></el-select></el-form-item>
+          <el-form-item label="执行者ID"><el-input-number v-model="taskForm.executorId" :min="0" controls-position="right" style="width:100%"></el-input-number></el-form-item>
+          <el-form-item label="旧成员ID"><el-input-number v-model="taskForm.memberId" :min="0" controls-position="right" style="width:100%"></el-input-number></el-form-item>
+          <el-form-item label="状态"><el-select v-model="taskForm.status" clearable style="width:100%"><el-option v-for="s in ['pending','assigned','in_progress','completed','rejected','overdue','cancelled','locked','pending_review','paused']" :key="s" :label="s" :value="s"></el-option></el-select></el-form-item>
+
+          <!-- 周期与频率 -->
+          <el-divider content-position="left">周期与频率</el-divider>
+          <el-form-item label="重复类型"><el-select v-model="taskForm.repeatType" clearable style="width:100%"><el-option v-for="r in ['none','daily','weekly','monthly']" :key="r" :label="r" :value="r"></el-option></el-select></el-form-item>
+          <el-form-item label="频率"><el-select v-model="taskForm.frequency" clearable style="width:100%"><el-option v-for="f in ['daily','weekly','monthly','every_other_day','custom','hourly','none']" :key="f" :label="f" :value="f"></el-option></el-select></el-form-item>
+          <el-form-item label="频率单位"><el-select v-model="taskForm.frequencyUnit" clearable style="width:100%"><el-option v-for="u in ['DAY','WEEK','MONTH','YEAR']" :key="u" :label="u" :value="u"></el-option></el-select></el-form-item>
+          <el-form-item label="频率间隔"><el-input-number v-model="taskForm.frequencyInterval" :min="0" controls-position="right" style="width:100%"></el-input-number></el-form-item>
+          <el-form-item label="周期锚点"><el-date-picker v-model="taskForm.cycleAnchor" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择时间" style="width:100%"></el-date-picker></el-form-item>
+          <el-form-item label="最多次数"><el-input-number v-model="taskForm.maxFrequency" :min="0" controls-position="right" style="width:100%"></el-input-number></el-form-item>
+          <el-form-item label="时长(分)"><el-input-number v-model="taskForm.duration" :min="0" controls-position="right" style="width:100%"></el-input-number></el-form-item>
+          <el-form-item label="已暂停"><el-switch v-model="taskForm.isPaused" :active-value="1" :inactive-value="0"></el-switch></el-form-item>
+          <el-form-item label="模板任务"><el-switch v-model="taskForm.isTemplate" :active-value="1" :inactive-value="0"></el-switch></el-form-item>
+          <el-form-item label="模板ID"><el-input-number v-model="taskForm.templateId" :min="0" controls-position="right" style="width:100%"></el-input-number></el-form-item>
+
+          <!-- 时间与窗口 -->
+          <el-divider content-position="left">时间与窗口</el-divider>
+          <el-form-item label="截止时间"><el-date-picker v-model="taskForm.deadline" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择时间" style="width:100%"></el-date-picker></el-form-item>
+          <el-form-item label="最早开始"><el-date-picker v-model="taskForm.earliestStart" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择时间" style="width:100%"></el-date-picker></el-form-item>
+          <el-form-item label="最晚结束"><el-date-picker v-model="taskForm.latestEnd" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择时间" style="width:100%"></el-date-picker></el-form-item>
+          <el-form-item label="接受截止"><el-date-picker v-model="taskForm.acceptDeadline" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择时间" style="width:100%"></el-date-picker></el-form-item>
+
+          <!-- 完成与审核 -->
+          <el-divider content-position="left">完成与审核</el-divider>
+          <el-form-item label="需审核"><el-switch v-model="taskForm.needReview" :active-value="1" :inactive-value="0"></el-switch></el-form-item>
+          <el-form-item label="按分类审核"><el-switch v-model="taskForm.reviewByCategory" :active-value="1" :inactive-value="0"></el-switch></el-form-item>
+          <el-form-item label="审核类型"><el-select v-model="taskForm.reviewType" clearable style="width:100%"><el-option v-for="r in ['creator','parent','teacher','ai']" :key="r" :label="r" :value="r"></el-option></el-select></el-form-item>
+          <el-form-item label="完成方式"><el-select v-model="taskForm.completeTypes" multiple filterable allow-create default-first-option style="width:100%"><el-option v-for="c in ['text','photo','video','minigame','checkin','buy','use']" :key="c" :label="c" :value="c"></el-option></el-select></el-form-item>
+          <el-form-item label="需填写内容"><el-switch v-model="taskForm.requireInput" :active-value="1" :inactive-value="0"></el-switch></el-form-item>
+          <el-form-item label="需先开始"><el-switch v-model="taskForm.startRequired" :active-value="1" :inactive-value="0"></el-switch></el-form-item>
+          <el-form-item label="最短时长(秒)"><el-input-number v-model="taskForm.minDurationSeconds" :min="0" controls-position="right" style="width:100%"></el-input-number></el-form-item>
+
+          <!-- 动作与目标 -->
+          <el-divider content-position="left">动作与目标</el-divider>
+          <el-form-item label="动作类型"><el-select v-model="taskForm.actionType" clearable style="width:100%"><el-option v-for="a in ['checkin','diet','exercise','sleep','focus','article','buy','cart','order','use','survey','activity','minigame']" :key="a" :label="a" :value="a"></el-option></el-select></el-form-item>
+          <el-form-item label="动作配置(JSON)"><el-input type="textarea" v-model="taskForm.actionConfig" placeholder='如 {"productId":123}'></el-input></el-form-item>
+          <el-form-item label="每日进度"><el-switch v-model="taskForm.isDailyProgress" :active-value="1" :inactive-value="0"></el-switch></el-form-item>
+          <el-form-item label="目标值"><el-input-number v-model="taskForm.targetValue" :min="0" controls-position="right" style="width:100%"></el-input-number></el-form-item>
+          <el-form-item label="前置任务ID"><el-input-number v-model="taskForm.prerequisiteTaskId" :min="0" controls-position="right" style="width:100%"></el-input-number></el-form-item>
+          <el-form-item label="流式任务"><el-switch v-model="taskForm.isFlowTask" :active-value="1" :inactive-value="0"></el-switch></el-form-item>
+          <el-form-item label="后继任务IDs"><el-input v-model="taskForm.successorTaskIds" placeholder="逗号分隔"></el-input></el-form-item>
+          <el-form-item label="小游戏"><el-input v-model="taskForm.minigameCode"></el-input></el-form-item>
+
+          <!-- 积分与来源 -->
+          <el-divider content-position="left">积分与来源</el-divider>
+          <el-form-item label="积分规则(JSON)"><el-input type="textarea" v-model="taskForm.bonusRule"></el-input></el-form-item>
+          <el-form-item label="积分有效期"><el-input-number v-model="taskForm.pointsExpireDays" :min="0" controls-position="right" style="width:100%"></el-input-number></el-form-item>
+          <el-form-item label="仅会员"><el-switch v-model="taskForm.memberOnly" :active-value="1" :inactive-value="0"></el-switch></el-form-item>
+          <el-form-item label="维度编码"><el-input v-model="taskForm.dimensionCode"></el-input></el-form-item>
+          <el-form-item label="维度权重(JSON)"><el-input type="textarea" v-model="taskForm.dimensionWeights"></el-input></el-form-item>
+          <el-form-item label="来源类型"><el-input v-model="taskForm.sourceType"></el-input></el-form-item>
+          <el-form-item label="来源ID"><el-input-number v-model="taskForm.sourceId" :min="0" controls-position="right" style="width:100%"></el-input-number></el-form-item>
         </el-form>
         <div v-if="taskFormErrors._form" class="wb-field-error">{{ taskFormErrors._form }}</div>
       </div>
@@ -388,6 +447,7 @@ import {
   getConversationMessages,
   createFamilyTask,
   updateFamilyTask,
+  getFamilyTaskDetail,
   createFamilyPlan,
   updateFamilyPlan,
   getFamilyCfLogs
@@ -743,9 +803,21 @@ export default {
       this.taskList = (res.data && res.data.records) || []
       this.taskTotal = (res.data && res.data.total) || 0
     },
-    openTaskForm(row) {
-      this.taskForm = row ? { ...row } : { title: "", category: "", points: 0, taskType: "once", description: "" }
+    async openTaskForm(row) {
       this.taskFormErrors = {}
+      if (row && row.id) {
+        try {
+          const detail = await getFamilyTaskDetail(this.familyId, row.id)
+          const d = (detail && detail.data) || {}
+          // completeTypes 存库是逗号字符串,编辑框用数组
+          this.taskForm = { ...d, completeTypes: d.completeTypes ? String(d.completeTypes).split(',').filter(Boolean) : [] }
+        } catch (e) {
+          // 详情失败时退回列表行数据,避免完全打不开
+          this.taskForm = { ...row }
+        }
+      } else {
+        this.taskForm = { title: "", category: "", points: 0, taskType: "once", description: "" }
+      }
       this.taskFormVisible = true
     },
     async submitTaskForm() {

+ 245 - 0
docs/superpowers/plans/2026-11-29-task-evening-encouragement.md

@@ -0,0 +1,245 @@
+# 任务晚间关怀鼓励提醒 Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** 把晚间任务提醒改为"当天完成情况汇总 + 四档关怀鼓励文案",经微信待办 webhook 发给用户(默认开启、设置页显示一致),早提醒与两档到期提醒不变。
+
+**Architecture:** 改动集中在现有 `TaskDailyReminderScheduledTask`:晚间分支重写文案与发送(直接组装 NotificationMessage 指定 `in_app,wechat` 通道并遍历 NotificationChannel 分发,复用已投产的 WebhookNotificationChannel),拆出晚用"默认开启"判断与早用原判断;`TaskReminderConfigService` 的 getConfig/saveConfig/DTO 默认 dailyEnabled=1;小程序 reminder-config 默认开;追加幂等迁移改表默认值。
+
+**Tech Stack:** Java 17 / Spring Boot 2.7 / MyBatis-Plus / JUnit5+Mockito / Vue(uni-app) 小程序
+
+**Spec:** `docs/superpowers/specs/2026-11-29-task-evening-encouragement-design.md`
+
+## Global Constraints
+
+- 所有金额/单位口径不变;本功能不涉及金额。
+- 晚提醒 cron 固定 `0 0 21 * * ?`;早提醒 `0 30 7 * * ?` 与 `sendMorningReminder()` 整体不动。
+- 收件人仅 `executor_type='parent'` 任务执行人(executorId=users.id);幂等靠 `user_notifications` 当日同 (type, ref_type='task', createdAt) 判重。
+- 渠道:in_app 恒兜底 + wechat(`WebhookNotificationChannel`,isEnabled=true,按手机号定向);**不接公众号模板消息**,不依赖 notification_templates 表。
+- 文案四档精确字符串见 spec §5;昵称查不到回退"您"。
+- 默认开启口径:无配置/null daily_enabled → 1(开启);仅显式 0 → 关闭。
+- 早提醒收件人不得因本改动扩大(用独立 helper)。
+- 无今日到期任务的用户不发(保留 early return)。
+
+## Review Focus
+
+- 完成率恰好 80% / 恰好 100% / 恰好 0% 的边界档位 → Task 1 边界测试。
+- 用户昵称为 null 或查询异常 → Task 1 回退"您"测试。
+- 显式 daily_enabled=0 的无任务/有任务用户 → Task 3 跳过测试。
+- wechat 通道 send 抛异常 → 不阻断 in_app(仿现有 dispatch 的 try-catch)→ Task 2 分发测试。
+- 设置页保存把 dailyEnabled 传 null → 落 1 不落 0 → Task 4 测试。
+
+---
+
+### Task 1: 晚间四档文案 + 昵称(纯函数)
+
+**Files:**
+- Modify: `cfc-backend/src/main/java/com/etotem/cfc/task/TaskDailyReminderScheduledTask.java`(新增 `buildEveningEncouragement(List<Task>, String nickname)` 方法;保留旧 `buildEveningContent` 或替换)
+- Test: `cfc-backend/src/test/java/com/etotem/cfc/unit/TaskReminderDailyScheduledTaskContractTest.java`(追加测试)
+
+**Interfaces:**
+- Consumes: `com.etotem.cfc.entity.Task`(getStatus/getCompletedAt/getTitle/getDeadline),`isSameDay(Date,Date)`(现有私有方法)
+- Produces: `String buildEveningEncouragement(List<Task> tasks, String nickname)` —— 四档文案,被 Task 2 调用
+
+- [ ] **Step 1: 写失败测试**(新测试类或追加,反射调私有方法)
+
+```java
+// 100%:2/2 完成(completed + completedAt 今日)
+@Test void evening_100_allDone_praise() throws Exception {
+  Task a = doneTask("跳绳", today()); Task b = doneTask("阅读", today());
+  String s = invokeBuild(Arrays.asList(a,b), "小明");
+  assertTrue(s.contains("全都完成了")); assertTrue(s.contains("小明"));
+}
+// 80%:4/5 完成 → "就差一点点"
+@Test void evening_80_almost() throws Exception { /* 4 done 1 pending */ assertTrue(s.contains("就差一点点")); }
+// 50%:1/2 → "每一步都算数" + 含 1/2
+@Test void evening_50_partial() throws Exception { /* ... */ assertTrue(s.contains("1/2")); }
+// 0%:0/2 → "有点忙" 不指责
+@Test void evening_0_caring() throws Exception { /* ... */ assertTrue(s.contains("有点忙")); }
+// 昵称回退
+@Test void evening_nullNickname_fallback() throws Exception { /* ... */ assertTrue(s.contains("您")); }
+```
+
+- [ ] **Step 2: 运行测试确认失败**
+
+Run: `mvn test -Dtest=TaskReminderDailyScheduledTaskContractTest -Dmaven.compile.fork=true -q`
+Expected: FAIL(方法不存在/断言不符)
+
+- [ ] **Step 3: 实现 `buildEveningEncouragement`**
+
+在 `TaskDailyReminderScheduledTask` 新增:遍历 tasks,按 `completed && isSameDay(completedAt, startOfToday())` 计已完成数;rate=done/total;按 spec §5 四档返回文案(100% / ≥0.8 / >0 / ==0),`「{昵称}」` 前缀(nickname 空/null → "您")。不要在此方法里发消息。
+
+- [ ] **Step 4: 运行测试确认通过**
+
+Run: 同 Step 2;Expected: PASS(含边界:4/5=80% 走第二档、2/2=100% 走第一档、0 走第四档)
+
+- [ ] **Step 5: 提交**
+
+```bash
+git add cfc-backend/src/main/java/com/etotem/cfc/task/TaskDailyReminderScheduledTask.java cfc-backend/src/test/java/com/etotem/cfc/unit/TaskReminderDailyScheduledTaskContractTest.java
+git commit -m "feat(task): 晚间提醒四档关怀鼓励文案 + 昵称回退"
+```
+
+---
+
+### Task 2: 晚间发送改 wechat webhook 分发(不依赖模板表)
+
+**Files:**
+- Modify: `cfc-backend/src/main/java/com/etotem/cfc/task/TaskDailyReminderScheduledTask.java`(`sendEveningSummary()` 发送段;新增 `dispatchEvening(...)`;注入 `UserMapper`、`List<NotificationChannel>`)
+- Test: 同测试类(追加 channels 断言)
+
+**Interfaces:**
+- Consumes: Task 1 的 `buildEveningEncouragement`;`NotificationMessage`(构造器 `(userId, type, title, content, refType, refId, channels)`);`NotificationChannel`(getChannelType/isEnabled/send);`UserMapper.selectById(Long)`
+- Produces: `sendEveningSummary()` 走 wechat 分发,早提醒不受影响
+
+- [ ] **Step 1: 写失败测试**(断言晚提醒触发 webhook channel.send 且 content 含鼓励档)
+
+```java
+@Test void evening_dispatchesViaWechatChannel() throws Exception {
+  // mock: taskMapper 返回今日到期1条 completed;userMapper 返回昵称"小明";
+  // mock NotificationChannel(type=wechat, enabled=true) 与 in_app
+  task.sendEveningSummary();
+  verify(wechatChannel).send(argThat(m -> m.getContent().contains("全都完成了") && m.getChannels().contains("wechat")));
+  verify(inAppChannel, atLeastOnce()).send(any());
+}
+```
+
+- [ ] **Step 2: 运行测试确认失败**
+
+Run: `mvn test -Dtest=TaskReminderDailyScheduledTaskContractTest -Dmaven.compile.fork=true -q`
+Expected: FAIL(未走 wechannel / 未注入)
+
+- [ ] **Step 3: 实现发送改造**
+
+`sendEveningSummary()` 中:汇总后对每个用户取昵称(注入 UserMapper,try-catch 回退"您"),`content = buildEveningEncouragement(userTasks, nickname)`,组装 `NotificationMessage(userId, TYPE_EVENING, "今日任务总结", content, REF_TYPE, refId, "in_app,wechat")`,调用新增 `dispatchEvening(msg)` 遍历 `List<NotificationChannel>`(仿 `TaskCheckinWebhookReminderTask.dispatch()`:跳过不存在/未启用,try-catch 不阻断)。保留 `notificationDispatchService` 字段(早提醒仍用)。移除晚提醒对 `sendByTemplate` 的调用。
+
+- [ ] **Step 4: 运行测试确认通过 + 早提醒回归**
+
+Run: `mvn test -Dtest=TaskReminderDailyScheduledTaskContractTest -Dmaven.compile.fork=true -q`
+Expected: PASS;早提醒相关既有用例仍绿
+
+- [ ] **Step 5: 提交**
+
+```bash
+git add cfc-backend/src/main/java/com/etotem/cfc/task/TaskDailyReminderScheduledTask.java cfc-backend/src/test/java/com/etotem/cfc/unit/TaskReminderDailyScheduledTaskContractTest.java
+git commit -m "feat(task): 晚间提醒改走wechat webhook分发(in_app兜底)"
+```
+
+---
+
+### Task 3: 拆早晚开关(晚默认开、早不变)
+
+**Files:**
+- Modify: `cfc-backend/src/main/java/com/etotem/cfc/task/TaskDailyReminderScheduledTask.java`(新增 `isDailyEnabledEvening()`;`sendEveningSummary()` 改用它;`isDailyEnabled()` 保留给早提醒)
+- Test: 同测试类(追加默认开启/显式关闭用例)
+
+**Interfaces:**
+- Consumes: `TaskReminderConfigService.loadAllConfigs()` → `Map<Long, TaskReminderConfig>`,`TaskReminderConfig.getDailyEnabled()`
+- Produces: `boolean isDailyEnabledEvening(Long userId)` —— null config / null dailyEnabled / 非0 → true;显式 0 → false;服务为 null(单测)→ true
+
+- [ ] **Step 1: 写失败测试**
+
+```java
+@Test void eveningDefaultOn_noConfig() throws Exception {
+  // configs 空 → sendEveningSummary 仍对无配置用户发送(verify wechat.send)
+}
+@Test void eveningOff_explicitZero() throws Exception {
+  // config dailyEnabled=0 → 不发送(verify wechat.send never)
+}
+@Test void morningRecipientUnchanged_noConfig() throws Exception {
+  // 无配置用户早提醒仍不发(原 isDailyEnabled 逻辑未动)
+}
+```
+
+- [ ] **Step 2: 运行测试确认失败** — Expected: FAIL
+
+- [ ] **Step 3: 实现 `isDailyEnabledEvening`**
+
+新增 helper:`if (taskReminderConfigService == null) return true; config=loadAllConfigs().get(userId); return config==null || config.getDailyEnabled()==null || !Integer.valueOf(0).equals(config.getDailyEnabled());`;`sendEveningSummary()` 改调此方法;`sendMorningReminder()` 仍调原 `isDailyEnabled()`。
+
+- [ ] **Step 4: 运行测试确认通过** — Expected: PASS(早提醒回归用例仍绿)
+
+- [ ] **Step 5: 提交**
+
+```bash
+git add <same two files>
+git commit -m "fix(task): 晚提醒默认开启(拆早晚开关,早提醒收件人不变)"
+```
+
+---
+
+### Task 4: 全栈默认开启(配置服务/DTO/前端)
+
+**Files:**
+- Modify: `cfc-backend/src/main/java/com/etotem/cfc/service/TaskReminderConfigService.java`(`getConfig` 59/83 行、`saveConfig` 141 行默认值 0→1)
+- Modify: `cfc-backend/src/main/java/com/etotem/cfc/dto/TaskReminderConfigDTO.java`(dailyEnabled 注释与默认语义)
+- Modify: `cfc-frontend/pages/reminder-config/index.vue`(`data().dailyEnabled: 0→1`,`233 行 d.dailyEnabled===1?1:0` 改为 `d.dailyEnabled===0?0:1`)
+- Test: `cfc-backend/src/test/java/com/etotem/cfc/unit/TaskReminderDailyConfigContractTest.java`(默认值断言 0→1);新建/更新 saveConfig null 测试
+
+**Interfaces:**
+- Consumes: 无(内部改动)
+- Produces: 未配置用户 getConfig().dailyEnabled=1;saveConfig(null dailyEnabled) 落 1
+
+- [ ] **Step 1: 写/改失败测试**
+
+改 `TaskReminderDailyConfigContractTest` 默认断言为 1;新增 `saveConfig_dailyEnabledNull_defaultsToOne` 断言落库 1。
+
+- [ ] **Step 2: 运行测试确认失败** — Expected: FAIL(当前返回 0)
+
+- [ ] **Step 3: 实现默认 1**
+
+`getConfig`:无 entity → `dto.setDailyEnabled(1)`;有 entity → `entity.getDailyEnabled()==null ? 1 : 值`;`saveConfig`:`int daily = dto.getDailyEnabled()==null ? 1 : dto.getDailyEnabled();`;DTO 注释改"默认 1";前端 `dailyEnabled` 初值 1、赋值 `d.dailyEnabled===0?0:1`。
+
+- [ ] **Step 4: 运行测试确认通过 + 前端构建**
+
+Run: `mvn test -Dtest=TaskReminderDailyConfigContractTest -Dmaven.compile.fork=true -q`;前端 `cd cfc-frontend && npm run build`(或对应构建命令)
+Expected: PASS / 构建成功
+
+- [ ] **Step 5: 提交**
+
+```bash
+git add <backend files> cfc-frontend/pages/reminder-config/index.vue
+git commit -m "feat(task): 日提醒配置默认开启(全栈一致)"
+```
+
+---
+
+### Task 5: 迁移 daily_enabled 默认值 + 集成验证 + 部署
+
+**Files:**
+- Modify: `cfc-backend/src/main/java/com/etotem/cfc/config/DatabaseInitializer.java`(追加幂等迁移改默认值,try-catch)
+- Test: 无独立单测(迁移幂等靠启动日志/DB 验证)
+
+**Interfaces:**
+- Consumes: 无
+- Produces: 生产库 task_reminder_config.daily_enabled 默认 1(迁移失败也不影响代码默认开启)
+
+- [ ] **Step 1: 写迁移**
+
+追加 `ALTER TABLE task_reminder_config ALTER COLUMN daily_enabled SET DEFAULT 1`(MySQL 8 用 `ALTER TABLE ... MODIFY COLUMN daily_enabled TINYINT DEFAULT 1 COMMENT '...'`),try-catch 吞异常,日志 info/warn。不改已有行值。
+
+- [ ] **Step 2: test-compile + 相关测试全绿**
+
+Run: `mvn test-compile -q -Dmaven.compile.fork=true` 与 `mvn test -Dtest=TaskReminderDailyScheduledTaskContractTest,TaskReminderDailyConfigContractTest -Dmaven.compile.fork=true -q`
+Expected: EXIT 0,全绿
+
+- [ ] **Step 3: 构建 jar + 备份 + 部署 + 验证**
+
+构建后端 jar;备份 `/app/pro/cfc_backup_*.tar.gz`;替换 jar + `systemctl restart cfc-backend`;验证 active/9082/API 200/ERROR=0;DB 查 `SHOW COLUMNS FROM task_reminder_config LIKE 'daily_enabled'` 默认 1。
+
+- [ ] **Step 4: 提交**
+
+```bash
+git add cfc-backend/src/main/java/com/etotem/cfc/config/DatabaseInitializer.java
+git commit -m "feat(task): 日提醒表默认开启迁移 + 部署验证"
+```
+
+---
+
+## Self-Review
+
+- **Spec coverage:** §5 四档文案→Task1;wechat webhook→Task2;拆开关→Task3;默认开启全栈→Task4;迁移→Task5;幂等/早提醒不变/无任务不发→Task2/3 回归断言 + Global Constraints。全覆盖。
+- **Step scan:** 每步单一动作;代码步骤给签名与值,不写完整方法体。
+- **Type consistency:** `buildEveningEncouragement(List<Task>, String)`、`isDailyEnabledEvening(Long)`、`NotificationMessage(...7参)`、`getConfig/saveConfig` 签名与现有代码一致。
+- **Review Focus:** 五类边界各有 Task1/2/4 测试;迁移失败兜底由代码默认开启覆盖。
+- **Proportion:** 计划与 spec 体量相当,未贴代码。

+ 66 - 0
docs/superpowers/specs/2026-11-29-task-evening-encouragement-design.md

@@ -0,0 +1,66 @@
+# 任务晚间关怀鼓励提醒 — 设计文档
+
+日期:2026-11-29
+能力键:`task.reminder.daily`(晚间分支增强)
+状态:设计定稿(含 builder-check 补充,待实现)
+
+## 1. 意图与 why
+
+用户希望任务提醒中的**晚间那条**从"催办式通知"改为"关怀、鼓励式":汇总当天任务完成情况,并根据完成情况对用户进行鼓励。早上的提醒保持现状不动。
+
+消息通过**微信待办消息 webhook**(已投产的 `WebchatWaitMsgService` / `WebhookNotificationChannel`,channel type=`wechat`)发给用户,按用户手机号定向。不依赖公众号模板消息配置(生产 `wechat:` 凭据为空、`WechatNotificationChannel.isEnabled()` 固定 false)。
+
+## 2. 目标 / 非目标 / 反目标
+
+- 目标:晚间 21:00 提醒 = 当天完成情况汇总 + 四档关怀鼓励 + 微信 webhook 发送 + 默认开启覆盖存量用户;设置页显示与实际发送一致。
+- 非目标:不改早提醒(07:30 清单式提醒、收件人、文案、cron 全部保持);不改 before_deadline/after_timeout 两档;不新增数据库表;不接公众号模板消息。
+- 反目标:早提醒收件人因默认开启而意外扩大;用户没配过设置却收不到晚间鼓励;设置页显示关闭却仍发消息、或一保存就写死 0 关掉;同一天重复发送。
+
+## 3. 约束
+
+- 收件人:`executor_type='parent'` 任务执行人(executorId=users.id),手机号定向(`WebhookNotificationChannel` 已实现)。
+- 幂等:`user_notifications` 当日同 (type, ref_type='task', createdAt) 判重,同一用户同一自然日晚提醒只发一次。
+- 渠道:**不依赖** `notification_templates` 表(无 task_daily_evening 模板 seed);调度器直接组装 `NotificationMessage(userId, TYPE_EVENING, "今日任务总结", content, REF_TYPE, refId, "in_app,wechat")`,遍历 `List<NotificationChannel>` 分发(仿 `TaskCheckinWebhookReminderTask.dispatch()`)。in_app 恒兜底 + wechat webhook。
+- 无任务用户:沿用现有 early return(今日无到期任务不发),鼓励只发给有任务的用户。
+
+## 4. 已定设计决策(用户拍板)
+
+1. **四档鼓励**(按当天到期任务完成率):
+   - 100% → 真诚表扬;≥80%<100% → "就差一点点,已经很厉害";1~79% → 肯定已完成+温和加油;0% → 关怀不指责+邀请明天。
+2. **只改晚提醒**,早提醒清单式文案/收件人/cron 不变。
+3. **拆两个开关**(builder-check 决策 #1):晚提醒用"默认开启"判断(无配置/null daily_enabled → 开启,显式 0 → 关闭);早提醒保留原 `isDailyEnabled`(无配置 → 不发)。两个独立 helper,避免早提醒收件人扩大。
+4. **全栈一致**(builder-check 决策 #2):`getConfig()` 对未配置/null 用户返回 `dailyEnabled=1`;`saveConfig()` 把 null 映射为 1;DTO 默认 1;前端 reminder-config 开关默认开;同步更新 `TaskReminderDailyConfigContractTest` 默认值断言。
+5. **带昵称**:晚间文案开头用 users.nickname(查不到回退"您")。
+6. **微信走 webhook**:晚提醒 channels 固定含 `wechat`,复用已投产 `WebhookNotificationChannel`。
+
+## 5. 文案规格(晚间四档)
+
+变量:`{昵称}`、`{已完成数}`、`{总数}`。
+
+- 100%:`「{昵称}」,今天的任务全都完成了,太棒啦!为你的坚持点赞~`
+- ≥80%<100%:`「{昵称}」,今天完成了大部分任务,就差一点点,已经很厉害啦~`
+- 1~79%:`「{昵称}」,今天完成了 {已完成数}/{总数} 项,每一步都算数,明天继续加油哦~`
+- 0%:`「{昵称}」,今天可能有点忙,没完成任务也没关系,明天我们慢慢来~`
+
+标题:"今日任务总结"。
+
+## 6. 实现要点(留给 builder)
+
+- `TaskDailyReminderScheduledTask`:
+  - `sendEveningSummary()`:汇总沿用现有;`buildEveningContent()` 改四档文案 + 昵称查询(注入 UserMapper,失败回退"您"不阻塞);发送改为直接组装 `NotificationMessage(..., "in_app,wechat")` + `List<NotificationChannel>` 分发(保留/调整 notificationDispatchService 注入以兼容单测)。
+  - 拆开关:`isDailyEnabledEvening()`(晚,默认开)与 `isDailyEnabled()`(早,原逻辑);晚调用前者,早仍调用后者。
+  - `sendMorningReminder()` 整体不动。
+- `TaskReminderConfigService.getConfig()` / `saveConfig()` / 相关 DTO:未配置/null → 1。
+- 迁移:追加幂等迁移把 `task_reminder_config.daily_enabled` 默认值改 1(try-catch 吞异常;代码口径兜底,迁移失败不影响默认开启逻辑)。
+- 前端 `cfc-frontend/pages/reminder-config/index.vue`:开关默认开。
+
+## 7. 验收标准
+
+- 单测:四档文案各一断言(含昵称回退"您");晚提醒 channels 含 wechat(webhook send 被调用);默认开启(无配置用户被处理、显式 0 跳过);早提醒收件人未变(回归);幂等。
+- 全栈单测:`TaskReminderDailyConfigContractTest` 默认 1 断言更新。
+- `mvn test-compile` 通过、相关测试类全绿;前端构建通过。
+- 部署:jar + 前端替换、重启、API 健康、ERROR=0。晚提醒真实触发在 21:00(可用测试钩子/手工触发验证文案)。
+
+## 8. builder-check 结论
+
+三处关键歧义已由用户拍板并写入本文档:早晚开关拆分、全栈默认开启一致、无任务用户不发。其余低优先级项(配置读取异常 fail-closed、迁移编号、测试注入方式)由 builder 自行决定。

+ 110 - 0
docs/tdd/orchestration/report-dev-2026-11-29-2253.md

@@ -0,0 +1,110 @@
+# 研发负责人工作汇报(CF 31 分档 · 错峰档收割)
+
+> 档位说明:本档=CF 错峰档(31 分档)。按 SKILL.md 收割骨架执行;**S2 失败补跑由 01 分档标准轮承担,本档跳过**;S3 走精简变体(跳过 `--changes`/`--clean-check`,由标准轮承接);S5/S6 未启用跳过。触发漂移按骨架容忍,触发到即完整跑轮。
+
+## 基本信息
+
+| 项目 | 内容 |
+|------|------|
+| 汇报人 | 研发负责人(自动化收割轮 · software-company 专家团编排) |
+| 汇报周期 | 2026-11-29 22:36 触发 ~ 22:58 收口(第 R597 轮,错峰档) |
+| 负责模块/单元范围 | 全量(scope 空=不限);主线 ref=`origin/cfclub` |
+
+## 一、本轮工作数据汇总
+
+### 1.0 场景覆盖矩阵(硬职责增列)
+
+单一计数源:`docs/tdd/orchestration/sc-key-map.md`(对应 `tests/user-scenarios/应用场景总览.md`)。
+
+| 指标 | 值 | 说明 |
+|------|-----|------|
+| 场景总数 | 243 | sc-key-map 台账(游客12/家长96/孩子26/规划师32/运营27/服务商11/跨角色22/AI教练10/真人管家7) |
+| 累计已跑通 | 27 | 沿承 21 分档口径(O-3 5 + 游客域 10 + P-94/95 2 + C-22/T-06 2 + P-12 1 + C-09/P-77/P-86 3 + 11-27 报告闭环 4) |
+| 本轮新增跑通 | 0 | 本轮无新增三类流执行证据转正 |
+| 失败 | 0 | 无新证伪场景 |
+| 阻塞 | 0 | 实时 blockers 登记 0 |
+| 未跟踪 | 216 | =243−27−0−0−0 |
+
+本轮可转正候选(待测试侧三类流证据,非本轮计入):S-cfc-260 `family.member.update`(RED 提交 05e9da42c/ec6f9df47)、S-cfc-287 `privacy.setting.config`(114fe0e5f)、S-cfc-289 `tongue.emotion.capture`(4ae17f603,SC-P-70)、S-cfc-440 `food.rule.pairingMatrix`(29a3dc985,CR-03 §4.3)——四卡本档 backfill 已认 done,具备实现/用例推远端 + 契约测试执行证据,缺三类流用例级 SC 转正证据。
+
+### 1.1 问题接收与处置
+
+| 指标 | 数量 | 填写说明 |
+|------|------|---------|
+| 收到的测试反馈问题数 | 0 | 实时 blockers 登记 0;TR/O/B 均为历史项(见 1.3 口径) |
+| 已解决问题数 | 4 | backfill 认领 4 卡 RED 契约测试证据闭环(S-cfc-260/287/289/440,证据见上) |
+| 待解决研发问题数 | 0 | 无新增未闭环研发侧问题 |
+
+### 1.2 任务分发与会话管理
+
+| 指标 | 数量 | 填写说明 |
+|------|------|---------|
+| 分派任务数 | 0 | `--auto` 与备用 `--dispatch` 双路径 hang(见 1.3),零 verified 派发(合法情形②) |
+| 恢复智能体会话数 | 1 | mes-local-45278 半途会话 ses_de6706026ffeM25OY5ICJENmdC(mid-work 延续语,S4 实恢复) |
+| 当前在用会话数 | 8 busy / 291 idle | lan-189 busy1、lan-204 busy0、local-lan-4090 busy0、mes-local-45278 busy3、prod-etotem busy2、pub-iwintrue busy2(各 50 会话枚举口径) |
+| 会话平均利用率 | ~2.7% | busy 8/300;受 pending=0 与派发通道 hang 双重压制 |
+
+### 1.2b 各会话当前工作状态列表
+
+| 会话标签 | 会话 ID | 当前状态 | 当前任务 | 静默/空闲时长 | 工作目录 | 备注 |
+|----------|---------|----------|----------|---------------|----------|------|
+| cfc-prod(环境=production) | ses_f719c9326ffeMp0i4xZi6oNFFt | busy | 生产部署会话(anchored) | — | /root/cfc | prod-etotem,默认不派不停 |
+| cfc-test(环境=testing) | ses_e4804838affeBHv6uKhYS4x7o7 | busy | 测试环境会话(anchored) | — | /sc-data/cfc | pub-iwintrue |
+| mes-local-45278 | ses_de6706026ffeM25OY5ICJENmdC | running | 收敛 portal invokeStub 页面(docs/12 口径) | 本档刚恢复 | E:/cfc | S4 实恢复 1 个 |
+| lan-189 / lan-204 / local-lan-4090 / pub-iwintrue 其余 | — | idle | — | — | 各节点目录 | 48~50 idle/节点;配额占用 0~3/上限 |
+| wb-cloud | — | unknown | — | — | — | list_sessions **401**(沿承多轮,P0 交标准轮) |
+
+### 1.3 关键区间数据
+
+| 项 | 值 | 说明 |
+|----|----|------|
+| 状态机 | RED 5 / YELLOW 131 / GREEN 10 / DONE 117 | 263 键无 UNTRACKED 缺口;admin.family.workbenchPolish、contact.card.manage、food.rule.pairingMatrix、privacy.setting.config、tongue.emotion.capture 处 RED(red_by 未回填=台账阶段失真,标准轮域) |
+| 部署在途 | pending 140 / confirmed 80 | testing@0a01a0e8、testing@f6590c89 |
+| 任务账本 | 510 条:done 466 / failed 24 / dispatched 19 / superseded 1 / **pending 0** | backfill 前 done 462/dispatched 23 |
+| 卡龄回收 | 31 条(stale_dispatched_24h_no_evidence → pending) | 沿承 |
+| 各节点配额 | lan-189 剩3(占用1/4)、lan-204 剩4、local-lan-4090 剩6、mes-local 剩3(占用3/6)、prod 剩2(占用2/4)、pub 剩4(占用2/6) | 并发闸门未满 |
+| git 主线 | tip=**c60177e2d**(fix(task) 今日任务列表排除模板行) | fetch OK;预检曾 20s 超时告警(非致命) |
+| 断档告警 | monitor.log 1270.6min / worklog.last_entry 999.5min | 平台触发停摆迹象;S0 建议全量,按档位指令走精简( noted ) |
+
+## 二、执行步骤明细(S0-S11)
+
+| # | 步骤 | 结果 | 备注 |
+|---|------|------|------|
+| S0 | `--reclaim-rubble` | 无残骸;`[gap]` monitor 1270.6min + worklog 999.5min | 无 `[cleaned]`;断档追平建议 vs 档位指令冲突以档位指令为准 |
+| S1 | `--mutex-check` | **PASS** | state mtime 41.6min>mutex5、worklog.active=null、无锁、slot_now=s41/slot_of_active=s51、released_by_other_slot=false |
+| S2 | 失败补跑 | **跳过**(错峰档职责,01 分档标准轮承担) | — |
+| S3 | 精简盘点 | 完成 | `--status --top 12` + `--inspect --role 测试` + `--resume --dry-run` + 近 20 条 git log;**跳过 --changes/--clean-check**(间隔档精简盘点,由标准轮承接) |
+| S3.5 | 稳态承袭 | 未触发 | `steady_state.enabled` 未配置;blockers 实时 0,无承袭对象 |
+| S4 | `--resume` | 实恢复 **1** 个 | mes-local-45278 mid-work 会话;prod-etotem 默认跳过;跳过并发满 0 |
+| S5 | 心跳 tick | **跳过** | `heartbeat.enabled=false`,S5 未启用 |
+| S6 | 填充 fill_capacity | **跳过** | `fill_capacity.enabled=false`,S6 未启用 |
+| S7a | backfill | ✅ 完成 | 批量回填 ~30 键(~17s),done 462→466、dispatched 23→19;S-cfc-456~503 段:爱云医族 456/457/468~478/489、family.invite 481、auth.profile.edit 486、ai.coach.safetyGuard 488、activity.enroll.join 490、shop.review 499/500、food 501/502、S-cfc-503@6ad62ad22ea8 |
+| S7 | `--auto --role 开发 --limit 2` | 🔴 **hang**(400s EXIT=124,零输出,仅预检行) | 连续多轮同症状 |
+| S7 | 备用 `--dispatch --limit 1 --no-generate` | 🔴 **hang**(150s EXIT=124,零输出,fetch 失败告警) | 双路径全挂 |
+| S8 | 池空续建 | **0 建单** | 四类溯源实证:① 未跑通 SC 无键——state.json 263 键无 UNTRACKED 缺口、SC 映射键均已在状态机(走既有键推进,不新建);② --changes/CF-CR —— 本档精简跳过,近 20 条 git log 无新未入池键(CR-03 §4.3 已由 S-cfc-440 闭环);③ TR/O/B —— 实时 blockers 0,TR 均为历史测试侧项,O-26 待裁决属主理人域;④ CI —— 无 open 项(沿承)。**合法零派发情形②**:无 pending 可派且无实际工作溯源可建单 |
+| S9 | 收口纪律 | 单文件临时索引法 | 见 1.4 git 证据段;主工作树 417 处他人 WIP 只报不动 |
+| S10 | 标准汇报 | 本文件 | — |
+| S11 | 通用铁律 | 遵守 | 未伪造证据;他人 WIP 只报不动;无人值守未提问 |
+
+## 三、阻塞与风险(P0/P1)
+
+1. **P0 `--auto`/`--dispatch` hang 复现(连续第 7 轮同症状)**:两路径分别 400s/150s EXIT=124 零输出。账本实证 pending=0(tasks.json 直读 510=done466/fail24/disp19/sup1/pend0)+ 19 条 dispatched 无新证据 + wb-cloud list_sessions 401 → hang 致卡龄回收 requeue 不可达 → stale dispatched 无法回池 → 池恒空且无法派发。**这不是无料,而是派发主流程停摆**。交标准轮排查:wb-cloud 401 凭证/重试、enumerate_sessions 超时、节点连通性、requeue 环节卡点;恢复后池回填、19 条 requeue + 场景优先派发。
+2. **P1 wb-cloud list_sessions 401**:`--inspect` P7-B 持续报错(<html>401 Authorization Required</html>),影响云端会话枚举完整性。
+3. **P1 台账阶段失真沿承**:RED 5 键 red_by 全空(含三键已由测试侧推 RED 契约单测 114fe0e5f/4ae17f603/29a3dc985),阶段与证据登记脱节;标准轮 R596 已报,仍在处置域。
+4. **P2 断档留痕**:monitor.log 1270.6min + worklog 999.5min(平台触发停摆迹象,多轮同因)。
+
+## 四、下一步事项
+
+| 事项 | 依赖 | 预估 |
+|------|------|------|
+| 标准轮排查 `--auto`/`--dispatch` hang 根因(重点:wb-cloud 401 → 会话枚举 → requeue 链路) | 运维/凭证 | 下一标准轮(01 分档) |
+| 19 条 stale dispatched 卡龄回收 requeue 回池 | hang 修复后自然解锁 | 随标准轮 |
+| S-cfc-260/287/289/440 四键 RED 证据的 SC 三类流转正 | 测试侧(正常/异常/权限流用例+执行证据) | 测试负责人侧 |
+| 主工作树 417 处他人 WIP | 不属于本轮职责,只报不动 | — |
+
+## 1.4 git 证据(本轮汇报提交)
+
+- 汇报文件:`docs/tdd/orchestration/report-dev-2026-11-29-2253.md`(本档唯一目标文件,单文件临时索引法入库)
+- 提交方式:`git hash-object -w` → `GIT_INDEX_FILE=<临时> git read-tree origin/cfclub` → `update-index --cacheinfo` → `write-tree` → `commit-tree -p origin/cfclub` → `diff --name-status` 校验仅目标文件 → push → `merge-base --is-ancestor` 核验
+- backfill 引用证据(已推 origin/cfclub):6ad62ad22ea8(S-cfc-503)等 ~30 键,均 `merge-base --is-ancestor` 可验
+- 主线 tip:c60177e2d(收口时以 fetch 后实际 tip 为准)