diff --git a/splitmind/core/splitter.py b/splitmind/core/splitter.py index f875adb..c4bc238 100644 --- a/splitmind/core/splitter.py +++ b/splitmind/core/splitter.py @@ -10,6 +10,8 @@ import json from dataclasses import dataclass, field +from splitmind.core.privacy import PrivacyHandler + class TaskType(str, Enum): ANALYSIS = "analysis" @@ -249,9 +251,12 @@ def __init__( self.max_subtasks = max_subtasks self.semantic_threshold = semantic_threshold + self.privacy_handler = PrivacyHandler() self._sensitive_patterns = self._get_default_patterns() if custom_patterns: - self._sensitive_patterns.extend(custom_patterns) + for idx, pattern in enumerate(custom_patterns): + self._sensitive_patterns[f"custom_{idx}"] = re.compile(pattern, re.IGNORECASE) + self.privacy_handler.add_custom_pattern(f"custom_{idx}", pattern) self._counter = 0 def _get_default_patterns(self) -> Dict[str, re.Pattern]: @@ -272,28 +277,47 @@ def _generate_id(self) -> str: self._counter += 1 return f"subtask_{self._counter:03d}" + def _placeholder_type(self, info_type: str) -> str: + """Normalize PrivacyHandler types for stable SplitMind placeholders.""" + if info_type == "id_card_cn": + return "id_card" + if info_type == "address_cn": + return "address" + return info_type + def detect_sensitive_info(self, text: str) -> Dict[str, List[str]]: - detected = {} - for info_type, pattern in self._sensitive_patterns.items(): - matches = pattern.findall(text) - if matches: - detected[info_type] = list(set(matches)) + """Detect sensitive information using the shared PrivacyHandler source of truth. + + Values are returned in text-position order. Repeated values are preserved + because placeholder mapping must be deterministic by occurrence, not by + a deduplicating set. + """ + detected: Dict[str, List[str]] = {} + for item in sorted(self.privacy_handler.detect(text), key=lambda i: i.position[0]): + info_type = self._placeholder_type(item.info_type) + detected.setdefault(info_type, []).append(item.original_value) return detected def redact_text(self, text: str) -> tuple[str, Dict[str, str]]: if not self.enable_auto_redaction: return text, {} - redacted = text - placeholders = {} + items = sorted(self.privacy_handler.detect(text), key=lambda i: i.position[0]) + counters: Dict[str, int] = {} + placeholders: Dict[str, str] = {} + replacements: List[Tuple[int, int, str]] = [] - sensitive_info = self.detect_sensitive_info(text) + for item in items: + info_type = self._placeholder_type(item.info_type) + idx = counters.get(info_type, 0) + counters[info_type] = idx + 1 + placeholder = f"[REDACTED_{info_type.upper()}_{idx}]" + placeholders[placeholder] = item.original_value + replacements.append((item.position[0], item.position[1], placeholder)) - for info_type, items in sensitive_info.items(): - for idx, item in enumerate(items): - placeholder = f"[REDACTED_{info_type.upper()}_{idx}]" - placeholders[placeholder] = item - redacted = redacted.replace(item, placeholder, 1) + redacted = text + for start, end, placeholder in sorted(replacements, key=lambda r: r[0], reverse=True): + redacted = redacted[:start] + placeholder + redacted[end:] return redacted, placeholders diff --git a/tests/test_core.py b/tests/test_core.py index d862e17..3e643cf 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -99,6 +99,44 @@ def test_calculate_execution_order(self): execution_order = splitter.calculate_execution_order([subtask1, subtask2, subtask3]) assert execution_order == ["1", "2", "3"] + def test_redaction_uses_privacy_handler_without_false_name_cn(self): + """实际子任务脱敏应与 PrivacyHandler 基础类型一致,避免把提示词误判成人名。""" + splitter = TaskSplitter() + task = "请分析客户需求,客户邮箱是 alice@example.com,手机号是 13800138000。" + result = splitter.split(task, strategy="single") + subtask = result.subtasks[0] + + assert "[REDACTED_EMAIL_0]" in subtask.input_data + assert "[REDACTED_PHONE_0]" in subtask.input_data + assert "[REDACTED_NAME_CN_0]" not in subtask.input_data + assert subtask.sensitive_info == { + "[REDACTED_EMAIL_0]": "alice@example.com", + "[REDACTED_PHONE_0]": "13800138000", + } + + def test_redaction_placeholder_order_is_position_stable(self): + """占位符编号应按文本出现位置稳定生成,且重复值按出现次数处理。""" + splitter = TaskSplitter() + text = "先联系 a@example.com,再联系 b@example.com,备用邮箱 a@example.com。" + redacted, mapping = splitter.redact_text(text) + + assert redacted == "先联系 [REDACTED_EMAIL_0],再联系 [REDACTED_EMAIL_1],备用邮箱 [REDACTED_EMAIL_2]。" + assert mapping == { + "[REDACTED_EMAIL_0]": "a@example.com", + "[REDACTED_EMAIL_1]": "b@example.com", + "[REDACTED_EMAIL_2]": "a@example.com", + } + + def test_engine_privacy_report_matches_subtask_redaction_types(self): + """引擎隐私报告和实际子任务映射不应描述两套不同的脱敏行为。""" + engine = SplitMindEngine(config=ExecutionConfig(execution_mode=ExecutionMode.LOCAL_ONLY)) + task = "请分析客户需求,客户邮箱是 alice@example.com,手机号是 13800138000。" + result = engine.execute_sync(task, split_strategy="single") + + subtask = result.split_result.subtasks[0] + assert result.privacy_report["items_by_type"] == {"email": 1, "phone": 1} + assert set(subtask.sensitive_info.keys()) == {"[REDACTED_EMAIL_0]", "[REDACTED_PHONE_0]"} + class TestResultAggregator: """测试结果聚合器功能"""