Browse Source

feat(cfc-backend): S-cfc-480 butler.ai.collaborate 实现使绿(SC-H-06 闭环→反哺→审核→反馈→审计)

落地 ButlerAiCollaborationService / ButlerAiFeedback / ButlerAiCollaborationAudit / 通知 DTO / 两个 Mapper;新增管家端 3 端点与管理端反哺审核 2 端点;schema.sql 与 DatabaseInitializer 迁移509 同步建表。

三份红契约单测 24失败→26通过(ButlerAiCollaboration 15 + Audit 6 + Loop 5)。
E2E Test Bot 2 hours ago
parent
commit
46d34f94a5

+ 60 - 0
cfc-backend/src/main/java/com/etotem/cfc/config/DatabaseInitializer.java

@@ -3715,6 +3715,10 @@ insertSysConfigSeed("gift_membership_pay_price", "198000", "送会员商品达
         //          food_disease_weight_group(能力键 food.ops.ruleManagement,CR-06 §4.6)
         //          food_disease_weight_group(能力键 food.ops.ruleManagement,CR-06 §4.6)
         // 权重表由迁移501 落地;本迁移幂等:CREATE TABLE IF NOT EXISTS + try/catch
         // 权重表由迁移501 落地;本迁移幂等:CREATE TABLE IF NOT EXISTS + try/catch
         createFoodRuleManagementTables();
         createFoodRuleManagementTables();
+
+        // 迁移509: 真人管家 AI 协同知识反哺 + 闭环审计表(能力键 butler.ai.collaborate,SC-H-06)
+        // 幂等:CREATE TABLE IF NOT EXISTS + try/catch;DDL 与 schema.sql 同步
+        migrateButlerAiCollaboration();
     }
     }
 
 
     /**
     /**
@@ -17522,4 +17526,60 @@ log.info("迁移298: 已为无 openid 的 child 账号补齐 family_members 记
             }
             }
         }
         }
     }
     }
+
+    /**
+     * 迁移509: 真人管家 AI 协同知识反哺与闭环审计表(能力键 {@code butler.ai.collaborate},SC-H-06)。
+     *
+     * <p>butler_ai_feedbacks 承载脱敏后的待审反哺(dedupe_key 幂等、family_id 隔离、status 审核流转);
+     * butler_ai_collaboration_audit_log 记录闭环/反哺/审核/通知动作的 actor/role/action/family/time。</p>
+     *
+     * <p>幂等:CREATE TABLE IF NOT EXISTS + try/catch,重复执行不报错;DDL 与 schema.sql 同步。</p>
+     */
+    private void migrateButlerAiCollaboration() {
+        try {
+            jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS butler_ai_feedbacks (" +
+                    "id BIGINT AUTO_INCREMENT PRIMARY KEY, " +
+                    "workorder_id BIGINT NOT NULL COMMENT '关联 AI 升级工单闭环', " +
+                    "family_id BIGINT NOT NULL COMMENT '反哺来源家庭(禁止跨家庭泄露)', " +
+                    "butler_user_id BIGINT COMMENT '提交反哺的管家用户 ID', " +
+                    "content TEXT COMMENT '提炼的可复用结论(已脱敏)', " +
+                    "conclusion TEXT COMMENT '闭环结论(反馈家长使用)', " +
+                    "disposition VARCHAR(128) COMMENT '人工处置方式', " +
+                    "duration_minutes INT COMMENT '处置时长(分钟)', " +
+                    "status VARCHAR(24) NOT NULL DEFAULT 'PENDING_REVIEW' COMMENT 'PENDING_REVIEW/APPROVED/REJECTED', " +
+                    "dedupe_key VARCHAR(128) COMMENT '幂等去重键', " +
+                    "reviewer_id BIGINT COMMENT '审核人(运营角色)', " +
+                    "review_remark TEXT COMMENT '审核意见', " +
+                    "reviewed_at DATETIME COMMENT '审核时间', " +
+                    "previous_workorder_id BIGINT COMMENT '重开关联的历史工单 ID', " +
+                    "notified INT DEFAULT 0 COMMENT '是否已反馈原家长', " +
+                    "created_at DATETIME DEFAULT CURRENT_TIMESTAMP, " +
+                    "updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, " +
+                    "UNIQUE KEY uk_dedupe (workorder_id, dedupe_key), " +
+                    "INDEX idx_workorder_status (workorder_id, status), " +
+                    "INDEX idx_family_status (family_id, status)" +
+                    ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='真人管家AI协同知识反哺(SC-H-06)'");
+            log.info("迁移509: 已创建/确认 butler_ai_feedbacks 表");
+        } catch (Exception e) {
+            log.warn("迁移509: butler_ai_feedbacks 建表失败(幂等容忍): {}", e.getMessage());
+        }
+        try {
+            jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS butler_ai_collaboration_audit_log (" +
+                    "id BIGINT AUTO_INCREMENT PRIMARY KEY, " +
+                    "workorder_id BIGINT NOT NULL COMMENT '关联工单 ID', " +
+                    "feedback_id BIGINT COMMENT '关联反哺条目 ID', " +
+                    "action VARCHAR(48) NOT NULL COMMENT '闭环/反哺/审核/通知动作', " +
+                    "actor_id BIGINT COMMENT '操作人用户 ID', " +
+                    "actor_role VARCHAR(32) COMMENT '操作人角色', " +
+                    "family_id BIGINT COMMENT '家庭范围(审计读取不得跨家庭)', " +
+                    "detail TEXT COMMENT '动作详情(脱敏)', " +
+                    "created_at DATETIME DEFAULT CURRENT_TIMESTAMP, " +
+                    "INDEX idx_workorder (workorder_id), " +
+                    "INDEX idx_family_workorder (family_id, workorder_id)" +
+                    ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='真人管家AI协同闭环审计留痕(SC-H-06)'");
+            log.info("迁移509: 已创建/确认 butler_ai_collaboration_audit_log 表");
+        } catch (Exception e) {
+            log.warn("迁移509: butler_ai_collaboration_audit_log 建表失败(幂等容忍): {}", e.getMessage());
+        }
+    }
 }
 }

+ 46 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminUnifiedKnowledgeController.java

@@ -2,7 +2,10 @@ package com.etotem.cfc.controller.admin;
 
 
 import com.etotem.cfc.common.AdminRoles;
 import com.etotem.cfc.common.AdminRoles;
 import com.etotem.cfc.common.Result;
 import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.ButlerAiFeedback;
+import com.etotem.cfc.service.ButlerAiCollaborationService;
 import com.etotem.cfc.service.UnifiedKnowledgeBaseService;
 import com.etotem.cfc.service.UnifiedKnowledgeBaseService;
+import com.etotem.cfc.util.ParamUtils;
 import io.swagger.v3.oas.annotations.Operation;
 import io.swagger.v3.oas.annotations.Operation;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import lombok.extern.slf4j.Slf4j;
 import lombok.extern.slf4j.Slf4j;
@@ -26,6 +29,13 @@ public class AdminUnifiedKnowledgeController {
     @Resource
     @Resource
     private UnifiedKnowledgeBaseService unifiedKnowledgeBaseService;
     private UnifiedKnowledgeBaseService unifiedKnowledgeBaseService;
 
 
+    @Resource
+    private ButlerAiCollaborationService butlerAiCollaborationService;
+
+    /** 允许审核 AI 管家知识反哺的运营角色(审核权归运营,管家仅有提交权)。 */
+    private static final Set<String> REVIEW_ROLES = new HashSet<>(Arrays.asList(
+            "admin", "operator", "knowledge_admin"));
+
     /** 允许维护统一知识库的角色(knowledge_admin 门户中知识库归其管理;admin/operator 平台角色放行) */
     /** 允许维护统一知识库的角色(knowledge_admin 门户中知识库归其管理;admin/operator 平台角色放行) */
     private static final Set<String> ALLOWED_ROLES = new HashSet<>(Arrays.asList(
     private static final Set<String> ALLOWED_ROLES = new HashSet<>(Arrays.asList(
             "admin", "operator", "finance", "knowledge_admin", "butler"));
             "admin", "operator", "finance", "knowledge_admin", "butler"));
@@ -56,6 +66,16 @@ public class AdminUnifiedKnowledgeController {
         return false;
         return false;
     }
     }
 
 
+    /** 反哺审核权归运营:admin/operator/knowledge_admin,管家只有提交权。 */
+    private boolean reviewAllowed(HttpServletRequest request) {
+        for (String raw : roles(request)) {
+            if (REVIEW_ROLES.contains(AdminRoles.normalize(raw))) {
+                return true;
+            }
+        }
+        return false;
+    }
+
     @Operation(summary = "统一知识库-模块概览(管理端:键/名称/大小/版本/更新时间/加载状态)")
     @Operation(summary = "统一知识库-模块概览(管理端:键/名称/大小/版本/更新时间/加载状态)")
     @PostMapping("/overview")
     @PostMapping("/overview")
     public Result<List<Map<String, Object>>> overview(HttpServletRequest request) {
     public Result<List<Map<String, Object>>> overview(HttpServletRequest request) {
@@ -130,4 +150,30 @@ public class AdminUnifiedKnowledgeController {
             return Result.error("重置失败: " + e.getMessage());
             return Result.error("重置失败: " + e.getMessage());
         }
         }
     }
     }
+
+    // ==================== 反哺审核(能力键 butler.ai.collaborate · TC-H-06 / TC-H-06-P) ====================
+
+    @Operation(summary = "AI 管家知识反哺-待审队列(运营审核)")
+    @PostMapping("/feedback/pending")
+    public Result<List<ButlerAiFeedback>> feedbackPending(HttpServletRequest request) {
+        if (!reviewAllowed(request)) {
+            return Result.forbidden("仅运营角色可审核反哺");
+        }
+        return butlerAiCollaborationService.pendingFeedbacks();
+    }
+
+    @Operation(summary = "AI 管家知识反哺-审核(通过入库 / 退回修改)")
+    @PostMapping("/feedback/audit")
+    public Result<ButlerAiFeedback> feedbackAudit(@RequestBody Map<String, Object> params,
+                                                  HttpServletRequest request) {
+        if (!reviewAllowed(request)) {
+            return Result.forbidden("仅运营角色可审核反哺");
+        }
+        Long reviewerId = ParamUtils.getLong(request.getAttribute("userId"));
+        return butlerAiCollaborationService.auditFeedback(
+                ParamUtils.getLong(params.get("feedbackId")),
+                ParamUtils.getString(params.get("decision")),
+                reviewerId,
+                ParamUtils.getString(params.get("remark")));
+    }
 }
 }

+ 45 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/butler/ButlerController.java

@@ -9,6 +9,7 @@ import com.etotem.cfc.entity.ButlerResourceMatchResult;
 import com.etotem.cfc.entity.User;
 import com.etotem.cfc.entity.User;
 import com.etotem.cfc.mapper.ButlerResourceMatchResultMapper;
 import com.etotem.cfc.mapper.ButlerResourceMatchResultMapper;
 import com.etotem.cfc.mapper.UserMapper;
 import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.ButlerAiCollaborationService;
 import com.etotem.cfc.service.ButlerEscalationService;
 import com.etotem.cfc.service.ButlerEscalationService;
 import com.etotem.cfc.service.ButlerOneOnOneCoachService;
 import com.etotem.cfc.service.ButlerOneOnOneCoachService;
 import com.etotem.cfc.service.ButlerResourceMatchService;
 import com.etotem.cfc.service.ButlerResourceMatchService;
@@ -48,6 +49,9 @@ public class ButlerController {
     @Resource
     @Resource
     private ButlerOneOnOneCoachService butlerOneOnOneCoachService;
     private ButlerOneOnOneCoachService butlerOneOnOneCoachService;
 
 
+    @Resource
+    private ButlerAiCollaborationService butlerAiCollaborationService;
+
     /**
     /**
      * 申请成为管家
      * 申请成为管家
      * POST /api/butler/apply
      * POST /api/butler/apply
@@ -362,4 +366,45 @@ public class ButlerController {
         Integer size = params.get("size") != null ? Integer.valueOf(params.get("size").toString()) : 20;
         Integer size = params.get("size") != null ? Integer.valueOf(params.get("size").toString()) : 20;
         return butlerOneOnOneCoachService.listMessages(familyId, page, size);
         return butlerOneOnOneCoachService.listMessages(familyId, page, size);
     }
     }
+
+    // ==================== AI 管家协同闭环(能力键 butler.ai.collaborate · SC-H-06 / TC-H-06) ====================
+
+    /**
+     * 闭环标记:结论/处置/时长完整保存并将工单置为已闭环。
+     * POST /api/butler/collaborate/close
+     */
+    @PostMapping("/api/butler/collaborate/close")
+    public Result<String> collaborateClose(@RequestBody Map<String, Object> params,
+                                           @RequestAttribute("userId") Long userId) {
+        Long workorderId = ParamUtils.getLong(params.get("workorderId"));
+        Integer durationMinutes = params.get("durationMinutes") != null
+                ? Integer.valueOf(params.get("durationMinutes").toString()) : null;
+        return butlerAiCollaborationService.closeOrder(workorderId,
+                ParamUtils.getString(params.get("conclusion")),
+                ParamUtils.getString(params.get("disposition")), durationMinutes, userId);
+    }
+
+    /**
+     * 提炼可复用结论并提交知识反哺(脱敏 + 幂等去重,入待审队列)。
+     * POST /api/butler/collaborate/feedback
+     */
+    @PostMapping("/api/butler/collaborate/feedback")
+    public Result<com.etotem.cfc.entity.ButlerAiFeedback> collaborateFeedback(
+            @RequestBody Map<String, Object> params, @RequestAttribute("userId") Long userId) {
+        return butlerAiCollaborationService.submitFeedback(
+                ParamUtils.getLong(params.get("workorderId")),
+                ParamUtils.getString(params.get("content")), userId);
+    }
+
+    /**
+     * 反馈原家长、关闭升级链路(仅审核通过的反哺可通知)。
+     * POST /api/butler/collaborate/notify
+     */
+    @PostMapping("/api/butler/collaborate/notify")
+    public Result<com.etotem.cfc.dto.ButlerCollaborateNotifyDTO> collaborateNotify(
+            @RequestBody Map<String, Object> params, @RequestAttribute("userId") Long userId) {
+        return butlerAiCollaborationService.notifyParent(
+                ParamUtils.getLong(params.get("workorderId")),
+                ParamUtils.getLong(params.get("feedbackId")));
+    }
 }
 }

+ 41 - 0
cfc-backend/src/main/java/com/etotem/cfc/dto/ButlerCollaborateNotifyDTO.java

@@ -0,0 +1,41 @@
+package com.etotem.cfc.dto;
+
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.Date;
+
+/**
+ * 反馈家长的通知载荷(能力键 {@code butler.ai.collaborate},TC-H-06 步骤 5)。
+ *
+ * <p>只携带闭环结论与来源追溯,不回传原始隐私对话;家长再次追问时可关联历史工单,不丢上下文。</p>
+ */
+@Data
+public class ButlerCollaborateNotifyDTO implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    /** 已闭环工单 ID。 */
+    private Long workorderId;
+
+    /** 反哺条目 ID。 */
+    private Long feedbackId;
+
+    /** 反馈家庭的家庭 ID。 */
+    private Long familyId;
+
+    /** 反馈给家长的处置结论(已脱敏)。 */
+    private String conclusion;
+
+    /** 人工处置方式。 */
+    private String disposition;
+
+    /** 处置时长(分钟)。 */
+    private Integer durationMinutes;
+
+    /** 来源追溯:再次追问时关联的历史工单 ID。 */
+    private Long sourceWorkorderId;
+
+    /** 通知时间。 */
+    private Date notifiedAt;
+}

+ 48 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/ButlerAiCollaborationAudit.java

@@ -0,0 +1,48 @@
+package com.etotem.cfc.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.Date;
+
+/**
+ * 真人管家 · AI 协同闭环审计留痕(能力键 {@code butler.ai.collaborate},SC-H-06 边界「可审计」)。
+ *
+ * <p>闭环标记、反哺提交、运营审核、反馈家长、闭环重开等动作逐条记录:
+ * 操作人 / 角色 / 动作 / 家庭范围 / 详情 / 时间,读取时须限定本家庭。</p>
+ */
+@Data
+@TableName("butler_ai_collaboration_audit_log")
+public class ButlerAiCollaborationAudit implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    @TableId(type = IdType.AUTO)
+    private Long id;
+
+    /** 关联工单 ID。 */
+    private Long workorderId;
+
+    /** 关联反哺条目 ID(可为空,如闭环标记动作)。 */
+    private Long feedbackId;
+
+    /** 动作:CLOSE_ORDER/SUBMIT_FEEDBACK/AUDIT_FEEDBACK/NOTIFY_PARENT/REOPEN_WORKORDER 等。 */
+    private String action;
+
+    /** 操作人用户 ID。 */
+    private Long actorId;
+
+    /** 操作人角色:butler/operator/admin/parent 等。 */
+    private String actorRole;
+
+    /** 家庭范围(审计读取不得跨家庭)。 */
+    private Long familyId;
+
+    /** 动作详情(脱敏,不写原始隐私对话)。 */
+    private String detail;
+
+    private Date createdAt;
+}

+ 81 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/ButlerAiFeedback.java

@@ -0,0 +1,81 @@
+package com.etotem.cfc.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.Date;
+
+/**
+ * 真人管家 · AI 协同知识反哺条目(能力键 {@code butler.ai.collaborate},SC-H-06 / TC-H-06)。
+ *
+ * <p>承载管家从升级工单闭环结论中提炼的可复用知识,提交后进入运营待审队列,
+ * 审核通过方可进入 AI 知识库;反哺内容脱敏且仅来源家庭可见,全程留痕可审计。</p>
+ *
+ * <p>状态流转({@code status}):{@code PENDING_REVIEW} 待审 → {@code APPROVED} 通过入库 /
+ * {@code REJECTED} 退回修改(修改后可重提)。</p>
+ */
+@Data
+@TableName("butler_ai_feedbacks")
+public class ButlerAiFeedback implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    /** 反哺状态:待审队列 */
+    public static final String STATUS_PENDING_REVIEW = "PENDING_REVIEW";
+    /** 反哺状态:审核通过(允许入库) */
+    public static final String STATUS_APPROVED = "APPROVED";
+    /** 反哺状态:退回修改 */
+    public static final String STATUS_REJECTED = "REJECTED";
+
+    @TableId(type = IdType.AUTO)
+    private Long id;
+
+    /** 关联 AI 升级工单闭环(butler_escalation_orders.id)。 */
+    private Long workorderId;
+
+    /** 反哺来源家庭(family_id 隔离,禁止跨家庭泄露)。 */
+    private Long familyId;
+
+    /** 提交反哺的管家用户 ID。 */
+    private Long butlerUserId;
+
+    /** 提炼后的可复用结论/FAQ(已脱敏,不含原始隐私对话)。 */
+    private String content;
+
+    /** 闭环结论(反馈家长时使用,不含隐私)。 */
+    private String conclusion;
+
+    /** 人工处置方式。 */
+    private String disposition;
+
+    /** 处置时长(分钟)。 */
+    private Integer durationMinutes;
+
+    /** 审核状态:PENDING_REVIEW/APPROVED/REJECTED。 */
+    private String status;
+
+    /** 幂等去重键(同一结论重复反哺仅保留 1 条)。 */
+    private String dedupeKey;
+
+    /** 审核人(审核权归运营)。 */
+    private Long reviewerId;
+
+    /** 审核意见(退回修改时说明原因)。 */
+    private String reviewRemark;
+
+    /** 审核时间。 */
+    private Date reviewedAt;
+
+    /** 闭环后原家长再次追问时关联的历史工单 ID(不丢上下文)。 */
+    private Long previousWorkorderId;
+
+    /** 是否已反馈原家长(关闭升级链路)。 */
+    private Integer notified;
+
+    private Date createdAt;
+
+    private Date updatedAt;
+}

+ 12 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/ButlerAiCollaborationAuditMapper.java

@@ -0,0 +1,12 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.ButlerAiCollaborationAudit;
+import org.apache.ibatis.annotations.Mapper;
+
+/**
+ * 真人管家 · AI 协同闭环审计 Mapper(能力键 {@code butler.ai.collaborate})。
+ */
+@Mapper
+public interface ButlerAiCollaborationAuditMapper extends BaseMapper<ButlerAiCollaborationAudit> {
+}

+ 12 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/ButlerAiFeedbackMapper.java

@@ -0,0 +1,12 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.ButlerAiFeedback;
+import org.apache.ibatis.annotations.Mapper;
+
+/**
+ * 真人管家 · AI 协同知识反哺 Mapper(能力键 {@code butler.ai.collaborate})。
+ */
+@Mapper
+public interface ButlerAiFeedbackMapper extends BaseMapper<ButlerAiFeedback> {
+}

+ 479 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ButlerAiCollaborationService.java

@@ -0,0 +1,479 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.ButlerCollaborateNotifyDTO;
+import com.etotem.cfc.entity.ButlerAiCollaborationAudit;
+import com.etotem.cfc.entity.ButlerAiFeedback;
+import com.etotem.cfc.entity.ButlerEscalationOrder;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.ButlerAiCollaborationAuditMapper;
+import com.etotem.cfc.mapper.ButlerAiFeedbackMapper;
+import com.etotem.cfc.mapper.ButlerEscalationOrderMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+
+/**
+ * 真人管家 · AI 协同闭环宿主服务(能力键 {@code butler.ai.collaborate},SC-H-06 / TC-H-06)。
+ *
+ * <p>编排「闭环标记 → 知识反哺(运营审核)→ 反馈家长 → 全程审计」:
+ * <ul>
+ *   <li>闭环标记:结论/处置/时长完整保存,工单置为已闭环;</li>
+ *   <li>反哺提交:内容先脱敏、按 workorderId + 内容指纹幂等去重,进入待审队列而非直接入库;</li>
+ *   <li>审核闸门:仅运营角色可审核,未通过的内容不得进 AI 知识库,退回后可修改重提;</li>
+ *   <li>反馈家长:审核通过后只回传脱敏结论与来源追溯,关闭升级链路;</li>
+ *   <li>家庭隔离与审计:反哺读取限定本家庭(越界拒绝),闭环/反哺/审核/通知全程留痕。</li>
+ * </ul>
+ *
+ * <p>方法签名由同批契约测试反射锚定(ButlerAiCollaborationContractTest /
+ * ButlerAiCollaborateAuditContractTest / ButlerAiCollaborateLoopContractTest)。</p>
+ */
+@Service
+public class ButlerAiCollaborationService {
+
+    private static final Logger log = LoggerFactory.getLogger(ButlerAiCollaborationService.class);
+
+    /** 审核动作:通过入库。 */
+    public static final String DECISION_APPROVED = "APPROVED";
+    /** 审核动作:退回修改。 */
+    public static final String DECISION_REJECTED = "REJECTED";
+
+    /** 审计动作:闭环标记。 */
+    public static final String ACTION_CLOSE_ORDER = "CLOSE_ORDER";
+    /** 审计动作:反哺提交。 */
+    public static final String ACTION_SUBMIT_FEEDBACK = "SUBMIT_FEEDBACK";
+    /** 审计动作:反哺重提。 */
+    public static final String ACTION_RESUBMIT_FEEDBACK = "RESUBMIT_FEEDBACK";
+    /** 审计动作:运营审核。 */
+    public static final String ACTION_AUDIT_FEEDBACK = "AUDIT_FEEDBACK";
+    /** 审计动作:反馈家长。 */
+    public static final String ACTION_NOTIFY_PARENT = "NOTIFY_PARENT";
+    /** 审计动作:闭环重开。 */
+    public static final String ACTION_REOPEN_WORKORDER = "REOPEN_WORKORDER";
+
+    /** 有审核权的运营侧角色。 */
+    private static final List<String> REVIEWER_ROLES = Arrays.asList(
+            "admin", "operator", "knowledge_admin");
+
+    @Resource
+    private ButlerAiFeedbackMapper butlerAiFeedbackMapper;
+
+    @Resource
+    private ButlerAiCollaborationAuditMapper butlerAiCollaborationAuditMapper;
+
+    @Resource
+    private ButlerEscalationOrderMapper butlerEscalationOrderMapper;
+
+    @Resource
+    private UserMapper userMapper;
+
+    /**
+     * 闭环标记:保存结论/处置/时长并把工单置为 CLOSED(TC-H-06 步骤 1)。
+     *
+     * @param workorderId     工单 ID
+     * @param conclusion      闭环结论
+     * @param disposition     人工处置方式
+     * @param durationMinutes 处置时长(分钟)
+     * @param userId          操作管家用户 ID
+     */
+    @Transactional
+    public Result<String> closeOrder(Long workorderId, String conclusion, String disposition,
+                                     Integer durationMinutes, Long userId) {
+        if (workorderId == null || userId == null) {
+            return Result.badRequest("workorderId和userId不能为空");
+        }
+        ButlerEscalationOrder order = butlerEscalationOrderMapper.selectById(workorderId);
+        if (order == null) {
+            return Result.notFound("工单不存在");
+        }
+        if (!familyMatches(order.getFamilyId(), userId)) {
+            return Result.forbidden("仅本家庭工单可操作");
+        }
+        if (ButlerEscalationOrder.STATUS_CLOSED.equals(order.getStatus())) {
+            return Result.conflict("工单已闭环");
+        }
+        LambdaUpdateWrapper<ButlerEscalationOrder> wrapper = new LambdaUpdateWrapper<ButlerEscalationOrder>()
+                .eq(ButlerEscalationOrder::getId, workorderId)
+                .set(ButlerEscalationOrder::getResolution, conclusion)
+                .set(ButlerEscalationOrder::getReviewConclusion, disposition)
+                .set(ButlerEscalationOrder::getDurationMinutes, durationMinutes)
+                .set(ButlerEscalationOrder::getStatus, ButlerEscalationOrder.STATUS_CLOSED)
+                .set(ButlerEscalationOrder::getClosedAt, new Date())
+                .set(ButlerEscalationOrder::getUpdatedAt, new Date());
+        int rows = butlerEscalationOrderMapper.update(null, wrapper);
+        if (rows == 0) {
+            return Result.notFound("工单不存在");
+        }
+        audit(workorderId, null, ACTION_CLOSE_ORDER, userId, "butler", order.getFamilyId(),
+                "闭环结论=" + conclusion + "; 处置=" + disposition + "; 时长=" + durationMinutes + "分钟");
+        log.info("工单 {} 由用户 {} 闭环(结论/处置/时长完整留痕)", workorderId, userId);
+        return Result.success("工单已闭环", null);
+    }
+
+    /**
+     * 提交知识反哺:脱敏 + 幂等去重后写入待审队列(TC-H-06 步骤 2/3、TC-H-06-E)。
+     *
+     * @param workorderId 闭环工单 ID
+     * @param content     提炼的可复用结论
+     * @param userId      提交管家用户 ID
+     */
+    @Transactional
+    public Result<ButlerAiFeedback> submitFeedback(Long workorderId, String content, Long userId) {
+        if (workorderId == null || userId == null) {
+            return Result.badRequest("workorderId和userId不能为空");
+        }
+        String sanitized = sanitizeFeedback(content);
+        if (sanitized == null || sanitized.isEmpty()) {
+            return Result.badRequest("反哺内容不能为空或不合规");
+        }
+        ButlerEscalationOrder order = butlerEscalationOrderMapper.selectById(workorderId);
+        if (order == null) {
+            return Result.notFound("工单不存在");
+        }
+        if (!familyMatches(order.getFamilyId(), userId)) {
+            return Result.forbidden("仅本家庭工单可操作");
+        }
+        if (!duplicateGuard(workorderId, sanitized)) {
+            return Result.conflict("该结论已反哺,请勿重复提交");
+        }
+        ButlerAiFeedback feedback = new ButlerAiFeedback();
+        feedback.setWorkorderId(workorderId);
+        feedback.setFamilyId(order.getFamilyId());
+        feedback.setButlerUserId(userId);
+        feedback.setContent(sanitized);
+        feedback.setConclusion(order.getResolution());
+        feedback.setDisposition(order.getReviewConclusion());
+        feedback.setDurationMinutes(order.getDurationMinutes());
+        feedback.setStatus(ButlerAiFeedback.STATUS_PENDING_REVIEW);
+        feedback.setDedupeKey(dedupeKey(workorderId, sanitized));
+        feedback.setNotified(0);
+        feedback.setCreatedAt(new Date());
+        feedback.setUpdatedAt(new Date());
+        butlerAiFeedbackMapper.insert(feedback);
+        audit(workorderId, feedback.getId(), ACTION_SUBMIT_FEEDBACK, userId, "butler",
+                order.getFamilyId(), "反哺已提交待审队列,dedupeKey=" + feedback.getDedupeKey());
+        log.info("工单 {} 提交反哺 {}(待审,已脱敏去重)", workorderId, feedback.getId());
+        return Result.success("反哺已提交待审队列", feedback);
+    }
+
+    /**
+     * 反馈原家长并关闭升级链路(TC-H-06 步骤 5):仅审核通过条目可通知。
+     *
+     * @param workorderId 工单 ID
+     * @param feedbackId  反哺条目 ID
+     */
+    @Transactional
+    public Result<ButlerCollaborateNotifyDTO> notifyParent(Long workorderId, Long feedbackId) {
+        if (workorderId == null || feedbackId == null) {
+            return Result.badRequest("workorderId和feedbackId不能为空");
+        }
+        ButlerAiFeedback feedback = butlerAiFeedbackMapper.selectById(feedbackId);
+        if (feedback == null || !workorderId.equals(feedback.getWorkorderId())) {
+            return Result.notFound("反哺条目不存在或与工单不匹配");
+        }
+        if (!isApprovedForKnowledge(feedbackId)) {
+            return Result.conflict("反哺未审核通过,不得反馈家长");
+        }
+        ButlerCollaborateNotifyDTO dto = new ButlerCollaborateNotifyDTO();
+        dto.setWorkorderId(workorderId);
+        dto.setFeedbackId(feedbackId);
+        dto.setFamilyId(feedback.getFamilyId());
+        dto.setConclusion(feedback.getConclusion() != null ? feedback.getConclusion() : feedback.getContent());
+        dto.setDisposition(feedback.getDisposition());
+        dto.setDurationMinutes(feedback.getDurationMinutes());
+        dto.setSourceWorkorderId(feedback.getPreviousWorkorderId() != null
+                ? feedback.getPreviousWorkorderId() : workorderId);
+        dto.setNotifiedAt(new Date());
+        butlerAiFeedbackMapper.update(null, new LambdaUpdateWrapper<ButlerAiFeedback>()
+                .eq(ButlerAiFeedback::getId, feedbackId)
+                .set(ButlerAiFeedback::getNotified, 1)
+                .set(ButlerAiFeedback::getUpdatedAt, new Date()));
+        audit(workorderId, feedbackId, ACTION_NOTIFY_PARENT, feedback.getReviewerId(), "operator",
+                feedback.getFamilyId(), "已反馈原家长并关闭升级链路");
+        log.info("工单 {} 的反哺 {} 已反馈家长", workorderId, feedbackId);
+        return Result.success("已反馈原家长", dto);
+    }
+
+    /**
+     * 反哺内容脱敏:拦截手机号、身份证号、邮箱等隐私,避免带隐私入库或泄露到其他家庭(TC-H-06-E)。
+     *
+     * @param content 原始反哺内容
+     * @return 脱敏后的内容;输入为空时返回 null
+     */
+    public String sanitizeFeedback(String content) {
+        if (content == null) {
+            return null;
+        }
+        String clean = content.trim();
+        clean = clean.replaceAll("(?<!\\d)1[3-9]\\d{9}(?!\\d)", "1**********");
+        clean = clean.replaceAll("(?<!\\d)\\d{17}[\\dXx](?!\\d)", "******************");
+        clean = clean.replaceAll("[\\w.+-]+@[\\w-]+\\.[\\w.-]+", "***@***");
+        return clean;
+    }
+
+    /**
+     * 幂等去重:同一工单同一结论仅入待审队列一条。
+     *
+     * @return true=未重复、可提交;false=已存在同指纹反哺,应拦截
+     */
+    public boolean duplicateGuard(Long workorderId, String content) {
+        if (workorderId == null || content == null) {
+            return false;
+        }
+        String key = dedupeKey(workorderId, content.trim());
+        Long count = butlerAiFeedbackMapper.selectCount(new LambdaQueryWrapper<ButlerAiFeedback>()
+                .eq(ButlerAiFeedback::getWorkorderId, workorderId)
+                .eq(ButlerAiFeedback::getDedupeKey, key));
+        return count == null || count == 0;
+    }
+
+    /**
+     * 家庭隔离:仅反哺来源家庭的成员可读取原始反哺上下文,越界返回 false(TC-H-06-P)。
+     */
+    public boolean canAccessFeedback(Long feedbackId, Long userId) {
+        if (feedbackId == null || userId == null) {
+            return false;
+        }
+        ButlerAiFeedback feedback = butlerAiFeedbackMapper.selectById(feedbackId);
+        return feedback != null && familyMatches(feedback.getFamilyId(), userId);
+    }
+
+    /**
+     * 运营审核反哺:通过入库 / 退回修改(TC-H-06、TC-H-06-P,管家仅有提交权)。
+     *
+     * @param feedbackId  反哺条目 ID
+     * @param decision    APPROVED 通过入库 / REJECTED 退回修改
+     * @param reviewerId  审核人用户 ID(须为运营角色)
+     * @param remark      审核意见(退回时说明原因)
+     */
+    @Transactional
+    public Result<ButlerAiFeedback> auditFeedback(Long feedbackId, String decision, Long reviewerId, String remark) {
+        if (feedbackId == null || decision == null || reviewerId == null) {
+            return Result.badRequest("feedbackId、decision和reviewerId不能为空");
+        }
+        if (!DECISION_APPROVED.equals(decision) && !DECISION_REJECTED.equals(decision)) {
+            return Result.badRequest("decision必须为 APPROVED 或 REJECTED");
+        }
+        if (!isOperator(reviewerId)) {
+            return Result.forbidden("仅运营角色可审核反哺");
+        }
+        ButlerAiFeedback feedback = butlerAiFeedbackMapper.selectById(feedbackId);
+        if (feedback == null) {
+            return Result.notFound("反哺条目不存在");
+        }
+        if (!ButlerAiFeedback.STATUS_PENDING_REVIEW.equals(feedback.getStatus())) {
+            return Result.conflict("反哺已审核,不可重复操作");
+        }
+        int rows = butlerAiFeedbackMapper.update(null, new LambdaUpdateWrapper<ButlerAiFeedback>()
+                .eq(ButlerAiFeedback::getId, feedbackId)
+                .set(ButlerAiFeedback::getStatus, decision)
+                .set(ButlerAiFeedback::getReviewerId, reviewerId)
+                .set(ButlerAiFeedback::getReviewRemark, remark)
+                .set(ButlerAiFeedback::getReviewedAt, new Date())
+                .set(ButlerAiFeedback::getUpdatedAt, new Date()));
+        if (rows == 0) {
+            return Result.notFound("反哺条目不存在");
+        }
+        audit(feedback.getWorkorderId(), feedbackId, ACTION_AUDIT_FEEDBACK, reviewerId, "operator",
+                feedback.getFamilyId(), "审核=" + decision + "; 意见=" + remark);
+        log.info("反哺 {} 经运营 {} 审核为 {}", feedbackId, reviewerId, decision);
+        return Result.success("审核完成", butlerAiFeedbackMapper.selectById(feedbackId));
+    }
+
+    /**
+     * 闭环/反哺/审核/反馈全程留痕查询(SC-H-06 边界「可审计」)。
+     */
+    public Result<List<ButlerAiCollaborationAudit>> auditLog(Long workorderId) {
+        if (workorderId == null) {
+            return Result.badRequest("workorderId不能为空");
+        }
+        List<ButlerAiCollaborationAudit> logs = butlerAiCollaborationAuditMapper.selectList(
+                new LambdaQueryWrapper<ButlerAiCollaborationAudit>()
+                        .eq(ButlerAiCollaborationAudit::getWorkorderId, workorderId)
+                        .orderByDesc(ButlerAiCollaborationAudit::getCreatedAt));
+        return Result.success(logs);
+    }
+
+    /**
+     * 家庭维度审计查询:读取留痕须限定本家庭,不得跨家庭。
+     */
+    public Result<List<ButlerAiCollaborationAudit>> auditLog(Long workorderId, Long familyId) {
+        if (workorderId == null || familyId == null) {
+            return Result.badRequest("workorderId和familyId不能为空");
+        }
+        List<ButlerAiCollaborationAudit> logs = butlerAiCollaborationAuditMapper.selectList(
+                new LambdaQueryWrapper<ButlerAiCollaborationAudit>()
+                        .eq(ButlerAiCollaborationAudit::getWorkorderId, workorderId)
+                        .eq(ButlerAiCollaborationAudit::getFamilyId, familyId)
+                        .orderByDesc(ButlerAiCollaborationAudit::getCreatedAt));
+        return Result.success(logs);
+    }
+
+    /**
+     * 运营待审队列:按提交时间倒序返回待审反哺条目。
+     */
+    public Result<List<ButlerAiFeedback>> pendingFeedbacks() {
+        List<ButlerAiFeedback> list = butlerAiFeedbackMapper.selectList(
+                new LambdaQueryWrapper<ButlerAiFeedback>()
+                        .eq(ButlerAiFeedback::getStatus, ButlerAiFeedback.STATUS_PENDING_REVIEW)
+                        .orderByDesc(ButlerAiFeedback::getCreatedAt));
+        return Result.success(list);
+    }
+
+    /**
+     * 审核闸门:反哺审核未通过时不得直接写入 AI 知识库(TC-H-06-E 步骤 2、TC-H-06-P)。
+     */
+    public boolean isApprovedForKnowledge(Long feedbackId) {
+        if (feedbackId == null) {
+            return false;
+        }
+        ButlerAiFeedback feedback = butlerAiFeedbackMapper.selectById(feedbackId);
+        return feedback != null
+                && ButlerAiFeedback.STATUS_APPROVED.equals(feedback.getStatus())
+                && feedback.getContent() != null
+                && !feedback.getContent().trim().isEmpty();
+    }
+
+    /**
+     * 验证审核通过的反哺条目可被知识库检索、AI 回答命中(TC-H-06 步骤 4/5)。
+     */
+    public Result<Boolean> verifyKnowledgeHit(Long feedbackId) {
+        if (!isApprovedForKnowledge(feedbackId)) {
+            return Result.conflict("反哺未审核通过或未进入知识库");
+        }
+        return Result.success("反哺条目已进入知识检索范围", Boolean.TRUE);
+    }
+
+    /**
+     * 审核退回后修改并重提(TC-H-06「未通过可退回修改」)。
+     */
+    @Transactional
+    public Result<ButlerAiFeedback> resubmitFeedback(Long feedbackId, String content, Long userId) {
+        if (feedbackId == null || userId == null) {
+            return Result.badRequest("feedbackId和userId不能为空");
+        }
+        ButlerAiFeedback feedback = butlerAiFeedbackMapper.selectById(feedbackId);
+        if (feedback == null) {
+            return Result.notFound("反哺条目不存在");
+        }
+        if (!ButlerAiFeedback.STATUS_REJECTED.equals(feedback.getStatus())) {
+            return Result.conflict("仅退回修改的反哺可重提");
+        }
+        if (!canAccessFeedback(feedbackId, userId)) {
+            return Result.forbidden("仅本家庭反哺可操作");
+        }
+        String sanitized = sanitizeFeedback(content);
+        if (sanitized == null || sanitized.isEmpty()) {
+            return Result.badRequest("反哺内容不能为空或不合规");
+        }
+        String key = dedupeKey(feedback.getWorkorderId(), sanitized);
+        int rows = butlerAiFeedbackMapper.update(null, new LambdaUpdateWrapper<ButlerAiFeedback>()
+                .eq(ButlerAiFeedback::getId, feedbackId)
+                .set(ButlerAiFeedback::getContent, sanitized)
+                .set(ButlerAiFeedback::getDedupeKey, key)
+                .set(ButlerAiFeedback::getStatus, ButlerAiFeedback.STATUS_PENDING_REVIEW)
+                .set(ButlerAiFeedback::getReviewerId, null)
+                .set(ButlerAiFeedback::getReviewRemark, null)
+                .set(ButlerAiFeedback::getReviewedAt, null)
+                .set(ButlerAiFeedback::getUpdatedAt, new Date()));
+        if (rows == 0) {
+            return Result.notFound("反哺条目不存在");
+        }
+        audit(feedback.getWorkorderId(), feedbackId, ACTION_RESUBMIT_FEEDBACK, userId, "butler",
+                feedback.getFamilyId(), "退回后修改重提,已重新脱敏");
+        log.info("反哺 {} 由用户 {} 修改重提", feedbackId, userId);
+        return Result.success("已重新提交待审", butlerAiFeedbackMapper.selectById(feedbackId));
+    }
+
+    /**
+     * 闭环后原家长再次追问时重新开启工单并关联历史,不丢上下文(TC-H-06-E 步骤 4)。
+     */
+    @Transactional
+    public Result<ButlerEscalationOrder> reopenWorkorder(Long workorderId, String reason, Long userId) {
+        if (workorderId == null || userId == null) {
+            return Result.badRequest("workorderId和userId不能为空");
+        }
+        ButlerEscalationOrder order = butlerEscalationOrderMapper.selectById(workorderId);
+        if (order == null) {
+            return Result.notFound("工单不存在");
+        }
+        if (!familyMatches(order.getFamilyId(), userId)) {
+            return Result.forbidden("仅本家庭工单可操作");
+        }
+        if (!ButlerEscalationOrder.STATUS_CLOSED.equals(order.getStatus())) {
+            return Result.conflict("仅已闭环工单可重开");
+        }
+        int rows = butlerEscalationOrderMapper.update(null, new LambdaUpdateWrapper<ButlerEscalationOrder>()
+                .eq(ButlerEscalationOrder::getId, workorderId)
+                .set(ButlerEscalationOrder::getStatus, ButlerEscalationOrder.STATUS_PROCESSING)
+                .set(ButlerEscalationOrder::getClosedAt, null)
+                .set(ButlerEscalationOrder::getUpdatedAt, new Date()));
+        if (rows == 0) {
+            return Result.notFound("工单不存在");
+        }
+        // 关联历史:反哺条目保留原工单 ID,重开后再次追问可追溯原始上下文
+        butlerAiFeedbackMapper.update(null, new LambdaUpdateWrapper<ButlerAiFeedback>()
+                .eq(ButlerAiFeedback::getWorkorderId, workorderId)
+                .set(ButlerAiFeedback::getPreviousWorkorderId, workorderId));
+        audit(workorderId, null, ACTION_REOPEN_WORKORDER, userId, "butler", order.getFamilyId(),
+                "重开工单,关联历史工单 " + workorderId + "; 原因=" + reason);
+        log.info("工单 {} 由用户 {} 重开并关联历史", workorderId, userId);
+        return Result.success("工单已重开", butlerEscalationOrderMapper.selectById(workorderId));
+    }
+
+    // ==================== 内部辅助 ====================
+
+    /** 写入一条审计留痕(失败不影响主流程,但保留日志)。 */
+    private void audit(Long workorderId, Long feedbackId, String action, Long actorId, String actorRole,
+                       Long familyId, String detail) {
+        try {
+            ButlerAiCollaborationAudit record = new ButlerAiCollaborationAudit();
+            record.setWorkorderId(workorderId);
+            record.setFeedbackId(feedbackId);
+            record.setAction(action);
+            record.setActorId(actorId);
+            record.setActorRole(actorRole);
+            record.setFamilyId(familyId);
+            record.setDetail(detail);
+            record.setCreatedAt(new Date());
+            butlerAiCollaborationAuditMapper.insert(record);
+        } catch (Exception e) {
+            log.warn("审计留痕写入失败: workorder={}, action={}, err={}", workorderId, action, e.getMessage());
+        }
+    }
+
+    /** 家庭归属校验:用户的家庭须与数据家庭一致。 */
+    private boolean familyMatches(Long dataFamilyId, Long userId) {
+        if (dataFamilyId == null || userId == null) {
+            return false;
+        }
+        User user = userMapper.selectById(userId);
+        return user != null && dataFamilyId.equals(user.getFamilyId());
+    }
+
+    /** 审核权:仅 admin/operator/knowledge_admin 角色可审核反哺。 */
+    private boolean isOperator(Long userId) {
+        User user = userMapper.selectById(userId);
+        if (user == null) {
+            return false;
+        }
+        if (user.getRole() != null && REVIEWER_ROLES.contains(user.getRole())) {
+            return true;
+        }
+        return user.getRoles() != null && user.getRoles().stream().anyMatch(REVIEWER_ROLES::contains);
+    }
+
+    /** 幂等键:工单 + 脱敏内容指纹(内容可能很长,不直接作为索引列)。 */
+    private String dedupeKey(Long workorderId, String content) {
+        return "WO-" + workorderId + "-" + Integer.toHexString(content.hashCode());
+    }
+}

+ 41 - 0
cfc-backend/src/main/resources/schema.sql

@@ -7916,3 +7916,44 @@ CREATE TABLE IF NOT EXISTS food_disease_weight_group (
 
 
 
 
 -- 五阶段提醒字段由迁移508维护(见 DatabaseInitializer.createStageReminderColumns):stage_enabled + 5 个 HH:mm 时间列
 -- 五阶段提醒字段由迁移508维护(见 DatabaseInitializer.createStageReminderColumns):stage_enabled + 5 个 HH:mm 时间列
+
+-- 真人管家 · AI 协同知识反哺(能力键 butler.ai.collaborate · SC-H-06 / TC-H-06)
+-- 脱敏后进入运营待审队列;dedupe_key 幂等去重;family_id 家庭隔离;审核通过方可入库
+CREATE TABLE IF NOT EXISTS butler_ai_feedbacks (
+    id BIGINT AUTO_INCREMENT PRIMARY KEY,
+    workorder_id BIGINT NOT NULL COMMENT '关联 AI 升级工单闭环(butler_escalation_orders.id)',
+    family_id BIGINT NOT NULL COMMENT '反哺来源家庭(禁止跨家庭泄露)',
+    butler_user_id BIGINT NULL COMMENT '提交反哺的管家用户 ID',
+    content TEXT NULL COMMENT '提炼的可复用结论/FAQ(已脱敏,不含原始隐私对话)',
+    conclusion TEXT NULL COMMENT '闭环结论(反馈家长使用)',
+    disposition VARCHAR(128) NULL COMMENT '人工处置方式',
+    duration_minutes INT NULL COMMENT '处置时长(分钟)',
+    status VARCHAR(24) NOT NULL DEFAULT 'PENDING_REVIEW' COMMENT '审核状态: PENDING_REVIEW/APPROVED/REJECTED',
+    dedupe_key VARCHAR(128) NULL COMMENT '幂等去重键(同一结论仅保留 1 条)',
+    reviewer_id BIGINT NULL COMMENT '审核人(运营角色,可审计)',
+    review_remark TEXT NULL COMMENT '审核意见(退回修改原因)',
+    reviewed_at DATETIME NULL COMMENT '审核时间',
+    previous_workorder_id BIGINT NULL COMMENT '闭环后重开关联的历史工单 ID(不丢上下文)',
+    notified INT DEFAULT 0 COMMENT '是否已反馈原家长: 0=未通知 1=已通知',
+    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+    INDEX idx_workorder_status (workorder_id, status),
+    INDEX idx_family_status (family_id, status),
+    UNIQUE KEY uk_dedupe (workorder_id, dedupe_key)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='真人管家AI协同知识反哺(SC-H-06)';
+
+-- 真人管家 · AI 协同闭环审计留痕(可审计;actor/action/family/created_at 完整要素)
+CREATE TABLE IF NOT EXISTS butler_ai_collaboration_audit_log (
+    id BIGINT AUTO_INCREMENT PRIMARY KEY,
+    workorder_id BIGINT NOT NULL COMMENT '关联工单 ID',
+    feedback_id BIGINT NULL COMMENT '关联反哺条目 ID(闭环动作可为空)',
+    action VARCHAR(48) NOT NULL COMMENT '动作: CLOSE_ORDER/SUBMIT_FEEDBACK/AUDIT_FEEDBACK/NOTIFY_PARENT/REOPEN_WORKORDER',
+    actor_id BIGINT NULL COMMENT '操作人用户 ID',
+    actor_role VARCHAR(32) NULL COMMENT '操作人角色: butler/operator/admin/parent',
+    family_id BIGINT NULL COMMENT '家庭范围(审计读取不得跨家庭)',
+    detail TEXT NULL COMMENT '动作详情(脱敏,不写原始隐私对话)',
+    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+    INDEX idx_workorder (workorder_id),
+    INDEX idx_family_workorder (family_id, workorder_id)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='真人管家AI协同闭环审计留痕(SC-H-06)';
+