Преглед изворни кода

feat(health): S-cfc-432 health.plan.medicalRedline - turn red contract tests green

- Java call sites now inject medical_constraints (user diagnoses / current medications
  from health_status) into health_plan_graph request body (callLangGraphPlanData) and
  AiGateway.generateHealthPlan inputs (generateFromSelfCheck).
- Publish gate approveAndPublish now applies section 8.1 redline R1-R4 output audit
  (new MedicalRedlineUtil, fail-closed) and blocks non-compliant plans.
- HealthPlanMedicalRedlineContractTest: 7 tests, 6 failures -> 7 passed.
E2E Test Bot пре 4 дана
родитељ
комит
4df6de0520

+ 89 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/impl/HealthPlanServiceImpl.java

@@ -10,6 +10,7 @@ import com.etotem.cfc.entity.FamilyMember;
 import com.etotem.cfc.entity.FiveDimensionSelfCheck;
 import com.etotem.cfc.entity.HealthPlan;
 import com.etotem.cfc.entity.HealthReport;
+import com.etotem.cfc.entity.HealthStatus;
 import com.etotem.cfc.entity.Product;
 import com.etotem.cfc.entity.Task;
 import com.etotem.cfc.entity.Family;
@@ -20,6 +21,7 @@ import com.etotem.cfc.mapper.FamilyMemberMapper;
 import com.etotem.cfc.mapper.FiveDimensionSelfCheckMapper;
 import com.etotem.cfc.mapper.HealthPlanMapper;
 import com.etotem.cfc.mapper.HealthReportMapper;
+import com.etotem.cfc.mapper.HealthStatusMapper;
 import com.etotem.cfc.mapper.ProductMapper;
 import com.etotem.cfc.mapper.TaskMapper;
 import com.etotem.cfc.mapper.UserMapper;
@@ -30,6 +32,7 @@ import com.etotem.cfc.service.CartService;
 import com.etotem.cfc.service.HealthPlanService;
 import com.etotem.cfc.service.ProductRecommendationService;
 import com.etotem.cfc.service.api.WechatServiceInterface;
+import com.etotem.cfc.util.MedicalRedlineUtil;
 import com.etotem.cfc.util.PlanContentSafetyUtil;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Value;
@@ -84,6 +87,10 @@ public class HealthPlanServiceImpl implements HealthPlanService {
     @Resource
     private HealthReportMapper healthReportMapper;
 
+    /** §三 P1-1 / §8.1:用户已有诊断、在服药物(注入 health_plan_graph 的 medical_constraints) */
+    @Resource
+    private HealthStatusMapper healthStatusMapper;
+
     @Resource
     private DanAssessmentResultMapper danAssessmentResultMapper;
 
@@ -2002,6 +2009,7 @@ public class HealthPlanServiceImpl implements HealthPlanService {
      * SC-T-28 AI 方案内容安全复核(命中即拦截,fail-closed):
      * <ol>
      *   <li>内置敏感词/违规医疗主张检测(基础闸门,无条件执行);</li>
+     *   <li>§八 8.1 医疗红线正则审计({@link MedicalRedlineUtil#matchRedline(String)},R1~R4 命中即拦截);</li>
      *   <li>外部内容安全原语 {@link WechatServiceInterface#checkText(String)} 叠加复核
      *       (可用时执行,true=安全、false=拦截;wechatService 未注入时跳过,不阻碍内置闸门)。</li>
      * </ol>
@@ -2019,6 +2027,11 @@ public class HealthPlanServiceImpl implements HealthPlanService {
         if (hit != null) {
             return "命中违规词「" + hit + "」";
         }
+        // §三 P1-1 + §八 8.1:医疗红线输出正则审计(R1~R4),命中即拦截发布(fail-closed)
+        String redline = MedicalRedlineUtil.matchRedline(text);
+        if (redline != null) {
+            return "命中医疗红线(§8.1 " + redline + ")";
+        }
         if (wechatService != null && !wechatService.checkText(text)) {
             return "第三方内容安全检测未通过";
         }
@@ -2204,6 +2217,8 @@ public class HealthPlanServiceImpl implements HealthPlanService {
             inputs.put("familyId", user.getFamilyId());
             inputs.put("dimensions", String.join(",", lowDims));
             inputs.put("goal", "基于五维自检结果,针对低分维度制定改善计划");
+            // §三 P1-1 / §8.1:Java 调用侧注入用户已有诊断、在服药物,供 prompt 约束
+            inputs.put("medical_constraints", buildMedicalConstraints(userId, null));
             String planContent = aiGateway.generateHealthPlan(inputs);
             if (planContent == null) return null;
             HealthPlan plan = new HealthPlan();
@@ -2315,6 +2330,8 @@ public class HealthPlanServiceImpl implements HealthPlanService {
             body.put("member_ids", memberIds);
             body.put("dimensions", dimensions);
             body.put("goal", goal);
+            // §三 P1-1 / §8.1:Java 调用侧注入用户已有诊断、在服药物,供 health_plan_graph 作 prompt 约束
+            body.put("medical_constraints", buildMedicalConstraints(null, memberIds));
             String url = langgraphBaseUrl + "/api/v1/health/plan/generate";
             ResponseEntity<String> response = restTemplate.postForEntity(url, body, String.class);
             if (response.getBody() != null && response.getStatusCode().is2xxSuccessful()) {
@@ -2329,6 +2346,78 @@ public class HealthPlanServiceImpl implements HealthPlanService {
         return null;
     }
 
+    /**
+     * §三 P1-1 / §8.1:构造调用侧输入字段 {@code medical_constraints}(用户已有诊断、在服药物)。
+     *
+     * <p>数据来源为 {@code health_status.disease_history / medications}(账号级优先,其次首个方案成员);
+     * 任何数据源不可用或读取失败时降级为空列表,保证请求体始终携带该字段(输入契约 fail-closed)。</p>
+     */
+    private Map<String, Object> buildMedicalConstraints(Long userId, String memberIds) {
+        Map<String, Object> constraints = new LinkedHashMap<>();
+        List<String> diagnoses = new ArrayList<>();
+        List<String> medications = new ArrayList<>();
+        StringBuilder notes = new StringBuilder();
+        try {
+            HealthStatus status = null;
+            if (healthStatusMapper != null) {
+                if (userId != null) {
+                    status = healthStatusMapper.selectOne(
+                            new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<HealthStatus>()
+                                    .eq(HealthStatus::getUserId, userId)
+                                    .orderByDesc(HealthStatus::getUpdatedAt)
+                                    .last("LIMIT 1"));
+                }
+                if (status == null && memberIds != null && !memberIds.trim().isEmpty()) {
+                    String first = memberIds.split(",")[0].trim();
+                    if (!first.isEmpty()) {
+                        Long memberId = Long.valueOf(first);
+                        status = healthStatusMapper.selectOne(
+                                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<HealthStatus>()
+                                        .eq(HealthStatus::getMemberId, memberId)
+                                        .orderByDesc(HealthStatus::getUpdatedAt)
+                                        .last("LIMIT 1"));
+                    }
+                }
+            }
+            if (status != null) {
+                diagnoses.addAll(parseMedicalNames(status.getDiseaseHistory()));
+                medications.addAll(parseMedicalNames(status.getMedications()));
+                if (status.getNotes() != null && !status.getNotes().trim().isEmpty()) {
+                    notes.append(status.getNotes().trim());
+                }
+            }
+        } catch (Exception e) {
+            log.warn("读取用户医疗约束失败(降级为空约束): {}", e.getMessage());
+        }
+        constraints.put("diagnoses", diagnoses);
+        constraints.put("medications", medications);
+        constraints.put("notes", notes.toString());
+        return constraints;
+    }
+
+    /** 解析 health_status 中的 [{name,note}] JSON 为名称列表(兼容纯字符串数组),异常返回空列表。 */
+    private List<String> parseMedicalNames(String json) {
+        List<String> names = new ArrayList<>();
+        if (json == null || json.trim().isEmpty()) {
+            return names;
+        }
+        try {
+            JsonNode arr = objectMapper.readTree(json);
+            if (arr != null && arr.isArray()) {
+                for (JsonNode node : arr) {
+                    String name = node.isTextual() ? node.asText()
+                            : (node.has("name") ? node.get("name").asText() : null);
+                    if (name != null && !name.trim().isEmpty() && !names.contains(name.trim())) {
+                        names.add(name.trim());
+                    }
+                }
+            }
+        } catch (Exception e) {
+            log.warn("解析医疗约束JSON失败: {}", e.getMessage());
+        }
+        return names;
+    }
+
     private String buildPlanJsonFromData(JsonNode data) {
         try {
             // 多人方案:原样透传 common + individual 结构(与前端保存的 planJson 一致),

+ 104 - 0
cfc-backend/src/main/java/com/etotem/cfc/util/MedicalRedlineUtil.java

@@ -0,0 +1,104 @@
+package com.etotem.cfc.util;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * 健康计划输出侧医疗红线正则审计(§三 P1-1 / §八 8.1 归因禁区,能力键
+ * {@code health.plan.medicalRedline})。
+ *
+ * <p>fail-closed:方案文本命中任一红线措辞即返回命中说明,发布门禁须据此拒绝发布。
+ * R5「行为判读先排除医学约束」属 Python prompt 约束侧,不在 Java 输出审计范畴。</p>
+ *
+ * <p>四类红线:</p>
+ * <ul>
+ *   <li>R1 器质性诊断只作前提约束,不得写成改善目标;</li>
+ *   <li>R2 处方药不得建议增减或停用,用药只做「请与开方医生确认」;</li>
+ *   <li>R3 12 周内不设不可测目标(骨密度/骨代谢标志物/器质性病变);</li>
+ *   <li>R4 急症信号只做转介,禁写疗效承诺(「见效后…不再发作」)。</li>
+ * </ul>
+ */
+public final class MedicalRedlineUtil {
+
+    /** R1:器质性诊断词 */
+    private static final String ORGANIC =
+            "(?:器质性(?:病变|疾病)?|二尖瓣脱垂|心脏问题|心脏病|冠心病|高血压|糖尿病|肝硬化"
+            + "|肾功能不全|肿瘤|癌症|癫痫|骨质疏松|骨密度降低)";
+    /** R1:把诊断写成改善目标的措辞 */
+    private static final String IMPROVE_GOAL =
+            "(?:随(?:本)?方案(?:改善|好转)|方案(?:改善|见效|好转)|会(?:随方案)?改善"
+            + "|可(?:随方案)?改善|得到改善|改善目标|纳入(?:调理|改善)?目标"
+            + "|作为(?:改善|调理)?目标|随之改善)";
+
+    /** R2:增减/停用处方药的动作词 */
+    private static final String RX_ACTION =
+            "(?:停用|停掉|停服|停止服用|停止使用|减少|减量|降低剂量|增加|增量|加大剂量"
+            + "|加量|自行调整|换用|改用|替代|替换)";
+    /** R2:处方药/在服药物词 */
+    private static final String RX_DRUG =
+            "(?:美托洛尔|处方药|降压药|降糖药|他汀|阿司匹林|二甲双胍|硝苯地平|药物|药剂|用药)";
+
+    /** R3:短期时间窗 */
+    private static final String SHORT_WINDOW =
+            "(?:12\\s*周内|十二周内|3\\s*个月内|半年内|短期内)";
+    /** R3:12 周内不可测指标 */
+    private static final String UNMEASURABLE =
+            "(?:骨密度|骨代谢标志物|骨转换标志物|器质性病变)";
+
+    /** R4:急症信号 */
+    private static final String ACUTE_SIGN =
+            "(?:晕厥|黑便|胸痛|静息心悸|进行性消瘦)";
+    /** R4:疗效承诺措辞 */
+    private static final String GUARANTEE =
+            "(?:不再发作|不会发作|不再出现|不会再发|不会再发作|消失|痊愈)";
+    /** R4:见效前提措辞 */
+    private static final String EFFECTIVE_CLAIM =
+            "(?:见效后|方案见效后|坚持本方案后|调理后|执行本方案后|本方案见效后)";
+
+    private static final Redline[] REDLINES = {
+        new Redline("R1 器质性诊断被写成改善目标", Pattern.compile(
+                ORGANIC + "[^。;,\\n]{0,16}" + IMPROVE_GOAL
+                + "|" + IMPROVE_GOAL + "[^。;,\\n]{0,16}" + ORGANIC)),
+        new Redline("R2 建议增减或停用处方药", Pattern.compile(
+                RX_ACTION + "[^,。;\\n]{0,14}" + RX_DRUG
+                + "|" + RX_DRUG + "[^,。;\\n]{0,14}" + RX_ACTION)),
+        new Redline("R3 12 周内设立不可测目标", Pattern.compile(
+                SHORT_WINDOW + "[^。;\\n]{0,24}" + UNMEASURABLE
+                + "|" + UNMEASURABLE + "[^。;\\n]{0,24}" + SHORT_WINDOW)),
+        new Redline("R4 急症信号写入疗效承诺", Pattern.compile(
+                EFFECTIVE_CLAIM + "[^。;\\n]{0,16}" + ACUTE_SIGN
+                + "|" + ACUTE_SIGN + "[^。;\\n]{0,16}" + GUARANTEE
+                + "|" + EFFECTIVE_CLAIM + "[^。;\\n]{0,16}" + GUARANTEE))
+    };
+
+    private MedicalRedlineUtil() {}
+
+    /**
+     * 审计方案文本是否命中 §8.1 医疗红线。
+     *
+     * @param text 待审计的方案正文(planContent 或 planJson)
+     * @return 命中说明(含红线编号与实际命中片段);未命中返回 null
+     */
+    public static String matchRedline(String text) {
+        if (text == null || text.trim().isEmpty()) {
+            return null;
+        }
+        for (Redline redline : REDLINES) {
+            Matcher matcher = redline.pattern.matcher(text);
+            if (matcher.find()) {
+                return redline.label + "(命中:" + matcher.group() + ")";
+            }
+        }
+        return null;
+    }
+
+    private static final class Redline {
+        private final String label;
+        private final Pattern pattern;
+
+        private Redline(String label, Pattern pattern) {
+            this.label = label;
+            this.pattern = pattern;
+        }
+    }
+}