# -*- coding: utf-8 -*- from __future__ import annotations import asyncio from copy import deepcopy import hashlib import importlib import pathlib import sys from types import SimpleNamespace import types import unittest sys.path.insert(0, str(pathlib.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_shadow_hook_companion" if PACKAGE not in sys.modules: package = types.ModuleType(PACKAGE) package.__path__ = [str(pathlib.Path(__file__).resolve().parents[1])] sys.modules[PACKAGE] = package contract = importlib.import_module(f"{PACKAGE}.context_orchestration") main = importlib.import_module(f"{PACKAGE}.main") core_store = importlib.import_module(f"{PACKAGE}.core_store") person_contract = importlib.import_module(f"{PACKAGE}.unified_person_contract") PERSON_ID = "person_0123456789abcdef01234567" def finalized_state(*, status: str = "allowed", response_policy: str = "inherit") -> dict: state = contract.new_context_state(created_at="2026-07-29T00:00:00.000Z") contract.update_security(state, status=status, response_policy=response_policy) for layer in contract.LAYERS: contract.complete_layer(state, layer) contract.finalize_state(state) assert state["finalized"] is True return state class _Host: def __init__(self, *, enabled: bool = True, authority: dict | None = None) -> None: self.enable_p4_shadow_observer = enabled self.authority = authority if authority is not None else { "unified_person_projection": { "person_id": PERSON_ID, "profile_status": "active", "identity_assurance": "verified", }, "unified_person_source_identity": { "companion_instance_id": "companion-a", "bot_account_id": "bot-a", "adapter_instance_id": "telegram-main", "subject_namespace": "telegram.user", "platform_subject_id": "sender-42", }, } self.calls: list[tuple[tuple, dict]] = [] @staticmethod def _event_message_id(event): return str(getattr(event, "message_id", "") or "") @staticmethod def _safe_event_sender_id(event): return str(getattr(event, "sender_id", "") or "") def _memory_companion_unified_person_authority(self, event, *, expected_user_id=""): if expected_user_id != "sender-42": return {} return deepcopy(self.authority) def _apply_unified_person_lifecycle(self, *args, **kwargs): self.calls.append((args, kwargs)) return {"ok": True, "code": "p4_shadow_event_recorded"} class _RegistryHost(core_store.CoreStoreMixin, _Host): def __init__(self) -> None: _Host.__init__(self) self.data = {"unified_person": person_contract.empty_unified_person_store()} self.save_calls = 0 def _schedule_data_save(self) -> None: self.save_calls += 1 class P4ShadowHookTests(unittest.TestCase): def _invoke(self, host: _Host, state: dict, *, message_id: str = "msg-42", text: str = "hello"): event = SimpleNamespace(message_id=message_id, message_str=text, sender_id="sender-42") request = SimpleNamespace(system_prompt="unchanged") contract.attach_context_state(state, request, event) state_before = deepcopy(state) asyncio.run(main.PrivateCompanionPlugin.record_p4_shadow_normal_observer(host, event, request)) self.assertEqual(request.system_prompt, "unchanged") self.assertEqual(event.message_str, text) self.assertEqual(state, state_before) return event, request def test_observer_runs_after_p3_finalizer_and_writes_minimal_normal_shadow_event(self): self.assertEqual(main.P4_SHADOW_OBSERVER_PRIORITY, contract.FINALIZE - 1000) self.assertEqual(main.P4_SHADOW_OBSERVER_PRIORITY, -23000) host = _Host() self._invoke(host, finalized_state()) self.assertEqual(len(host.calls), 1) args, kwargs = host.calls[0] self.assertEqual(args[:2], ("record_p4_shadow_event", PERSON_ID)) event = args[2] digest = hashlib.sha256(b"msg-42").hexdigest() self.assertEqual(event, { "event_id": f"p4.normal:{digest}", "occurred_at": "2026-07-29T00:00:00.000Z", "kind": "normal", "firewall_safe": True, "is_command": False, "is_empty": False, }) self.assertNotIn("msg-42", repr(event)) self.assertNotIn("hello", repr(event)) self.assertEqual(kwargs, { "operation_id": f"p4.shadow.normal:{PERSON_ID}:{digest}", "actor_id": "p4_shadow_observer", }) def test_observer_is_fail_closed_for_flag_p3_message_and_person_authority_gates(self): low_assurance = _Host().authority low_assurance["unified_person_projection"]["identity_assurance"] = "observed" cases = [ (_Host(enabled=False), finalized_state(), "msg-42", "hello"), (_Host(), finalized_state(status="blocked"), "msg-42", "hello"), (_Host(), finalized_state(status="quarantined"), "msg-42", "hello"), (_Host(), finalized_state(status="unavailable"), "msg-42", "hello"), (_Host(), finalized_state(response_policy="deny"), "msg-42", "hello"), (_Host(), finalized_state(), "", "hello"), (_Host(authority={}), finalized_state(), "msg-42", "hello"), (_Host(authority=low_assurance), finalized_state(), "msg-42", "hello"), ] for host, state, message_id, text in cases: with self.subTest(message_id=message_id, state=state["security"]["status"]): self._invoke(host, state, message_id=message_id, text=text) self.assertEqual(host.calls, []) not_finalized = contract.new_context_state(created_at="2026-07-29T00:00:00.000Z") host = _Host() self._invoke(host, not_finalized) self.assertEqual(host.calls, []) def test_sanitized_event_is_shadowed_but_commands_and_empty_text_are_not_recovery_eligible(self): host = _Host() self._invoke(host, finalized_state(status="sanitized"), text="/放出 person_0123456789abcdef01234567") self.assertEqual(host.calls[0][0][2]["is_command"], True) host = _Host() self._invoke(host, finalized_state(), text=" ") self.assertTrue(host.calls[0][0][2]["is_empty"]) def test_observer_errors_are_nonfatal_and_do_not_write_shadow_state(self): class _BrokenMessageIdHost(_Host): @staticmethod def _event_message_id(event): raise RuntimeError("message id unavailable") class _BrokenAuthorityHost(_Host): def _memory_companion_unified_person_authority(self, event, *, expected_user_id=""): raise RuntimeError("authority unavailable") for host in (_BrokenMessageIdHost(), _BrokenAuthorityHost()): with self.subTest(host=type(host).__name__): self._invoke(host, finalized_state()) self.assertEqual(host.calls, []) def test_hook_to_registry_persists_only_p4_shadow_and_is_idempotent(self): host = _RegistryHost() observed_identity = { "companion_instance_id": "companion-a", "bot_account_id": "bot-a", "adapter_instance_id": "telegram-main", "subject_namespace": "telegram.user", "platform_subject_id": "sender-42", } linked_identity = { **observed_identity, "bot_account_id": "bot-b", } registry = host._unified_person_registry() created = registry.upsert_observed_identity( observed_identity, operation_id="p4-hook-observe", display_name="sender", ) person_id = created["person_id"] self.assertTrue(registry.link_identity( linked_identity, person_id, operation_id="p4-hook-link", actor_id="test", reason="test_relink", authorized=True, )["ok"]) self.assertTrue(registry.unlink_identity( observed_identity, operation_id="p4-hook-unlink", actor_id="test", reason="test_relink", authorized=True, )["ok"]) projection_before = person_contract.build_person_projection(host.data, person_id) self.assertIsNotNone(projection_before) assert projection_before is not None self.assertEqual(projection_before["identity_assurance"], "explicit_linked") profile_before = deepcopy(host.data["unified_person"]["profiles"][person_id]) host.authority = { "unified_person_projection": projection_before, "unified_person_source_identity": linked_identity, } self._invoke(host, finalized_state()) self.assertEqual(host.save_calls, 1) self.assertEqual(host.data["unified_person"]["profiles"][person_id], profile_before) self.assertEqual(person_contract.build_person_projection(host.data, person_id), projection_before) entry = host.data["unified_person"]["p4_shadow"]["people"][person_id] self.assertEqual(len(entry["events"]), 1) self.assertEqual(entry["state"]["score"], 0) self._invoke(host, finalized_state()) self.assertEqual(host.save_calls, 1) self.assertEqual(len(entry["events"]), 1) if __name__ == "__main__": unittest.main()