比较提交

...

7 提交

共有 21 个文件被更改,包括 1751 次插入 和 18 次删除

查看文件

@ -9141,6 +9141,62 @@
} }
} }
}, },
"p5c_safety_config": {
"description": "P5-C 多模态与输出安全门",
"type": "object",
"hint": "四项均默认关闭。当前仓内没有可验证的宿主 principal 或 opaque invocation 合同;任一项开启后会在对应已确认 sink 处拒绝,直至后续集成提供可验证授权。不要把页面、会话、事件或 JSON 当作授权凭据。",
"items": {
"enable_p5c_raw_image_provider_gate": {
"description": "拒绝私聊原图主模型挂载",
"type": "bool",
"default": false
},
"enable_p5c_group_image_vision_gate": {
"description": "拒绝群图视觉任务与摘要注入",
"type": "bool",
"default": false
},
"enable_p5c_context_image_caption_gate": {
"description": "拒绝上下文图片转写与回填",
"type": "bool",
"default": false
},
"enable_p5c_tool_parameter_gate": {
"description": "拒绝工具参数跨会话发送",
"type": "bool",
"default": false
}
}
},
"p5d_safety_config": {
"description": "P5-D 跨轮安全事件与人工恢复门",
"type": "object",
"hint": "两项均默认关闭。当前没有宿主签发的跨轮 issuer 或 owner capability;启用后仅受控拒绝,不会从事件、会话、页面或 JSON 推导授权。",
"items": {
"enable_p5d_cross_turn_correlation": {
"description": "拒绝跨轮安全事件关联",
"type": "bool",
"default": false
},
"enable_p5d_manual_recovery": {
"description": "拒绝无宿主能力的人工恢复",
"type": "bool",
"default": false
}
}
},
"p4_b_safety_config": {
"description": "P4-B 实效前置隔离门",
"type": "object",
"hint": "默认关闭以保持旧版本兼容。开启后只隔离旧 relationship_score 直写,不启用 P4 实效、禁闭或 owner 命令。",
"items": {
"enable_p4_b_legacy_score_isolation": {
"description": "隔离旧关系分直写",
"type": "bool",
"default": false
}
}
},
"legacy_compat_config": { "legacy_compat_config": {
"description": "旧版兼容项", "description": "旧版兼容项",
"type": "object", "type": "object",

查看文件

@ -632,6 +632,7 @@ class CoreStoreMixin:
"merge_people", "merge_people",
"split_merged_people", "split_merged_people",
"record_p4_shadow_event", "record_p4_shadow_event",
"record_p4_effect_event",
}: }:
return {"ok": False, "code": "unsupported_lifecycle_operation"} return {"ok": False, "code": "unsupported_lifecycle_operation"}
result = operation(*args, **kwargs) result = operation(*args, **kwargs)

查看文件

@ -19,6 +19,7 @@ except ImportError:
from astrbot.api.provider import ProviderRequest from astrbot.api.provider import ProviderRequest
from .helpers import _group_link_message_context, _safe_float, _safe_int, _single_line, _strip_internal_message_blocks from .helpers import _group_link_message_context, _safe_float, _safe_int, _single_line, _strip_internal_message_blocks
from .p5c_gate import RAW_IMAGE_PROVIDER_SINK, p5c_gate_allows
class ForwardMessageMixin: class ForwardMessageMixin:
"""Forward-message parsing and prompt-context helpers.""" """Forward-message parsing and prompt-context helpers."""
@ -953,6 +954,8 @@ class ForwardMessageMixin:
return context return context
async def _transcribe_forward_message_images(self, event: AstrMessageEvent, image_sources: list[str]) -> str: async def _transcribe_forward_message_images(self, event: AstrMessageEvent, image_sources: list[str]) -> str:
if not p5c_gate_allows(self, RAW_IMAGE_PROVIDER_SINK):
return ""
if not self.forward_message_image_vision: if not self.forward_message_image_vision:
logger.info("[PrivateCompanion] 合并/引用图片视觉跳过: forward_message_image_vision=false") logger.info("[PrivateCompanion] 合并/引用图片视觉跳过: forward_message_image_vision=false")
return "" return ""
@ -2174,4 +2177,3 @@ class ForwardMessageMixin:
) )
elif should_log_probe: elif should_log_probe:
logger.info("[PrivateCompanion] 合并消息请求未生成上下文: text=%s", message_text or "(empty)") logger.info("[PrivateCompanion] 合并消息请求未生成上下文: text=%s", message_text or "(empty)")

查看文件

@ -30,6 +30,7 @@ from .helpers import (
_strip_internal_message_blocks, _strip_internal_message_blocks,
) )
from .memo_notes import apply_memo_note_action, memo_note_sort_key, normalize_memo_note from .memo_notes import apply_memo_note_action, memo_note_sort_key, normalize_memo_note
from .p5c_gate import P5C_CONTROLLED_DENY_REASON, TOOL_PARAMETER_SINK, p5c_gate_allows
PHOTO_TOOL_SILENT_SENTINEL = "[[PC_PHOTO_SENT_NO_FOLLOWUP]]" PHOTO_TOOL_SILENT_SENTINEL = "[[PC_PHOTO_SENT_NO_FOLLOWUP]]"
@ -2796,6 +2797,8 @@ class LlmToolActionsMixin:
target_id: str, target_id: str,
chain: list[Any], chain: list[Any],
) -> tuple[bool, str, str]: ) -> tuple[bool, str, str]:
if not p5c_gate_allows(self, TOOL_PARAMETER_SINK):
return False, P5C_CONTROLLED_DENY_REASON, ""
errors: list[str] = [] errors: list[str] = []
candidates = self._atrelay_target_umo_candidates(event, message_type, target_id) candidates = self._atrelay_target_umo_candidates(event, message_type, target_id)
if not candidates: if not candidates:
@ -2838,6 +2841,8 @@ class LlmToolActionsMixin:
return False, ";".join(errors[-5:]) or "所有发送链路都失败", candidates[0] return False, ";".join(errors[-5:]) or "所有发送链路都失败", candidates[0]
async def _pc_relay_message_impl(self, event: AstrMessageEvent, **kwargs) -> str: async def _pc_relay_message_impl(self, event: AstrMessageEvent, **kwargs) -> str:
if not p5c_gate_allows(self, TOOL_PARAMETER_SINK):
return json.dumps({"status": "denied", "reason": P5C_CONTROLLED_DENY_REASON}, ensure_ascii=False)
if not self.enable_atrelay_tools: if not self.enable_atrelay_tools:
return json.dumps({"status": "disabled", "message": "跨会话转述工具未启用"}, ensure_ascii=False) return json.dumps({"status": "disabled", "message": "跨会话转述工具未启用"}, ensure_ascii=False)
# 统一入口也要先鉴权,否则非主人调用会先跑一次改写 LLM 才在底层被拒。 # 统一入口也要先鉴权,否则非主人调用会先跑一次改写 LLM 才在底层被拒。
@ -3081,6 +3086,8 @@ class LlmToolActionsMixin:
) )
async def _pc_send_to_group_impl(self, event: AstrMessageEvent, **kwargs) -> str: async def _pc_send_to_group_impl(self, event: AstrMessageEvent, **kwargs) -> str:
if not p5c_gate_allows(self, TOOL_PARAMETER_SINK):
return P5C_CONTROLLED_DENY_REASON
if not self.enable_atrelay_tools: if not self.enable_atrelay_tools:
return "发送失败:跨群转述工具未启用" return "发送失败:跨群转述工具未启用"
allowed, _requester_id = self._atrelay_tool_authorization(event) allowed, _requester_id = self._atrelay_tool_authorization(event)
@ -3160,6 +3167,8 @@ class LlmToolActionsMixin:
return f"消息已发送到群 {target_group}" + (f", 已 @ {at_label or at_qq}" if at_qq else "") return f"消息已发送到群 {target_group}" + (f", 已 @ {at_label or at_qq}" if at_qq else "")
async def _pc_send_to_private_user_impl(self, event: AstrMessageEvent, **kwargs) -> str: async def _pc_send_to_private_user_impl(self, event: AstrMessageEvent, **kwargs) -> str:
if not p5c_gate_allows(self, TOOL_PARAMETER_SINK):
return P5C_CONTROLLED_DENY_REASON
if not self.enable_atrelay_tools: if not self.enable_atrelay_tools:
return "发送失败:跨群转述工具未启用" return "发送失败:跨群转述工具未启用"
allowed, _requester_id = self._atrelay_tool_authorization(event) allowed, _requester_id = self._atrelay_tool_authorization(event)
@ -3231,6 +3240,8 @@ class LlmToolActionsMixin:
return f"已向 {target_user} 发送私聊消息" + (",会等待对方回复后带回回执" if need_receipt else "") return f"已向 {target_user} 发送私聊消息" + (",会等待对方回复后带回回执" if need_receipt else "")
async def _pc_send_to_groups_impl(self, event: AstrMessageEvent, **kwargs) -> str: async def _pc_send_to_groups_impl(self, event: AstrMessageEvent, **kwargs) -> str:
if not p5c_gate_allows(self, TOOL_PARAMETER_SINK):
return P5C_CONTROLLED_DENY_REASON
group_ids = kwargs.get("group_ids") or kwargs.get("groups") or kwargs.get("group_id") or kwargs.get("targets") or "" group_ids = kwargs.get("group_ids") or kwargs.get("groups") or kwargs.get("group_id") or kwargs.get("targets") or ""
message = kwargs.get("message") or kwargs.get("text") or kwargs.get("content") or kwargs.get("msg") or "" message = kwargs.get("message") or kwargs.get("text") or kwargs.get("content") or kwargs.get("msg") or ""
at_user = kwargs.get("at_user") or kwargs.get("at") or kwargs.get("target_user") or kwargs.get("user_id") or "" at_user = kwargs.get("at_user") or kwargs.get("at") or kwargs.get("target_user") or kwargs.get("user_id") or ""
@ -3253,6 +3264,8 @@ class LlmToolActionsMixin:
return "多群通知完成:\n" + "\n".join(results[: self.atrelay_multi_target_limit]) return "多群通知完成:\n" + "\n".join(results[: self.atrelay_multi_target_limit])
async def _pc_send_to_private_users_impl(self, event: AstrMessageEvent, **kwargs) -> str: async def _pc_send_to_private_users_impl(self, event: AstrMessageEvent, **kwargs) -> str:
if not p5c_gate_allows(self, TOOL_PARAMETER_SINK):
return P5C_CONTROLLED_DENY_REASON
user_ids = kwargs.get("user_ids") or kwargs.get("users") or kwargs.get("user_id") or kwargs.get("targets") or "" user_ids = kwargs.get("user_ids") or kwargs.get("users") or kwargs.get("user_id") or kwargs.get("targets") or ""
message = kwargs.get("message") or kwargs.get("text") or kwargs.get("content") or kwargs.get("msg") or "" message = kwargs.get("message") or kwargs.get("text") or kwargs.get("content") or kwargs.get("msg") or ""
relay_mode = kwargs.get("relay_mode") or kwargs.get("mode") or "" relay_mode = kwargs.get("relay_mode") or kwargs.get("mode") or ""
@ -3277,6 +3290,8 @@ class LlmToolActionsMixin:
return "多人转述完成:\n" + "\n".join(results[: self.atrelay_multi_target_limit]) return "多人转述完成:\n" + "\n".join(results[: self.atrelay_multi_target_limit])
async def _pc_schedule_group_relay_impl(self, event: AstrMessageEvent, **kwargs) -> str: async def _pc_schedule_group_relay_impl(self, event: AstrMessageEvent, **kwargs) -> str:
if not p5c_gate_allows(self, TOOL_PARAMETER_SINK):
return P5C_CONTROLLED_DENY_REASON
if not self.enable_atrelay_tools: if not self.enable_atrelay_tools:
return "挂起失败:跨群转述工具未启用" return "挂起失败:跨群转述工具未启用"
allowed, _requester_id = self._atrelay_tool_authorization(event) allowed, _requester_id = self._atrelay_tool_authorization(event)

103
main.py
查看文件

@ -139,6 +139,9 @@ from .context_orchestration import (
) )
from .p5_ingress_firewall import evaluate_ingress_segments from .p5_ingress_firewall import evaluate_ingress_segments
from .p5_provenance_attestation import FIREWALL_STATUSES, P5AttestationRegistry from .p5_provenance_attestation import FIREWALL_STATUSES, P5AttestationRegistry
from .p5c_gate import RAW_IMAGE_PROVIDER_SINK, p5c_gate_allows
from .p5d_security_events import p5d_security_event_allows
from .p6_readonly_projection import build_p6_readonly_status
from .segmented_message import flatten_component_chunks, split_plain_component_chain_detailed from .segmented_message import flatten_component_chunks, split_plain_component_chain_detailed
from .token_budget import TokenBudgetMixin from .token_budget import TokenBudgetMixin
from .balance_awareness import BalanceAwarenessMixin from .balance_awareness import BalanceAwarenessMixin
@ -279,6 +282,13 @@ class PrivateCompanionExtensionAPI:
def get_unified_person_registry_status(self) -> dict[str, Any]: def get_unified_person_registry_status(self) -> dict[str, Any]:
return self._plugin._unified_person_registry_status() return self._plugin._unified_person_registry_status()
def get_p6_readonly_status(self) -> dict[str, Any]:
"""Expose P6-A counts only; it has no mutation or authority surface."""
try:
return build_p6_readonly_status(self._plugin._unified_person_registry_status())
except Exception:
return build_p6_readonly_status(None)
def get_unified_person_audit_events(self, *, limit: int = 100) -> list[dict[str, Any]]: def get_unified_person_audit_events(self, *, limit: int = 100) -> list[dict[str, Any]]:
return self._plugin._unified_person_audit_events(limit=limit) return self._plugin._unified_person_audit_events(limit=limit)
@ -1931,6 +1941,10 @@ class PrivateCompanionPlugin(
# separate audit ledger, but it never changes a live score, reply, # separate audit ledger, but it never changes a live score, reply,
# ignore gate, or management-command outcome. # ignore gate, or management-command outcome.
self.enable_p4_shadow_observer = self._cfg_bool(c, "enable_p4_shadow_observer", False) self.enable_p4_shadow_observer = self._cfg_bool(c, "enable_p4_shadow_observer", False)
# This compatibility isolation does not enable P4-B. It only stops
# legacy direct score writes while the separate effect ledger is
# prepared and remains default-off for rollback compatibility.
self.enable_p4_b_legacy_score_isolation = self._cfg_bool(c, "enable_p4_b_legacy_score_isolation", False)
# P5-A only observes source metadata. It never rewrites a prompt, # P5-A only observes source metadata. It never rewrites a prompt,
# changes a live tool set, or changes retrieval/response behaviour. # changes a live tool set, or changes retrieval/response behaviour.
self.enable_p5_source_observer = self._cfg_bool(c, "enable_p5_source_observer", False) self.enable_p5_source_observer = self._cfg_bool(c, "enable_p5_source_observer", False)
@ -1951,6 +1965,17 @@ class PrivateCompanionPlugin(
self.enable_p5_b1_private_reply_vision_gate = self._cfg_bool( self.enable_p5_b1_private_reply_vision_gate = self._cfg_bool(
c, "enable_p5_b1_private_reply_vision_gate", False c, "enable_p5_b1_private_reply_vision_gate", False
) )
# P5-C confirms these real sinks but the host currently exposes no
# opaque invocation contract for them. Each is therefore default-off
# and deny-only while enabled; no mutable carrier can authorize it.
self.enable_p5c_raw_image_provider_gate = self._cfg_bool(c, "enable_p5c_raw_image_provider_gate", False)
self.enable_p5c_group_image_vision_gate = self._cfg_bool(c, "enable_p5c_group_image_vision_gate", False)
self.enable_p5c_context_image_caption_gate = self._cfg_bool(c, "enable_p5c_context_image_caption_gate", False)
self.enable_p5c_tool_parameter_gate = self._cfg_bool(c, "enable_p5c_tool_parameter_gate", False)
# P5-D has no host-verified owner capability or cross-turn issuer
# contract. These default-off flags therefore remain reject-only.
self.enable_p5d_cross_turn_correlation = self._cfg_bool(c, "enable_p5d_cross_turn_correlation", False)
self.enable_p5d_manual_recovery = self._cfg_bool(c, "enable_p5d_manual_recovery", False)
self.memory_companion_context_timeout_seconds = self._cfg_float(c, "memory_companion_context_timeout_seconds", 1.2, 0.2) self.memory_companion_context_timeout_seconds = self._cfg_float(c, "memory_companion_context_timeout_seconds", 1.2, 0.2)
self.enable_memory_companion_emotional_drift = self._cfg_bool(c, "enable_memory_companion_emotional_drift", True) self.enable_memory_companion_emotional_drift = self._cfg_bool(c, "enable_memory_companion_emotional_drift", True)
self.enable_memory_companion_cross_window_emotion = self._cfg_bool(c, "enable_memory_companion_cross_window_emotion", True) self.enable_memory_companion_cross_window_emotion = self._cfg_bool(c, "enable_memory_companion_cross_window_emotion", True)
@ -8137,10 +8162,10 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
user["reply_count"] = _safe_int(user.get("reply_count"), 0) + 1 user["reply_count"] = _safe_int(user.get("reply_count"), 0) + 1
self._note_action_reply_feedback( self._note_action_reply_feedback(
user, user,
str(user.get("last_proactive_action") or "message"), str(user.get("last_proactive_action") or "message"),
text, text,
) )
user["relationship_score"] = _safe_int(user.get("relationship_score"), 0) + 2 self._p4_b_apply_legacy_relationship_delta(user, 2, reason_code="proactive_reply")
user["awaiting_reply_since"] = 0 user["awaiting_reply_since"] = 0
user["last_reply_at"] = received_ts user["last_reply_at"] = received_ts
user["last_private_reply_at"] = received_ts user["last_private_reply_at"] = received_ts
@ -9302,7 +9327,15 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
buffered_image_vision = contextual_vision buffered_image_vision = contextual_vision
if buffered_images: if buffered_images:
direct_image_mounted = False direct_image_mounted = False
if buffered_image_mode == "direct" and self._event_main_provider_supports_image(event) and not buffered_images_include_gif: # The same gate protects every path that could put an original
# image source into the ProviderRequest, including text fallback.
raw_image_provider_allowed = self._p5c_gate_allows(RAW_IMAGE_PROVIDER_SINK)
if (
buffered_image_mode == "direct"
and self._event_main_provider_supports_image(event)
and not buffered_images_include_gif
and raw_image_provider_allowed
):
image_refs: list[str] = [] image_refs: list[str] = []
for image_ref in buffered_images[:5]: for image_ref in buffered_images[:5]:
for request_ref in self._private_image_sources_for_astrbot_request([image_ref]): for request_ref in self._private_image_sources_for_astrbot_request([image_ref]):
@ -9405,8 +9438,8 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
"image.fallback", "image.fallback",
"【本轮延迟图片】\n" "【本轮延迟图片】\n"
f"{image_context_intro}图片已暂存,但暂无可靠视觉摘要;" f"{image_context_intro}图片已暂存,但暂无可靠视觉摘要;"
"如果用户问图片内容,请自然说暂时没看清,不要编造画面。\n" "如果用户问图片内容,请自然说暂时没看清,不要编造画面。"
+ "\n".join(f"- {path}" for path in buffered_images), + ("\n" + "\n".join(f"- {path}" for path in buffered_images) if raw_image_provider_allowed else ""),
priority=55, priority=55,
source="private_image", source="private_image",
) )
@ -9856,6 +9889,44 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
return bool(getattr(self, "enable_p5_b1_private_reply_vision_gate", False)) return bool(getattr(self, "enable_p5_b1_private_reply_vision_gate", False))
return False return False
def _p5c_gate_allows(self, sink: str) -> bool:
"""Deny an enabled P5-C sink without treating carriers as authority."""
return p5c_gate_allows(self, sink)
def _p5d_security_event_allows(self, operation: str, *opaque: Any) -> bool:
"""Expose the P5-D reject-only boundary without creating a live hook."""
return p5d_security_event_allows(self, operation, *opaque)
def _p4_b_apply_legacy_relationship_delta(
self,
user: Any,
delta: int,
*,
reason_code: str,
) -> bool:
"""Apply one old score mutation unless P4-B compatibility isolation is on.
This narrow seam does not inspect or record person IDs, messages,
events, carriers, or authorization values. It can only suppress an
existing direct score write; it cannot create a P4 effect or command
exemption.
"""
if not isinstance(user, dict) or type(delta) is not int or not isinstance(reason_code, str):
return False
if bool(getattr(self, "enable_p4_b_legacy_score_isolation", False)):
try:
audit = getattr(self, "_p4_b_legacy_score_isolation_audit", None)
if not isinstance(audit, list):
audit = []
setattr(self, "_p4_b_legacy_score_isolation_audit", audit)
audit.append({"reason_code": reason_code, "delta": delta, "outcome": "isolated"})
del audit[:-64]
except Exception:
pass
return False
user["relationship_score"] = _safe_int(user.get("relationship_score"), 0) + delta
return True
def _p5_b1c_runtime_attestation_inputs( def _p5_b1c_runtime_attestation_inputs(
self, self,
event: AstrMessageEvent, event: AstrMessageEvent,
@ -11756,7 +11827,7 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
) )
rest_silence_applied = self._apply_user_rest_silence_from_message(fast_user, safe_text or text, now=received_ts) rest_silence_applied = self._apply_user_rest_silence_from_message(fast_user, safe_text or text, now=received_ts)
fast_user["inbound_count"] = _safe_int(fast_user.get("inbound_count"), 0) + 1 fast_user["inbound_count"] = _safe_int(fast_user.get("inbound_count"), 0) + 1
fast_user["relationship_score"] = _safe_int(fast_user.get("relationship_score"), 0) + 1 self._p4_b_apply_legacy_relationship_delta(fast_user, 1, reason_code="fast_inbound")
fast_user["episode_message_count"] = _safe_int(fast_user.get("episode_message_count"), 0, 0) + 1 fast_user["episode_message_count"] = _safe_int(fast_user.get("episode_message_count"), 0, 0) + 1
if _safe_float(fast_user.get("awaiting_reply_since"), 0) > 0: if _safe_float(fast_user.get("awaiting_reply_since"), 0) > 0:
fast_user["reply_count"] = _safe_int(fast_user.get("reply_count"), 0) + 1 fast_user["reply_count"] = _safe_int(fast_user.get("reply_count"), 0) + 1
@ -11765,7 +11836,7 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
str(fast_user.get("last_proactive_action") or "message"), str(fast_user.get("last_proactive_action") or "message"),
text, text,
) )
fast_user["relationship_score"] = _safe_int(fast_user.get("relationship_score"), 0) + 2 self._p4_b_apply_legacy_relationship_delta(fast_user, 2, reason_code="fast_proactive_reply")
fast_user["awaiting_reply_since"] = 0 fast_user["awaiting_reply_since"] = 0
fast_user["last_reply_at"] = received_ts fast_user["last_reply_at"] = received_ts
fast_user["last_private_reply_at"] = received_ts fast_user["last_private_reply_at"] = received_ts
@ -11778,7 +11849,7 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
if fast_user_is_owner: if fast_user_is_owner:
self._handle_meal_care_inbound(fast_user, safe_text or text, now=received_ts) self._handle_meal_care_inbound(fast_user, safe_text or text, now=received_ts)
if fast_user_is_owner and self._apply_interaction_warmth_to_state(text, fast_user): if fast_user_is_owner and self._apply_interaction_warmth_to_state(text, fast_user):
fast_user["relationship_score"] = _safe_int(fast_user.get("relationship_score"), 0) + 1 self._p4_b_apply_legacy_relationship_delta(fast_user, 1, reason_code="fast_interaction_warmth")
self._schedule_data_save() self._schedule_data_save()
if ( if (
rest_silence_applied rest_silence_applied
@ -12090,7 +12161,7 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
self._note_morning_greeting_reply(user, now=received_ts or _now_ts()) self._note_morning_greeting_reply(user, now=received_ts or _now_ts())
if text: if text:
user["inbound_count"] = _safe_int(user.get("inbound_count"), 0) + 1 user["inbound_count"] = _safe_int(user.get("inbound_count"), 0) + 1
user["relationship_score"] = _safe_int(user.get("relationship_score"), 0) + 1 self._p4_b_apply_legacy_relationship_delta(user, 1, reason_code="inbound")
suspended = user.get("suspended_proactive") suspended = user.get("suspended_proactive")
if ( if (
isinstance(suspended, dict) isinstance(suspended, dict)
@ -12110,7 +12181,7 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
str(user.get("last_proactive_action") or "message"), str(user.get("last_proactive_action") or "message"),
text, text,
) )
user["relationship_score"] = _safe_int(user.get("relationship_score"), 0) + 2 self._p4_b_apply_legacy_relationship_delta(user, 2, reason_code="proactive_reply")
user["awaiting_reply_since"] = 0 user["awaiting_reply_since"] = 0
user["last_reply_at"] = _now_ts() user["last_reply_at"] = _now_ts()
user["last_private_reply_at"] = user["last_reply_at"] user["last_private_reply_at"] = user["last_reply_at"]
@ -12220,10 +12291,10 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
} }
care_feedback_applied = bool(text) and user_is_owner and self._apply_care_feedback_to_state(text) care_feedback_applied = bool(text) and user_is_owner and self._apply_care_feedback_to_state(text)
if care_feedback_applied: if care_feedback_applied:
user["relationship_score"] = _safe_int(user.get("relationship_score"), 0) + 2 self._p4_b_apply_legacy_relationship_delta(user, 2, reason_code="care_feedback")
interaction_warmth_applied = bool(text) and is_target_user and user_is_owner and self._apply_interaction_warmth_to_state(text, user) interaction_warmth_applied = bool(text) and is_target_user and user_is_owner and self._apply_interaction_warmth_to_state(text, user)
if interaction_warmth_applied: if interaction_warmth_applied:
user["relationship_score"] = _safe_int(user.get("relationship_score"), 0) + 1 self._p4_b_apply_legacy_relationship_delta(user, 1, reason_code="interaction_warmth")
schedule_adjustment_applied = ( schedule_adjustment_applied = (
bool(text) bool(text)
and is_target_user and is_target_user
@ -12231,9 +12302,9 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
and self._record_schedule_adjustment_from_interaction(text, user) and self._record_schedule_adjustment_from_interaction(text, user)
) )
if schedule_adjustment_applied: if schedule_adjustment_applied:
user["relationship_score"] = _safe_int(user.get("relationship_score"), 0) + 1 self._p4_b_apply_legacy_relationship_delta(user, 1, reason_code="schedule_adjustment")
if food_feedback_applied: if food_feedback_applied:
user["relationship_score"] = _safe_int(user.get("relationship_score"), 0) + 1 self._p4_b_apply_legacy_relationship_delta(user, 1, reason_code="food_feedback")
response = "" response = ""
if is_target_user: if is_target_user:

28
p4_b1b_guards.py 普通文件
查看文件

@ -0,0 +1,28 @@
# -*- coding: utf-8 -*-
"""Reject-only placeholders for unavailable P4-B1b live-effect authorities."""
HOST_OWNER_CAPABILITY_UNAVAILABLE_CODE = "p4_b1b_host_owner_capability_unavailable"
REVIEW_PRODUCER_UNAVAILABLE_CODE = "p4_b1b_review_producer_unavailable"
def reject_unverified_owner_capability(claim: object = None) -> dict[str, object]:
"""Deny every proposed host-owner capability without reading the claim."""
del claim
return {
"accepted": False,
"live_effect_permitted": False,
"code": HOST_OWNER_CAPABILITY_UNAVAILABLE_CODE,
}
def reject_unverified_review_producer(candidate: object = None) -> dict[str, object]:
"""Deny every proposed review producer without reading the candidate."""
del candidate
return {
"accepted": False,
"live_effect_permitted": False,
"code": REVIEW_PRODUCER_UNAVAILABLE_CODE,
}

77
p5c_gate.py 普通文件
查看文件

@ -0,0 +1,77 @@
"""P5-C default-off, deny-only guards for confirmed Companion sinks.
This plugin does not receive a host-issued opaque invocation for raw media,
background group vision, context-image captioning, or LLM tool parameters.
Consequently an enabled P5-C flag can only deny its matching sink. No event,
P3 carrier, session, dict, JSON payload, or P5-B handle is ever inspected as
an allow credential.
"""
from __future__ import annotations
import hashlib
import logging
from typing import Any
logger = logging.getLogger("PrivateCompanion.P5C")
RAW_IMAGE_PROVIDER_SINK = "raw_image_provider"
GROUP_IMAGE_VISION_SINK = "group_image_vision"
CONTEXT_IMAGE_CAPTION_SINK = "context_image_caption"
TOOL_PARAMETER_SINK = "tool_parameter"
P5C_CONTROLLED_DENY_REASON = "p5c_host_opaque_invocation_unavailable"
P5C_SINK_FLAGS = {
RAW_IMAGE_PROVIDER_SINK: "enable_p5c_raw_image_provider_gate",
GROUP_IMAGE_VISION_SINK: "enable_p5c_group_image_vision_gate",
CONTEXT_IMAGE_CAPTION_SINK: "enable_p5c_context_image_caption_gate",
TOOL_PARAMETER_SINK: "enable_p5c_tool_parameter_gate",
}
def p5c_gate_allows(host: Any, sink: str) -> bool:
"""Return false only for an enabled, confirmed P5-C sink.
The audit projection is derived solely from the static sink name. It
deliberately avoids reading any event, request, source, media, tool
parameter, provider payload, or caller-provided identity object.
"""
flag = P5C_SINK_FLAGS.get(sink)
if not flag:
raise ValueError("p5c_unknown_sink")
try:
enabled = bool(getattr(host, flag, False))
except Exception:
enabled = True
if not enabled:
return True
audit = {
"sink": sink,
"outcome": "denied",
"reason_code": P5C_CONTROLLED_DENY_REASON,
"ref_hash": hashlib.sha256(f"p5c:{sink}".encode("utf-8")).hexdigest(),
}
try:
entries = getattr(host, "_p5c_denial_audit", None)
if not isinstance(entries, list):
entries = []
setattr(host, "_p5c_denial_audit", entries)
entries.append(audit)
del entries[:-64]
except Exception:
pass
logger.warning("[PrivateCompanion][P5-C] gate=%s", audit)
return False
__all__ = [
"CONTEXT_IMAGE_CAPTION_SINK",
"GROUP_IMAGE_VISION_SINK",
"P5C_CONTROLLED_DENY_REASON",
"P5C_SINK_FLAGS",
"RAW_IMAGE_PROVIDER_SINK",
"TOOL_PARAMETER_SINK",
"p5c_gate_allows",
]

68
p5d_security_events.py 普通文件
查看文件

@ -0,0 +1,68 @@
"""P5-D default-off, reject-only security-event boundary.
This plugin has no host-issued, owner-verified cross-turn capability. P5-A
projections, P5-B request handles, P5-C deny audits, P3 carriers, P4 shadow
state, events, sessions, mappings, and page payloads are not substitutes.
Accordingly, an enabled P5-D operation has exactly one outcome: deny.
"""
from __future__ import annotations
import hashlib
import logging
from typing import Any
logger = logging.getLogger("PrivateCompanion.P5D")
CROSS_TURN_CORRELATION_OPERATION = "cross_turn_correlation"
MANUAL_RECOVERY_OPERATION = "manual_recovery"
P5D_HOST_OWNER_CAPABILITY_UNAVAILABLE = "p5d_host_owner_capability_unavailable"
P5D_OPERATION_FLAGS = {
CROSS_TURN_CORRELATION_OPERATION: "enable_p5d_cross_turn_correlation",
MANUAL_RECOVERY_OPERATION: "enable_p5d_manual_recovery",
}
def p5d_security_event_allows(host: Any, operation: str, *opaque: Any) -> bool:
"""Bypass only while disabled; never derive allow from caller objects."""
# Do not inspect, serialize, compare, store, or log caller values. They
# are the future host contract's responsibility, not local credentials.
del opaque
flag = P5D_OPERATION_FLAGS.get(operation)
if not flag:
raise ValueError("p5d_unknown_operation")
try:
enabled = bool(getattr(host, flag, False))
except Exception:
enabled = True
if not enabled:
return True
audit = {
"operation": operation,
"outcome": "denied",
"reason_code": P5D_HOST_OWNER_CAPABILITY_UNAVAILABLE,
"ref_hash": hashlib.sha256(f"p5d:{operation}".encode("utf-8")).hexdigest(),
}
try:
entries = getattr(host, "_p5d_denial_audit", None)
if not isinstance(entries, list):
entries = []
setattr(host, "_p5d_denial_audit", entries)
entries.append(audit)
del entries[:-64]
except Exception:
pass
logger.warning("[PrivateCompanion][P5-D] gate=%s", audit)
return False
__all__ = [
"CROSS_TURN_CORRELATION_OPERATION",
"MANUAL_RECOVERY_OPERATION",
"P5D_HOST_OWNER_CAPABILITY_UNAVAILABLE",
"P5D_OPERATION_FLAGS",
"p5d_security_event_allows",
]

124
p6_four_package_manifest.py 普通文件
查看文件

@ -0,0 +1,124 @@
"""Pure validation for the P6 four-package manifest contract."""
import hashlib
import json
import re
FOUR_PACKAGE_MANIFEST_SCHEMA = "ops.p6.four_package_manifest.v1"
FOUR_PACKAGE_MANIFEST_REPORT_SCHEMA = "ops.p6.four_package_manifest_report.v1"
FOUR_PACKAGE_IDS = ("companion", "memory", "ops_archive", "peiban")
_REQUIRED_MANIFEST_FIELDS = (
"schema",
"package_id",
"manifest_version",
"package_fingerprint",
"compatibility_fingerprint",
)
_MANIFEST_VERSION_PATTERN = re.compile(r"^[1-9]\d*\.[0-9]+$")
_SHA256_PATTERN = re.compile(r"^[0-9a-f]{64}$")
def _contract_payload() -> dict[str, object]:
return {
"schema": FOUR_PACKAGE_MANIFEST_SCHEMA,
"report_schema": FOUR_PACKAGE_MANIFEST_REPORT_SCHEMA,
"package_ids": list(FOUR_PACKAGE_IDS),
"required_manifest_fields": list(_REQUIRED_MANIFEST_FIELDS),
}
def manifest_contract() -> dict[str, object]:
"""Return a fresh descriptor for the value-only manifest contract."""
descriptor = _contract_payload()
canonical_payload = json.dumps(
descriptor,
ensure_ascii=True,
sort_keys=True,
separators=(",", ":"),
).encode("utf-8")
descriptor["contract_fingerprint"] = hashlib.sha256(canonical_payload).hexdigest()
return descriptor
def _unverifiable_report(reason_code: str) -> dict[str, object]:
return {
"schema": FOUR_PACKAGE_MANIFEST_REPORT_SCHEMA,
"status": "unverifiable",
"reason_code": reason_code,
"expected_package_ids": list(FOUR_PACKAGE_IDS),
}
def _verified_report() -> dict[str, object]:
return {
"schema": FOUR_PACKAGE_MANIFEST_REPORT_SCHEMA,
"status": "verified",
"reason_code": "four_package_manifest_verified",
"expected_package_ids": list(FOUR_PACKAGE_IDS),
}
def verify_four_package_manifests(manifests: object) -> dict[str, object]:
"""Verify only the supplied in-memory four-package manifest values."""
if type(manifests) is not dict:
return _unverifiable_report("manifest_collection_not_exact_dict")
for package_id in manifests:
if type(package_id) is not str or package_id not in FOUR_PACKAGE_IDS:
return _unverifiable_report("unexpected_package_manifest")
for package_id in FOUR_PACKAGE_IDS:
if package_id not in manifests:
return _unverifiable_report("missing_package_manifest")
common_compatibility_fingerprint = None
for package_id in FOUR_PACKAGE_IDS:
package_manifest = manifests[package_id]
if type(package_manifest) is not dict:
return _unverifiable_report("package_manifest_not_exact_dict")
for field_name in package_manifest:
if type(field_name) is not str or field_name not in _REQUIRED_MANIFEST_FIELDS:
return _unverifiable_report("unexpected_manifest_field")
for field_name in _REQUIRED_MANIFEST_FIELDS:
if field_name not in package_manifest:
return _unverifiable_report("missing_manifest_field")
schema = package_manifest["schema"]
if type(schema) is not str or schema != FOUR_PACKAGE_MANIFEST_SCHEMA:
return _unverifiable_report("manifest_schema_mismatch")
declared_package_id = package_manifest["package_id"]
if type(declared_package_id) is not str or declared_package_id != package_id:
return _unverifiable_report("manifest_package_id_mismatch")
manifest_version = package_manifest["manifest_version"]
if (
type(manifest_version) is not str
or _MANIFEST_VERSION_PATTERN.fullmatch(manifest_version) is None
):
return _unverifiable_report("manifest_version_invalid")
package_fingerprint = package_manifest["package_fingerprint"]
if (
type(package_fingerprint) is not str
or _SHA256_PATTERN.fullmatch(package_fingerprint) is None
):
return _unverifiable_report("package_fingerprint_invalid")
compatibility_fingerprint = package_manifest["compatibility_fingerprint"]
if (
type(compatibility_fingerprint) is not str
or _SHA256_PATTERN.fullmatch(compatibility_fingerprint) is None
):
return _unverifiable_report("compatibility_fingerprint_invalid")
if common_compatibility_fingerprint is None:
common_compatibility_fingerprint = compatibility_fingerprint
elif compatibility_fingerprint != common_compatibility_fingerprint:
return _unverifiable_report("compatibility_fingerprint_mismatch")
return _verified_report()

51
p6_readonly_projection.py 普通文件
查看文件

@ -0,0 +1,51 @@
"""P6-A minimal read-only status projection for the Companion authority."""
from __future__ import annotations
import hashlib
import json
from typing import Any
P6_READONLY_STATUS_SCHEMA = "ops.p6.read_only_status.v1"
_STATUS_FIELDS = ("profiles", "identity_links", "audit_events", "operations")
_HEALTH = frozenset({"ready", "degraded", "unverifiable"})
def _fingerprint() -> str:
payload = {"schema_version": P6_READONLY_STATUS_SCHEMA, "count_fields": _STATUS_FIELDS}
encoded = json.dumps(payload, ensure_ascii=True, separators=(",", ":"), sort_keys=True).encode("utf-8")
return hashlib.sha256(encoded).hexdigest()
P6_READONLY_STATUS_FINGERPRINT = _fingerprint()
def _count(value: Any) -> int:
return value if type(value) is int and 0 <= value <= 10_000_000 else 0
def build_p6_readonly_status(status: Any, *, health: str = "ready", reason_code: str = "") -> dict[str, Any]:
"""Project only bounded counts and a static health reason.
The input may be a registry status object but no profile, identity, P4
event, audit body, carrier, capability, or authorization is returned.
"""
# `isinstance` can invoke an untrusted object's ``__class__`` hook; P6-A
# accepts only a concrete internal dict and otherwise fails closed.
source = status if type(status) is dict else {}
normalized_health = health if health in _HEALTH else "unverifiable"
normalized_reason = reason_code if isinstance(reason_code, str) and len(reason_code) <= 80 else "invalid_reason_code"
if type(status) is not dict:
normalized_health = "unverifiable"
normalized_reason = "registry_status_unavailable"
return {
"schema_version": P6_READONLY_STATUS_SCHEMA,
"source_plugin": "private_companion",
"contract_fingerprint": P6_READONLY_STATUS_FINGERPRINT,
"health": normalized_health,
"reason_code": normalized_reason,
"counts": {field: _count(source.get(field)) for field in _STATUS_FIELDS},
}
__all__ = ["P6_READONLY_STATUS_SCHEMA", "P6_READONLY_STATUS_FINGERPRINT", "build_p6_readonly_status"]

查看文件

@ -30,6 +30,7 @@ from astrbot.core.astr_main_agent import MainAgentBuildConfig, build_main_agent
from astrbot.core.utils.astrbot_path import get_astrbot_data_path from astrbot.core.utils.astrbot_path import get_astrbot_data_path
from .helpers import _missing_optional_model_dependency, _now_ts, _safe_float, _safe_int, _single_line, _strip_internal_message_blocks, _today_key, _url_host_is_public from .helpers import _missing_optional_model_dependency, _now_ts, _safe_float, _safe_int, _single_line, _strip_internal_message_blocks, _today_key, _url_host_is_public
from .p5c_gate import CONTEXT_IMAGE_CAPTION_SINK, GROUP_IMAGE_VISION_SINK, RAW_IMAGE_PROVIDER_SINK, p5c_gate_allows
from .segmented_message import split_plain_component_chain from .segmented_message import split_plain_component_chain
# 识图临时文件的存活上限。单次识图(含重试与多 provider 回退)远低于这个数量级, # 识图临时文件的存活上限。单次识图(含重试与多 provider 回退)远低于这个数量级,
@ -2336,6 +2337,9 @@ class PrivateImageMixin:
namespace: str = "private_vision", namespace: str = "private_vision",
) -> str: ) -> str:
clean_cache_scope = _single_line(cache_scope, 40) clean_cache_scope = _single_line(cache_scope, 40)
p5c_sink = GROUP_IMAGE_VISION_SINK if clean_cache_scope == "group_image" else RAW_IMAGE_PROVIDER_SINK
if not p5c_gate_allows(self, p5c_sink):
return ""
clean_task_name = _single_line(task_name, 80) or "private_image_vision" clean_task_name = _single_line(task_name, 80) or "private_image_vision"
clean_log_subject = _single_line(log_subject, 40) or "图片" clean_log_subject = _single_line(log_subject, 40) or "图片"
clean_namespace = _single_line(namespace, 60) or "vision" clean_namespace = _single_line(namespace, 60) or "vision"
@ -2813,6 +2817,8 @@ class PrivateImageMixin:
sender_id: str = "", sender_id: str = "",
text: str = "", text: str = "",
) -> asyncio.Task | None: ) -> asyncio.Task | None:
if not p5c_gate_allows(self, GROUP_IMAGE_VISION_SINK):
return None
if not bool(getattr(self, "enable_group_image_understanding", False)): if not bool(getattr(self, "enable_group_image_understanding", False)):
return None return None
group_id = _single_line(group_id, 80) group_id = _single_line(group_id, 80)
@ -2976,6 +2982,10 @@ class PrivateImageMixin:
event: AstrMessageEvent, event: AstrMessageEvent,
req: ProviderRequest, req: ProviderRequest,
) -> bool: ) -> bool:
# A completed background task has no host-issued invocation grant.
# Enforce again before it can be copied into the ProviderRequest.
if not p5c_gate_allows(self, GROUP_IMAGE_VISION_SINK):
return False
summary = await self._await_group_image_understanding_for_request(event) summary = await self._await_group_image_understanding_for_request(event)
if not summary: if not summary:
return False return False
@ -3266,6 +3276,10 @@ class PrivateImageMixin:
return None return None
async def _caption_context_image_sources(self, sources: list[str], *, umo: str = "") -> str: async def _caption_context_image_sources(self, sources: list[str], *, umo: str = "") -> str:
# Keep the provider boundary protected if a future caller bypasses
# `_enrich_request_context_image_placeholders`.
if not p5c_gate_allows(self, CONTEXT_IMAGE_CAPTION_SINK):
return ""
clean_sources = [str(item).strip() for item in sources if str(item or "").strip()][:5] clean_sources = [str(item).strip() for item in sources if str(item or "").strip()][:5]
if not clean_sources: if not clean_sources:
return "" return ""
@ -3283,6 +3297,8 @@ class PrivateImageMixin:
return "" return ""
async def _enrich_request_context_image_placeholders(self, event: AstrMessageEvent, req: ProviderRequest) -> dict[str, int]: async def _enrich_request_context_image_placeholders(self, event: AstrMessageEvent, req: ProviderRequest) -> dict[str, int]:
if not p5c_gate_allows(self, CONTEXT_IMAGE_CAPTION_SINK):
return {"contexts": 0, "replaced": 0, "missed": 0}
if not bool(getattr(self, "enable_context_image_captioning", True)): if not bool(getattr(self, "enable_context_image_captioning", True)):
return {"contexts": 0, "replaced": 0, "missed": 0} return {"contexts": 0, "replaced": 0, "missed": 0}
contexts = getattr(req, "contexts", None) contexts = getattr(req, "contexts", None)
@ -4316,6 +4332,8 @@ class PrivateImageMixin:
user_id: str, user_id: str,
buffer: dict[str, Any], buffer: dict[str, Any],
) -> None: ) -> None:
if not p5c_gate_allows(self, RAW_IMAGE_PROVIDER_SINK):
return
feature_checker = getattr(self, "_feature_enabled_or_temp_unlocked", None) feature_checker = getattr(self, "_feature_enabled_or_temp_unlocked", None)
feature_enabled = ( feature_enabled = (
feature_checker("enable_private_image_self_recognition") feature_checker("enable_private_image_self_recognition")

146
tests/test_p4_b1b_guards.py 普通文件
查看文件

@ -0,0 +1,146 @@
# -*- coding: utf-8 -*-
"""Contract tests for the P4-B1b reject-only guard boundary."""
import ast
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
import p4_b1b_guards as guards
from p4_b1b_guards import (
HOST_OWNER_CAPABILITY_UNAVAILABLE_CODE,
REVIEW_PRODUCER_UNAVAILABLE_CODE,
reject_unverified_owner_capability,
reject_unverified_review_producer,
)
from unified_person_contract import empty_unified_person_store
from unified_person_registry import UnifiedPersonRegistry
class _PoisonClaim:
"""Raises if a guard tries to observe it through common Python protocols."""
def __getattribute__(self, name: str) -> object:
raise AssertionError(f"unexpected attribute access: {name}")
def __getitem__(self, key: object) -> object:
raise AssertionError(f"unexpected mapping access: {key}")
def __iter__(self) -> object:
raise AssertionError("unexpected iteration")
def __len__(self) -> int:
raise AssertionError("unexpected length access")
def __bool__(self) -> bool:
raise AssertionError("unexpected truthiness access")
def __repr__(self) -> str:
raise AssertionError("unexpected repr access")
class P4B1bGuardTests(unittest.TestCase):
def test_owner_capability_is_always_denied_with_the_stable_code(self) -> None:
result = reject_unverified_owner_capability()
self.assertEqual(
result,
{
"accepted": False,
"live_effect_permitted": False,
"code": "p4_b1b_host_owner_capability_unavailable",
},
)
self.assertEqual(HOST_OWNER_CAPABILITY_UNAVAILABLE_CODE, result["code"])
def test_review_producer_is_always_denied_with_the_stable_code(self) -> None:
result = reject_unverified_review_producer()
self.assertEqual(
result,
{
"accepted": False,
"live_effect_permitted": False,
"code": "p4_b1b_review_producer_unavailable",
},
)
self.assertEqual(REVIEW_PRODUCER_UNAVAILABLE_CODE, result["code"])
def test_poison_claims_are_discarded_without_observation(self) -> None:
self.assertFalse(reject_unverified_owner_capability(_PoisonClaim())["accepted"])
self.assertFalse(reject_unverified_review_producer(_PoisonClaim())["accepted"])
def test_forged_dicts_never_enable_a_live_effect(self) -> None:
forged_claim = {
"accepted": True,
"live_effect_permitted": True,
"owner": True,
"review_producer": "trusted",
"code": "allow_everything",
}
for guard, code in (
(reject_unverified_owner_capability, HOST_OWNER_CAPABILITY_UNAVAILABLE_CODE),
(reject_unverified_review_producer, REVIEW_PRODUCER_UNAVAILABLE_CODE),
):
with self.subTest(guard=guard.__name__):
result = guard(forged_claim)
self.assertEqual(
result,
{
"accepted": False,
"live_effect_permitted": False,
"code": code,
},
)
def test_every_call_returns_an_independent_plain_dict(self) -> None:
first = reject_unverified_owner_capability()
second = reject_unverified_owner_capability()
review = reject_unverified_review_producer()
self.assertIsInstance(first, dict)
self.assertIsInstance(review, dict)
self.assertIsNot(first, second)
self.assertIsNot(first, review)
first["accepted"] = True
first["code"] = "forged"
self.assertEqual(False, second["accepted"])
self.assertEqual(HOST_OWNER_CAPABILITY_UNAVAILABLE_CODE, second["code"])
self.assertEqual(
REVIEW_PRODUCER_UNAVAILABLE_CODE,
reject_unverified_review_producer()["code"],
)
def test_module_has_no_import_or_call_integration_surface(self) -> None:
source = Path(guards.__file__).read_text(encoding="utf-8")
tree = ast.parse(source)
imports = [
node
for node in ast.walk(tree)
if isinstance(node, (ast.Import, ast.ImportFrom))
]
calls = [node for node in ast.walk(tree) if isinstance(node, ast.Call)]
self.assertEqual([], imports)
self.assertEqual([], calls)
def test_guard_usage_does_not_create_p4_effect_in_an_isolated_registry_store(self) -> None:
store = {"unified_person": empty_unified_person_store()}
registry = UnifiedPersonRegistry(store)
before = registry.status()
reject_unverified_owner_capability({"owner": "forged"})
reject_unverified_review_producer({"producer": "forged"})
self.assertEqual(before, registry.status())
self.assertNotIn("p4_effect", store["unified_person"])
if __name__ == "__main__":
unittest.main()

查看文件

@ -0,0 +1,125 @@
# -*- coding: utf-8 -*-
"""P4-B preparation ledger remains separate from P4-A and profiles."""
from __future__ import annotations
from copy import deepcopy
import importlib
from pathlib import Path
import sys
import types
import unittest
from unified_person_contract import empty_unified_person_store
from unified_person_registry import UnifiedPersonRegistry
sys.path.insert(0, str(Path(__file__).resolve().parent))
import _host_stub # noqa: E402
_host_stub.install()
PACKAGE = "_p4_b_effect_registry_companion"
if PACKAGE not in sys.modules:
package = types.ModuleType(PACKAGE)
package.__path__ = [str(Path(__file__).resolve().parents[1])]
sys.modules[PACKAGE] = package
core_store_module = importlib.import_module(f"{PACKAGE}.core_store")
def identity(subject_id: str) -> dict[str, str]:
return {
"companion_instance_id": "companion-a",
"bot_account_id": "bot-1",
"adapter_instance_id": "telegram-main",
"subject_namespace": "telegram.user",
"platform_subject_id": subject_id,
}
def normal_event(event_id: str) -> dict[str, str]:
return {"event_id": event_id, "occurred_at": "2026-07-30T00:00:00Z", "kind": "normal"}
class _CoreStoreHost(core_store_module.CoreStoreMixin):
def __init__(self, data: dict) -> None:
self.data = data
self.save_calls = 0
def _schedule_data_save(self) -> None:
self.save_calls += 1
class P4BEffectRegistryTests(unittest.TestCase):
def setUp(self) -> None:
self.store = {"unified_person": empty_unified_person_store()}
self.registry = UnifiedPersonRegistry(self.store)
def _observe(self, subject_id: str) -> str:
result = self.registry.upsert_observed_identity(identity(subject_id), operation_id=f"observe-{subject_id}")
self.assertTrue(result["ok"])
return result["person_id"]
def _record(self, person_id: str, event_id: str, operation_id: str) -> dict:
return self.registry.record_p4_effect_event(person_id, normal_event(event_id), operation_id=operation_id, actor_id="p4-b-test")
def test_effect_ledger_is_additive_and_never_creates_shadow_or_profile_effect(self) -> None:
person_id = self._observe("one")
before_profile = deepcopy(self.store["unified_person"]["profiles"][person_id])
result = self._record(person_id, "p4-effect-1", "effect-operation-1")
self.assertTrue(result["ok"])
self.assertEqual("p4_effect_event_recorded", result["code"])
self.assertNotIn("p4_shadow", self.store["unified_person"])
self.assertEqual(before_profile, self.store["unified_person"]["profiles"][person_id])
entry = self.store["unified_person"]["p4_effect"]["people"][person_id]
self.assertEqual("effect_preparation", entry["state"]["mode"])
self.assertEqual(person_id, entry["events"][0]["origin_person_id"])
def test_effect_event_and_operation_idempotence_are_fail_closed(self) -> None:
person_id = self._observe("two")
first = self._record(person_id, "p4-effect-idempotent", "effect-operation-idempotent")
self.assertTrue(first["ok"])
snapshot = deepcopy(self.store)
repeated = self._record(person_id, "p4-effect-idempotent", "effect-operation-idempotent")
self.assertTrue(repeated["ok"])
self.assertTrue(repeated["idempotent"])
self.assertEqual(snapshot, self.store)
duplicate = self._record(person_id, "p4-effect-idempotent", "effect-operation-duplicate")
self.assertTrue(duplicate["ok"])
self.assertTrue(duplicate["event_duplicate"])
conflict = self.registry.record_p4_effect_event(person_id, {**normal_event("p4-effect-idempotent"), "occurred_at": "2026-07-31T00:00:00Z"}, operation_id="effect-operation-conflict", actor_id="p4-b-test")
self.assertEqual("p4_effect_event_id_conflict", conflict["code"])
def test_merge_replays_origins_and_split_restores_exact_pre_merge_effect_ledgers(self) -> None:
source, target = self._observe("three-source"), self._observe("three-target")
self.assertTrue(self._record(source, "p4-effect-source", "effect-source")["ok"])
self.assertTrue(self._record(target, "p4-effect-target", "effect-target")["ok"])
merged = self.registry.merge_people(source, target, operation_id="merge-effect", actor_id="operator", reason="test", authorized=True)
self.assertTrue(merged["ok"])
merged_read = self.registry.read_p4_effect_state(target)
self.assertTrue(merged_read["ok"])
self.assertEqual(2, merged_read["event_count"])
origins = {item["origin_person_id"] for item in self.store["unified_person"]["p4_effect"]["people"][target]["events"]}
self.assertEqual({source, target}, origins)
split = self.registry.split_merged_people("merge-effect", operation_id="split-effect", actor_id="operator", reason="test", authorized=True)
self.assertTrue(split["ok"])
self.assertEqual(1, self.registry.read_p4_effect_state(source)["event_count"])
self.assertEqual(1, self.registry.read_p4_effect_state(target)["event_count"])
def test_split_rejects_effect_record_added_after_merge(self) -> None:
source, target = self._observe("four-source"), self._observe("four-target")
self.assertTrue(self._record(source, "p4-effect-source-2", "effect-source-2")["ok"])
self.assertTrue(self.registry.merge_people(source, target, operation_id="merge-effect-2", actor_id="operator", reason="test", authorized=True)["ok"])
self.assertTrue(self._record(target, "p4-effect-after-merge", "effect-after-merge")["ok"])
split = self.registry.split_merged_people("merge-effect-2", operation_id="split-effect-2", actor_id="operator", reason="test", authorized=True)
self.assertEqual("p4_effect_split_conflict", split["code"])
def test_core_store_allows_only_the_write_operation(self) -> None:
person_id = self._observe("five")
host = _CoreStoreHost(self.store)
result = host._apply_unified_person_lifecycle("record_p4_effect_event", person_id, normal_event("p4-effect-core"), operation_id="effect-core", actor_id="p4-b-test")
self.assertTrue(result["ok"])
self.assertEqual(1, host.save_calls)
self.assertEqual("unsupported_lifecycle_operation", host._apply_unified_person_lifecycle("read_p4_effect_state", person_id)["code"])
if __name__ == "__main__":
unittest.main()

查看文件

@ -0,0 +1,83 @@
# -*- coding: utf-8 -*-
"""P4-B legacy score isolation is a default-off compatibility seam."""
from __future__ import annotations
import importlib
from pathlib import Path
import sys
from types import SimpleNamespace
import types
import unittest
sys.path.insert(0, str(Path(__file__).resolve().parent))
import _host_stub # noqa: E402
_host_stub.install()
event_module = importlib.import_module("astrbot.api.event")
event_module.filter.EventMessageType = SimpleNamespace(ALL="ALL", PRIVATE_MESSAGE="PRIVATE_MESSAGE", GROUP_MESSAGE="GROUP_MESSAGE")
PACKAGE = "_p4_b_legacy_isolation_companion"
if PACKAGE not in sys.modules:
package = types.ModuleType(PACKAGE)
package.__path__ = [str(Path(__file__).resolve().parents[1])]
sys.modules[PACKAGE] = package
main = importlib.import_module(f"{PACKAGE}.main")
class _Host:
_p4_b_apply_legacy_relationship_delta = main.PrivateCompanionPlugin._p4_b_apply_legacy_relationship_delta
def __init__(self, enabled: bool) -> None:
self.enable_p4_b_legacy_score_isolation = enabled
class P4BLegacyIsolationTests(unittest.TestCase):
def test_default_off_preserves_all_legacy_delta_shapes(self) -> None:
host = _Host(False)
for reason_code, delta in (
("proactive_reply", 2),
("fast_inbound", 1),
("fast_proactive_reply", 2),
("fast_interaction_warmth", 1),
("inbound", 1),
("proactive_reply", 2),
("care_feedback", 2),
("interaction_warmth", 1),
("schedule_adjustment", 1),
("food_feedback", 1),
):
with self.subTest(reason_code=reason_code):
user = {"relationship_score": 7}
self.assertTrue(host._p4_b_apply_legacy_relationship_delta(user, delta, reason_code=reason_code))
self.assertEqual(7 + delta, user["relationship_score"])
def test_enabled_isolation_never_changes_score_or_records_user_content(self) -> None:
host = _Host(True)
user = {"relationship_score": 7, "message": "must not be audited", "user_id": "must not be audited"}
self.assertFalse(host._p4_b_apply_legacy_relationship_delta(user, 2, reason_code="proactive_reply"))
self.assertEqual(7, user["relationship_score"])
self.assertEqual(
[{"reason_code": "proactive_reply", "delta": 2, "outcome": "isolated"}],
host._p4_b_legacy_score_isolation_audit,
)
def test_invalid_inputs_cannot_mutate_or_create_audit(self) -> None:
host = _Host(True)
user = {"relationship_score": 7}
self.assertFalse(host._p4_b_apply_legacy_relationship_delta(user, True, reason_code="bad"))
self.assertFalse(host._p4_b_apply_legacy_relationship_delta(user, 1, reason_code=object()))
self.assertEqual(7, user["relationship_score"])
self.assertFalse(hasattr(host, "_p4_b_legacy_score_isolation_audit"))
def test_all_ten_legacy_direct_writes_use_the_narrow_helper(self) -> None:
source = (Path(__file__).resolve().parents[1] / "main.py").read_text(encoding="utf-8")
# The helper retains the sole legacy assignment for default-off
# compatibility; all ten former call sites must route through it.
self.assertEqual(1, source.count('relationship_score"] = _safe_int'))
self.assertEqual(10, source.count("_p4_b_apply_legacy_relationship_delta(" ) - 1)
if __name__ == "__main__":
unittest.main()

164
tests/test_p5c_gates.py 普通文件
查看文件

@ -0,0 +1,164 @@
# -*- coding: utf-8 -*-
"""Focused proof that enabled P5-C Companion sinks deny before egress."""
from __future__ import annotations
import importlib
import inspect
import json
from pathlib import Path
import sys
from types import SimpleNamespace
import types
import unittest
sys.path.insert(0, str(Path(__file__).resolve().parent))
import _host_stub # noqa: E402
_host_stub.install()
event_module = importlib.import_module("astrbot.api.event")
event_module.filter.EventMessageType = SimpleNamespace(
ALL="ALL", PRIVATE_MESSAGE="PRIVATE_MESSAGE", GROUP_MESSAGE="GROUP_MESSAGE"
)
PACKAGE = "_p5c_gate_companion"
if PACKAGE not in sys.modules:
package = types.ModuleType(PACKAGE)
package.__path__ = [str(Path(__file__).resolve().parents[1])]
sys.modules[PACKAGE] = package
gate = importlib.import_module(f"{PACKAGE}.p5c_gate")
main = importlib.import_module(f"{PACKAGE}.main")
private_image = importlib.import_module(f"{PACKAGE}.private_image")
forward = importlib.import_module(f"{PACKAGE}.forward_message")
tool_actions = importlib.import_module(f"{PACKAGE}.llm_tool_actions")
class _Host:
enable_p5c_raw_image_provider_gate = True
enable_p5c_group_image_vision_gate = True
enable_p5c_context_image_caption_gate = True
enable_p5c_tool_parameter_gate = True
class _ImageHost(_Host):
async def _prepare_private_image_sources_for_model(self, *_args, **_kwargs):
raise AssertionError("enabled raw-image gate must stop before image preparation")
class _ForwardHost(_Host):
forward_message_image_vision = True
async def _prepare_private_image_sources_for_model(self, *_args, **_kwargs):
raise AssertionError("enabled forward-image gate must stop before image preparation")
class _ToolHost(_Host):
def _atrelay_target_umo_candidates(self, *_args, **_kwargs):
raise AssertionError("enabled tool gate must stop before target resolution")
class P5CCompanionGateTests(unittest.IsolatedAsyncioTestCase):
async def test_default_off_does_not_change_paths_and_audit_has_no_carrier_values(self) -> None:
off = SimpleNamespace()
self.assertTrue(gate.p5c_gate_allows(off, gate.RAW_IMAGE_PROVIDER_SINK))
host = _Host()
host.event = "event-secret"
self.assertFalse(gate.p5c_gate_allows(host, gate.RAW_IMAGE_PROVIDER_SINK))
audit = host._p5c_denial_audit[-1]
self.assertEqual(
{"sink", "outcome", "reason_code", "ref_hash"},
set(audit),
)
self.assertNotIn("event-secret", repr(audit))
bound = _Host()
bound._p5c_gate_allows = main.PrivateCompanionPlugin._p5c_gate_allows.__get__(bound, _Host)
self.assertFalse(bound._p5c_gate_allows(gate.TOOL_PARAMETER_SINK))
async def test_enabled_media_sinks_stop_before_prepare_task_and_context_mutation(self) -> None:
image_host = _ImageHost()
result = await private_image.PrivateImageMixin._transcribe_private_inbound_images(
image_host, ["https://example.invalid/raw.png"]
)
self.assertEqual("", result)
group_host = _Host()
group_request = SimpleNamespace(system_prompt="unchanged", prompt="")
appended = await private_image.PrivateImageMixin._append_group_image_understanding_to_request(
group_host, SimpleNamespace(), group_request
)
self.assertFalse(appended)
self.assertEqual("unchanged", group_request.system_prompt)
context_host = _Host()
caption = await private_image.PrivateImageMixin._caption_context_image_sources(
context_host, ["https://example.invalid/context.png"]
)
self.assertEqual("", caption)
task = private_image.PrivateImageMixin._start_group_image_understanding(
group_host, SimpleNamespace()
)
self.assertIsNone(task)
request = SimpleNamespace(contexts=["[image placeholder]"])
result = await private_image.PrivateImageMixin._enrich_request_context_image_placeholders(
context_host, SimpleNamespace(), request
)
self.assertEqual({"contexts": 0, "replaced": 0, "missed": 0}, result)
self.assertEqual(["[image placeholder]"], request.contexts)
forward_host = _ForwardHost()
result = await forward.ForwardMessageMixin._transcribe_forward_message_images(
forward_host, SimpleNamespace(), ["https://example.invalid/forward.png"]
)
self.assertEqual("", result)
async def test_enabled_tool_gate_stops_before_target_resolution_and_final_send(self) -> None:
host = _ToolHost()
result = await tool_actions.LlmToolActionsMixin._pc_send_to_group_impl(
host, SimpleNamespace(), message="secret", group_id="123"
)
self.assertEqual(gate.P5C_CONTROLLED_DENY_REASON, result)
ok, reason, used_umo = await tool_actions.LlmToolActionsMixin._send_atrelay_chain_to_target(
host,
SimpleNamespace(),
message_type="group",
target_id="123",
chain=[],
)
self.assertFalse(ok)
self.assertEqual(gate.P5C_CONTROLLED_DENY_REASON, reason)
self.assertEqual("", used_umo)
scheduled = await tool_actions.LlmToolActionsMixin._pc_schedule_group_relay_impl(
host, SimpleNamespace(), message="secret", group_id="123"
)
self.assertEqual(gate.P5C_CONTROLLED_DENY_REASON, scheduled)
async def test_direct_raw_mount_is_gated_before_source_preparation_and_schema_is_default_off(self) -> None:
source = inspect.getsource(main.PrivateCompanionPlugin.inject_humanized_state)
buffered_start = source.index("direct_image_mounted = False")
direct_start = source.index('buffered_image_mode == "direct"', buffered_start)
gate_at = source.index("raw_image_provider_allowed = self._p5c_gate_allows(RAW_IMAGE_PROVIDER_SINK)", buffered_start)
prepare_at = source.index("self._private_image_sources_for_astrbot_request", direct_start)
self.assertLess(gate_at, direct_start)
self.assertLess(gate_at, prepare_at)
fallback_start = source.index('"image.fallback"', direct_start)
fallback_end = source.index('elif bool(getattr(event, "private_companion_deferred_private_image_only_ready"', fallback_start)
fallback = source[fallback_start:fallback_end]
self.assertIn("if raw_image_provider_allowed else \"\"", fallback)
self.assertNotIn('"\\n".join(f"- {path}" for path in buffered_images),', fallback)
schema = json.loads((Path(__file__).resolve().parents[1] / "_conf_schema.json").read_text(encoding="utf-8"))
items = schema["p5c_safety_config"]["items"]
self.assertEqual(set(gate.P5C_SINK_FLAGS.values()), set(items))
self.assertTrue(all(entry["default"] is False for entry in items.values()))
if __name__ == "__main__":
unittest.main()

查看文件

@ -0,0 +1,78 @@
# -*- coding: utf-8 -*-
"""Focused proof that P5-D never treats caller data as a capability."""
from __future__ import annotations
import importlib
import json
from pathlib import Path
import sys
from types import SimpleNamespace
import types
import unittest
sys.path.insert(0, str(Path(__file__).resolve().parent))
import _host_stub # noqa: E402
_host_stub.install()
event_module = importlib.import_module("astrbot.api.event")
event_module.filter.EventMessageType = SimpleNamespace(ALL="ALL", PRIVATE_MESSAGE="PRIVATE_MESSAGE", GROUP_MESSAGE="GROUP_MESSAGE")
PACKAGE = "_p5d_security_events_companion"
if PACKAGE not in sys.modules:
package = types.ModuleType(PACKAGE)
package.__path__ = [str(Path(__file__).resolve().parents[1])]
sys.modules[PACKAGE] = package
gate = importlib.import_module(f"{PACKAGE}.p5d_security_events")
main = importlib.import_module(f"{PACKAGE}.main")
class _EnabledHost:
enable_p5d_cross_turn_correlation = True
enable_p5d_manual_recovery = True
class _Poisoned:
def __getattribute__(self, name: str):
if name not in {"__class__", "__del__"}:
raise AssertionError(f"caller object must not be inspected: {name}")
return super().__getattribute__(name)
def __repr__(self) -> str: # pragma: no cover - called only on regression
raise AssertionError("caller object must not be represented")
class P5DSecurityEventTests(unittest.TestCase):
def test_default_off_preserves_bypass(self) -> None:
host = SimpleNamespace()
for operation in gate.P5D_OPERATION_FLAGS:
self.assertTrue(gate.p5d_security_event_allows(host, operation, _Poisoned(), _Poisoned()))
def test_enabled_operations_reject_without_inspecting_forged_inputs(self) -> None:
for operation in gate.P5D_OPERATION_FLAGS:
host = _EnabledHost()
with self.subTest(operation=operation), self.assertLogs("PrivateCompanion.P5D", level="WARNING") as logs:
allowed = gate.p5d_security_event_allows(host, operation, _Poisoned(), _Poisoned(), _Poisoned())
self.assertFalse(allowed)
audit = host._p5d_denial_audit[-1]
self.assertEqual({"operation", "outcome", "reason_code", "ref_hash"}, set(audit))
self.assertEqual(gate.P5D_HOST_OWNER_CAPABILITY_UNAVAILABLE, audit["reason_code"])
self.assertNotIn("Poisoned", "\n".join(logs.output))
def test_main_helper_and_unknown_operation_keep_the_same_contract(self) -> None:
host = _EnabledHost()
host._p5d_security_event_allows = main.PrivateCompanionPlugin._p5d_security_event_allows.__get__(host, _EnabledHost)
self.assertFalse(host._p5d_security_event_allows(gate.MANUAL_RECOVERY_OPERATION, _Poisoned()))
with self.assertRaisesRegex(ValueError, "p5d_unknown_operation"):
gate.p5d_security_event_allows(host, "forged_operation")
def test_schema_has_exactly_the_two_default_off_operations(self) -> None:
schema = json.loads((Path(__file__).resolve().parents[1] / "_conf_schema.json").read_text(encoding="utf-8"))
items = schema["p5d_safety_config"]["items"]
self.assertEqual(set(gate.P5D_OPERATION_FLAGS.values()), set(items))
self.assertTrue(all(item["type"] == "bool" and item["default"] is False for item in items.values()))
if __name__ == "__main__":
unittest.main()

查看文件

@ -0,0 +1,178 @@
import hashlib
import json
import unittest
from p6_four_package_manifest import (
FOUR_PACKAGE_IDS,
FOUR_PACKAGE_MANIFEST_REPORT_SCHEMA,
FOUR_PACKAGE_MANIFEST_SCHEMA,
manifest_contract,
verify_four_package_manifests,
)
def _synthetic_manifests() -> dict[str, dict[str, str]]:
compatibility_fingerprint = "a" * 64
return {
package_id: {
"schema": FOUR_PACKAGE_MANIFEST_SCHEMA,
"package_id": package_id,
"manifest_version": "1.0",
"package_fingerprint": f"{index:064x}",
"compatibility_fingerprint": compatibility_fingerprint,
}
for index, package_id in enumerate(FOUR_PACKAGE_IDS, start=1)
}
class _Poison:
def __bool__(self) -> bool:
raise AssertionError("truthiness must not be evaluated")
def __iter__(self):
raise AssertionError("iteration must not be evaluated")
def __repr__(self) -> str:
raise AssertionError("repr must not be evaluated")
class _DictSubclass(dict):
pass
class FourPackageManifestTests(unittest.TestCase):
def assert_unverifiable(self, manifests: object, reason_code: str) -> None:
report = verify_four_package_manifests(manifests)
self.assertEqual(type(report), dict)
self.assertEqual(report["schema"], FOUR_PACKAGE_MANIFEST_REPORT_SCHEMA)
self.assertEqual(report["status"], "unverifiable")
self.assertEqual(report["reason_code"], reason_code)
self.assertEqual(report["expected_package_ids"], list(FOUR_PACKAGE_IDS))
self.assertNotIn("manifests", report)
self.assertNotIn("fingerprint", report)
def test_contract_descriptor_is_exact_and_canonical(self) -> None:
descriptor = manifest_contract()
payload = {
"schema": FOUR_PACKAGE_MANIFEST_SCHEMA,
"report_schema": FOUR_PACKAGE_MANIFEST_REPORT_SCHEMA,
"package_ids": list(FOUR_PACKAGE_IDS),
"required_manifest_fields": [
"schema",
"package_id",
"manifest_version",
"package_fingerprint",
"compatibility_fingerprint",
],
}
expected_fingerprint = hashlib.sha256(
json.dumps(
payload,
ensure_ascii=True,
sort_keys=True,
separators=(",", ":"),
).encode("utf-8")
).hexdigest()
self.assertEqual(
descriptor,
{**payload, "contract_fingerprint": expected_fingerprint},
)
self.assertEqual(type(descriptor), dict)
def test_contract_descriptors_are_fresh(self) -> None:
first = manifest_contract()
second = manifest_contract()
self.assertIsNot(first, second)
self.assertIsNot(first["package_ids"], second["package_ids"])
first["package_ids"].append("changed")
self.assertEqual(second["package_ids"], list(FOUR_PACKAGE_IDS))
def test_synthetic_consistent_manifests_verify(self) -> None:
report = verify_four_package_manifests(_synthetic_manifests())
self.assertEqual(
report,
{
"schema": FOUR_PACKAGE_MANIFEST_REPORT_SCHEMA,
"status": "verified",
"reason_code": "four_package_manifest_verified",
"expected_package_ids": list(FOUR_PACKAGE_IDS),
},
)
def test_reports_are_fresh(self) -> None:
first = verify_four_package_manifests(_synthetic_manifests())
second = verify_four_package_manifests(_synthetic_manifests())
self.assertIsNot(first, second)
self.assertIsNot(first["expected_package_ids"], second["expected_package_ids"])
first["expected_package_ids"].append("changed")
self.assertEqual(second["expected_package_ids"], list(FOUR_PACKAGE_IDS))
def test_rejects_non_exact_outer_dict(self) -> None:
self.assert_unverifiable([], "manifest_collection_not_exact_dict")
self.assert_unverifiable(_Poison(), "manifest_collection_not_exact_dict")
self.assert_unverifiable(_DictSubclass(_synthetic_manifests()), "manifest_collection_not_exact_dict")
def test_rejects_missing_and_unexpected_package_manifests(self) -> None:
missing = _synthetic_manifests()
del missing["peiban"]
self.assert_unverifiable(missing, "missing_package_manifest")
unexpected = _synthetic_manifests()
unexpected["unexpected"] = unexpected["companion"].copy()
self.assert_unverifiable(unexpected, "unexpected_package_manifest")
def test_rejects_non_exact_package_manifests_without_inspecting_them(self) -> None:
manifests = _synthetic_manifests()
manifests["companion"] = _Poison()
self.assert_unverifiable(manifests, "package_manifest_not_exact_dict")
manifests = _synthetic_manifests()
manifests["companion"] = _DictSubclass(manifests["companion"])
self.assert_unverifiable(manifests, "package_manifest_not_exact_dict")
def test_rejects_missing_and_unexpected_fields(self) -> None:
missing = _synthetic_manifests()
del missing["companion"]["schema"]
self.assert_unverifiable(missing, "missing_manifest_field")
unexpected = _synthetic_manifests()
unexpected["companion"]["extra"] = "ignored"
self.assert_unverifiable(unexpected, "unexpected_manifest_field")
def test_rejects_schema_and_package_id_mismatch(self) -> None:
wrong_schema = _synthetic_manifests()
wrong_schema["companion"]["schema"] = "ops.p6.other.v1"
self.assert_unverifiable(wrong_schema, "manifest_schema_mismatch")
wrong_id = _synthetic_manifests()
wrong_id["companion"]["package_id"] = "memory"
self.assert_unverifiable(wrong_id, "manifest_package_id_mismatch")
def test_rejects_invalid_versions(self) -> None:
for invalid_version in ("0.0", "1", "1.", "1.a", 1.0, _Poison()):
with self.subTest(invalid_version=type(invalid_version).__name__):
manifests = _synthetic_manifests()
manifests["companion"]["manifest_version"] = invalid_version
self.assert_unverifiable(manifests, "manifest_version_invalid")
def test_rejects_invalid_fingerprints_without_inspecting_poison_values(self) -> None:
invalid_package_fingerprint = _synthetic_manifests()
invalid_package_fingerprint["companion"]["package_fingerprint"] = "A" * 64
self.assert_unverifiable(invalid_package_fingerprint, "package_fingerprint_invalid")
poison_package_fingerprint = _synthetic_manifests()
poison_package_fingerprint["companion"]["package_fingerprint"] = _Poison()
self.assert_unverifiable(poison_package_fingerprint, "package_fingerprint_invalid")
invalid_compatibility_fingerprint = _synthetic_manifests()
invalid_compatibility_fingerprint["companion"]["compatibility_fingerprint"] = "g" * 64
self.assert_unverifiable(invalid_compatibility_fingerprint, "compatibility_fingerprint_invalid")
def test_rejects_inconsistent_compatibility_fingerprints(self) -> None:
manifests = _synthetic_manifests()
manifests["memory"]["compatibility_fingerprint"] = "b" * 64
self.assert_unverifiable(manifests, "compatibility_fingerprint_mismatch")
if __name__ == "__main__":
unittest.main()

查看文件

@ -0,0 +1,70 @@
# -*- coding: utf-8 -*-
"""P6-C local two-repository contract and no-effect harness."""
from __future__ import annotations
from copy import deepcopy
from pathlib import Path
import sys
import unittest
from context_orchestration import contract_descriptor as companion_p3_descriptor
from p5_ingress_firewall import evaluate_ingress_segment
from p6_readonly_projection import build_p6_readonly_status
from unified_person_contract import empty_unified_person_store
from unified_person_registry import UnifiedPersonRegistry
WORKSPACE_ROOT = Path(__file__).resolve().parents[2]
MEMORY_ROOT = WORKSPACE_ROOT / "astrbot_plugin_memory_companion-main"
if str(MEMORY_ROOT) not in sys.path:
sys.path.insert(0, str(MEMORY_ROOT))
from core import context_orchestration as memory_p3 # noqa: E402
from core.p6_readonly_projection import build_p6_readonly_status as build_memory_p6_status # noqa: E402
from core.recall_firewall import MEMORY_RECALL_SINK, evaluate_recall_disposition # noqa: E402
def identity(subject_id: str) -> dict[str, str]:
return {
"companion_instance_id": "companion-a",
"bot_account_id": "bot-1",
"adapter_instance_id": "telegram-main",
"subject_namespace": "telegram.user",
"platform_subject_id": subject_id,
}
@unittest.skipUnless(MEMORY_ROOT.is_dir(), "P6 joint workspace requires the memory companion sibling repository")
class P6JointWorkspaceTests(unittest.TestCase):
def test_status_contract_p3_and_p5_boundaries_align_without_sensitive_projection(self) -> None:
status = {"profiles": 2, "identity_links": 2, "audit_events": 3, "operations": 4, "person_id": "not-exported"}
companion = build_p6_readonly_status(status)
memory = build_memory_p6_status(status)
self.assertEqual(companion["schema_version"], memory["schema_version"])
self.assertEqual(companion["contract_fingerprint"], memory["contract_fingerprint"])
self.assertEqual(companion["counts"], memory["counts"])
self.assertNotIn("person_id", companion)
self.assertNotIn("person_id", memory)
self.assertEqual(companion_p3_descriptor(), memory_p3.contract_descriptor())
ingress = evaluate_ingress_segment({"source_kind": "forwarded_text", "trust": "T3", "source_hash": "sha256:" + ("a" * 64), "sink": "tool_execution", "security_state": "sanitized"})
recall = evaluate_recall_disposition({"source_kind": "legacy_memory", "source_trust": "T4", "firewall_status": "allowed", "record_id": "p6-joint-untrusted", "target_sink": MEMORY_RECALL_SINK})
self.assertEqual("none", ingress["execution_authority"])
self.assertEqual("none", recall["audit"]["execution_authority"])
def test_p4_preparation_ledger_does_not_project_a_live_effect(self) -> None:
store = {"unified_person": empty_unified_person_store()}
registry = UnifiedPersonRegistry(store)
created = registry.upsert_observed_identity(identity("p6-person"), operation_id="p6-observe")
person_id = created["person_id"]
before = deepcopy(store["unified_person"]["profiles"][person_id])
recorded = registry.record_p4_effect_event(person_id, {"event_id": "p6-effect-normal", "occurred_at": "2026-07-30T00:00:00Z", "kind": "normal"}, operation_id="p6-effect-op", actor_id="p6-joint")
self.assertTrue(recorded["ok"])
self.assertEqual(before, store["unified_person"]["profiles"][person_id])
self.assertNotIn("p4_shadow", store["unified_person"])
state = registry.read_p4_effect_state(person_id)
self.assertEqual("effect_preparation", state["p4_effect_state"]["mode"])
if __name__ == "__main__":
unittest.main()

查看文件

@ -0,0 +1,51 @@
import importlib.util
import unittest
import p6_four_package_manifest as companion_manifest
_MEMORY_MANIFEST_MODULE_PATH = (
r"D:\CODEX\projects\我会永远陪着你\astrbot_plugin_memory_companion-main"
r"\core\p6_four_package_manifest.py"
)
def _load_memory_manifest_module():
spec = importlib.util.spec_from_file_location(
"p6_memory_manifest_joint_workspace",
_MEMORY_MANIFEST_MODULE_PATH,
)
if spec is None or spec.loader is None:
raise AssertionError("memory P6 manifest module could not be loaded")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def _synthetic_manifests() -> dict[str, dict[str, str]]:
return {
package_id: {
"schema": companion_manifest.FOUR_PACKAGE_MANIFEST_SCHEMA,
"package_id": package_id,
"manifest_version": "1.0",
"package_fingerprint": f"{index:064x}",
"compatibility_fingerprint": "c" * 64,
}
for index, package_id in enumerate(companion_manifest.FOUR_PACKAGE_IDS, start=1)
}
class P6ManifestJointWorkspaceTests(unittest.TestCase):
def test_value_contracts_match_across_companion_and_memory(self) -> None:
memory_manifest = _load_memory_manifest_module()
self.assertEqual(companion_manifest.manifest_contract(), memory_manifest.manifest_contract())
manifests = _synthetic_manifests()
self.assertEqual(
companion_manifest.verify_four_package_manifests(manifests),
memory_manifest.verify_four_package_manifests(manifests),
)
if __name__ == "__main__":
unittest.main()

查看文件

@ -0,0 +1,52 @@
from __future__ import annotations
import importlib.util
from pathlib import Path
import unittest
MODULE_PATH = Path(__file__).resolve().parents[1] / "p6_readonly_projection.py"
SPEC = importlib.util.spec_from_file_location("p6_readonly_projection_under_test", MODULE_PATH)
assert SPEC and SPEC.loader
projection = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(projection)
class P6ReadOnlyProjectionTests(unittest.TestCase):
def test_only_bounded_counts_and_static_contract_are_returned(self) -> None:
result = projection.build_p6_readonly_status({
"profiles": 3,
"identity_links": 4,
"audit_events": 5,
"operations": 6,
"person_id": "must-not-leak",
"p4_event": {"body": "must-not-leak"},
"capability": "must-not-leak",
})
self.assertEqual("private_companion", result["source_plugin"])
self.assertEqual({"profiles": 3, "identity_links": 4, "audit_events": 5, "operations": 6}, result["counts"])
self.assertEqual({"schema_version", "source_plugin", "contract_fingerprint", "health", "reason_code", "counts"}, set(result))
self.assertNotIn("must-not-leak", repr(result))
def test_invalid_status_fails_closed_without_reading_object(self) -> None:
class Poison:
def __getattribute__(self, name):
raise AssertionError(name)
result = projection.build_p6_readonly_status(Poison())
self.assertEqual("unverifiable", result["health"])
self.assertEqual("registry_status_unavailable", result["reason_code"])
self.assertEqual({"profiles": 0, "identity_links": 0, "audit_events": 0, "operations": 0}, result["counts"])
def test_memory_consumer_uses_the_same_frozen_contract_fingerprint(self) -> None:
memory_path = Path(__file__).resolve().parents[2] / "astrbot_plugin_memory_companion-main" / "core" / "p6_readonly_projection.py"
spec = importlib.util.spec_from_file_location("p6_readonly_projection_memory_under_test", memory_path)
self.assertIsNotNone(spec)
self.assertIsNotNone(spec.loader)
memory = importlib.util.module_from_spec(spec)
spec.loader.exec_module(memory)
self.assertEqual(projection.P6_READONLY_STATUS_SCHEMA, memory.P6_READONLY_STATUS_SCHEMA)
self.assertEqual(projection.P6_READONLY_STATUS_FINGERPRINT, memory.P6_READONLY_STATUS_FINGERPRINT)
if __name__ == "__main__":
unittest.main()

查看文件

@ -44,6 +44,7 @@ REGISTRY_VERSION = 1
_REGISTRY_LOCK = threading.RLock() _REGISTRY_LOCK = threading.RLock()
_MAX_AUDIT_EVENTS = 1000 _MAX_AUDIT_EVENTS = 1000
_P4_SHADOW_VERSION = 1 _P4_SHADOW_VERSION = 1
_P4_EFFECT_VERSION = 1
def _now() -> str: def _now() -> str:
@ -256,6 +257,161 @@ def _p4_shadow_summary(state: dict[str, Any]) -> dict[str, Any]:
} }
def _p4_effect_container(root: dict[str, Any]) -> dict[str, Any]:
"""Return the P4-B preparation ledger, never the P4-A shadow ledger."""
container = root.get("p4_effect")
if not isinstance(container, dict):
container = {}
root["p4_effect"] = container
if not isinstance(container.get("version"), int):
container["version"] = _P4_EFFECT_VERSION
if not isinstance(container.get("people"), dict):
container["people"] = {}
return container
def _p4_effect_fingerprint(origin_person_id: str, event: dict[str, Any]) -> str:
return hashlib.sha256(_canonical({"origin_person_id": origin_person_id, "event": event}).encode("utf-8")).hexdigest()
def _p4_effect_state(events: list[dict[str, Any]]) -> dict[str, Any] | None:
replay = replay_shadow_events(events)
state = replay.get("state") if isinstance(replay, dict) else None
if not isinstance(state, dict):
return None
state = deepcopy(state)
state["mode"] = "effect_preparation"
return state
def _new_p4_effect_person_entry(person_id: str, now: str) -> dict[str, Any]:
state = new_shadow_state()
state["mode"] = "effect_preparation"
return {
"person_id": person_id,
"state": state,
"events": [],
"created_at": now,
"updated_at": now,
"last_operation_id": "",
}
def _replay_p4_effect_entry(entry: Any, person_id: str) -> tuple[dict[str, Any] | None, dict[str, dict[str, Any]] | None, str]:
"""Validate an effect-preparation entry; origin survives a person merge."""
if not isinstance(entry, dict) or entry.get("person_id") != person_id:
return None, None, "p4_effect_person_conflict"
envelopes = entry.get("events")
if not isinstance(envelopes, list):
return None, None, "p4_effect_corrupt"
event_index: dict[str, dict[str, Any]] = {}
events: list[dict[str, Any]] = []
for envelope in envelopes:
if not isinstance(envelope, dict) or envelope.get("person_id") != person_id:
return None, None, "p4_effect_corrupt"
origin = envelope.get("origin_person_id")
event = envelope.get("event")
event_id = envelope.get("event_id")
if not isinstance(origin, str) or not origin or not isinstance(event, dict) or not isinstance(event_id, str):
return None, None, "p4_effect_corrupt"
if event.get("event_id") != event_id or event_id in event_index:
return None, None, "p4_effect_corrupt"
if envelope.get("event_fingerprint") != _p4_effect_fingerprint(origin, event):
return None, None, "p4_effect_corrupt"
event_index[event_id] = envelope
events.append(event)
state = _p4_effect_state(events)
if not isinstance(state, dict) or entry.get("state") != state:
return None, None, "p4_effect_state_mismatch"
return state, event_index, ""
def _p4_effect_summary(state: dict[str, Any]) -> dict[str, Any]:
return _p4_shadow_summary(state)
def _merge_p4_effect_people(root: dict[str, Any], source_person_id: str, target_person_id: str, operation_id: str, now: str) -> dict[str, Any] | None:
"""Merge preparation records without changing P4-A or profile fields."""
container = root.get("p4_effect")
if not isinstance(container, dict) or not isinstance(container.get("people"), dict):
return None
people = container["people"]
source_before = deepcopy(people.get(source_person_id))
target_before = deepcopy(people.get(target_person_id))
for entry, person_id in ((source_before, source_person_id), (target_before, target_person_id)):
if entry is not None:
_state, _index, error = _replay_p4_effect_entry(entry, person_id)
if error:
raise ValueError(error)
envelopes: list[dict[str, Any]] = []
seen: dict[str, str] = {}
for entry in (target_before, source_before):
if not isinstance(entry, dict):
continue
for envelope in entry.get("events", []):
event_id = str(envelope.get("event_id") or "") if isinstance(envelope, dict) else ""
fingerprint = str(envelope.get("event_fingerprint") or "") if isinstance(envelope, dict) else ""
if not event_id or not fingerprint:
raise ValueError("p4_effect_corrupt")
previous = seen.get(event_id)
if previous is not None:
if previous != fingerprint:
raise ValueError("p4_effect_event_id_conflict")
continue
seen[event_id] = fingerprint
moved = deepcopy(envelope)
moved["person_id"] = target_person_id
envelopes.append(moved)
snapshot = {"source": source_before, "target": target_before}
if not envelopes:
return snapshot
state = _p4_effect_state([item["event"] for item in envelopes])
if not isinstance(state, dict):
raise ValueError("p4_effect_replay_failed")
people[target_person_id] = {
"person_id": target_person_id,
"state": state,
"events": envelopes,
"created_at": str((target_before or source_before or {}).get("created_at") or now),
"updated_at": now,
"last_operation_id": operation_id,
}
people.pop(source_person_id, None)
return snapshot
def _restore_p4_effect_after_split(root: dict[str, Any], merge: dict[str, Any], source_person_id: str, target_person_id: str, merge_operation_id: str) -> str:
"""Restore the exact pre-merge ledger or reject post-merge mutations."""
if "p4_effect_snapshot" not in merge:
return ""
snapshot = merge.get("p4_effect_snapshot")
if not isinstance(snapshot, dict):
return "p4_effect_split_conflict"
container = root.get("p4_effect")
if not isinstance(container, dict) or not isinstance(container.get("people"), dict):
return "p4_effect_split_conflict"
people = container["people"]
current_source = people.get(source_person_id)
current_target = people.get(target_person_id)
if current_source is not None:
return "p4_effect_split_conflict"
if current_target is not None:
if not isinstance(current_target, dict) or current_target.get("last_operation_id") != merge_operation_id:
return "p4_effect_split_conflict"
_state, _index, error = _replay_p4_effect_entry(current_target, target_person_id)
if error:
return error
for person_id, key in ((source_person_id, "source"), (target_person_id, "target")):
previous = snapshot.get(key)
if previous is None:
people.pop(person_id, None)
elif isinstance(previous, dict):
people[person_id] = deepcopy(previous)
else:
return "p4_effect_split_conflict"
return ""
class UnifiedPersonRegistry: class UnifiedPersonRegistry:
"""Companion-only lifecycle authority. No consumer receives a write method.""" """Companion-only lifecycle authority. No consumer receives a write method."""
@ -494,6 +650,103 @@ class UnifiedPersonRegistry:
self._commit(root) self._commit(root)
return result return result
def read_p4_effect_state(self, person_id: str) -> dict[str, Any]:
"""Read P4-B preparation state without projecting it into a profile."""
try:
person_id = _identifier(person_id, "person_id")
except ValueError:
return _result(False, "invalid_request")
with _REGISTRY_LOCK:
root = self._root_copy()
profile = root["profiles"].get(person_id)
if not isinstance(profile, dict):
return _result(False, "person_not_found", person_id=person_id)
if profile.get("profile_status") != "active":
return _result(False, "person_not_active", person_id=person_id)
entry = _p4_effect_container(root)["people"].get(person_id)
if entry is None:
state = _new_p4_effect_person_entry(person_id, "")["state"]
return _result(True, "p4_effect_empty", person_id=person_id, p4_effect_exists=False, p4_effect_state=state, p4_effect_summary=_p4_effect_summary(state), event_count=0)
state, event_index, error = _replay_p4_effect_entry(entry, person_id)
if error:
return _result(False, error, person_id=person_id)
assert state is not None and event_index is not None
return _result(True, "p4_effect_read", person_id=person_id, p4_effect_exists=True, p4_effect_state=state, p4_effect_summary=_p4_effect_summary(state), event_count=len(event_index))
def record_p4_effect_event(
self,
person_id: str,
event: dict[str, Any],
*,
operation_id: str,
actor_id: str = "system",
) -> dict[str, Any]:
"""Append one P4-B preparation event without a runtime effect.
This is deliberately separate from ``record_p4_shadow_event``. It
writes no profile/projection field and is not connected to a Hook,
reply, confinement gate, or owner command.
"""
try:
operation_id = _identifier(operation_id, "operation_id", 120)
person_id = _identifier(person_id, "person_id")
actor_id = _identifier(actor_id, "actor_id", 160)
except ValueError:
return _result(False, "invalid_request")
if not isinstance(event, dict):
return _result(False, "invalid_p4_effect_event", operation_id=operation_id, person_id=person_id)
for field in ("person_id", "origin_person_id"):
if event.get(field) not in (None, "", person_id):
return _result(False, "p4_effect_person_mismatch", operation_id=operation_id, person_id=person_id)
normalized_event, event_errors = _normalize_p4_shadow_event(event)
if normalized_event is None:
return _result(False, "invalid_p4_effect_event", operation_id=operation_id, person_id=person_id, event_errors=event_errors)
event_id = str(normalized_event["event_id"])
payload = {"person_id": person_id, "actor_id": actor_id, "event": normalized_event}
with _REGISTRY_LOCK:
root = self._root_copy()
repeated, fresh = _operation_result(root, operation_id, "record_p4_effect_event", payload)
if repeated is not None:
return repeated
profile = root["profiles"].get(person_id)
if not isinstance(profile, dict):
return _result(False, "person_not_found", operation_id=operation_id, person_id=person_id)
if profile.get("profile_status") != "active":
return _result(False, "person_not_active", operation_id=operation_id, person_id=person_id)
people = _p4_effect_container(root)["people"]
entry = people.get(person_id)
if entry is None:
entry = _new_p4_effect_person_entry(person_id, _now())
event_index: dict[str, dict[str, Any]] = {}
else:
current_state, event_index, error = _replay_p4_effect_entry(entry, person_id)
if error:
return _result(False, error, operation_id=operation_id, person_id=person_id)
assert current_state is not None and event_index is not None
fingerprint = _p4_effect_fingerprint(person_id, normalized_event)
known = event_index.get(event_id)
if known is not None:
if known.get("event_fingerprint") != fingerprint:
return _result(False, "p4_effect_event_id_conflict", operation_id=operation_id, person_id=person_id, event_id=event_id)
result = _result(True, "p4_effect_event_duplicate", operation_id=operation_id, person_id=person_id, event_id=event_id, event_duplicate=True, p4_effect_summary=_p4_effect_summary(entry["state"]))
_record_operation(root, operation_id=operation_id, action="record_p4_effect_event", payload=payload, metadata={"event_id": event_id, "duplicate_event": True}, result=result, now=_now())
self._commit(root)
return result
now = _now()
entry["events"].append({"event_id": event_id, "person_id": person_id, "origin_person_id": person_id, "event": deepcopy(normalized_event), "event_fingerprint": fingerprint, "recorded_at": now, "operation_id": operation_id})
replay_state = _p4_effect_state([item["event"] for item in entry["events"]])
if not isinstance(replay_state, dict):
return _result(False, "p4_effect_replay_failed", operation_id=operation_id, person_id=person_id)
entry["state"] = replay_state
entry["updated_at"] = now
entry["last_operation_id"] = operation_id
people[person_id] = entry
result = _result(True, "p4_effect_event_recorded", operation_id=operation_id, person_id=person_id, origin_person_id=person_id, event_id=event_id, changed=True, affected_person_ids=[person_id], audit_event_id=operation_id, p4_effect_summary=_p4_effect_summary(replay_state))
_append_audit(root, operation_id=operation_id, action="p4_effect_event_recorded", actor_id=actor_id, code=result["code"], now=now, details={"person_id": person_id, "event_id": event_id, "event_kind": str(normalized_event.get("kind") or "invalid")})
_record_operation(root, operation_id=operation_id, action="record_p4_effect_event", payload=payload, metadata={"event_id": event_id}, result=result, now=now)
self._commit(root)
return result
def upsert_observed_identity( def upsert_observed_identity(
self, self,
identity: dict[str, Any], identity: dict[str, Any],
@ -745,6 +998,16 @@ class UnifiedPersonRegistry:
"overlays": before_overlays, "overlays": before_overlays,
"merged_aliases": merged_aliases, "merged_aliases": merged_aliases,
} }
try:
p4_effect_snapshot = _merge_p4_effect_people(
root,
source_person_id,
target_person_id,
operation_id,
now,
)
except ValueError as exc:
return _result(False, str(exc) or "p4_effect_merge_conflict", operation_id=operation_id)
for key in moved_keys: for key in moved_keys:
link = links[key] link = links[key]
link.update({"person_id": target_person_id, "previous_person_id": source_person_id, "merge_operation_id": operation_id, "updated_at": now, "last_operation_id": operation_id}) link.update({"person_id": target_person_id, "previous_person_id": source_person_id, "merge_operation_id": operation_id, "updated_at": now, "last_operation_id": operation_id})
@ -769,7 +1032,7 @@ class UnifiedPersonRegistry:
overlay["person_id"] = target_person_id overlay["person_id"] = target_person_id
overlay["origin_person_id"] = source_person_id overlay["origin_person_id"] = source_person_id
overlay["merge_operation_id"] = operation_id overlay["merge_operation_id"] = operation_id
root["merge_operations"][operation_id] = { merge_record = {
"operation_id": operation_id, "operation_id": operation_id,
"state": "active", "state": "active",
"source_person_id": source_person_id, "source_person_id": source_person_id,
@ -778,6 +1041,9 @@ class UnifiedPersonRegistry:
"snapshot": snapshot, "snapshot": snapshot,
"created_at": now, "created_at": now,
} }
if p4_effect_snapshot is not None:
merge_record["p4_effect_snapshot"] = p4_effect_snapshot
root["merge_operations"][operation_id] = merge_record
result = _result(True, "people_merged", person_id=target_person_id, source_person_id=source_person_id, target_person_id=target_person_id, moved_identity_keys=moved_keys, changed=True, affected_person_ids=[source_person_id, target_person_id], projection_revision=target["projection_revision"], audit_event_id=operation_id) result = _result(True, "people_merged", person_id=target_person_id, source_person_id=source_person_id, target_person_id=target_person_id, moved_identity_keys=moved_keys, changed=True, affected_person_ids=[source_person_id, target_person_id], projection_revision=target["projection_revision"], audit_event_id=operation_id)
_append_audit(root, operation_id=operation_id, action="explicit_merge", actor_id=actor_id, code=result["code"], now=now, details={"source_person_id": source_person_id, "target_person_id": target_person_id, "reason": reason, "moved_identity_keys": moved_keys}) _append_audit(root, operation_id=operation_id, action="explicit_merge", actor_id=actor_id, code=result["code"], now=now, details={"source_person_id": source_person_id, "target_person_id": target_person_id, "reason": reason, "moved_identity_keys": moved_keys})
_record_operation(root, operation_id=operation_id, action="merge_people", payload=payload, metadata={}, result=result, now=now) _record_operation(root, operation_id=operation_id, action="merge_people", payload=payload, metadata={}, result=result, now=now)
@ -841,6 +1107,15 @@ class UnifiedPersonRegistry:
if not remaining_keys: if not remaining_keys:
return _result(False, "split_conflict", operation_id=operation_id) return _result(False, "split_conflict", operation_id=operation_id)
replacement_key = remaining_keys[0] replacement_key = remaining_keys[0]
p4_effect_error = _restore_p4_effect_after_split(
root,
merge,
source_id,
target_id,
merge_operation_id,
)
if p4_effect_error:
return _result(False, p4_effect_error, operation_id=operation_id)
now = _now() now = _now()
source_revision = int(source.get("projection_revision") or 0) source_revision = int(source.get("projection_revision") or 0)
target_revision = int(target.get("projection_revision") or 0) target_revision = int(target.get("projection_revision") or 0)